LeetCode 310: Minimum Height Trees Posting my code for a LeetCode problem, if you'd like to review, please do so. Thank you for your time!
Problem
For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1 :
Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3

Output: [1]

Example 2 :
Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
      \ | /
        3
        |
        4
        |
        5

Output: [3, 4]

Note:
According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
Code
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <unordered_set>
#include <algorithm>

static const struct Solution {
        using ValueType = std::uint_fast16_t;

        static const std::vector<int> findMinHeightTrees(
            const int n,
            const std::vector<std::vector<int>>& edges
        ) {
            std::vector<int> buff_a;
            std::vector<int> buff_b;
            std::vector<int>* ptr_a = &buff_a;
            std::vector<int>* ptr_b = &buff_b;

            if (n == 1) {
                buff_a.emplace_back(0);
                return buff_a;
            }

            if (n == 2) {
                buff_a.emplace_back(0);
                buff_a.emplace_back(1);
                return buff_a;
            }

            std::vector<Node> graph(n);

            for (const auto& edge : edges) {
                graph[edge[0]].neighbors.insert(edge[1]);
                graph[edge[1]].neighbors.insert(edge[0]);
            }

            for (ValueType node = 0; node < n; ++node) {
                if (graph[node].isLeaf()) {
                    ptr_a->emplace_back(node);
                }
            }

            while (true) {
                for (const auto& leaf : *ptr_a) {
                    for (const auto& node : graph[leaf].neighbors) {
                        graph[node].neighbors.erase(leaf);

                        if (graph[node].isLeaf()) {
                            ptr_b->emplace_back(node);
                        }
                    }
                }

                if (ptr_b->empty()) {
                    return *ptr_a;
                }

                ptr_a->clear();
                std::swap(ptr_a, ptr_b);
            }
        }

    private:
        static const struct Node {
            std::unordered_set<ValueType> neighbors;
            const bool isLeaf() {
                return std::size(neighbors) == 1;
            }
        };
};

References

Problem

Discuss

Wiki

A triply nested loops always look scary. Especially with while (true).
First thing first, trust yourself. The leaf node (and the ptr_a contains only leafs) has only one neighbour. The
for (const auto& node : graph[leaf].neighbors)

loop is effectively
auto& node = graph[leaf].neighbors.begin();

Second, no naked loops please. And more functions please. The
for (const auto& leaf : *ptr_a)

prunes leaves from the tree. Factor it out into a prune_leaves function, which would return a set (technically a vector) of the new leaves:
leaves = prune_leaves(leaves, graph);

Third, the outer loop shall naturally terminate when less than 3 leaves remain.
Finally, separate IO from the business logic. That said, a code along the lines of
    graph = build_graph();
    leaves = collect_leaves(graph);
    while (leaves.size() < 3) {
        leaves = prune_leaves(leaves, graph);
    }
    return leaves;

would win my endorsement. Notice how ptr_a and ptr_b - which are not the most descriptive names - disappear.


Loop combinations of byte for Poker simulator In (this) Poker you have 2 hole cards that are combined with 5 shared cards on the board. Each player makes the best 5 card hand from the seven. Believe it or not that is over 2 billion runs to do them all.

I'm trying to create statistics for 2 known hole cards against random boards and random hands for a single opponent using Monte Carlo for like 20 million runs.

First get sets of 7 random for board plus 1 opponent from 50 (known 2 hole cards are removed).  From those 7 remove all 2 card combinations (21) to represent the opponent's hole cards.  The idea is better statistics with an exhaustive examination of the 7 rather than a random 5 and a random 2.  Computation on the random 5 plus random 2 is more efficient as you only need to run the known hand once for each random 5.

byte? skip1 = null;
byte? skip2 = null;
List<byte> deck50seven = null;
byte nextSevenLastStart = 42;
private IEnumerable<byte> NextSevenA(byte Skip1, byte Skip2)
{
    if (Skip1 == Skip2)
        throw new ArgumentOutOfRangeException("skip1 == skip2");
    if (Skip1 > 51 || Skip2 > 51 || Skip1 < 0 || Skip2 < 0)
        throw new ArgumentOutOfRangeException("51 0");
    if(skip1 == null)
    {
        skip1 = Skip1;
        skip2 = Skip2;
        deck50seven = new List<byte>(50);
        for(byte b = 0; b < 52; b++)
        {
            if (b == Skip1 || b == Skip2)
                continue;
            deck50seven.Add(b);
        }
    }
    else
    {
        if (Skip1 != skip1 || Skip2 != skip2)
            throw new ArgumentException("skippy");
    }
    if (nextSevenLastStart >= 42)
    {
        nextSevenLastStart = 0;
        // Yates shuffle
        for (int i = 49; i >= 1; i--)
        {   // int for indexing is faster (I think)
            int j = rand.Next(i + 1);  // it can get swapped with itself
            if (j != i)
            {   // exchange values
                byte curVal = deck50seven[i];
                deck50seven[i] = deck50seven[j];
                deck50seven[j] = curVal;
            }
        }
    }
    else
        nextSevenLastStart += 7;
    return deck50seven.GetRange(nextSevenLastStart, 7);
}
private IEnumerable<List<byte>> NextSevenAsFiveTwo(List<byte> input)
{
    // 21 ways to take 2 from 7
    // this is going to seem strange but need every combination of 2 to be the last 2
    if (input.Count() != 7)
        throw new ArgumentOutOfRangeException("input.Count() != 7");
    List<byte> output = new List<byte>();
    for (byte i = 0; i <= 5; i++)
    {
        for (byte j = (byte)(i + 1); j <= 6; j++)
        {
            output.Clear();
            for (byte k = 0; k < 7; k++)
                if (k != i && k != j)
                    output.Add(input[k]);
            output.Add(input[i]);
            output.Add(input[j]);
            yield return output;
        }
    }
}

can use this for test

for (int i = 0; i < 10; i++)
{
    List<byte> nextSevenA = new List<byte>(NextSevenA(11, 12));
    Debug.WriteLine("Base " + string.Join(", ", nextSevenA));
    foreach(List<byte> ss in NextSevenAsFiveTwo(nextSevenA))
        Debug.WriteLine("     Subset " + string.Join(", ", ss));
}

private IEnumerable<byte> NextSevenA(byte Skip1, byte Skip2)

Method arguments should be named using camelCase casing. In this way you wouldn't mistake them for being properties.

If you need the PascalCase casing of the arguments to distinguish them from your local variables, you should either change their names or use this for use with class level variables.
Omitting braces although they might be optional, like for single lined if statements, can lead to serious bugs which are hard to find. I would like to encourage you to always use them. This not only makes your code less error prone but also more readable because it looks more structured.
throwing an ArgumentOutOfRangeException is a good thing but the error message should be more expressive. "51 0" isn't telling really much.
You should validate

    if (Skip1 != skip1 || Skip2 != skip2)
        throw new ArgumentException("skippy");

earlier to make it clear where the validation happens.
by extracting the generation of the byte values of deck50seven to a separate method returning an IEnumerable<byte> the method could be shorter.

private static IEnumerable<byte> GetByteRange(byte start, byte end)
{
    for (byte b = start; b < end; b++)
    {
        yield return b;
    }
}

After introducing a private const int MaxCardsInDeck = 52 this could be called like

deck50seven = GetByteRange(0, MaxCardsInDeck).Except(new byte[] { Skip1, Skip2 }).ToList();

By changing the way you handle nextSevenLastStart you could get rid of the else part at the end. I say could because I don't know if you somewhere else using that variable. The way I would do this is like so

nextSevenLastStart += 7;
if (nextSevenLastStart >= 49)
{
    //shuffling now
}

If this isn't an option you should consider to invert the condition if (nextSevenLastStart >= 42) and return early which saves you one level of indentation.
The shuffeling of the deck50seven should be extracted to a separate method like so

private static Random rand = new Random();
private static void Shuffle(List<byte> items, int upperBound=42,int lowerBound=1)
{
    for (int i = upperBound; i >= lowerBound; i--)
    {
        int j = rand.Next(i + 1);
        if (j != i)
        {
            byte currentValue = items[i];
            items[i] = items[j];
            items[j] = currentValue;
        }
    }
}

You have a lot of magic numbers in your code of which I am unsure what they are about so I will leave them untouched. You should extract them to meaningful constants.

Implementing the mentioned points apart from the exception messages, because I don't have enough context, will lead to

private IEnumerable<byte> NextSevenA(byte skip1, byte skip2)
{
    if (skip1 == skip2)
    {
        throw new ArgumentOutOfRangeException("skip1 == skip2");
    }

    if (skip1 > 51 || skip2 > 51 || skip1 < 0 || skip2 < 0)
    {
        throw new ArgumentOutOfRangeException("51 0");
    }

    if (this.skip1.HasValue && (this.skip1 != skip1 || this.skip2 != skip2))
    {
        throw new ArgumentException("skippy");
    }

    if (skip1 == null)
    {
        this.skip1 = skip1;
        this.skip2 = skip2;
        deck50seven = GetByteRange(0, 52).Except(new byte[] { skip1, skip2 }).ToList();
    }

    nextSevenLastStart += 7;

    if (nextSevenLastStart >= 49)
    {
        nextSevenLastStart = 0;
        Shuffle(deck50seven);
    }

    return deck50seven.GetRange(nextSevenLastStart, 7);
}

private IEnumerable<List<byte>> NextSevenAsFiveTwo(List<byte> input)

Using the Count() extension method on a List<T> involves a (soft)cast to an ICollection<T> so it should be faster to just use the Count property.
Because the method is only called by requesting the enumerator you should extract the validation of the Count property to a separate method. IMO this ArgumentOutOfRangeException should be thrown at the moment you call the method.
Instead of the most inner loop and the check for if (k != i && k != j) you can use Enumerable.Range() excepting i and j. This range can be stored in a class level (but static) variable so we can make the method static as well.

Implementing the mentioned points will look like so

private static IEnumerable<List<byte>> NextSevenAsFiveTwo(List<byte> input)
{
    if (input.Count != 7)
    {
        throw new ArgumentOutOfRangeException("input.Count != 7");
    }
    return NextSevenAsFiveTwoIterator(input);
}
private static IEnumerable<int> range = Enumerable.Range(0, 7);
private static IEnumerable<List<byte>> NextSevenAsFiveTwoIterator(List<byte> input)
{
    // 21 ways to take 2 from 7
    // this is going to seem strange but need every combination of 2 to be the last 2

    List<byte> output = new List<byte>();
    for (int i = 0; i <= 5; i++)
    {
        for (int j = (i + 1); j <= 6; j++)
        {
            output.Clear();
            foreach (int k in range.Except(new int[] { i, j }))
            {
                output.Add(input[k]);
            }
            output.Add(input[i]);
            output.Add(input[j]);
            yield return output;
        }
    }
}


Protecting webpage text from being selected I've got a text I don't want to be copied by users.
To avoid that, I'm using this code:
index.php

<?php
session_start();
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < 100; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
$_SESSION['token'] = $randomString;
?>
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test</title>

Please wait...

page.php

<?php
session_start();
if(!empty($_SESSION['token']) AND $_GET['token']==$_SESSION['token']){echo '

Text...';
unset($_SESSION['token']);
}
else{echo 'Error.';
}
?>

Is this method reliable?

That is an old skool question, the common wisdom is that you cannot prevent a user from getting to the text. There are a number of ways to get around your protection.

For example, in Chrome, open Developers Tools, open your site, check the web request, and then all the text will be perfectly copy pastable.

Other than that:

alert() has been a bad practice for 20 years now, please use something else
Indent your code, use jsbeautifier if you have trouble
In the keydown, I would check whether the control key is pressed before throwing an error, unless the user never needs to press PageUp or PageDown
I am not entire surely, but I think you will need event.preventDefault(); to really prevent right clicking etc.


Splitting a div and positioning an inner div I have an outer div with...

Width
Number of slots the outer div represents

The intent is to add a child div, but position the child div based on the start and end slot in the parent div.

To achieve this behavior, I am calculating the width per slot and the width of child div, plus the margin left of child div.

import React from 'react';

let parentDivStyle = {
    border: '1px solid black',
    height: '50px',
    align: 'center',
    display: 'inline-block'
}

let childDivStyle = {
    backgroundColor: 'darkseagreen',
    marginTop: '5px',
    height: '40px',
}

const DivColoring = (props) => {
    let parentDivWith = props.parentDivWidth;
    let totalSlots = props.totalSlots;
    let startSlot = props.startSlot;
    let endSlot = props.endSlot;

    let widthPerSlot = Math.round(parentDivWith / totalSlots);

    console.log('widthPerSlot= ', widthPerSlot);
    let childWidth = parentDivWith;

    let marginLeft = 0;

    //if startSlot is greater than 1, calculate the Left Margin and Width.
    if (startSlot > 1) {
        marginLeft = (startSlot - 1) * widthPerSlot;
    }

    //if end is present and is less than totalSlots update childWidth

    if (endSlot && endSlot <= totalSlots) {
        childWidth = widthPerSlot * (endSlot - startSlot + 1);
    }

    //add 1 px to marginLeft of child div
    marginLeft = marginLeft + 1;
    //remove 2 px from childWidth to add a padding of 1px at end
    childWidth = childWidth - 2;

    return (

);
}

export default DivColoring;

Please see the working example here https://stackblitz.com/edit/react-be8wxg

Is there any better of achieving this behavior. Thanks.

There are 2 more ways to do this using css without the calculation. They are:

css positioning

Make the position of parent relative and child absolute. Now, using the slots value, left and right properties can be easily calculated for child div which will place it properly. The entire logic is reduces to the following without adding any additional elements:

const DivColoring = props => {
  let parentDivWidth = props.parentDivWidth;
  let totalSlots = props.totalSlots;
  let startSlot = props.startSlot;
  let endSlot = props.endSlot;
  return (

      <div
        style={{
          ...childDivStyle,
          position: "absolute",
          left: `${((startSlot - 1) * 100) / totalSlots}%`,
          right: `${((totalSlots - endSlot) * 100) / totalSlots}%`
        }}
      />

  );
};

The entire code can be found here: https://stackblitz.com/edit/react-qj3xsp

css flex

The DivColoring component can contain 3 child divs instead of one and you can use flex property to define relative width of the divs. The relative width can be easily calculated using totalSlots, startSlot and endSlot. The basic logic can be written as:

const DivColoring = props => {
  let totalSlots = props.totalSlots;
  let startSlot = props.startSlot;
  let endSlot = props.endSlot;
  let div3 = totalSlots - endSlot;
  let div2 = endSlot - startSlot + 1;
  let div1 = startSlot - 1;
  return (

  );
};

The complete code can be found here: https://stackblitz.com/edit/react-4mgl4c.
You also need to apply some extra css. Pros are calculation is reduced but con is that DOM will become heavy. Instead of 1, now there are 3 divs for each block.

The recommended approach will be using css positioning.

Hope it helps. Revert for any doubts/clarifications.


Swapping int with string using getchar() and putchar() I wrote code that replaces integers from 0 to 3 with strings. I was only allowed to use getchar() and putchar(). If the input is 1, the output will become "one".

#include <stdio.h>

int main()
{

int c;

char* arr[4] = {"zero", "one", "two","three"};

int i;

  while ((c = getchar ()) != EOF)
    {

        if(c==0+'0'){
        char* str = arr[0];
    for (i = 0; str[i] != '\0'; i++) {

    putchar(str[i]);

}
}

else if(c==1+'0'){
char* str = arr[1];
      for (i= 0; str[i] != '\0';i++) {

    putchar(str[i]);

}
}

else if(c==2+'0'){
char* str = arr[2];
      for (i = 0; str[i] != '\0'; i++) {
        putchar(str[i]);

}
}
else if(c==3+'0'){

    char* str = arr[3];
     for (i = 0; str[i] != '\0'; i++) {
    putchar(str[i]);

}
}

        else
        putchar(c);

   }

return 0;

}

The code is pretty long. Is there a shorter way to write it?

Review
Vertical White Space
You have way too many blank lines.
Please remove 90% of them.
Formatting
This code is horribly formatted.
Code is designed for humans to read. Part of that is making sure it is easy to read.
DRY
There is one piece of code that is repeated several times.
for (i = 0; str[i] != '\0'; i++) {
    putchar(str[i]);
}

You can simplify your code by putting this into its own function. Then calling the function when you want to print out the string.
Easier to read
Your comparisons to check for a number is overly complex:
else if(c==2+'0'){

The c is a character so simply compare the user input to the expected character:
 else if (c == '2') {


Scraping game data from web My code currently:
import os
import pandas as pd
from selenium import webdriver
from tabulate import tabulate
from datetime import datetime
import time
from bs4 import BeautifulSoup as bs

start = datetime.now()

browser = webdriver.Chrome()

class GameData:

    def __init__(self):
        self.date = []
        self.time = []
        self.game = []
        self.score = []
        self.home_odds = []
        self.draw_odds = []
        self.away_odds = []

def parse_data(url):
    browser.get(url)
    df = pd.read_html(browser.page_source, header=0)[0]
    time.sleep(3)
    html = browser.page_source
    soup = bs(html,"lxml")
    cont = soup.find('div', {'id':'wrap'})
    conti = cont.find('div', {'id':'col-content'})
    content = conti.find('table', {'class':'table-main'}, {'id':'tournamentTable'})
    main = content.find('th', {'class':'first2 tl'})
    count = main.findAll('a')
    country = count[1].text
    league = count[2].text
    game_data = GameData()
    game_date = None
    for row in df.itertuples():
        if not isinstance(row[1], str):
            continue
        elif ':' not in row[1]:
            game_date = row[1].split('-')[0]
            continue
        game_data.date.append(game_date)
        game_data.time.append(row[1])
        game_data.game.append(row[2])
        game_data.score.append(row[3])
        game_data.home_odds.append(row[4])
        game_data.draw_odds.append(row[5])
        game_data.away_odds.append(row[6])
    browser.quit()
    return game_data, country, league

# You can input as many URLs you want
urls = {
"https://www.oddsportal.com/soccer/europe/champions-league/results/"
}

if __name__ == '__main__':

    results = None

    for url in urls:
        game_data, country, competition = parse_data(url)
        result = pd.DataFrame(game_data.__dict__)
        result['country'] = country
        result['competition'] = competition
        if results is None:
            results = result
        else:
            results = results.append(result, ignore_index=True)

results

|    | date        | time   | game                                 | score   |   home_odds |   draw_odds |   away_odds | country   | competition      |
|----|-------------|--------|--------------------------------------|---------|-------------|-------------|-------------|-----------|------------------|
|  0 | 17 Mar 2021 | 20:00  | Bayern Munich - Lazio                | 2:1     |        1.35 |        6.02 |        7.53 | Europe    | Champions League |
|  1 | 17 Mar 2021 | 20:00  | Chelsea - Atl. Madrid                | 2:0     |        2.33 |        3.1  |        3.49 | Europe    | Champions League |
|  2 | 16 Mar 2021 | 20:00  | Manchester City - B. Monchengladbach | 2:0     |        1.28 |        6.25 |       10.17 | Europe    | Champions League |
|  3 | 16 Mar 2021 | 20:00  | Real Madrid - Atalanta               | 3:1     |        2.26 |        3.6  |        3.16 | Europe    | Champions League |
|  4 | 10 Mar 2021 | 20:00  | Liverpool - RB Leipzig               | 2:0     |        2.37 |        3.8  |        2.85 | Europe    | Champions League |

How can I make this code better for readability?
Also, since CR is asking to explain further, (mods can delete this)

Some quick comments. Since your request is about readability, you can do three things at least:

get rid of unused variables eg: start = datetime.now()
improve the naming conventions for your variables: variables like cont or conti are quite similar (risk of typos/confusion) but the names are not intuitive and do not accurately describe the data you are manipulating. count is also too generic to be meaningful. Note that game_date looks confusingly similar to game_data and you even have a line: game_data.date.append(game_date). I think the risk of typo bugs is not negligible here.
add some line spacing here and there, plus a few comments. You can afford it as the code is less than 100 lines of code, so the implementation is reasonable and not bloated.

I don't think the class GameData is really useful the way it is implemented. To get the final printable result you could stick with a dataframe, you already have one, so see if it can be transformed further or transposed to another.
You have time.sleep after pd.read_html, but it does not guarantee that the page will be fully loaded. There are several functions in Selenium that you can use to wait for the presence of a given element. But probably you could use the requests module instead. On sites that use JS/Ajax, you may have no other choice but to use Selenium, but it takes more effort to do it right.
It would be good to add some validation to make sure that the result of your scraping is not void. Otherwise the processing will be wrong and return garbage. The BS find function will return None if the element is not found. So all you have to do is something like:
if None in (cont, conti, content, main):

or you can use the any function for this purpose.
However, findAll has a different behavior and will return an empty list if there is no matching element found.


Checking directories for .pgp files This script checks specific directories for *.pgp files. It returns a list of the filenames and modified dates. It then returns a list of the filenames and modified dates, each on a new line. I'm new to Python, like literally two weeks now and this script was written for a specific work purpose, but I'm betting it could be tweaked.

import glob
import os
from datetime import datetime

monitor_files = []

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/adr01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("adr01 | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/chpt/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("chpt | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/emb01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("emb01 | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/exp01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("exp01 | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/iix01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("iix01 | " + file + (" | ") + str(last_modified_date) + "\n")

print("\n".join(monitor_files))

Some improvement (DRY - Don't Repeat Yourself):

import glob
import os
import os.path                    # another import
from datetime import datetime

monitor_files = []

# Instead of your 5-time repetition then use this part:

PREFIX = "/home/skeer/Documents/Projects/Python_temp/home"
subdirs = ["chpt", "adr01", "emb01", "exp01", "iix01"]       # We will loop over these
UP = "upload"
PATTERN = "*.pgp"

for sd in subdirs:
    full_path = os.path.join(PREFIX, sd, UP)        # Inteligent joining of path's parts
    os.chdir(full_path)
    for file in glob.glob(PATTERN):
        if os.path.isfile(file):
            last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
        else:
            last_modified_date = datetime.fromtimestamp(0)
        monitor_files.append(sd + " | " + file + (" | ") + str(last_modified_date) + "\n")

print("\n".join(monitor_files))   # Your code after repetitions is OK


Calculating and improving time and memory complexity private static int Sum (int[] a, int from, int to){
   int total=0;
   for (int i=from; i <= to; i++)
       res += a[i];
   return total;
}

public static int Method3 (int []a){
    int temp=0;
    for (int i=0; i <= a.length; i++)
    {
        for (int j=0; j <= a.length; j++)
        {
           int c = Sum(a,i,j);
           if (c%3 == 0)
           {
            if (j-i+1 > temp)
            temp = j-i+1;
           }
        }
    }
return temp;
}

The purpose of Method3 method is to find the longest combination of a given array numbers', so that the sum of the numbers of the combination can be divided by 3 without remainder.

How do I make it more efficient in terms of both time and memory complexity?
How do I even approach to something like this?
ow can I know that the complexity I've reached is the best possible?

It is possible to make it much more efficient by using a completely different algorithm. The idea is to take a closer look at prefix sums. Let's assume that a subarray [L, R] is divisible by 3. It means that prefixSum[R] - prefixSum[L - 1] == 0 (mod 3), or prefixSum[R] == prefixSum[L - 1] (mod 3). It results in a simple solution: iterating over all elements of the array from left to right and maintaining the current prefix sum modulo 3 and keeping track of the first occurrence of each value modulo 3. The code can look like this:

int getLongestSubarray(int[] a) {
    int[] firstOccurrence = new int[3];
    firstOccurrence[0] = -1;
    firstOccurrence[1] = a.length;
    firstOccurrence[2] = a.length;
    int prefixSum = 0;
    int result = 0;
    for (int i = 0; i < a.length; i++) {
        prefixSum = (prefixSum + a[i]) % 3;
        if (prefixSum < 0)
            prefixSum += 3;
        result = Math.max(result, i - firstOccurrence[prefixSum]);
        firstOccurrence[prefixSum] = Math.min(firstOccurrence[prefixSum], i);
    }
    return result;
}

The time complexity is O(n) and the space complexity is O(1). It is optimal because it is not possible to find the longest subarray divisble by 3 without seeing all elements of the input array.


10 minute Tic Tac Toe After seeing Snake coded in 10 minutes, I decided to try a similar challenge, albeit easier. The following is Tic Tac Toe that I coded in 10 minutes. Given the short time frame, I'm sure there are style and convention errors abound, and would appreciate any suggestions :)

I will also specifically ask about one thing - checking if there is a winner(done in the only ActionPerformed method). It feels long and convoluted, but it was the best I could think of at the time. Looking back, I still can't really think of any ways to write it better, actually...

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TicTacToe {
  private JFrame main;
  private TicButton[][] buttons;
  private JPanel[] rows;
  private boolean p1turn = true;
  private final Color bg1 = new Color(255,0,0);
  private final Color bg2 = new Color(0,255,0);
  public static void main(String[] args) {
    new TicTacToe().go();
  }
  public void go() {
    main = new JFrame("Tic Tac Toe!");
    buttons = new TicButton[3][3];
    rows = new JPanel[3];
    int r = 0;
    main.getContentPane().setLayout(new BoxLayout(main.getContentPane(),BoxLayout.Y_AXIS));
    for (int i = 0; i < 3; i++) {
      rows[r] = new JPanel();
      for (int j = 0; j < 3; j++) {
        buttons[i][j] = new TicButton();
        rows[r].add(buttons[i][j]);
      }
      main.getContentPane().add(rows[r]);
      r++;
    }
    main.pack();
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setVisible(true);
  }
  private class TicButton extends JButton{
    int value;
    private boolean clicked;
    public TicButton() {
      super("-");
      this.value = -1;
      clicked = false;
      setFocusable(false);
      this.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            if (!clicked) {
              clicked = true;
              setText(p1turn ? "X" : "O");
              value = p1turn ? 1 : 2;
              setBackground(p1turn ? bg1 : bg2);
              p1turn = !p1turn;
              setEnabled(false);
            }

          boolean winner = false;
          String win = "";
          for (TicButton[] tt : buttons) {
            if (tt[0].value == tt[1].value && tt[0].value == tt[2].value && tt[0].value != -1) {
              winner = true;
              win = tt[0].value == 1 ? "X" : "O";
              break;
            }
          }
          for (int j = 0; j < 3; j++) {
            if (buttons[0][j].value == buttons[1][j].value &&
                buttons[0][j].value == buttons[2][j].value &&
                buttons[0][j].value != -1) {
              winner = true;
              win = buttons[0][j].value == 1 ? "X" : "O";
              break;
            }
          }
          if (buttons[0][0].value == buttons[1][1].value && buttons[0][0].value == buttons[2][2].value &&
              buttons[0][0].value != -1) {
            winner = true;
            win = buttons[0][0].value == 1 ? "X" : "O";
          }
          if (buttons[0][2].value == buttons[1][1].value && buttons[0][2].value == buttons[2][0].value &&
              buttons[0][2].value != -1) {
            winner = true;
            win = buttons[0][2].value == 1 ? "X" : "O";
          }
          if (winner) {
            JOptionPane.showMessageDialog(main, win + " wins!");
            main.setVisible(false);
            System.exit(0);
          }
        }
      });
    }
  }

}

When it is X’s turn, and they make a move, only player X can win.  Similarly, only Y can win on Y’s turn.  So why all these tests?

win = tt[0].value == 1 ? "X" : "O";

If there is a winner, just test p1turn in the if (winner) { code!

String win = p1turn ? "X" : "O";

Okay, you may want to move p1turn = !p1turn; to the end of the function, first, to avoid X/O confusion.

This code is checking if the row has all the same symbols, and the symbol is not blank:

if (tt[0].value == tt[1].value && tt[0].value == tt[2].value && tt[0].value != -1) {

When the player moves, this.value is set to their code.  And only they can win on this move.  So we could instead write:

if (tt[0].value == value && tt[1].value == value && tt[2].value == value) {

Slightly shorter.  But we can do better.

Change X’s & O’s values to +1 and -1.  Use 0 for blank.  Then, if a row sums to +3 or -3, you have a winner!

if (tt[0].value + tt[1].value + tt[2].value == 3*value) {

Similarly for other winning directions.


Looping over pixels in an image I have the following code which iterates over all pixels of an image and does some manipulations on two images of the same size. I would like to speed it up and to avoid iterating over the positions in a for loop:

import numpy as np
import cv2

# Two images of same size
image_in = cv2.imread('my_image.png')
image_in2 = cv2.imread('my_image2.png')
image_new = np.ones(image_in.shape[:2], dtype="uint8") * 255

counter = 0
counter2 = 0

for i in range(image_in.shape[0]):
    for j in range(image_in.shape[1]):
        if image_in[i, j] < 255:
            counter += 1
            if image_in2[i, j] == 0:
                image_new[i, j] = 0
            else:
                image_new[i, j] = 255
                counter2 += 1

How can I improve my code?

I think the trick is trying to vectorise this as much as possible:

By the look of it, the code is trying to threshold at 0 and count pixels under 255.

We can change the first part of the loop to:

counter = np.sum(image_in < 255) # Sums work on binary values
counter2 = np.sum(np.bitwise_and(image_in < 255, image_in2 != 0))

And the second to:

# This is 0 or 1 depending on whether it is == 0
image_new[:,:] = (image_in2 != 0) # image_new[i,j] = (image_in2[i,j] != 0)

# So scale the values up with a simple multiplcation
image_new = image_new*255 # image_new[i,j] = image_new[i,j]*255


Recurse on complex Perl data structure, applying needed rules Inspired by this answer and previous a commentator of code review use:

Given a complex Perl data structure, traverse/jigger/modify as follows:

If ORACLE_SID is 'key' in any hash then keep only ORACLE_SID section matching of $ENV{ORACLE_SID}
Eliminate any single level arrays, if after step 1, we're left with s_level arrays
Enhance values of simple content values based on requirement

What else or better way can be done to achieve the intended goal?

# $reduce_1level is set by the caller of jigger()
our $reduce_1level = 1;

sub jigger
{
    our $cds; local *cds = \shift;

    my $type = ref $cds or return;

    if ($type eq 'HASH') {
        foreach my $key (keys %$cds) {
            if (ref $cds->{$key}) {
                $cds->{$key} = reduce_by_oracle_sid ($cds->{$key});
                delete $cds->{$key} if not defined $cds->{$key};
                jigger ($cds->{$key}) if ref $cds->{$key};
            }
            else {
                $cds->{$key} = enhance_value ($cds->{$key});
            }
        }
    }
    elsif ($type eq 'ARRAY')
    {
        @$cds = grep { $_ = reduce_by_oracle_sid($_); defined } @$cds;

        foreach my $elem (@$cds) {
            if (ref $elem) {
                jigger ($elem);
            }
            else {
                $elem = enhance_value ($elem);
            }
        }
        $cds = $cds->[0] if @$cds == 1 and $reduce_1level;
    }
}

I'm really only after jigger(). I'm listing the helper subs for the the same price.

sub reduce_by_oracle_sid
{
    my $node = shift;

    return $node unless ref $node eq 'HASH' and exists $node->{ORACLE_SID};
    return unless $node->{ORACLE_SID} =~ /$ENV{ORACLE_SID}/;

    delete $node->{ORACLE_SID};

    # If there was was just 'value' then we return only value...
    return exists $node->{value} ? $node->{value} : $node;
}

sub enhance_value
{
    my $v = shift;

    # Take out double //'s
    $v =~ s{//}{}g;

    # trim whitesapce
    $v =~ s/^\w*(\W*)\w*$/$1/;

    # inject SQL commands ...
    #
    # ... n more ...

    return $v;
}

Is there an obvious reason why you don't use a cross-sectional Path tracer?

For instance, with Data::Dpath, seems like it could do what you want without too much fuss.

Your complicated example is quite trivial to extract nodes by ORACLE_ID at arbitrary depths.

use strict;
use warnings;

use Data::DPath qw( dpath );
use Data::Dump qw( pp );

$ENV{ORACLE_SID} = 6;

my $struct = {
  a => {
    b => {
      c => {
        x => {
          y => {
            name       => "In Hash",
            ORACLE_SID => $ENV{ORACLE_SID}
          },
          z => {
            name       => "Non Target",
            ORACLE_SID => 5,
          }
        },
        aa => [ { ORACLE_SID => $ENV{ORACLE_SID}, name => "In Array" } ],    # just to make things interesting
      }
    },
  },
};

# find all nodes no matter how deep that have a child, which, themselves
# contains a hash with a key "ORACLE_SID"

my (@oracles) = dpath( '//ORACLE_SID[value eq ' . $ENV{ORACLE_SID} . ']/..' )->match($struct);
pp(@oracles);

#(
#  { name => "In Hash", ORACLE_SID => 6 },
#  { name => "In Array", ORACLE_SID => 6 },
#)

That at very least, makes the most of your logic extraneous, and the essentials of "what data are you querying" and "What are you doing with that data" become more clear to the code reader.


Number uncovering with given equations I am making a number uncovering app. The program takes in an equation that has numbers hidden as letters, like:
abc + d = efg - hi

and it will return all the strings like
290 + 6 = 347 - 51
290 + 7 = 348 - 51
250 + 6 = 347 - 91
250 + 7 = 348 - 91
290 + 4 = 365 - 71
270 + 4 = 365 - 91
290 + 4 = 375 - 81
280 + 4 = 375 - 91
290 + 7 = 358 - 61
260 + 7 = 358 - 91
290 + 5 = 376 - 81
280 + 5 = 376 - 91
490 + 6 = 527 - 31
...

But there can will be duplicated strings. For example, when I input
a + b = c

the program returns
...
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 2 = 3
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
1 + 3 = 4
...

I know that I can put all the strings into set and then iterate through the set again to print out the strings, but I want to know if that is necessary.
Perhaps in my program there is an unnecessary loop or such that is causing the duplicated strings, which in turns makes its performance slower? If so, I would like to know the proper way of doing it.
Here is my code:
from itertools import permutations
from re import findall

ope = '+-*/( ).='
var = 'abcdefghijklmnopqrstuvwxyz'
num = '1234567890'

while True:
    while True:
        whole = input(">>> ") # User inputs equation here
        if any(c not in ope + var + num for c in whole): # Makes sure that all the characters are valid
            print(f'You may only use: {ope}{var}{num}')
            continue
        chars = list({char for char in whole if char in var}) # Extract all the mystery numbers

        if len(chars) > 10: # There are only 10 different digits, so the user may only input 10 different mystery numbers
            print('Enter at most 9 different letters.')
            continue
        while len(chars) < 10: # If there are less that 10 different mystery numbers
            chars.append(None) # add None until the length of the list is 10

        # From here to the break is to check if the syntax works, so a bit processing time is used on the first permutation of chars
        exp = whole
        for i, v in enumerate(chars):
            if v:
                exp = exp.replace(v, str(i))

        if all(int(e[0]) for e in findall('\d+', exp)):
            try:
                eval(exp.replace('=', '=='))
            except SyntaxError:
                print('Invalid Syntax')
                continue
        break # If not continue was hit, that means that the equation is valid

    for p in permutations(chars):
        exp = whole
        for i, v in enumerate(p):
            if v:
                exp = exp.replace(v, str(i))
        if all(int(e[0]) for e in findall('[\d\w]+', exp)): # If all the individual numbers don't begin with 0
            if eval(exp.replace('=', '==')): # If the equation is correct
                print(exp) # Print the equation

Functions
Split your code into individual smaller functions, doing singular tasks. A few examples would be validating the expression, extracting variables and so on.
if __name__ block
For scripts, it is a good practice to put your executable feature inside the if __name__ == "__main__" clause.
Comments
The comments like in:
while len(chars) < 10: # If there are less that 10 different mystery numbers

are pointless. The condition already explains what you write in 10 words. A more important comment here could've been what the mystery numbers are?
This applies to almost all of the comments you have added in your program. Once you split to functions, add docstrings to those functions explaining what and maybe why the function does. The code should be self-explanatory on the how.
Execution logic
From what I understand of the program, you are:

asking user for expression
validating if there are any invalid characters
extracting variables (and creating a forced list of 10 elements)
Not sure about the findall('\d+', exp) validation, and later the same thing is being achieved by a different regex pattern
check if the expression is mathematically consistent
permute all elements from variables list (created above)
iterate on all permutations and replace into the expression
evaluate expression and print if successful

A lot of the code seems duplicated, for eg. the exp.replace calls, the findall validation etc. You have to work with 2 nested loops just because there are no helper functions to assist you.
For the permutations themselves, you can obviously permute over a forced set of length 10, or you can just permute over the integers range(10) selecting as many elements as there are variables. Since you anyway need those integers (using enumerate), I'd go for this.
As a side note, instead of printing all valid results in the main loop, use a generator and yield valid results.

Example rewrite
from typing import Tuple, Set
from itertools import count, permutations

OPERATORS = '+-*/( ).='
VARIABLES = 'abcdefghijklmnopqrstuvwxyz'
NUMERALS = '1234567890'
VALID_CHARACTERS = OPERATORS + VARIABLES + NUMERALS

def is_expression_valid(expression: str) -> bool:
    return all(c in VALID_CHARACTERS for c in expression)

def is_expression_consistent(expression: str, variables: Set[str]) -> bool:
    for index, value in zip(count(1), variables):
        expression = expression.replace(value, str(index))
    try:
        eval(expression.replace("=", "=="))
    except SyntaxError:
        return False
    return True

def extract_variables(expression: str) -> Set[str]:
    variables = {char for char in expression if char in VARIABLES}
    if len(variables) > 10:
        raise ValueError()
    return variables

def get_expression() -> Tuple[str, Set[str]]:
    while True:
        expression = input(">>> ")
        if not is_expression_valid(expression):
            print(f"Invalid characters in the expression. Use only from: {VALID_CHARACTERS}")
            continue
        try:
            variables = extract_variables(expression)
        except ValueError:
            print("Expected at most 9 variable/letters!")
            continue
        if not is_expression_consistent(expression, variables):
            print("Invalid syntax!")
            continue
        break
    return expression, variables

def substitute_expression_format(expression: str) -> str:
    return "".join(r"{}" if c in VARIABLES else c for c in expression)

def valid_results(expression: str, variables: Set[str]) -> str:
    formatted_expression = substitute_expression_format(expression)
    for permute in permutations(range(10), len(variables)):
        variation = formatted_expression.format(*permute)
        if eval(variation.replace("=", "==")):
            yield variation

def main():
    expression, variables = get_expression()
    for result in valid_results(expression, variables):
        print(result)

if __name__ == "__main__":
    main()

Notice in is_expression_consistent, I've use zip with itertools.count, so that the dependency on regex is removed.
Now, the above fails for invalid token check, when the first substitution is \$ 0 \$; which can be resolved by having a try-except in the generator:
def valid_results(expression: str, variables: Set[str]) -> str:
    formatted_expression = substitute_expression_format(expression)
    for permute in permutations(range(10), len(variables)):
        variation = formatted_expression.format(*permute)
        try:
            if eval(variation.replace("=", "==")):
                yield variation
        except SyntaxError:
            continue

You can check the code on tio.run.

EDIT
For fixing the issue mentioned in comments (about repeated letters):
def substitute_expression_format(expression: str) -> str:
    return "".join(f"{{{c}}}" if c in VARIABLES else c for c in expression)

def valid_results(expression: str, variables: Set[str]) -> str:
    formatted_expression = substitute_expression_format(expression)
    for permute in permutations(range(10), len(variables)):
        variation = formatted_expression.format(**dict(zip(variables, permute)))
        try:
            if eval(variation.replace("=", "==")):
                yield variation
        except SyntaxError:
            continue

Updated example on tio.run.


Carousel in Vanilla JavaScript I finally got my carousel to work in JavaScript, and I want to know what you guys think about it and what I can do better.

var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction) {
  for (var i = 0; i < reviews.length; i++) {
    if (reviews[i].classList.contains("show")) {
      currentReview = reviews[i];
      if (direction == 'forward') {
        if (i + 1 > reviews.length - 1) {
          nextReview = reviews[0];
        } else {
          nextReview = reviews[i + 1];
        }
      } else {
        if (i - 1 < 0) {
          nextReview = reviews[reviews.length - 1];
        } else {
          nextReview = reviews[i - 1];
        }
      }
    }
  }

  currentReview.classList.remove("show");
  nextReview.classList.add("show");
}

leftArrow.onclick = function() {
  carousel('backward');
}
rightArrow.onclick = function() {
  carousel('forward');
}
* {
  font-family: Arial;
}

.carousel {
  display: flex;
  align-items: center;
  justify-content: center;
}

.review {
  display: none;
  text-align: center;
}

.show {
  display: block;
}

.arrow {
  margin-left: 25vw;
  margin-right: 25vw;
}

.arrow-left {
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-right: 10px solid black;
}

.arrow-right {
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid black;
}

Title1

Title2

Title3

It can also be demonstrated in this JSFiddle

Arrow elements

There are two elements for the arrows, and presuming there is only one of each type (i.e. one left, one right) then it would be more appropriate to use an id attribute for distinguishing between those two.

Instead of

use the id attribute:

And instead of selecting elements by class name and taking the first one:

var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

select them using document.getElementById():

var leftArrow = document.getElementById('arrow-left');
var rightArrow = document.getElementById('arrow-right');

Obviously this would require the CSS to be updated as well.

Direction parameter

There are only two possible values for direction, so it could be changed to a boolean like forward that defaults to true (default parameters is a feature of ecmascript-6 so be aware of the browser compatibility).

function carousel(forward = true) {
  if (forward) {
    //move forward
  }
  else {
    //move backward
  }

Simplify onclick event handlers

After making the first parameter for carousel a boolean that defaults to true (for the direction), the onclick handlers can be simplified to function references. false can be tied to the leftArrow handler by employing a partially applied function with Function.bind()

leftArrow.onclick = carousel.bind(null, false);
rightArrow.onclick = carousel;

If there was a need to have multiple event handlers on each element then addEventListener() could be used:

leftArrow.addEventListener('click', carousel.bind(null, false));
rightArrow.addEventListener('click', carousel);

Simplify logic for current and next

Instead of looping through the reviews, select the elements that have class name show (should only be one):

var shownReviews = document.getElementsByClassName('show');

That will be a live HTMLCollection, meaning that it updates as the DOM is updated, so there is no need to re-query it.

Then you can utilize shownReviews[0] - this can be used to set currentReview. Then when forward is true the value for nextReview can be set utilizing nextElementSibling or if that is null using parentElement.firstElementChild (and conversely using previousElementSibling and lastElementChild when forward is false).

function carousel(forward = true) {
  currentReview = shownReviews[0];
  if (forward) {
    nextReview = currentReview.nextElementSibling || currentReview.parentElement.firstElementChild;
  }
  else {
    nextReview = currentReview.previousElementSibling || currentReview.parentNode.lastElementChild;
  }
  currentReview.classList.remove("show");
  nextReview.classList.add("show");
}

Simplify CSS

The following styles can be moved out of each of the rulesets for the arrows and moved into the ruleset for .arrow:

width: 0;
height: 0;
border: 10px solid transparent;

Then the rulesets for the arrows becomes a single style:

#arrow-left {
  border-right: 10px solid black;
}

#arrow-right {
  border-left: 10px solid black;
}

The margin styles for .arrow can be combined to a single style using two values:

margin: 0 25vw; /* top & bottom: 0, left & right: 25vw */

Rewrite

Below is simplified code using the advice above.

var shownReviews = document.getElementsByClassName('show');
var leftArrow = document.getElementById('arrow-left');
var rightArrow = document.getElementById('arrow-right');

var currentReview;
var nextReview;

function carousel(forward = true) {
  currentReview = shownReviews[0];
  if (forward) {
    nextReview = currentReview.nextElementSibling || currentReview.parentElement.firstElementChild;
  }
  else {
    nextReview = currentReview.previousElementSibling || currentReview.parentNode.lastElementChild;
  }
  currentReview.classList.remove("show");
  nextReview.classList.add("show");
}

leftArrow.onclick = carousel.bind(null, false);

rightArrow.onclick = carousel;
* {
  font-family: Arial;
}

.carousel {
  display: flex;
  align-items: center;
  justify-content: center;
}

.review {
  display: none;
  text-align: center;
}

.show {
  display: block;
}

.arrow {
  border: 10px solid transparent;
  width: 0;
  height: 0;
  margin: 0 25vw;
}

#arrow-left {
  border-right: 10px solid black;
}

#arrow-right {
  border-left: 10px solid black;
}

Title1

Title2

Title3


Using GeoComplete with RequireJS (with shim config) I am using the GeoComplete plugin with RequireJS
It works, but please could someone confirm I've done this correctly, mainly my understanding of shim:

    requirejs.config({
        waitSeconds: 120,
        paths: {
            async: './lib/async',
            jquery: './lib/jquery-1.7.2.min',
            geocomplete: './lib/jquery.geocomplete.min'
        },
        shim: {
            'geocomplete': ['jquery'],
        }
    });

    require(['async!http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false', 'jquery', 'geocomplete'], function () {
        $("#geocomplete").geocomplete({
            map: "#map_canvas"
        });
    }
    );

The way I understand shim, is, GeoComplete doesn't support AMD, but has a dependency on jQuery, so my set up basically says "load geocomplete after jquery"

Is that correct?

The only thing that I see looking at this code is that you didn't keep a fully consistent formatting, and I at first thought you had an extra set of brackets or parentheses.

You should do it like the }); farther above in the code.

Keep everything consistent, you probably already know this though.


Finding the number of boxes that fit into a truck using JavaScript (Followup Q) I have made a lot of changes to the code over the course of the evening, but after making most of the suggested changes, the variable that the answer is returning is showing up as "undefined". Could someone please help me find my errors in this code? I have tried and have not been able to find the errors due to my limited knowledge of JS.

<!DOCTYPE html>
<html>
<script>

  ////////////////////////////
 // Code by Zachary Holmes //
////////////////////////////

// This program determines the number of boxes that can fit into the back of a truck

// Declaring box size in centimetres, and converting it into metres
var boxHeight = prompt("What is the height of your box in centimetres?") / 100;
var boxWidth = prompt("What is the width of your box in centimetres?") / 100;
var boxLength = prompt("What is the length of your box in centimetres?") / 100;

// Declaring truck size in metres
var truckHeight = prompt("What is the height of your truck in metres?");
var truckWidth = prompt("What is the width of your truck in metres?");
var truckLength = prompt("What is the length of your truck in metres?");

// Declaring variables used in equation
var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var widthA = boxWidth > 0 ? ((truckWidth / boxWidth) | 0) : 0;
var lengthA = boxLength > 0 ? ((truckLength / boxLength) | 0) : 0;

var heightB = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var widthB = boxWidth > 0 ? ((truckLength / boxWidth) | 0) : 0;
var lengthB = boxLength > 0 ? ((truckWidth / boxLength) | 0) : 0;

var heightC = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;
var widthC = boxWidth > 0 ? ((truckHeight / boxWidth) | 0) : 0;
var lengthC = boxLength > 0 ? ((truckLength / boxLength) | 0) : 0;

var heightD = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;
var widthD = boxWidth > 0 ? ((truckLength / boxWidth) | 0) : 0;
var lengthD = boxLength > 0 ? ((truckHeight / boxLength) | 0) : 0;

var heightE = boxHeight > 0 ? ((truckLength / boxHeight) | 0) : 0;
var widthE = boxWidth > 0 ? ((truckWidth / boxWidth) | 0) : 0;
var lengthE = boxLength > 0 ? ((truckHeight / boxLength) | 0) : 0;

var heightF = boxHeight > 0 ? ((truckLength / boxHeight) | 0) : 0;
var widthF = boxWidth > 0 ? ((truckHeight / boxWidth) | 0) : 0;
var lengthF = boxLength > 0 ? ((truckWidth / boxLength) | 0) : 0;

var multiplesA = heightA * widthA * lengthA;
var multiplesB = heightB * widthB * lengthB;
var multiplesC = heightC * widthC * lengthC;
var multiplesD = heightD * widthD * lengthD;
var multiplesE = heightE * widthE * lengthE;
var multiplesF = heightF * widthF * lengthF;

var arrayA = [multiplesB, multiplesC, multiplesD, multiplesE, multiplesF];
var arrayB = [multiplesA, multiplesC, multiplesD, multiplesE, multiplesF];
var arrayC = [multiplesB, multiplesA, multiplesD, multiplesE, multiplesF];
var arrayD = [multiplesB, multiplesC, multiplesA, multiplesE, multiplesF];
var arrayE = [multiplesB, multiplesC, multiplesD, multiplesA, multiplesF];
var arrayF = [multiplesB, multiplesC, multiplesD, multiplesE, multiplesA];

// Calculations
var boxCount;

if (multiplesA > arrayA)
{
boxCount = multiplesA;
}

else if (multiplesB > arrayB)
{
boxCount = multiplesB;
}

else if (multiplesC > arrayC)
{
boxCount = multiplesC;
}

else if (multiplesD > arrayD)
{
boxCount = multiplesD;
}

else if (multiplesE > arrayE)
{
boxCount = multiplesE;
}

else if (multiplesF > arrayF)
{
boxCount = multiplesF;
}

// Output answer
alert("You can fit up to " + boxCount + (1 == boxCount ? " box" : " boxes") + " into the truck");

</script>
</html>

This is an interesting pattern:

var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;

I assume you intend to be using integer division here? Ie, 5/2 | 0 = 2?

Also.. why are you repeatedly declaring different variables with the same values?

var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var heightB = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var heightC = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;

Here you are comparing two fundamentally different types:

if (multiplesA > arrayA)
{
boxCount = multiplesA;
}

Comparing different data types in Javascript involves the type coercion system, which in javascript is a Bad Thing -- you're basically putting yourself at the mercy of an extremely unpredictable system. But, beyond that, it's not even clear what your intention with this line is -- how does it make sense to compare a float to an array?


Remove duplicates from array of non-equatable objects I have an array of non-Equatable objects. I want to remove all the duplicates from the array.

class SearchResult { // non-equatable
    var index: Int!
    var score: Int!

    init(_ index: Int, score: Int = 0) {
        self.index = index
        self.score = score
    }
}
var searchResults: [SearchResult] = [SearchResult(0), SearchResult(1), SearchResult(1), SearchResult(2), SearchResult(2)]

searchResults.map { $0.index } gives us: 0, 1, 1, 2, 2

Currently, I do so by mapping the objects' property index, which is equatable, since it's an Int. This way, I can remove the duplicates from the indices array:

let withDupes: [SearchResult] = searchResults
let indices = withDupes.map { $0.index }.removingDuplicates()

For reference, .removingDuplicates() comes from a post on StackOverflow

Note: this is the part I want to be reviewed.

Then, I get the object with the corresponding index by looping through the indices array and add it to the noDupes array.

var noDupes: [SearchResult] = []
indices.forEach { (index) in
    guard let notADupe = (withDupes.filter { $0.index == index }).first else { return }
    noDupes.append(notADupe)
}

noDupes.map { $0.index } now is: 0, 1, 2

Now, this code works, but it will be executed very often. Since I feel like this is not a very efficient way to remove the duplicates, I fear a performance drop.
How can I improve and / or simplify my code and still successfully remove the duplicates from the array?

First note that there is no need to make the SearchResult properties (implicitly unwrapped) optionals, as they are always initialized:

class SearchResult { // non-equatable
    var index: Int
    var score: Int

    init(_ index: Int, score: Int = 0) {
        self.index = index
        self.score = score
    }
}

Your approach is indeed not optimal, after determining a unique set of property
values, the original array must be searched for each value separately. This lookup can be improved slightly by using first(where:)

var noDupes: [SearchResult] = []
indices.forEach { (index) in
    guard let notADupe = withDupes.first(where: { $0.index == index }) else { return }
    noDupes.append(notADupe)
}

The advantage of first(where:) over filter + first is that it short-circuits and does not create an intermediate array.

But a better and faster solution would be to modify the removingDuplicates()
method so that it compares the array elements according to a given key (which is
then required to be Equatable).

Here is a possible implementation, using the “Smart KeyPath” feature
from Swift 4:

extension Array {
    func removingDuplicates<T: Equatable>(byKey key: KeyPath<Element, T>)  -> [Element] {
        var result = [Element]()
        var seen = [T]()
        for value in self {
            let key = value[keyPath: key]
            if !seen.contains(key) {
                seen.append(key)
                result.append(value)
            }
        }
        return result
    }
}

This can then simply be used as

let searchResults: [SearchResult] = [SearchResult(0), SearchResult(1), SearchResult(1), SearchResult(2), SearchResult(2)]

let withoutDuplicates = searchResults.removingDuplicates(byKey: \.index)

It might also be worth to add another specialization for the case that the key is
Hashable (as it is in your example) because then the seen array can be replaced by a set,
which improves the lookup speed from O(N) to O(1):

extension Array {
    func removingDuplicates<T: Hashable>(byKey key: KeyPath<Element, T>)  -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(value[keyPath: key]).inserted {
                result.append(value)
            }
        }
        return result
    }
}

Note that if seen.insert(key).inserted does the “test and insert if not present” with a single call.

Another (more flexible) option is to pass a closure to the function which determines
the uniquing key for each element:

extension Array {
    func removingDuplicates<T: Hashable>(byKey key: (Element) -> T)  -> [Element] {
        var result = [Element]()
        var seen = Set<T>()
        for value in self {
            if seen.insert(key(value)).inserted {
                result.append(value)
            }
        }
        return result
    }
}

Example:

let withoutDuplicates = searchResults.removingDuplicates(byKey: { $0.index })


Print an integer and its digits reversed This Common Lisp program is an exercise to print an integer and its digits reversed to the screen:

(defun read-number () (format t "Enter a number: ~%") (read))

(defun reverse-string (the-string)
  (if (eq (length the-string) 0)
    ""
    (concatenate 'string (reverse-string (subseq the-string 1)) (subseq the-string 0 1))))

(defun reverse-digits (the-number) (reverse-string (write-to-string the-number)))

(let ((the-number (read-number)))
  (format t "N->: ~a~%<-N: ~a~%" the-number (reverse-digits the-number)))

This problem is more about numbers than strings, so I felt the need to post a non-string-based solution. I've got my original Scheme version, and a Common Lisp adaptation of same.

Scheme version:

(define (reverse-digits n)
  (let loop ((n n) (r 0))
    (if (zero? n) r
        (loop (quotient n 10) (+ (* r 10) (remainder n 10))))))

Common Lisp translation of the Scheme version:

(defun reverse-digits (n)
  (labels ((next (n v)
             (if (zerop n) v
                 (multiple-value-bind (q r)
                     (truncate n 10)
                   (next q (+ (* v 10) r))))))
    (next n 0)))


Simple object oriented design for an Temperature class Design a temperature class for nurses to store patient temperature and the method of taking the temperature.
  How would you handle different units of temperature? Write a function to determine if a patient has a fever.

My approach

class Temperature
    attr_accessor :temp, :method

    def initialize(temp,method)
        @temp = temp
        @method =method
    end

end

class Celsius < Temperature

    TEMP = 37

    def has_fever
        if temp > TEMP
            true
        else
            false
        end
    end

end

class Fahrenheit < Temperature

    TEMP =98.6

        def has_fever
            if temp > TEMP
                true
            else
                false
            end
        end
end

I know there is a code duplication in Celsius and Fahrenheit class. I tried declaring has_fever method in Temperature class but it didn't work. It says "uninitialized constant Temperature::TEMP".

Is there something to improve this design?

Make the base class meaningful

Right now you've declared Temperature as a base class, but all it really does is set up your two variables.  One way to utilize it more would be to assign a unit of some sort to the class (I've chosen Kelvin, but it could have been anything).

In my version, Temperature stores everything as Kelvin.  Any class that inherits from it only has to know how to convert back and forth to Kelvin (So Celsius<->Kelvin and Fahrenheit<->Kelvin).  Later, if I wanted to add operators to add/subtract/compare temperatures, since the base units are all kelvin, everything is easy.

You'll also notice that I've moved has_temp? to the base class and the threshold temperature is in Kelvin.  This gives all sub-classes the functionality without having to know anything about where the theshold is, and likewise the base class will always work without needing to know the details of a particular unit of measure.

Finally, while I've used Kelvin as the unit for Temperature, the base class could have just as easily been called Kelvin.

class Temperature
  attr_accessor :temp, :method

  FEVER_THRESHOLD = 310.15  # 98.6F to K

  def initialize(temp, method)
    @temp = temp
    @method =method
  end

  def to_s
    "#{@temp} K"
  end

  def has_fever?
    @temp > FEVER_THRESHOLD
  end
end

class Celsius < Temperature
  def self.to_k(value)
    value + 273.15
  end

  def self.from_k(value)
    value - 273.15
  end

  def initialize(temp, method)
    super(Celsius.to_k(temp), method)
  end

  def to_s
    "%0.2f C" % [Celsius.from_k(@temp)]
  end
end

class Fahrenheit < Temperature
  def self.to_k(value)
    (value + 459.67) * (5.0/9.0)
  end

  def self.from_k(value)
    (value * 9.0/5.0) - 459.67
  end

  def initialize(temp, method)
    super(Fahrenheit.to_k(temp), method)
  end

  def to_s
    "%0.2f F" % [Fahrenheit.from_k(@temp)]
  end
end

#test Celsius
temp = Celsius.new(39, nil)
puts temp.to_s         # 39.0 C
puts temp.has_fever?   # true

#test Fahrenheit
temp = Fahrenheit.new(97.9, nil)
puts temp.to_s         # 97.90 F
puts temp.has_fever?   # false

On a personal note, I wouldn't necessarily use inheritance as my go-to solution for this problem without a lot more knowledge and thought about the use-cases; I only followed your initial design.  Temperatures themselves are fairly trivial, but perhaps for a more complicated scenario this implementation would have advantages.


Permutation of words in a sentence There is a problem which discusses in how many ways can the words in a sentence be permuted . I wrote a code as follows which works for the sentences (I think so) . It would be helpful if anyone can assure me if it's actually correct or not . Besides , any suggestion regarding the shortening of code or easing the logic is appreciated . Thanks...

#include <stdio.h>
#include <string.h>

int factorial(int x)
{
    if(x<=0) return 1;
    else return x*factorial(x-1);
};

int main(void)
{
    int T;//number of test cases
    scanf("%d",&T);
    while(T--){
    char str[20];
    scanf(" %[^\n]",str);
    int i,j,k,m,count=0,l,p=1,n;
    l=strlen(str);
    for(i=0;i<l;i++){
        if(str[i]==' '){
            count++;
        }
    }
    m=count+1;
    char arr[m][50];
    int check[m],func[m];
    for(i=0,k=0,j=0;j<=l;j++){
        if(str[j]==' '||j==l){
            check[i]=0;func[i]=1;
            arr[i][k]='\0';
            i++;
            k=0;
        }
        else{
            arr[i][k]=str[j];
            k++;
        }
    }
    for(i=0;i<m;i++){
  for(j=i+1;j<m;j++){
    if(check[i]==0&&strcmp(arr[i],arr[j])==0){
        check[j]++;
        func[i]++;
    }
  }
}
for(i=0;i<m;i++){
    p*=factorial(func[i]);
}
n=factorial(m)/p;
printf("%d/%d\n",1,n);
   }
 return 0;
}

Input:

       2

       I eat rice

       no game no life

Output:

       1/6

       1/12

N.B.: The permutation within a word is to be ignored .

Some comments on the style of your code.

Formatting. Your code is hard to read because there are no spaces.
Also the formatting seems to be off. It might be easier to read like this:

int main(void)
{
    int T;//number of test cases
    scanf("%d", &T);
    while (T--) {

        char str[20];
        scanf(" %[^\n]", str);

        int i, j, k, m, count = 0, l, p = 1, n;
        l = strlen(str);

        for (i = 0; i < l; i++) {
            if (str[i] == ' ') {
                count++;
            }
        }

        m = count + 1;
        char arr[m][50];
        int check[m], func[m];

        for (i = 0, k = 0, j = 0; j <= l; j++) {
            if (str[j] == ' ' || j == l) {
                check[i] = 0; func[i] = 1;
                arr[i][k] = '\0';
                i++;
                k = 0;
            }
            else {
                arr[i][k] = str[j];
                k++;
            }
        }

        for (i = 0; i < m; i++) {
            for (j = i + 1; j < m; j++) {
                if (check[i] == 0 && strcmp(arr[i], arr[j]) == 0) {
                    check[j]++;
                    func[i]++;
                }
            }
        }

        for (i = 0; i < m; i++) {
            p *= factorial(func[i]);
        }

        n = factorial(m) / p;
        printf("%d/%d\n", 1, n);
    }
    return 0;
}

Don't use comments for what could be described in the code directly. This:

    int T;//number of test cases
    scanf("%d", &T);
    while (T--) {

Should be really this:

    int number_of_test_cases;
    scanf("%d", &number_of_test_cases);
    while (number_of_test_cases--) {

Avoid long functions for maintainability and readability. You wrote one function for the factorial calculation; good. But now take a look
    at the main() function. Can you guess what the steps are in the while
    by looking at it? There's too much stuff going on in the main().
    Isolate parts which do one thing into a function. For example this
    piece:

    int i, j, k, m, count = 0, l, p = 1, n;
    l = strlen(str);

    for (i = 0; i < l; i++) {
        if (str[i] == ' ') {
            count++;
        }
    }

First of all I would write the variables on several lines to have it more readable:

    int i;
    int j;
    int k;
    int m;
    int count = 0;
    int l;
    int p = 1;
    int n;
    l = strlen(str);

    for (i = 0; i < l; i++) {
        if (str[i] == ' ') {
            count++;
        }
    }

Then we realize that j, k, m, p and n are not even needed yet at this point, so we put
 them after all this:

    int i;
    int count = 0;
    int l;
    l = strlen(str);

    for (i = 0; i < l; i++) {
        if (str[i] == ' ') {
            count++;
        }
    }

    int p = 1;
    int j;
    int k;
    int m;
    int n;

Then another thing is l can be directly initialized with strlen(str). Also I renamed
it everywhere in the program to length which  states more easily for a reader what it
does.

This gives us this:

    int i;
    int count = 0;
    int length = strlen(str);

    for (i = 0; i < length; i++) {
        if (str[i] == ' ') {
            count++;
        }
    }

Now we should make it a function so it looks like this:

    int length = strlen(str);
    int count = get_count_of_whitespace(&str, length);

Proceed with the rest of the main function like that by refactoring it into
manageable chunks, and probably with that alone you will find some mistakes or improvements
for your algorithm.


Scala object-function balance I am learning Scala, coming from Java background. Here I have written a small prototype proof of concept program that is a part of concept base for a simple upcoming tutorial game. There are two game objects: a Cell and a Breed of cells (a 1d row). The operations are simple. One can create a breed with a number of cells. Each cell can mutate with a custom function chosen randomly from the available set. If the breed mutates, all of it's cells mutate. My question is the one common today - how Scala-ish is my code? How to improve? Coming from OOP, I have witnessed a very strange feeling while writing this code: it feels just like the internals of objects leak out from their ripped bodies just like in a real OOP thriller movie. But everyone suggests breaking the code into functions... so where is the balance?

package main
import scala.util.Random

object Breed extends App{

val rand:Random = new Random

//mutations
def mutF(f:Int => Int)(v:Int) : Int = {f(v)}

def mutFA(v:Int) : Int = mutF(x => x)(v)
def mutFB(v:Int) : Int = mutF(x => x + x)(v)
def mutFC(v:Int) : Int = mutF(x => x * x)(v)

val mutations : List[Int=>Int] = List(mutFA, mutFB, mutFC)

//constants (sources)
val emptyCellList : List[Cell] = List[Cell]()

//mutations manipulations
def nextMutation(f:Int=>Int) : Int=>Int = {
    val i = mutations.indexOf(f)
    if(i == mutations.length - 1) mutations(0)
    else mutations(i + 1)
}

def randomMutation : Int=>Int = {
    mutations(rand.nextInt(mutations.length))
}

//---CELL---
class Cell(f:Int=>Int, value:Int) {
    def mutate() = new Cell(nextMutation(f), f(value))
    override def toString = "[" + value + "]"
}

def cellsToString(l:List[Cell]) : String = {
    l match {
        case Nil => ""
        case y :: ys => y.toString + cellsToString(ys)
    }

}

//breeder
def createBreed(num:Int) : Breed = {

    def makeCell() : Cell = new Cell(randomMutation, rand.nextInt(10))

    def makeCells(acc:Int, cells:List[Cell]) : List[Cell] = {
        if(acc == 0) cells
        else makeCells(acc - 1, makeCell :: cells)
    }

    new Breed(0, makeCells(num, List[Cell]()))
}

def mutateBreed(gens:Int, breed:Breed) : Breed = {
    def mutate(acc:Int, b:Breed) : Breed = {
        if(acc == 0) b
        else {
            val mutated : Breed = b.mutate();
            println(b.output() + " ---> " + mutated.output())
            mutate(acc - 1, mutated)
        }
    }
    mutate(gens, breed)
}

//---BREED---
class Breed(generation:Int, cells:List[Cell]) {

    def mutateCells() : List[Cell] = {
        def f(l:List[Cell]) : List[Cell] = {
            l match {
                case Nil => Nil
                case x :: xs => x.mutate() :: f(xs)
            }
        }
        println("BREED: size=" + cells.length)
        f(cells)
    }

    def mutate() : Breed = new Breed(generation + 1, mutateCells)

    def output() : String = {
        "BREED: [" + generation + "] = " + cellsToString(cells)
    }
}

// /\/\/\/\/test/\/\/\/\
def test() {
    val breed = createBreed(10)
    mutateBreed(10, breed)
}

test
}

Some improvements:

Try to minimize all mutable state and side effecting methods to single places. Don't divide them through the whole program.
Scala is object oriented. Therefore use methods of the objects you want to work with instead of global functions.
use methods with an empty parameter list only if these methods has side effects.
search the API for methods you can work with.

That's what I came up with:

object Game {

  import util.Random

  val rand: Random = new Random
  val mutations: Seq[Int => Int] = Seq(x => x, x => x + x, x => x * x)

  case class Cell(f: Int => Int, value: Int) {
    def mutate = {
      def nextMutation: Int => Int =
        mutations(((mutations indexOf f) + 1) % mutations.size)
      Cell(nextMutation, f(value))
    }

    override def toString = "["+value+"]"
  }

  case class Breed(generation: Int, cells: Seq[Cell]) {
    def mutate: Breed =
      Breed(generation + 1, cells map { _.mutate })

    override def toString: String =
      "BREED: ["+generation+"] = "+cells.mkString
  }

  def makeCells(num: Int) = {
    def randomMutation =
      mutations(rand nextInt mutations.size)

    def makeCell =
      Cell(randomMutation, (rand nextInt 10))

    (Seq fill num) { makeCell }
  }

  def test() {
    val firstBreed = Breed(0, makeCells(10))
    val breeds = ((1 to 10).iterator scanLeft firstBreed) {
      (b, _) => b.mutate
    }
    printBreeds(breeds)
  }

  def printBreeds(breeds: Iterator[Breed]) {
    (breeds sliding 2) foreach {
      case Seq(b, mutated) =>
        println("BREED: size="+b.cells.size)
        println(b+" ---> "+mutated)
    }
  }

}


Macro to convert an indented hierarchy to a database format Our business intelligence suite outputs data as an indented hierarchy, as below:

Level 1            1000
   Level 2a        600
      Level 3a     500
      Level 3b     100
   Level 2b        400
      Level 3c     400

I've written a macro that converts this into a 'database' format, where only rows with the base (most granular) level are preserved, and the parents are listed to the left as below (this way the # column is summable):

   1         2          3         #
Level 1   Level 2a   Level 3a    500
Level 1   Level 2a   Level 3b    100
Level 1   Level 2b   Level 3c    400

The problem I've been running into is that it takes 5-10 minutes to process a file with ~8000 rows. Although my code works, I'm convinced there's a faster way. See below for my code:

Sub Database()

Application.ScreenUpdating = False

Dim WS      As Worksheet
Dim SR      As Range
Dim Rows    As Integer
Dim Indent  As Integer
Dim TR      As Integer
Dim BR      As Integer

Set WS = ActiveWorkbook.ActiveSheet
'StartCell is a function that returns the address of the first cell in the hierarchy
Set SR = WS.Range(StartCell())
Rows = SR.End(xlDown).Row - SR.Row
BR = SR.End(xlDown).Row
TR = SR.Row

'Insert 4 columns & add headers (Level 1, Level 2, etc.)
For x = 0 To 3
    SR.EntireColumn.Insert
    SR.Offset(-1, -1) = "Level " & x + 3
Next x

x = 0
q = 0

'The main code
Do While x < Rows + 1
    'Identifies a row with base-level indentation & sets indent value to this level
    If Left(SR.Offset(x, 0), 5) = "P_PC7" Then
        Indent = SR.Offset(x, 0).IndentLevel
    End If
    i = 0
    'Loop while the indentation level is greater than one
    Do While Indent > 1
        'Move upwards and check whether indentation of new cell is one less than initial cell
        If SR.Offset(x - i, 0).IndentLevel = Indent - 1 Then
            'If so, this cell is the parent of the initial cell - copy it into the appropriate spot to the left of the base level cell
            SR.Offset(x - i, 0).Copy SR.Offset(x, -1 * (6 - Indent))
            'Set new indent level - the next loop will now look for the parent of the new cell
            Indent = SR.Offset(x - i, 0).IndentLevel
        'If indent level is not one less than initial cell, continue moving upward
        Else: i = i + 1
        End If
    Loop
    x = x + 1
Loop

'Remove all rows that are not base-level
For q = BR To TR Step -1
    If WS.Cells(q, 6).IndentLevel <> 5 Then
       WS.Cells(q, 6).EntireRow.Delete
    End If
Next q

WS.UsedRange.IndentLevel = 0

Application.ScreenUpdating = True

End Sub

Thanks very much to JNevill for his solution - it is indeed significantly faster than my original code. I had to make some changes to accommodate more than one # column, as well as headers to the left of the indented hierarchy column i.e.:

Region        Base Level        Account 1     Account 2

 USA         Level 1               500           800
 USA             Level 2a          300           400
 USA             Level 2b          200           400

Here is my new code based on JNevill's framework:

Sub HierarchyConvert()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Dim WS                      As Worksheet
Dim SR                      As Range
Dim LastRow                 As Long
Dim rngReadCell             As Range
Dim rngWriteRow             As Range
Dim Indent                  As Integer
Dim LastIndent              As Integer
Dim MaxIndent               As Integer
Dim ValueArray(0 To 19)     As Variant

Set WS = ActiveWorkbook.ActiveSheet
Set SR = WS.Range(StartCell())
LastRow = SR.End(xlDown).Row
MaxIndent = 5

Set rngWriteRow = WS.Rows(SR.Row)

For x = 0 To 4
    SR.Offset(0, 1).EntireColumn.Insert
    SR.Offset(-1, 1) = "Level " & 7 - x
Next x

SR.Offset(-1, 0) = "Level 2"
SR.Offset(-1, 5) = "PC"

For Each rngReadCell In WS.Range(SR.Address & ":B" & LastRow)
    Indent = rngReadCell.IndentLevel
    If Indent <= LastIndent And LastIndent <> 0 Then
        Set rngWriteRow = rngWriteRow.Offset(1)
        For i = 1 To Indent
            rngWriteRow.Cells(1, i + 1).Value = rngWriteRow.Cells(1, i + 1).Offset(-1).Value
        Next i
    End If
    rngWriteRow.Cells(Indent + 2).Value = Trim(rngReadCell.Value)
    If Indent = MaxIndent Then
        'Copies leftmost header from base-level row to top left of write-row
        rngWriteRow.Cells(1) = rngReadCell.Offset(, -1).Value
        'Copies data to right of base-level row to the write-row
        For Z = 0 To 19
            ValueArray(Z) = rngReadCell.Offset(, Z + 6).Value
        Next Z
        For M = 0 To 19
            rngWriteRow.Cells(Indent + M + 3).Value = ValueArray(M)
        Next M
    End If
    LastIndent = Indent
Next rngReadCell

Range("A" & SR.Offset(0, 1).End(xlDown).Row + 1 & ":Z" & LastRow + 1).ClearContents
WS.UsedRange.IndentLevel = 0

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub


MVVM notification messages I have been looking at a couple of different approaches on how I can notify the UI about messages coming from the ViewModel, and wanted to see if this seemed appropriate or if it is too coupled. (We already have a static class that deals with notifications that I am trying to wrap for now, and maybe remove at a later time?)

INotifier
{
  void Notify(Notification notification);
}

ConcreteNotifier()
{
  void Notify(Notification notification)
  {
    Notification.ShowMessage(notification.Title, notification.Message, notification.MessageLevel);
  }
}

Main will create ConcreteNotifier and pass it into each View, which will pass it into each VM

ViewModel(INotifier notifier)
{
  _notifier = notifier;
}

DoStuff()
{
  try
  {
  }
  catch(Exception ex)
  {
    _notifier.Notify(new Notification{Title="DoStuff Error", Message=ex.Message, MessageLevel=Error});
  }
}

This seems ok to me, however there is coupling due to the Notification class. This is really just encapsulating parameters, so it is probably ok, but I wanted to run it past some people who are more familiar with MVVM and UI interaction. I only need to talk one way, so the Messenger pattern seems like overkill as I do not need to talk to other VM's, and this seemed like a simplistic way of dealing with this issue.  Can anybody verify that this approach is ok, or if it has some issues with it?

Generally speaking, view should bind to viewmodel and viewmodel should notify view through injected adapter. I read about this approach in Mark Seemann's "Dependency injection in .NET" book.

You are injecting, to your viewmodels, interface like this:

public interface IWindow
    {
        void Close();

        IWindow CreateChild(object viewModel);

        void Show();

        bool? ShowDialog();
    }

Download source code to see usage: http://www.manning.com/seemann/

Another approach, through static Messager, is proposed by mvvm light framework.
Here are some tutorials and videos: http://www.galasoft.ch/mvvm/#tutorials

Personally I prefer injection, because only stateless classes should be considered as static (otherwise there are not testable). Besides, static Messager hides class dependency.


Replace CASE WHEN statement with something more sensible While checking my SPs today I found that I have,

SELECT  COUNT(*)
,CASE WHEN ISNULL(MIN(COALESCE(MP.NewPrice, MP.Price, 2147483647)),0) = 2147483647 THEN 0 ELSE ISNULL(MIN(COALESCE(MP.NewPrice, MP.Price, 2147483647)), 0) END
FROM    MerchantsProducts MP

I need to replace this with something which make more sense. Can someone please review this?

COALESCE(…, …, 2147483647) will never return NULL.  Furthermore, MIN(…) will only return NULL when all of its inputs are NULL.

Assuming that every NewPrice and every Price is at most 2147483647, the following query should be equivalent.

SELECT COUNT(*)
     , ISNULL(MIN(COALESCE(NewPrice, Price)), 0)
    FROM MerchantsProducts


Assigning Clients a random number I have a program that creates 100,000 objects of class Client, puts them into array and then goes through that array 100 times, each time assigning each Client a different random number through Rnd() function:

Main sub:

Sub start()
    Dim i As Long
    Dim j As Long

    Dim clientsColl() As Client
    ReDim clientsColl(1 To 100000) As Client

    For j = 1 To 100000
        Set clientsColl(j) = New Client
        clientsColl(j).setClientName = "Client_" & j

        Application.StatusBar = "Getting client " & j

        DoEvents
    Next

    Dim tempCount As Long
    Dim clientCopy As Variant
    For i = 1 To 100
        tempCount = 0
        For Each clientCopy In clientsColl
            tempCount = tempCount + 1

            clientCopy.generateRandom

            'Application.StatusBar = "Calculating " & i & ": " & tempCount & "/" & 100000  '(1)

            'DoEvents
        Next

        Application.StatusBar = "Calculating " & i

        DoEvents
    Next

    MsgBox ("done")
End Sub

Client class:

Option Explicit

Dim clientName As String
Dim randomNumber As Double

Public Sub generateRandom()
    randomNumber = Rnd()
End Sub

Public Property Get getClientName()
    getClientName = clientName
End Property

Public Property Let setClientName(value As String)
    clientName = value
End Property

The problem is, the execution time depends on whether or not line (1) is commented out. If it's executed, the status bar gets renewed, but the execution time is very slow. If it's not executed, the program gets done really fast. Why does this happen?

Your question is why does it take a long time to update the Application.StatusBar 10,000,000 times?  The answer is that you are updating the Application.StatusBar 10,000,000 times.

Using the Timer from TheSpreadSheetGuru, I calculated that it takes roughly 1 sec to do 10,000 updates.  So it will take roughly 10,000,000/10,000/60 minutes just to do the updates.  That is roughly 16.667 minutes.

Sub CalculateRunTime_Seconds()
'PURPOSE: Determine how many seconds it took for code to completely run
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
    Dim x As Long
    Dim StartTime As Double
    Dim SecondsElapsed As Double

    'Remember time when macro starts
    StartTime = Timer

    '*****************************
    'Insert Your Code Here...
    For x = 1 To 1000
        Application.StatusBar = x
    Next
    '*****************************

    'Determine how many seconds code took to run
    SecondsElapsed = Round(Timer - StartTime, 2)

    'Notify user in seconds
    MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub


Build menu from MS Word XML I've recently assembled some jQuery that allows a user to build out a bulleted list in MS Word with hyperlinks and turn that into a HTML unordered list.  Ideas for uses are website menu systems where the user may not have a clue about HTML. You can also extend this with jQuery UI plugins for effects.  Looking for edge cases.

/*
    The following will read in a bullet list from in a MS Word XML file and turn it into a
    unordered list with hyperlinks. Perhaps to use as a menu.
*/
$.ajax({
    type: "GET",
    async: false,
    url: "Menu.xml",
    dataType: "xml",
    success:function(results){
        var currentDepth = 0;
        $("#menu").append('

');
        $(results).find("[nodeName=w:p]").each(function(){
            if($(this).find("[nodeName=w:pStyle]").attr('w:val') == 'ListParagraph'){
                var liValue = $(this).find("[nodeName=w:t]").text();
                var hyper = $(this).find("[nodeName=w:hyperlink]").attr('r:id');
                var placeAtDepth = parseInt($(this).find("[nodeName=w:ilvl]").attr('w:val'), 10);

                if(placeAtDepth > currentDepth){
                    $(".menuLvl"+ currentDepth).append('
');
                }

                currentDepth = placeAtDepth;

                //Determine if we have an hyperlink
                if(hyper != null){
                    var link = $(results).find('Relationship[Id='+hyper+']').attr('Target');
                    liValue = ''+ liValue +'';
                }

                $(".menuLvl"+currentDepth).last().append('
'+ liValue +'
');
            }
        });
    }
});

Looks fine (maybe some stricter formatting could help readibility, but not an issue), so I'll suggest completely optional improvements that might help spotting important improvements.

As a general principle, try to be ready for bogus values in your input so you can avoid generating nonsense. Being more robust will also make reusing your code for somewhat different tasks easier.

$.ajax({
/// [...]
    success:function(results){
/// [...]
        $(results).find("[nodeName=w:p]").each(function(){
            if($(this).find("[nodeName=w:pStyle]").attr('w:val') == 'ListParagraph'){
                var liValue = $(this).find("[nodeName=w:t]").text();
/// -^ What if the input has an empty value here? Skip?

                var hyper = $(this).find("[nodeName=w:hyperlink]").attr('r:id');
                var placeAtDepth = parseInt($(this).find("[nodeName=w:ilvl]").attr('w:val'), 10);
/// -^ parseInt can return a NaN, maybe you want to bail out in that case?
///    Should also handle some bogus results for .find.

                if(placeAtDepth > currentDepth){
                    $(".menuLvl"+ currentDepth).append('
');
                }

                currentDepth = placeAtDepth;

                //Determine if we have an hyperlink
                if(hyper != null){
                    var link = $(results).find('Relationship[Id='+hyper+']').attr('Target');
/// -^ This can result in an invalid link for broken input. But what if
       the input is malicious (JS hrefs)?

                    liValue = ''+ liValue +'';


Generating random and secure CSRF tokens I googled around for secure random number generation and random string generation, combining them with some user data.

Is this good or am I totally off-base?  I don't know much about cryptography but I do not see many alternatives, other than some bad code that gets copied around a lot with mt_rand and uniqid.

//csrf tokens
    public function csrf_token($regen = false)
    {
        if($regen === true) {
            //we need to give the user a token
            if(isset($_SESSION["__csrf_token"])) {
                unset($_SESSION["__csrf_token"]);
            }
            $max = mt_rand(0, mt_getrandmax());
            $rand_num = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
            $rand_string = "";
            for($i=0; $i < 11; $i++) {
                $x = mt_rand(0, 2);
                switch($x) {
                    case 0: $rand_string.= chr(mt_rand(97,122));break;
                    case 1: $rand_string.= chr(mt_rand(65,90));break;
                    case 2: $rand_string.= chr(mt_rand(48,57));break;
                }
            }

            $_SESSION["__csrf_token"] = hash('whirlpool', $rand_num . $this->username . $rand_string . $this->hash_pw);
            $this->csrf_token = $_SESSION["__csrf_token"];
            return $this->csrf_token;
        }else{
            //the user already has a token
            return $this->csrf_token;
        }
    }

If CSRF stands for Cross Site Request Forgery, then it's hard to imagine why I should help.

In any case, simply doing a cryptographic Whirlpool hash of a user-supplied string with a random seed value should be sufficiently random for most every purpose.  The rest is just obfuscation and doesn't add to security.


BMI Calculator in Java My task:

  Body Mass Index (BMI) is a measure of health based on height and weight. It can be calculated by taking your weight in kilograms and dividing it by the square of your height in meters.

  Write a java code to let the user enter weight, feet, and inches and interpret the users BMI.

My code:

//import scanner
import java.util.Scanner;

//import Math class
import java.lang.Math;

public class ComputeBMI {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //create scanner
        Scanner input = new Scanner(System.in);

        //declare variables
        double weight;
        int feet;
        int inches;

        //prompt user
        System.out.print("Enter weight in pounds: ");
        weight = input.nextFloat();

        System.out.print("Enter feet: ");
        feet = input.nextInt();

        System.out.print("Enter inches: ");
        inches = input.nextInt();

        //convert measurements
        double weightInKilos = weight * 0.453592;
        double heightInMeters = (((feet * 12) + inches) * .0254);
        double bmi = weightInKilos / Math.pow(heightInMeters, 2.0);
//      double bmi = weightInKilos / (heightInMeters * heightInMeters);

        //display output
        System.out.println("Your BMI is: " + bmi);

        //interpret BMI
        if (bmi < 18.5 ) {
            System.out.print("Underweight");
        }

        else if (bmi >= 18.5 && bmi < 25) {
            System.out.print("Normal");
        }

        else if (bmi >= 25 && bmi < 30) {
            System.out.print("Overweight");
        }

        else if (bmi >= 30) {
            System.out.print("Obese");
        }

//      Do I need this last else if there?
//      else {
//          System.out.print("");
//      }

        input.close();

    }

}

I used only the material we've been taught thus far to complete my code. My POC is clarity/fluidity of my code and my variable data types. In my mind, feet and inches should be integers and weight should be a double. Valid hypothesis?

Thanks, y'all.

You run all the computations in the main method. It's not a good practice. One method should do one focused thing. That's why I'd recommend to create a separate method for "step" of your computation:

converting measurements (something like double poundsToKilograms(double weightInPounds)
computing the BMI given the height and the weight of the user
converting a numeric value of the BMI to a human-readable message

This way, you main method would just read the input, call these methods and print the result. It would make your code more readable and testable (you would be able to test your methods separately)
The comments should explain what the code does and why it does what it does. They shouldn't describe how it works. That is, it's a good idea to create a doc comment for each method saying what it does, how it behaves if it gets an incorrect input and so on. Conversely, comments like //declare variables or //create scanner actually harm the readability. They just create noise. They don't add anything useful to the code itself.  Writing self-documenting code is a good practice (that is, ideally it should be clear what your code does from the code itself).
ComputeBMI doesn't sound like a good class name to me. I'd rather call it a BMICalculator (it's conventional to name classes with nouns and methods with verbs).
The message Enter feet: looks kind of strange. I think it should say that it requests the user's height (it's not clear from the message itself).
It's fine to keep the height as an int, but I would show a message to the user saying that. Otherwise, they may get an unexpected error.
You could also add some kind of input validation and error handling so that your program doesn't fail with an exception (it might be confusing for the user) but rather prints a more suitable message and possible prompts the user again.


Minimum element in a sorted rotated array A sorted array [0,1,2,3,4,5] when rotated n times (3 times in this case) becomes [3,4,5,0,1,2], meaning elements in the front move to the end. The code below finds the minimum element in this array, which is the pivot point of rotation.

function findminimum(a, start, end){
    if(start>end || start == end || a[start]<a[end])
        return a[start];

    var mid = start + Math.floor((end-start)/2);

    //check if mid is the minimum element - also if mid is greater than start
    if(mid>start && a[mid]<a[mid-1])
        return a[mid];

    //check if mid+1 is the minimum element - also if mid is less than end
    if(mid<end && a[mid]>a[mid+1])
        return a[mid+1];

    //handles duplicate elements case
    if(a[start]==a[mid] && a[mid]==a[end]){
        //search both sides and get the minimum
        return Math.min(findminimum(a, start, mid-1), findminimum(a, mid+1,    end));
    }
    //left half is sorted or every element is same, search right half
    if(a[start]<=a[mid])
        return findminimum(a, mid+1, end);
    return findminimum(a, start, mid-1); //search left half
}
var a = [3,4,5,0,1,2];
//original array [0,5,5,5,5] rotated 2 times
//var a = [5,5,5,0,5];
console.log(findminimum(a, 0, a.length-1));

Code also handles duplicates. Any comments or suggestions on improving this code will be helpful.

The same can be achieved in much simpler way using Array.slice and Math.min functions:

var a = [8,1,2,3,4,3,0];

function findMinimum(a, start, end){
    if (a.length < end) {
        throw new Error("Invalid end range boundary!");
    }
    return Math.min.apply(null, a.slice(start, end + 1));
}

console.log(findMinimum(a, 3, 5));  // 3
console.log(findMinimum(a, 0, 2));  // 1
console.log(findMinimum(a, 1, 6));  // 0