Rust Book Ch 13 Closures with Generic Parameters and HashMap for memoization

Even though I'm relatively new to Rust myself, I'll give this a shot since no one else has responded so far.
Is Cacher caching?
Let's test that Cacher is working as intended (wouldn't call calc on the same value twice) by adding a log:
// --snip--
let mut workout = Cacher::new(|x| {
    println!("calc {}", x);
    x + 1
});
// --snip--

The output is:
calc 4
5
calc 5
6
calc 3
4
calc 4
5

Why is calc called twice on 4? Let's check the implementation of Cacher::get:
fn get(&mut self, n: &I) -> &O {
    self.cache.entry(*n).or_insert((self.calc)(*n))
}

The problem is that the expression (self.calc)(*n) is evaluated and the result value given to or_insert whenever Cacher::get is called, even though the result is discarded if the key *n already exists in the hashmap. This can be fixed by using or_insert_with:
fn get(&mut self, n: &I) -> &O {
    let calc = &self.calc;
    self.cache.entry(*n).or_insert_with(|| calc(*n))
}

Now the output is as expected:
calc 4
5
calc 5
6
calc 3
4
5

NB: The borrow checker wouldn't let us simply write || (self.calc)(*n). The reason is self.cache is borrowed mutably within Cacher::get, and the whole self (implying self.cache) would be borrowed within the closure. That would violate the rule that a mutable borrow is exclusive. We circumvent this by explicitly splitting the borrow outside of the closure. The closure then captures only calc.
Some links to read up on this:

https://doc.rust-lang.org/nomicon/borrow-splitting.html
https://stackoverflow.com/questions/61699010/rust-not-allowing-mutable-borrow-when-splitting-properly
https://www.reddit.com/r/rust/comments/cufiq7/rust_mutably_borrows_the_whole_struct_even_though/

Trait Bounds
Let's get to your question on trait bounds. First off, it does make a real difference where we put them:

When the trait bounds are on the struct, then the compiler will not let us instantiate the generic without satisfying the trait bounds, at all.

When the trait bounds are on the impl block, then we are allowed to instantiate the generic with types that do not satisfy the trait bounds, but the methods defined in the impl block will be available only to instances where the trait bounds are satisfied.

In fact, if you have a look at the implementation of HashMap, you'll notice that HashMap has trait bounds only on impl blocks for particular sets of methods that require the respective traits. Thus we may create, but not insert into, a HashMap whose key type doesn't satisfy Eq + Hash:
// This is alright:
struct X {}
let mut map = HashMap::<X, u32>::new();

// This won't compile:
map.insert(X {}, 1);

This being a factual difference, what should we do here? A question on StackOverflow has some interesting answers discussing this question: https://stackoverflow.com/questions/49229332/should-trait-bounds-be-duplicated-in-struct-and-impl. In this case, I'd probably stick with HashMap's approach and be as specific as possible (see code below).
A Note on Tooling
Rust's ecosystem brings some nice tools. Clippy is a linter that does, in fact, hint at the aforementioned bug:
$ cargo clippy
warning: use of `or_insert` followed by a function call
  --> src/main.rs:26:30
   |
26 |         self.cache.entry(*n).or_insert((self.calc)(*n))
   |                              ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(|| (self.calc)(*n))`
   |
   = note: `#[warn(clippy::or_fun_call)]` on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call

Also, there's cargo fmt to enforce a standard code style. In this case, it sorts the imports, adds a trailing comma in the struct and removes a duplicated blank line.
Final Code
Here's the code I ended up with, including some further remarks:
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;

// We may even leave out the trait bound for `T`
// (Example: Perhaps at some point you want to add another implementation
//           where calculation isn't done via a closure/function,
//           but via some special object. This is general enough to allow that.)
struct Cacher<I, O, T> {
    calc: T,
    cache: HashMap<I, O>,
}

// Here I'm splitting into two `impl` blocks.
// A `Cacher` may be created without knowing anything about the types.
impl<I, O, T> Cacher<I, O, T> {
    fn new(calc: T) -> Cacher<I, O, T> {
        Cacher {
            calc,
            cache: HashMap::new(),
        }
    }
}

// Now that the hashmap is used, and `calc` is used,
// the trait bounds are indeed required
impl<I, O, T> Cacher<I, O, T>
where
    // For clarity and consistency, I put all trait bounds into the where block
    I: Eq + Hash + Copy,
    T: Fn(I) -> O,
{
    fn get(&mut self, n: &I) -> &O {
        let calc = &self.calc;
        self.cache.entry(*n).or_insert_with(|| calc(*n))
    }
}

fn main() {
    let mut workout = Cacher::new(|x| x + 1);
    println!("{}", workout.get(&4));
    println!("{}", workout.get(&5));
    println!("{}", workout.get(&3));
    println!("{}", workout.get(&4));
}


I would change this:

alertButton.isEnabled = !Utils.isValidEmail(testStr: e) ? false : true

to this one:

alertButton.isEnabled = Utils.isValidEmail(testStr: e)


Stripping leading tab of each line from a file

You can use a different approach here:

Open file in r+ mode, it allows us to read as well as write the file along with truncation.
Read the content first and store it in a variable.
Seek back to 0th position using file.seek(0).
Truncate the file using file.truncate(), i.e it will truncate it to 0 bytes.
Now write the new content to the file object.

Code:

def clean_file(filename):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0)
        f.truncate()
        f.write(content.replace('\n\t', '\n'))

Few other points:

Prefer variable names with underscores in Python.
Always open files using the with statement in Python.
You can change the variable name file to filename to make it clearer to the user, otherwise it's hard to tell whether the file object expects a file name or file object.
Instead of using regex simply use the str.replace method.
To modify a file line by line in-place you can look into fileinput module.


Use more meaningful variable names, for example:

lines instead of t
length instead of l
Since y is a character position, I would rename to pos
let to letter, because it's not much longer and a bit more readable (since let is keyword in some other programming languages, I find it confusing to read)

Since lines[0] is kind of special, and you make many references to it, it would be good to give it a name:

first = lines[0]

Your input lines end with a trailing newline character, but in the main logic of pattern matching this is just noise, not an important detail. I recommend this:

first = lines[0].strip()

This will get rid of the trailing newline character, and in the main logic you don't have to worry about checking letters until first[-1], you can consider the letters in first, which is simpler.

If you make changes to the script, you have to repeat all the tests to see if it's still working. That's very troublesome. To make that easier, add some unit tests, and refactor the main method to make it more testable, for example:

import unittest
from test.test_support import run_unittest

def main():
    n = int(sys.stdin.readline())
    lines = sys.stdin.readlines()[0:n]
    print find_common_pattern(lines)

def find_common_pattern(lines):
    # the rest of the code from the old version of `main`

class FindPatterns(unittest.TestCase):
    def test_given_examples(self):
        self.assertEqual('xab', find_common_pattern(['?ab\n', '??b\n']))
        self.assertEqual('?', find_common_pattern(['a\n', 'b\n']))
        self.assertEqual('xaxb', find_common_pattern(['?a?b\n']))

run_unittest(FindPatterns)

After this, it will be easy to follow my suggestions below and verify that the script is still working correctly, passing all test cases. (Feel free to add more!)

Instead of range(0, length-1), you can write simply range(length-1).

if let == '?' and t[x][y]!= '?':
    let = t[x][y]
if t[x][y] != let and t[x][y] != '?':
    result += '?'

If the first if was true, the second will not be true, and it's a waste to evaluate it again. You could make the second if an elif instead.

The last elif in your for loop is a bit dirty: it's for checking if you're on the last line. The condition will be evaluated for every line where the current position is ?, which is a bit wasteful. It would be better to refactor that loop to perform that check only once at the end, for example:

for pos in range(length):
    letter = first[pos]
    newletter = letter
    for x in range(1, len(lines)):
        if letter == '?' and lines[x][pos] != '?':
            letter = lines[x][pos]
        elif lines[x][pos] != letter and lines[x][pos] != '?':
            newletter = '?'
            break
    if letter == '?':
        result += 'x'
    else:
        result += newletter

After this refactoring, you don't need the value of x inside the loop anymore, so you could rewrite more intuitively as:

for line in lines[1:]:
    if letter == '?' and line[pos] != '?':
        letter = line[pos]
    elif line[pos] != letter and line[pos] != '?':
        newletter = '?'
        break

Since the characters ? and x appear several times in the code, I would treat them as constants and name them for example:

ANYCHAR = '?'
SAMPLECHAR = 'x'

Instead of running main, the common way is like this:

if __name__ == '__main__':
    main()

This way, your script will still run as before when you do python script.py, and at the same time it will be possible to import it from another python script as a library without automatically running it. It's a good practice to get used to, even if you don't intend to make this a library.

Putting it all together, and some other minor improvements, this would be more Pythonic, and slightly more readable and efficient:

ANYCHAR = '?'
SAMPLECHAR = 'x'

def find_common_pattern(lines):
    first = lines[0].strip()
    lines = lines[1:]
    if not lines:
        return first.replace(ANYCHAR, SAMPLECHAR)
    result = ''
    for pos in range(len(first)):
        letter = first[pos]
        newletter = letter
        for line in lines:
            if line[pos] != ANYCHAR:
                if letter == ANYCHAR:
                    letter = line[pos]
                elif line[pos] != letter:
                    newletter = ANYCHAR
                    break
        if letter == ANYCHAR:
            result += SAMPLECHAR
        else:
            result += newletter
    return result


Your variable's names confused me; I'd suggest renaming 'previous' to 'current', and 'tmp' to 'previous'.
You don't do anything sensible if malloc fails.
The following ...

else if (tmp != NULL)
{
    tmp = previous;
    previous = previous->next;
    break;
}
else
{
    break;
}

... could be rewritten as ...

else
{
    if (tmp != NULL)
    {
        tmp = previous;
        previous = NULL;
    }
    break;
}

IMO you should ignore the alleged priority assigned to the head q element (because you never want to put anything in front of it).

1st version

In summary you could rewrite it to be something like this:

bool add (Queue q, int priority, Datatyp *d)
{
    // initiation
    Queue element = (Queue)malloc (sizeof(struct Qelement));
    if (element == NULL)
        return false;
    element->prio = priority;
    element->dataptr = d;

    // loop until end of list or higher priority than next item
    for (; (q->next != NULL) && (q->next->prio >= priority); q = q->next)
    { } // an empty statement

    // insert element
    element->next = q->next;
    q->next = element;
    return true;
}

Advantages of this version over your implementation:

No danger of adding in front of the first, passed-in q element, even if the passed-in priority is greater than MAX_PRIO
No extra local variables (you have 2: tmp and previous)
No if or else statements (you have 5)
It's obvious what the algorithm is (search the list after the first node until you find the right spot, then insert into the list there)

2nd version

It's not clear whether your Queue new_queue() is part of the code which we're allowed to review.

Assuming that we are allowed to review/change that, I would add, "**Don't create "first element" which represents (contains a first pointer to) the queue: instead the queue should be represented by a pointer to the first real element."

Your first node (allocated using new_queue) might be what's called a "sentinel node" (see references here and here). It's also possible to create a queue without using a sentinel node: the "queue" is simply a pointer to the first node (instead of being a pointer to a node which contains a pointer to the first real node).

void add (Queue* qptr, int priority, Datatyp *d)
{
    // initiation
    Queue element = (Queue)malloc (sizeof(struct Qelement));
    element->prio = priority;
    element->dataptr = d;

    // get first element of queue
    Queue q = *qptr;
    if ((q == NULL) // queue was empty
        || (priority > q->prio)) // higher priority than first queue item
    {
        // insert at front of queue
        element->next = q;
        // caller's qptr now points to the new first node
        *qptr = element;
        return;
    }

    // else insert later in the queue using the same code as above
    for (; (q->next != NULL) && (q->next->prio >= priority); q = q->next)
    { }

    // insert element
    element->next = q->next;
    q->next = element;
}

... used like this ...

int main () {
    const char *daniel = "Daniel";
    const char *lisa = "Lisa";
    const char *a[] = {"Kalle", "Olle", "Eva", lisa, "Stina",
                      "Peter", "Anna", daniel, "Johan", "Maria"};

    // not q = new_queue()
    // instead let q be pointer to first real node
    // and q is null represent an empty list
    Queue q = NULL;

    for (int i=0; i<10; i++) {
        // pass Queue* qptr = &q (address of queue)
        // so that add can modify the value contained in q
        // (i.e. modify the node to which q is pointing)
        add(&q, i%4, a[i]);
    }

    // q is now a pointer to the first element
}

  Sadly, I can not change add to be a bool either. Is there any other way of handling it (except of very obscured ones) without changing add to a bool?

Some C conventions are:

return int (often 0 for success and -1 for failure)
return something useful like 'Queue' (the most recently-added element) or 0 (if a new element couldn't be created
throw an exception (if it's C++)
Include <stdbool.h>
Ignore the fact that malloc might fail.

  Tell me about it, that is how I did it at first, and it turned out that the main function gave me a billion errors because apparently the first element of the queue should only be a pointer to the first real element.

I tested the above code by adding the following statement to the end of main:

// q is now a pointer to the first element

for (;q;q=q->next)
{
    printf(q->dataptr);
    printf("\r\n");
}

It generated the following output (which I think is correct):

Lisa
Daniel
Eva
Anna
Olle
Peter
Maria
Kalle
Stina
Johan


This can be reduced to a common problem : smallest range containing elements from k lists.

Assuming \$N\$ is the number of inputs and \$M\$ the number of companies in listCompanies.

In your problem, what you would do is make a set from your listCompanies (\$M \log M\$). Make a map where the keys are those companies and the values are lists (\$M \log M\$). Then, loop your input and if it's a company of interest (it has a key on the map), add that time to the list of that company.

So in your first example, IBM would be [10000000, 10000012]. After you have done this, you have now the common problem of finding the minimum range in which you can have one item from each of those lists (minimum range that has each of your companies in listCompanies).

You can then apply the algorithm linked and end up with a complexity of (\$N \log M\$ -> each element will enter and leave a heap of size \$M\$ only once). \$N\$ in this case will be the amount of inputs that are related to companies from your listCompanies.

Here is a C++ implementation.


Check that input is list of lists of coordinates

My main problem with this method is that you don't make a useful docstring and consequently it's unclear what should or shouldn't pass.

You say that you're checking if the input is a lost of lists of pairs of numbers, but not explaining how. If I had a class with __len__ defined and could be iterated over, that would pass your test. That might sound unlikely, but consider someone passing a set of generators:

>>> coords = [xrange(2)] * 10
>>> _check_args(coords)

...no errors. But xrange most certainly does not return lists. If you only need the pairs to iterate over you'll be fine, but if you want to index them to get the two values then a generator will throw errors. This method should be testing what aspects of the data you need, such as indexing, not just using methods that indicate they're collections or collection like objects.

Once you know what does need to be tested this way, it would be beter to document it clearly in the docstring, so that if unusual data passes, the user can be sure that's because it's acceptable for your purposes and not just something you didn't account for.

Some other quick notes, assert is a statement not a function. You don't need to use brackets for it:

assert len(coord) == 2

You build the error string up front, which seems unnecessary and slightly wasteful as you may never need it. If you want to create it on its own line then you should still put it in the except block.

Your names could be clearer. I don't know what a coords_features is. arguments or args could be better names, since this function isn't really co-ordinate specific so much as it is format specific. I'd recommend either coordinates or pairs for the longer lists and coordinate or pair for the 2 item collections. The choice depends on how broad or narrow you intend this to be, but the docstring currently sounds more generic.

Last nitpick, in your error message you refer to lists only. If you want it to be broad you may want to use Collection as that refers to the range of list and dict like objects. Though if your intent is to encourage the user to use lists then it's a good error message.


For an extremely short version of the (not tail-) recursive algorithm, I recommend using walk. You can write the code with walk like this:

(defn my-reverse-v3 [input]
  (walk #(if (sequential? %) (my-reverse-v3 %) %) reverse input))

For a properly tail-recursive version, my cleanest results use clojure.zip:

(defn my-reverse-v4 [input]
  (loop [z-input
         (zipper sequential? seq (fn [_ c] c) input)]
    (if (end? z-input)
      (root z-input)
      (recur (next (edit z-input #(if (sequential? %) (reverse %) %)))))))

For this solution, I followed a structure which I found at Exploration through Example.

(Incidentally, your my-reverse-v2 is not tail-recursive. The function calls itself within a call to cons. One of the nice things about Clojure's recur is that it will throw a compile error when it's not used in a tail-recursive position; you'd surely see that in action here.)


This is a bad example of correcting user input:

$filecontent = str_replace(array("<?php", "<?", "?>"), "", $filecontent);

I could still upload an image with the following comment in it:

<?<?phpphp echo "this code gets executed"; ??>>

because after your str_replace the comment would be

<?php echo "this code gets executed"; ?>

Instead of correcting user input, you should simply search for these strings reject and the image if it contains <?. Why should you save the image anyway if you suspect an hacker attack? ;-)

Edit: This would be better

// test for opening php tags
// including asp-style opening tags (http://www.php.net/manual/en/ini.core.php#ini.asp-tags)
if(strpos($filecontent, "<?") !== false || strpos($filecontent, "<%") !== false) {
  // stop upload
}

Edit:
And one other thing I forgot to mention. Never use the original filename of the upload without validating it!

Because you could receive a request like this:

POST /upload.php HTTP/1.1
Host: localhost
Content-Length: 318
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L

------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="../hello.jpg"
Content-Type: image/jpeg

<?php echo "evil code"; ?>
------WebKitFormBoundaryePkpFF7tjBAqx29L

And the "image" file gets saved in the directory above.

Better generate your own file names.


Reading a properties file using design patterns

DI means injecting dependencies in  and not creating them directly in a class. Your properties file contains the String value of the keys. You need not compile your java classes if the string value are changed. Thus your string literals and your classes are de-coupled from each other.

Dependency Injection is a Design principle. (I suggest you to study SOLID design Principles). Along with it also we should pay due respects to principles like KISS and YAGNI. These say we should keep the code simple and avoid over-engineering.

You should have different Properties object for each file and pass the object from which you wish to read in your PropHolder.


Naming
Adhere to the Java Naming Conventions.

Names of methods and variables start with a lowercase letter, names of classes with an uppercase letter.

Method names should start with a verb so that they read like an instruction. Names of variables should start with a noun.

Exception to that are variables holding or methods returning a boolean which both should start with is, can, has or alike.

Don't surprise your readers
You have a variable named numberTest but it does not contain a test for a number but the current operation or the users choice.
Code Quality
Structure  your code with methods.
You wrote a single long method.
This method contains an if/else cascade that somehow separates the method in to different sections.
You should extract this blocks in to separate Methods (leaving the if/else instructions in main) so that the main method becomes shorter and easier to read (and to maintain).
Don't repeat yourself
All over your code you repeat this two lines with varying variable names:
            System.out.println(questionSix);
            double number2 = scan.nextDouble();

This two lines could be extracted to a separate method that takes the String as parameter and returns the double value. That would shrink four lines in your code to just one.


JUnit 4 has a Parameterized test runner that does most of the work for you. For your tests, it would look like:

import maharishi.DigitIncreasing;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class DigitIncreasingTest {

    @Parameters(name = "Test {index}: isDigitIncreasing({0})={1}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
              { 7, true }, { 36, true }, { 984, true }, { 7404, true }, { 37, false }
        });
    }

    private int input;

    private boolean expected;

    private DigitIncreasing digitIncreasing = new DigitIncreasing();

    public DigitIncreasingTest(int input, boolean expected) {
        input = input;
        expected = expected;
    }

    @Test
    public void test() {
        assertEquals(expected, digitIncreasing.isDigitIncreasing(input));
    }
}

This is easier to understand (in my opinion) than your formulation, where you shadow the name of the class under test, and actually runs each case as a separate test.


Welcome to Code Review!
PEP-8
Since you're still new to python, it's a good idea to keep a window/tab open with PEP-8 loaded into it. It is mostly suggestions for coding style. Few things that can be picked up from the same:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.
Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:

Functions
As you've already raised this point, splitting the code into individual functions is always a good practice.
if __name__ block
Put the execution logic of your script inside the if __name__ == "__main__" block. Read more about the details on why on stack overflow.
f-string
Python 3.x also introduced literal string interpolation, or more commonly used term: f-string. Read more about it here (PEP-498).
Type hinting
When writing functions, you can also make use of type hinting to provide a more readable flow of your code to anyone. This helps removing the manual labour of having to backtrack variable types etc. More details can be found in PEP-484.
Game logic
The initialisation of presentation array can be simplified to:
presentation = ["_"] * len(answer)

For every guessed character from the user, you keep looping over the answer_list, irrespective of validating whether the guess is correct or not.
Before the loop over each character of the correct word, you have setup ind = 0 which is never really used.
Your global while loop relies on the condition completion == False (which should ideally be completion is False) but you break out before the loop/condition really has a chance to do so for you, making the variable useless.

Rewrite
from typing import List

MAX_ATTEMPTS: int = 5

def get_answer() -> str:
    return input("What's the word? ")

def correct_guess(char_count: int, guessed_word: List[str]):
    print(f"Your guess is correct, there was/were {char_count} matches in the word.")
    print(" ".join(guessed_word))

def game_win(guessed_word: List[str]) -> bool:
    return "_" in guessed_word

def game():
    answer = get_answer()
    correct_letters = set(answer)
    guessed_word = ["_"] * len(answer)
    incorrect = 0
    while True:
        if incorrect >= MAX_ATTEMPTS:
            print("You lost!")
            break
        attempt = input("Guess: ")
        if attempt not in correct_letters:
            incorrect += 1
            continue
        char_count = 0
        for index, char in enumerate(answer):
            if char == attempt:
                guessed_word[index] = char
                char_count += 1
        correct_guess(char_count, guessed_word)
        if game_win(guessed_word):
            print("Congrats, you got everything correct")
            break

if __name__ == "__main__":
    game()


Most of the solutions provided so far is hard to read, and you need to really think before you understand what is happening, so I would like to propose an alternative approach as a response to a more straightforward algorithm:

def evaluate_guess(secret_code, guesses):

    score = []
    remaining_secrets = []
    remaining_guesses = []

    # Check exact matches
    for guess, secret in zip(secret_code, guesses):
        if guess == secret:
            score.append(1)

        else:
            remaining_guesses.append(guess)
            remaining_secrets.append(secret)

    # Check wrong placing
    for guess in remaining_guesses:

        if guess in remaining_secrets:
            score.append(0)
            remaining_secrets.remove(guess)

    return score

The only magic in this code is the joining of secret_code and guesses using zip which joins them index for index. This allows for, in my opinion, code that is easier to understand instead of list comprehensions, ifilters, index searching, sorting, sliceing and other stuff.


Getting list of colours from image in lab format

There's no docstring for get_histogram. What does this function do? What kind of object should I pass for the img argument?
You import skimage.io.imread and PIL.Image but you don't use either of them.
This comment doesn't seem relevant:

#histogram = plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)

There are two useless print statements. I presume that these are left over from a debugging session and you forgot to remove them. You might find it useful to learn to use the Python debugger which would avoid the need to add print statements to the code.
There are two pieces of functionality here: (i) extracting the colour data from an image into a Numpy array; (ii) converting colour data from RGB to the Lab colour space. It would make sense to split these up (especially as piece (ii) is so simple).
The function is poorly named: it does not actually get a histogram. (Because you discard the colour counts in the num array.) This makes me wonder what you are using this function for.
You use the spelling "colour" but the APIs you are calling use the spelling "color". Even if you prefer the "colour" spelling, it's better to be consistent. That way there's less chance of forgetting and making a mistake.
Creating a Numpy array from an a Python list is usually straightforward if you pass the list to the numpy.array function. There's no need to mess about with numpy.zeros and assigning column-wise.

So I'd write the following:

import numpy as np

def distinct_colors(img):
    """Return the distinct colors found in img.
    img must be an Image object (from the Python Imaging Library).
    The result is a Numpy array with three columns containing the
    red, green and blue values for each distinct color.

    """
    width, height = img.size
    colors = [rgb for _, rgb in img.getcolors(width * height)]
    return np.array(colors, dtype=np.uint8)

The conversion to Lab colour space is so simple that I don't think it needs a function.

Update

There's one minor difficulty: the skimage.color functions all demand an array with 3 or 4 dimensions, and so only support 2- and 3- dimensional images. Your array of distinct colours is a 1-dimensional image, so it's rejected. But you can easily use numpy.reshape to turn it into a 2-dimensional image whose first dimension is 1 before passing it to rgb2lab, like this:

colors = distinct_colors(img)
rgb2lab(colors.reshape((1, -1, 3)))

Or if you prefer the second dimension to be 1, use .reshape((-1, 1, 3)).

(Personally I think the skimage.color behaviour is absurd. Why does it care about the number of dimensions? There doesn't seem to be any obvious reason in the code. Maybe it would be worth filing a bug report?)


Using objects to make state with AJAX functions as properties

Your setPlacement method returns the "correct" data because whatever d is in your data object you receive from Service.asmx/GetDrugs is compared to be greater than 4. If it is then it will set the tooltip placement of the $('#click') element to bottom, otherwise it will set it to right. You can check it out by sticking this code at the bottom of the page:

alert('this is 3 characters: ' + tooltipManager.placement.setPlacement('asd'));
alert('this is 5 characters: ' + tooltipManager.placement.setPlacement('asdfg'));

All that placement does is it returns the words "left","top","right", or "bottom" depending on what it's set to in the placement object. You can change that object to this and it will still work:

placement: {
    l: 'left',
    t: 'top',
    r: 'right',
    b: 'bottom',
    setPlacement: function (data) {
        if (data.length > 4) {
            return this.b;
        }
        else {
            return this.r;
        }
    }
}

The setPlacement method doesn't actually set anything. What does is your jQuery's tooltip method.

You can change up all of line 48 like this (you also had a typo):

$('#click').on('click', tooltipManager.title);

You can delete the sizer function as I don't see a use for it. Something like that should be a method of the tooltipManager object anyways. On the same subject, since setPlacement doesn't actually set anything, you should probably change it to getPlacement or calcPlacement. It's more semantic and will help other developers that come behind you.

I would personally redo the entire tooltipManager.placement object to show the actual data that would be unknown. As an example, why on Earth would you need a static object to tell you what the number 2 is? Same for the string 'bottom'. tooltipManager.placement.bottom is the same thing as 'bottom'. Here's how I would structure that:

var tooltipManager = {
    setTitle: function () {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "Service.asmx/GetDrugs",
            dataType: "json",
            success: function (data) {
                $('#click').attr('title', data.d)
                .tooltip({
                    trigger: 'click',
                    html: false,
                    placement: tooltipManager.setPlacement(data.d)
                }).click();
            },
            error: function (xhr) {
                console.error('Failed tooltip request: ' + xhr.status);
            }
        });
    },
    setPlacement: function (data) {
        if (data.length > 4) {
            tooltipManager.placement = 'bottom';
            return 'bottom';
        } else {
            tooltipManager.placement = 'right';
            return 'right';
        }
    }
}

$('#click').on('click', tooltipManager.setTitle);

Note: I actually kept the setPlacement method, I just changed it so that it actually sets data. You can access the placement of the tooltip in javascript with tooltipManager.placement if you want. If you intend on having multiple tooltips you can just convert this all into a class. Also, I changed the tooltipManager.title method into tooltipManager.setTitle because it actually sets data.


And there's always a place for a regular expression (especially when searching for a pattern in a string of characters ;-)).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            string pattern = @"\{(?<expr>[a-zA-Z0-9.]+?)\}";
            string formula = @"{City.a}+5*(2/{City.b})";

            var matches = Regex.Matches(formula, pattern).OfType<Match>();
            foreach (var match in matches)
            {
                Console.WriteLine(match.Groups["expr"]);
            }
            // prints
            // City.a
            // City.b

            string splitPattern = @"\{(?<object>[a-zA-Z0-9]+?)\.(?<field>[a-zA-Z0-9]+?)\}";

            matches = Regex.Matches(formula, splitPattern).OfType<Match>();
            foreach (var match in matches)
            {
                Console.WriteLine("Object: {0}   Field: {1}", match.Groups["object"], match.Groups["field"]);
            }

            // prints
            // Object: City   Field: a
            // Object: City   Field: b
        }
    }
}


Is this an efficient way of mounting a file-system via SSH (SSHFS)?

Efficiency is just not an issue in this kind of task.  As "glue" code, it's not computationally intensive.  There are, however, some maintainability issues.

In mount(), the basic outline is:

def mount():
    if os.path.exists('/home/user/MNT/MEDIA/'):
        ...
        exit(0)
    if not os.path.exists('/home/user/MNT/MEDIA/'):
        ...

… which should be expressed as:

def mount_or_unmount():
    if os.path.exists('/home/user/MNT/MEDIA/'):
        ...
    else:
        ...

Using recursion for error handling is weird.  That would normally be handled using a while-loop.  It's also slightly odd that the empty string triggers a retry, but any other invalid input would exit the script.
The two sudo sshfs commands differ only slightly.  Your code should be structured accordingly.

REMOTE_FS = {
    'i': 'user@10.0.0.100:/media/Hitachi/',
    'e': 'user@xxxxxxxx.com/media/Hitachi/',
}

...
while True:
    ip = input("Type I/i for local connection, E/e for external\n")
    fs = REMOTE_FS.get(ip.lower())
    if fs is None:    # Input was not 'i' or 'e'
        continue
    subprocess.call(['sudo sshfs -o idmap=user -o uid=1000 -o gid=1000 -o allow_other -o default_permissions -p 100 %s /home/user/MNT' % (fs)], shell=True)
    break


Creating and displaying a checkers board

A few small points

replicate is deprecated. Use repeat instead.
Use - instead of _ in names.
The cond in str-piece compares piece against a number of
constants. Use case instead.
Simplify the :when conditions to (= (even? x) (even? y))

This gives us

(ns sandbox.checkers)

(def standard-size 10)

(defn empty-board [size]
  (vec (repeat size (vec (repeat size :empty)))))

(defn str-piece [piece]
  (case piece
    :empty " "
    :white-man "O"
    :black-man "0"))

(defn str-board [board]
  (str "\n"
    (clojure.string/join
      "\n"
      (map
        #(clojure.string/join " | " (map str-piece %))
        board))))

(defn print-board [board]
  (println (str-board board)))

(defn fill-white [size]
  (apply comp
         (map
           (fn [pos]
             (fn [board] (assoc-in board pos :white-man)))
           (for [x (range size)
                 y (range (inc (/ size 2)) size)
                 :when (= (even? x) (even? y))]
             [y x]))))

(defn fill-black [size]
  (apply comp
    (map
      (fn [pos]
        (fn [board] (assoc-in board pos :black-man)))
      (for [x (range size)
            y (range 0 (dec (/ size 2)))
            :when (= (even? x) (even? y))]
        [y x]))))

(defn starting-board [size]
  ((fill-black size) ((fill-white size) (empty-board size))))

(print-board (starting-board standard-size))

Edited subsequently:

There are simpler ways to generate the lists of squares for fill-white and fill-black.

For a given row y, the required xs are (range (mod y 2) size 2). The functions become

(defn fill-white [size]
  (apply comp
         (map
           (fn [pos] (fn [board] (assoc-in board pos :white-man)))
           (for [y (range (inc (/ size 2)) size)
                 x (range (mod y 2) size 2)]
             [y x]))))

(defn fill-black [size]
  (apply comp
         (map
           (fn [pos] (fn [board] (assoc-in board pos :black-man)))
           (for [y (range 0 (dec (/ size 2)))
                 x (range (mod y 2) size 2)]
             [y x]))))

A thorough reworking

The fill... functions construct and apply a sequence of functions, one function for each change to the empty board.

It is simpler to describe the repetitive pattern using functions cycle and take, with vec to convert to vectors:

(defn starting-board [size]
  (let [block (fn [rows piece]
                (let [source (cycle [piece :empty])
                      row-pair (map (comp vec (partial take size))
                                    [source (rest source)])]
                  (take rows (cycle row-pair))))
        block-size (dec (quot size 2))]
    (vec (concat (block block-size :black-man)
                 (block 2 :empty)
                 (block block-size :white-man)))))

Notice that the same row vectors are used again and again, not copies. This works in Clojure because vectors (and other native data structures) are immutable.


First of all I would recommend not to use regex for handling HTML. You can use a library like BeautifulSoup for this.
As all we're doing is finding the first match using tag name and class name we can define a function that uses BeautifulSoup to find such matches bases on the tag and class name. BeautifulSoup provides two functions find and findAll, find returns the first match and findAll returns all the matches.
Note that in regex just to find the first match you should not use re.findall, better use re.search which only returns the first match found otherwise None.
On the last return line we can use string formatting.

from BeautifulSoup import BeautifulSoup
from functools import partial

def find_by_tag_name_class(soup, tag, cls_name, many=False):
    if many:
        matches = soup.findAll(tag, {"class": cls_name})
        return [match.text for match in matches]
    else:
        match = soup.find(tag, {"class": cls_name})
        return match.text

def read_mail(html):
    soup = BeautifulSoup(html)
    # Instead of passing the same `soup` multiple times to
    # `find_by_tag_name_class` we can create a partial function
    # with `soup` already applied to it.
    find_by_tag_name_class_soup = partial(find_by_tag_name_class, soup)
    dropped = find_by_tag_name_class_soup('td', 'item_dropped')
    destroyed = find_by_tag_name_class_soup('td', 'item_destroyed')
    total = find_by_tag_name_class_soup('strong', 'item_dropped')

    return "Info: {} {} {} " .format(dropped, destroyed, total)

html = '''Foo bar	spam eggs
Hakuna	Matatat
Some strong textEven more strong text'''

print read_mail(html)
# Info: Foo bar Hakuna Some strong text

Note that in the latest version of BeautifulSoup findAll has been renamed to find_all.


Read files from a directory using Promises

For the most part, your use of promises is idiomatic. Good work! Most people new to promises fail to chain them and end up with a similar pyramid to your original code.

fs.exists is deprecated, you should either use fs.stat, fs.access, or just catch the exception when trying to read it. Additionally, the use of fs.exists introduces a race condition where the file could be deleted between the exists call and the read call.
If the first file turns out to be very large, you may run into memory issues since you first read the file into memory and then write it out to another file. Thankfully, you can use fs.copyFile to resolve this, and also reduce the amount of code you have to write. If you are stuck with a version of Node older than 8.5.0, you can use fs.createReadStream and fs.createWriteStream to copy the file without the memory issues.
As elclanrs mentioned in the comments, you can use util.promisify to automatically wrap some functions in a promise based api. It was added in 8.0.0, but is fairly simple to implement.
You should not construct a promise to just return a value.

new Promise(function(resolve, reject) {
    resolve(1);
})

is equivalent to

Promise.resolve(1)

In your case, since you don't actually use the return value, it is better to just begin the promise chain with getAListOfFiles(), and even if you did use the return value, you should just start with getAListOfFiles(1).

Here's how I would write this script with promises:

const { promisify } = require('util');
const fs = require('fs');

const readdir = promisify(fs.readdir);
const copy = promisify(fs.copyFile);

readdir('.')
.then(files => copy(files[0], 'Test'))
.then(() => console.log('Data copied!'))
.catch(console.error);

Bonus: It's a really good idea to understand how promises work before using async / await, but once you do, async functions can help make the logic look more synchronous. In this case, there isn't really a benefit, but for more complex situations, it can help immensely.

const { promisify } = require('util');
const fs = require('fs');

const readdir = promisify(fs.readdir);
const copy = promisify(fs.copyFile);

async function main() {
    try {
        const files = await readdir('.');
        await copy(files[0], 'Test');
        console.log('Data copied!');
    } catch (err) {
        console.error(err);
    }
}

main();


Filling a container with objects using pointers / iterators

std::list is usually implemented as a doubly-linked list which is very inefficient for your purpose.  You should definitely use std::vector for this (or similar dynamic array structure, possibly some stream).

Your second approach is the idea I got while reading your question. You don't need an iterator (and I don't think you can call push_back on it), but a reference to the vector - vector<byte>& buffer as the argument.

The same applies to serizalize() on the main list with possible default argument creating the vector. If you want to have the final packet somewhere, you can track some dirty flag (if you can modify the structure) to re-serialize it as needed.

You could do that last approach in two phases:

Track the sizes to compute the total size needed
Allocate the buffer (you could use byte* or vector)
Do the same again, but passing index together with the vector (buf[i++] = data)

...it is a bit more low-level solution, but possibly fastest. I would personally not worry that much and use the direct approach with vector (it should be fast enought).

Some notes about errors in the code:

class Sublist {
  std::vector<Items*> items;
  std::list<unsigned char> subpacket;

  std::list<unsigned char> Sublist::serialize() {

You do use Sublist:: prefix when you define the methoud outside of the class, not here (remove it).

class Sublist { ...
    std::vector<unsigned char>& serialize(std::vector<unsigned char>& buffer) const { ...

This should be the final signature (taking reference, returning the reference and with const modifier on the method because you are not modifying the class).


Point and Size structures

I would go even further than @glampert and create Point and Size structures as well as a Rectangle one. Experience has shown that this kind of small classes are extremely useful and can be used at many places in a GUI library (for example, getting the coodinates of the mouse can return a Point, computing the centre of a rectangle too, etc...). Moreover, once you have Point and Size classes, you can overload some of their operators to implement expressive and unambiguous operations such as multiplication by an integer.

In the long run, you will see that it is easier to reason with these objects, and you can even return them from functions while you can't return x and y if they're not in a structure.

Back to the Rectangle

Here is a concrete example of what your class does but should be actually performed by a Rectangle class instead:

template <typename T>
bool pointInElement(T x, T y) {
    return (x > this->x && y > this->y && x < this->x + this->width && this->y < this->y + this->height);
}

This should look like this, assuming that you have a Rectangle member named box and that your Rectangle class has a method named contains which takes a Point and returns a bool:

template<typename T>
bool pointInElement(const Point<T&>& point) const {
    return box.contains(point);
}

Constructor initialization list

Whenever possible, try to use the constructor initialization list. As it is now, your code constructs an Element instance, then assigns values to its fields. If you leave the job to the constructor initialization list, your object will be directly constructed with the appropriate values:

Element(int x, int y, int width, int height, Element* parent):
    x(x), y(y),
    width(width), height(height) {

    if (parent != nullptr) {
        parent->children.push_back(this);
    }
}

As you can see, it even allows to drop the this-> needed to differentiate the variables. The syntax only allows the member names on the left and the name resolution picks the parameters first on the right.

About the virtual destructor

I bet that you will want runtime polymorphism with your widgets. In this case, follow @glampert's advice: make the destructor virtual and public. If it does not do anything, the simplest thing to do is to explicitly default it:

virtual ~Element() = default;

Now, if a destructor is public and virtual in a base class, then the derived class automagically have a virtual destructor, you don't have to write anything. Therefore, the simplest thing to do would be to simply remove the destructors from TopLevelWindow, Window and Button if they don't do anything more than Element's destructor; you program will then be correct but simpler.


Disclaimer: I don't know Objective-C. The proposed changes are quite basic, though, and should give the same result as your original code.

Intermediate variables

To shorten your expressions, you may want to use an intermediate variable:

NSString *absUrl = request.URL.absoluteString;

Then, you can group your conditions using boolean operators.

Boolean logic

if (   [absUrl rangeOfString:MAPS].location != NSNotFound
    || [absUrl rangeOfString:DOCUMENTS].location != NSNotFound
    || (    [absUrl rangeOfString:DOMINIO].location == NSNotFound
         && [absUrl rangeOfString:LOGIN_SALES_FORCE].location == NSNotFound))
{
    NSURL *url = [NSURL URLWithString:request.URL.absoluteString];
    return [[UIApplication sharedApplication] openURL:url];
}

Remarks

Reading this documentation, I find it strange that you are converting request.URL to url using URLWithString. I may be wrong, but you could use absoluteUrl to achieve the same effect.


Enter year, date, and month in any order, I'll organize it

Besides the obvious points already mentioned in the other answers

Don't populate member variables in a constructor from streamed input

Passing std::istream to populate members in the constructor looks weird:

date(istream &is) { is >> year >> month >> day; }

The canonical way is to provide an input operator:

class date {
     friend std::istream& operator>>(std::istream& is, date& d) {
          is >> d.year >> d.month >> d.day;
          return is;
     }
     // ....
};

This allows to check the stream state for input errors after using it.

Don't promise things to users of your API, you cannot ever guarantee

As going for the logic you're trying to implement:

You are aware that it's not really possible to distinguish day, month and year inputs just by the bare numbers?

Some test cases in day, month, year order:

1 3 2
5 11 23
...

Well, month must be below or equal 12 and days below or equal 31, but what about days up to 12 or years input up to 12/31?

You actually have to require a specific date format for user input

Users won't be happy with wrong guesses from your code, and what you're promising isn't possible at all.

This is a major flaw in your code, and renders any other discussion merely useless.


As everyone has immediately pointed out, please stick with the namingConventions for methods and parameter names.

Your code is not object oriented, as Java code should be.  One sign is that you are using static functions everywhere.  Another hint is that the name of a class should always be a noun; if it's a verb then your objects are likely to be crappy.  You want to define a MaxHeap class.  Its outline should look like this:

public class MaxHeap {
    private int data[];
    private int size;

    public static void sort(int data[]) { ... }

    public MaxHeap(int data[]) { ... }
    public int removeNext() { ... }
    public int size() { return this.size; }

    private int leftChild(int i) { return 2 * i + 1; }
    private int rightChild(int i) { return 2 * i + 2; }
    private void heapify(int i) { ... }
}

Decide what operations you want to publicly support in your interface.  You'll need the constructor.  Since you will be doing removal of the root node in your HEAD_SORT() function anyway, you might as well support that in the public interface as removeNext().  A size() method is trivial to implement.  It would be nice to implement add(int datum) as well, but for now let's leave it out since it's not necessary for your immediate goal of implementing heapsort.  We should also provide sort(int[] data) as a class method, because that is the point of this exercise.  (There's no need to call it heapSort(int[] data), as "heap" is already part of the name of the class.)  Everything else should be declared private — the inner workings of the class are nobody else's business.

The heap constructor is just your BUILD_MAX_HEAP() code.  The only real correction I would make is that you can start i one element before where you did.

public MaxHeap(int data[]) {
    this.data = data;
    this.size = data.length;
    for (int i = size / 2 - 1; i >= 0; i--) {
        heapify(i);
    }
}

Now, on to the heapify() method.  There's no need to call it maxHeapify(), since it's a member of the MaxHeap class.  It can just take one parameter, since the data array is now an instance variable.  Also,

private void heapify(int i) {
    // You might as well start with this optimistic assumption
    int largestElementIndex = i;

    // The optimistic assumption leads to nice parallelism between the
    // left-child and right-child cases.
    int l = leftChild(i);
    if (l < size && data[l] > data[largestElementIndex]) {
        largestElementIndex = l;
    }
    int r = rightChild(i);
    if (r < size && data[r] > data[largestElementIndex]) {
        largestElementIndex = r;
    }

    // If heap consistency was locally violated
    if (largestElementIndex != i) {
        int swap = data[i];
        data[i] = data[largestElementIndex];
        data[largestElementIndex] = swap;

        // Recursively heapify the affected sub-tree
        heapify(largestElementIndex);
    }
}

Here's removeNext().  It returns the next largest element (the root node value) and shrinks the heap.

public int removeNext() throws NoSuchElementException {
    if (size == 0) {
        throw new NoSuchElementException();
    }
    int next = data[0];
    data[0] = data[--size];
    heapify(0);
    return next;
}

Finally, here's sort().

public static void sort(int[] data) {
    MaxHeap heap = new MaxHeap(data);
    for (int i = heap.size() - 1; i >= 0; i--) {
        int nextMax = heap.removeNext();

        // This is a rather naughty move, since heap.data is
        // aliased to data.  We do this only because we know
        // from the way the heap works that the end of the array
        // can be used to store our sorted result in place.
        data[i] = nextMax;
    }
}

One thing I'm not happy about in the above code is the fact that the MaxHeap adopts the input array rather than making a copy.  That is probably surprising behaviour to users of the class, who probably don't expect the contents of the passed-in data array to be modified.

On the other hand, it's nice to be able to implement sort() in place without allocating another array.

One cop-out would be to make the constructor private, essentially declaring that the code in this class is only usable through the sort() function.

A workaround is to implement two variants of the constructor, such that you have to explicitly ask for the array to be adopted:

/**
 * Copies the data
 */
public MaxHeap(int data[]) {
    this(data, true);
}

/**
 * If copyData is false, MaxHeap adopts the data array, and may overwrite its
 * contents; it does not make a copy!
 */
public MaxHeap(int data[], boolean copyData) {
    this.data = copyData ? Arrays.copyOf(data, data.length) : data;
    ...
}

public static void sort(int[] data) {
    MaxHeap heap = new MaxHeap(data, false);
    ...
}


Method to return statistics from a collection with O(1) time and space

Initializing in the declaration

    private DelayQueue<Transaction> transactions;

    public TransactionManager() {
        transactions = new DelayQueue<>();
    }

You could replace this entire block with just

    private BlockingQueue<Transaction> transactions = new DelayQueue<>();

This has the identical effect.  No big advantage, just less code.

Using the interface rather than the implementation is good practice, as it makes the code more flexible.

Statistics

You have

        Statistic statistics = new Statistic();
        transactions.forEach(transaction -> {
            statistics.setCount(statistics.getCount() + 1);
            statistics.setSum(statistics.getSum() + transaction.getAmount());
            statistics.setMax(statistics.getMax() > transaction.getAmount() ? statistics.getMax() : transaction.getAmount());
            statistics.setMin(statistics.getMin() < transaction.getAmount() ? statistics.getMin() : transaction.getAmount());
        });
        if (statistics.getCount() > 0) {
            statistics.setAvg(statistics.getSum() / statistics.getCount());
        }

And

  Statistic.class with getters and setters.

public class Statistic {
private double sum = 0.0;
private double avg = 0.0;
private double max = 0.0;
private double min = 0.0;
private int count = 0;}

Consider getting rid of the setters.  Instead, move that block from the getStatistics method into an addDatum method in the Statistics class.

public class Statistics {

    private double sum = 0.0;
    private double maximum = 0.0;
    private double minimum = 0.0;
    private int count = 0;

    public void addDatum(double amount) {
        count++;
        sum += amount;

        if (amount > maximum) {
            maximum = amount;
        } else if (amount < minimum) {
            minimum = amount;
        }
    }

    public double calculateAverage() {
        return (count > 0) ? (sum / count) : 0.0;
    }

}

This way the Statistics class knows how to do calculations.  In the original, it was only a dumb container.  So you had to get the value, update it, and then set to the result.

I also fixed the indentation and spacing of the class.

I updated the name.  Average is a statistic.  This is a collection of statistics.

I moved the average calculation into a replacement for getAvg.  It calculates it on the fly.  You could memoize the result if you wanted, but you'd have to invalidate it with each addition.  Or you could recalculate the average each time you add something.

Updating as you go

You are considering making changes to update as you go.  This is still consistent with that.

You may also want to consider how you use this.  You say

     * Return statistics of transaction for the last 60 seconds.

But there are easier ways to do that than to use a DelayQueue.  Rather than use a sorted queue, use buckets.  E.g. with a HashMap<MinuteTime, Transactions>:

buckets.get(timeToTheMinute).add(transaction);

Then you can calculate the statistics in the add method.  And you don't have to worry about expirations to separate one period from another.


First of all, I think you are putting time.sleep() calls into the wrong places - you are putting them into the loops where you iterate over the extracted elements. Elements are already extracted and no requests are issued at that point - add delays between each requests - at the end of your functions.

I would also improve naming - Yp_link and Tuts_link can be renamed to more explicit YELLOW_PAGES_URL and WISEOWL_URL - note that I think these two need to be defined as proper constants - in upper case.

And, I would also switch to CSS selector locators for process_links() function as well.

As far as imports go, just don't put them on same lines - put each import on it's own line as per PEP8 importing guidelines.


Learning Java: Celcius to Fahrenheit Conversion

double celciusInputs, fahrenheitInputs = celciusInputs = 0;

Variables declared and initialized this way are hard to read. Prefer:
double celciusInputs = 0;
double fahrenheitInputs = 0;

double celciusInputs, fahrenheitInputs = celciusInputs = 0;

The Inputs in the name signals to me that it is an array of values. It is not. Prefer celciusInputsSum and fahrenheitInputsSum

System.out.print("Enter Temp in Centigrade or <= -100.0 to quit: ");

Spell out Temp as temperature to avoid confusion. Centigrade should also be worded as "Celsius" to avoid confusion (even variable names use "celsius", not "centigrade")
Why is minimum allowed temperature -100.0 °C? Absolute zero is at -273.15 °C

input = in.nextDouble();

Error handling should be added. What do you want to do when user enters foobar as input?

double conversion = ((9.0/5.0) * input) + 32.0;

From this line alone, we do not know the units. Prefer fahrenheitConverted or similar

counter += 1;

Instead of summing the inputs, perhaps consider ArrayList to store the inputs. The sum can only go so far before celciusInputs and fahrenheitInputs overflow. It also provides more flexibility if you want to do other calculations (such as calculating mode and median, along with the mean/average)

celciusInputs /= counter;
fahrenheitInputs /= counter;

Doing it like this means the variable names no longer reflect its contents. Prefer using new variables like this: double celsiusInputAverage = celciusInputs / numInputs

public static void main(String[] args) {

This line is missing indentation (2 spaces)


0/1 knapsack algorithm implementation with possibilities vector

Since you declare a three parameter constructor, the default constructor will not be implicitly defined, so it does not need to be explicitly deleted.  There's no real harm in providing a default constructor, since you have initializers for all your members.  Alternatively, since the only constructor you supply requires three parameters that initialize all three members of your class, you do not need to provide initializers for them (although doing so can lead to fewer problems in the future if this is expanded on).

The comparison operators should a be declared as const functions.  The use of this-> in them is not necessary.

The output operator should take item as a reference to avoid making a copy.

The weight and profit functions assume that both provided vectors have the same size.  The size used to end the loop can be stored in a variable to avoid potentially recomputing it every time.

In increment, predecrement should be used for iterators (--it_bit;) to avoid making an unnecessary copy.  Have you considered using reverse iterators here (using vec.rbegin())?

The last for loop in main can use the range-for-loop (e.g. for (auto p: possible)).


On the idiomatic front this code is excellent. All looks good.

You should use a priority queue to implement Dijkstra's algorithm. It is both far more efficient, and also more concise. I would go so far as to say that the beauty of Dijkstra's algorithm is underpinned by the priority queue data structure (which in turn is underpinned by the concept of a heap). There is much written about these topics, so I won't expand on that here unless it is not clear why. Java has a priority queue implementation that you can use via interop.

You only need a open list of candidates (in a priority queue so you can efficiently take the next minimum distance expansion, efficiently update shorter candidates as discovered, and remove visited nodes), and one map of visited nodes parents (you currently have a set and a parents map, the set is just the keys of parents).

The add/update/remove operations on a priority queue don't need to be implemented by you (they are methods of the datastructure), so less code :)


I am happy you posted your best script, you can still see a ton of repetition here.. If you were to always name the navbutton after the scroll target and title ( "aboutnav" -> about & abouttitle ) then this can be much shorter. For now I can only see resultsnav break the mold.

I would suggest something like this :

window.onload = function () {

    [].forEach.call(document.querySelectorAll('.navico'), function (el) {
        el.addEventListener('click', imageButtonClickHandler);
    });

    function imageButtonClickHandler() {
      var buttonId = this.id,
          target   = buttonId.substring( 0 , buttonId.length - 3 ),
          titleId = '#' + target + 'title',
          scrollTarget = '#' + target;

      var navMap = {
          'aboutnav'   : '#a',
          'routenav'   : '#b',
          'enternav'   : '#c',
          'racedaynav' : '#d'
          //etc. etc.
      }

      grey();
      $( titleId ).css('color', 'blue');
      $( navMap[ target ] ).css('color', 'blue');
      $('html, body').animate({
        scrollTop: $(scrollTarget).offset().top - 90
      }, 2000);
   }
};

function grey() {
    $('.sectitle').css('color', 'grey');
    $('.roger').css('color', 'grey');
    return;
}

Basically, I derive the link id, the scroll target id from the name of the nav link. Then, I also mapped the nav names to 'a','b','c' etc. From there this becomes a really short piece of code. I also changed the tabs to 4 spaces, if you use more than 4 spaces, then it becomes harder to grok the code and realy understand what you are doing. I also opted for single quote strings, easier to read and less carpal tunnel by hitting shift all the time ;)

Note that you could write grey like this:

function grey() {
    $('.sectitle, .roger').css('color', 'grey');
}

You can comma chain selectors, also the function will return regardless at the end, you dont need to put return.


You might not need to loop through an object, and a simple switch statement would suffice.

function getSize(number) {
    switch (true) {
        case number < 100: return "url_t";
        case number < 240: return "url_s";
        case number < 320: return "url_n";
        case number < 500: return "url_m";
        case number < 640: return "url_z";
        case number < 800: return "url_c";
        default:           return "url_l";
    }
}

As a side note, I've seem people use switch (true) before when they want to use some logic in their case's instead of just hard coded values. Kind of a nice alternative to an if-else construct, and would probably perform better than looping over an object using a for-in loop.

You could still keep the sizes in an object:

var sizes = {
    100 : 'url_t',
    240 : 'url_s',
    320 : 'url_n',
    500 : 'url_m',
    640 : 'url_z',
    800 : 'url_c',
    1024 : 'url_l'
};

function getSize(number) {
    switch (true) {
        case number < 100: return sizes[100];
        case number < 240: return sizes[240];
        case number < 320: return sizes[320];
        case number < 500: return sizes[500];
        case number < 640: return sizes[640];
        case number < 800: return sizes[800];
        default:           return sizes[1024];
    }
}

Edit: A problem arises if you need to change the sizes for your application. That's why I'm leaning towards the first function, which just a switch statement and hard coded values.


Only two values of the sorted array are needed to decide the resultant tags, so the algo is:

scan all entries and find the maximum and pre-maximum.
scan all entries and tag them accordingly in a new object

Tests show 10x speed-up, but of course it's noticeable only on large number of repetitions.

tagValues(data : any) {
    let keys = Object.keys(data);
    let len = keys.length;
    let max = -Infinity, max2 = -Infinity;
    for (let i = 0; i < len; i++) {
        let value = data[keys[i]];
        if (value > max) {
            max2 = max;
            max = value;
        }
    }
    let tagged = {};
    for (let i = 0; i < len; i++) {
        let key = keys[i];
        let value = data[key];
        tagged[key] = value === max ? 'big' : value === max2 ? 'medium' : 'small';
    }
    return tagged;
}

P.S. As for sortByValues, instead of reversing an array after sorting it, invert the comparison.


Find majority element in an array given constant external space

What is a "majority element" ?

It would be good to define this, as there could be multiple interpretations:

It could be the element that occurs more than any other in the array. This seems the most natural, intuitive interpretation
It could be the element that occurs more than n / 2 times, as in this online challenge. I think they made a mistake, the common name for this is leader element instead of "majority".

Off-by-one error

The program gives incorrect result for the input [3, 2, 3].
The culprit is here:

int count = 0;
while ( (i+count) < a.length && a[i] == a[i+count]) {
    count++;
    if (count == a.length/2) {
        return a[i];
    }

The sorted array contains [2, 3, 3].
At i=0, since (i+0) < a.length and a[i] == a[i+0],
count is incremented to 1 on the next line,
and since a.length/2 is 1, the method prematurely returns 2.

The fix is to move count++ to the end of the while loop.

Notice that starting from count = 0 is pointless.
It would be better to start from count = 1.

Index out of bounds for singleton array

The program will crash for the input [1].
In this case maxIdx will never change,
its value remains at Integer.MIN_VALUE,
and so it will crash on the line return a[maxIdx].

Slowness

The program is too slow for large arrays, because after counting the consecutive numbers,
it does not skip those,
and continues checking from the next value of i.
Due to this, the time complexity of the loop degenerates to \$O(n^2)\$.

You can improve by adding to i the number of elements that can be skipped.

int count = 1;
while ((i + count) < a.length && a[i] == a[i + count]) {
    if (count == a.length / 2) {
        return a[i];
    }
    if (count > maxCount) {
        maxCount = count;
        maxIdx = i;
    }
    count++;
}
i += count - 1;

Alternative implementation

If you're really looking for the majority element and not the leader element, then your implementation can be written slightly simpler without a nested loop:

public int findMajority(int[] nums) {
    Arrays.sort(nums);

    int maxCount = 0;
    int maxIndex = 0;

    int count = 1;

    for (int i = 1; i < nums.length; i++) {
        if (nums[i - 1] == nums[i]) {
            count++;
            if (count > maxCount) {
                maxIndex = i;
                maxCount = count;
            }
        } else {
            count = 1;
        }
    }
    return nums[maxIndex];
}

Finding the leader element

If you're actually looking for the leader element,
the element that occurs more than n / 2 times,
then an \$O(n)\$ solution is possible:

track a candidate and its count
increment the count when the same candidate is seen
decrement the count when a different value is seen
replace the candidate when the count is 0

Like this:

public int majorityElement(int[] nums) {
    int candidate = 0;
    int count = 0;
    for (int num : nums) {
        if (count == 0) {
            count = 1;
            candidate = num;
        } else if (candidate == num) {
            count++;
            // as a further optimization, you can add a condition here to return early if the required count is reached
        } else {
            count--;
        }
    }
    return candidate;
}

This works when the leader element is guaranteed to exist.
If it's not guaranteed to exist,
then you need another \$O(n)\$ pass to verify the count of the candidate is indeed greater than half of the number of all elements.


Your code has no chance of working, because the only non-static data member of your function<void(void)> is a single pointer of type void (*)(void). There's no room to store any other kind of functor.

In other words, you've implemented the concept of "function pointer wrapped in a struct", but you haven't implemented anything like std::function yet.


Simple Question about Numeric Operations

Division by zero gets you infinity.

Note that (5/9) is an int expression, and resolves to int 0!

To fix things, make your literals doubles :

double celsius = 30d;
double fahrenheit = (celsius + 32.0d) / (5d/9d);


Increment value in a list of dictionaries

Should have spaces around =, and += would shorten it a bit. And I'd be consistent with the variable name (not switch from d to v) and use better names for the lists (l looks too much like 1 and is just too short for something presumably living longer (unlike d, which I find ok in such small contexts)):
lst2 = [d.copy() for d in lst]
for d in lst2:
    d['a'] += 4

I'd say that's alright then. But here are two alternatives:
>>> [d | {'a': d['a'] + 4} for d in lst]
[{'a': 5, 'b': 2}, {'a': 9, 'b': 6}, {'a': 7, 'b': 2}]

>>> [{**d, 'a': d['a'] + 4} for d in lst]
[{'a': 5, 'b': 2}, {'a': 9, 'b': 6}, {'a': 7, 'b': 2}]


Improving the manipulation of 2D Arrays for an easy challenge on HackerRank with Python 3

Generating all possible hourglasses

Don't :-) It's a lot of memory and processing churn.

A more efficient alternative is to write a function that takes as parameters a matrix and the starting position of an hourglass, and return the sum of values at the appropriate relative positions:

def compute_hourglass_sum(matrix, top, left):
    return sum(matrix[top][left:left+3]) + ...

The caller is responsible for passing parameters to valid hourglasses.

As for the unnecessary recomputing of sums of overlapping hourglasses, given the small sizes of hourglass dimensions, I don't think it's worth it to come up with something more clever.

However, if the dimensions became significantly bigger, then that would indeed make sense. Perhaps prefix sums would be useful for that. I suggest to check out the concept, it's very interesting stuff.

Processing the input

In make_matrix it's not so great that the input parameter is named matrix when in fact it's just unprocessed text. I'd name it input. And then the local final_matrix variable could be renamed to simply matrix.

And I would rewrite the function with a list comprehension:

return [map(int, line.split()) for line in input]

(Thanks @Graipher for simplifying line.strip().split(" ") to line.split().)

Minor things

There is an official coding style guide for Python called PEP8. I suggest to check it out. There is a command line tool that can check your code.

There are some redundant parentheses here and there. I suggest to remove them. The pep8 tool can pinpoint them for you.

The default start value of range(...) is 0, so instead of range(0, 4) you can write simply range(4).


"Of three points supplied, is one a midpoint of the other two?"

All of the previous answers seem to work on averages of each of the 2 numbers (expressed as either division or multiplication). But I'm working on averages of all 3 numbers, on the assertion that the average of 3 numbers would be the midpoint of the min and the max...

It would seem to be fewer operations.

I'm not a Java developer, so be kind if I've missed something....

public static boolean hasMidpoint(int a, int b, int c) {
    int iTotal = a + b + c;
    // I took mleyfman's idea and replaced division with multiplication
    return (3 * a == iTotal) || (3 * b == iTotal) || (3 * c == iTotal);
}

Edit: Implementing suggestions, the code is now:

public static boolean hasMidpoint(int a, int b, int c) {
    long total = a + b + c;
    // I took mleyfman's idea and replaced division with multiplication
    // A midpoint will always be the average of the 3 values, so 3*midpoint must equal sum of a, b and c.
    return (3 * a == total) || (3 * b == total) || (3 * c == total);
}


I think you're right to be concerned with the names you're using.

I'd start with the name of the base class. CPrintReport strikes me as a rather poor name. First of all, it sounds like a verb phrase (Print Report). Most classes should be nouns. Second, you typically want the name to reflect the fact that it's an abstract base class. Finally, tacking a C onto the beginning of a class name is, frankly, a pretty lousy idea.

I'd probably start with a report namespace, and name this base:

namespace report {
    class Base {
        // ...
    };
}

The other reports would derive from it, so you might have something like:

namespace report {
    class Verification : public Base {
        // ...
    };

    class Identification : public Base {
        // ..
    };
}

Then when you want to print one, your code would be something like:

report::Verification verification_report;
verification_report.print(printer);

As far as the names of the individual functions go, I think the problem is fairly simple: right now, your names basically reflect the mechanics of generating the reports. I'd prefer to see names that reflect the sections of the report they generate instead.

For example, your PrintCommon, PrintCustom and PrintChart might become: PrintIntroduction, PrintDetails, and PrintSummary respectively. Of course, I don't know for sure how your reports are structured, so there might be other names that make more sense, but the basic idea still applies--to the extent possible, base the names on their effect in the final product rather than on the details of how you're implementing the code.


Stop repeating myself: Similar pattern used on multiple event handlers

Id suggest something like:

$('body').on('click.alert.data-api', '[data-dismiss="alert"]', function () {
  trackEvent('Alerts', $(this).next().text());
});

instead of the whole alert code, and similar things for the other items.


I'd have to rate your program a "D-Minus".

incorrectly labels 1, 0, and all negative numbers as prime!
runs in \$O(n)\$ time, instead of \$O(\sqrt n)\$ time
runs in \$O(n)\$ space, instead of \$O(1)\$ space

Other deficiencies:

'''docstrings''' should be used for describing "how" to use the module/class/method; comments should be used to explain how the code works
variable names are cryptic; too short to be descriptive
PEP8 guidelines are not consistently followed.  Operators like = should have 1 space on each side.  No space should be used after (, or before ), as well as not before :
a dictionary is being used to store a list of values; a simple list would suffice
dl.values() is an iterable; there is no need to convert it into a list in order to use in the for z in ...

As suggested by aaaaa says reinstate Monica,
please work on your solution and then submit it as a new question.


JavaScript form validation: improve on 'good, but not good enough'

Separation of Concerns
So I agree with rolfl, but I also want to expand a bit, and provide some small bit of skeleton code for you to go on.  When I do validation on the client, I usually set up variables for errors, conditions, and dependencies.  This allows me to use a simple handling structure that can be used if needed (as @rolfl suggested), and ignored if not, that way you aren't validating fields that don't need validation, or if they do, you're only performing exactly as much validation as needed.
This simple "boilerplate" that I've just created will also allow you to inject functionality to any of your variables by adding objects to your arrays.  As long as your validate function executes the conditions and dependencies injected, you should have a very nice reusable client validation boilerplate.
Then, you just attach an event listener to whatever form element you want to validate, and run a validate function on that callback.  It'll efficiently go through conditions that exist on elements, instead of the other way around, and you can be as flexible you want with your view code without tying it to your validation function.
One of the key principles of coding is Separation of Concerns.  Any of your code that performs app logic (the validation) shouldn't have any sort of view code in it if at all possible.  I believe this is the biggest single concept that would have made the difference in the feedback you received . If you maintain SOC in this case, no matter how the form changes, your validate function won't have to change, or will be at least very flexible, and if you all of a sudden needed to use the same form but on a mobile page, you could just change the renderErrors function to alter your view code to fit the new display without changing anything else.
That's what I would consider great.  See my fiddle: http://jsfiddle.net/LongLiveCHIEF/sqwYT/
I'll update it a bit, but wanted to give you a head start on my line of thought.


I may have went overboard on the Python-ification, but this is a refactoring of the current solution.

What I did was create a Card class which contained the suit and value of the card. To get the value, I added all items to an array and then got the index of the card's value from the array's offset, which allowed card_value to be removed.

There was lots of duplication when displaying that the user got the correct answer. I made this a function and was able to minimize the method's body by using an iterator which contained the current card and the previous card (thus avoiding having to set the previous card to the current card and then get the next card.)

Here is a rewritten version: (comments to follow)

import random
import itertools

card_faces = [
    '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King',
    'Ace'
]

class Card:
    """
  Defines a Card with a suit and face, and allows retrieving the points of the card
  """

    def __init__(self, face_suit):
        self.face = face_suit[0]
        self.suit = face_suit[1]

    def getPoints(self):
        return card_faces.index(self.face) + 2

    def __str__(self):
        return self.face + ' ' + self.suit

    def __gt__(self, other):
        return self.getPoints() > other.getPoints()

    def __lt__(self, other):
        return self.getPoints() < other.getPoints()

    def __eq__(self, other):
        return self.getPoints() == other.getPoints()

def generate_card_deck():
    """
    Creates a shuffled list of cards as [(c0, c1), (c1, c2), ...]
    """
    card_suits = ['♠', '♦', '♥', '♣']
    deck = list(map(Card, itertools.product(card_faces, card_suits)))
    random.shuffle(deck)
    return deck

def user_guessed_correctly():
    """
  Congratulates the user if they have a correct guess, and increments
  the counter
  """
    print("Correct!")
    global correct_guesses
    correct_guesses += 1

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

correct_guesses = 0
deck = pairwise(generate_card_deck())

while True:
    card, next_card = next(deck, (None, None))
    if not card:
        print("You've done it! You've won with", correct_guesses,
              "correct guesses!")
        break

    print("Your card is: ", card)
    user_guess = input('(H)igher, (L)ower, or (S)ame?:\t').lower()
    if user_guess not in ('h', 'l', 's'):
        break

    if (card < next_card and user_guess == 'h') or (
            card > next_card and user_guess == 'l') or (card == next_card
                                                        and user_guess == 's'):
        user_guessed_correctly()
    else:
        print('You lose: the next card was ', next_card)
        print('You had', correct_guesses, 'correct guesses.')
        break


I'd wrap the <Component>s in a <Components> tag. Maybe you want to add more attributes to spells later. In fact, I'd probably make <ItemComponents> and <SpellComponents>.

I'm also thinking you might be better off here and there by using some sort of "quantity". Lets say a spell had 10 components (for some arbitrary game design reason)...

    <Spell name="RestoreMana">
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
        <Component>Mana</Component>
    </Spell>

or

    <Spell name="RestoreMana">
        <Component quantity="10">Mana</Component>
    </Spell>

I like the second one more, it's smaller. Plus, I don't wanna be the one who has to check if the balancing is done right by counting whether this spell has 10 components via a process which includes manually counting lines.

From this point, however, you can go pretty much everywhere. Future proofing your schema is hard without fully knowing what data it will have to support, so I'd focus on getting the domain model right and then looking at the xml schema again.


What improvements are needed in this class to fill DropDown using PetaPoco?

Firstly, data access should be separate from your UI logic. Certainly create a new layer, where you'll manage CRUD operations.

Secondly, I'm not really fond of your naming convention of classes. Even though it may be a subjective matter, many people tend to use capitalized names for classes and certainly not using words like "getBlocks". This isn't a name for a class, that's a name for a getter method.

Thirdly, you're dealing with your parameters the wrong way, at least in my opinion. I believe it would be more appropriate to have private fields of type DropDownList and String, populate them in the constructor and then just use these private variables (and/or properties, depends on your needs) instead of specifying parameters for the method itself. Seems more OOP to me that way. Otherwise I don't really see a reason why not just create a helper class with a static method you'll call whenever needed, without the need to instantiate the class itself.

Another thing to consider - usually it's better to use an using statement instead of manually calling Dispose method.

Edit based on the comment:

1.) example using private fields

public sealed class Blocks
{
    private DropDownList _ddList;
    private int _districtId;

    public Blocks(DropDownList dropDownList, int districtId)
    {
        _ddList = dropDownList;
        _districtId = districtId;
    }

    public void PopulateDropDownList()
    {
        var results = MyDbAccessClass.GetBlocks(_districtId);

        _ddList.DataSource = results;
        _ddList.DataTextField = "blockname";
        _ddList.DataValueField = "blockid";
        _ddList.DataBind();
        _ddList.Items.Insert(0, "-- Select --");
    }
}

2.) example using static method

public sealed class MyHelperMethods
{
    public static void PopulateWithBlocks(DropDownList ddList, int districtId)
    {
         var results = MyDbAccessClass.GetBlocks(districtId);

        ddList.DataSource = results;
        ddList.DataTextField = "blockname";
        ddList.DataValueField = "blockid";
        ddList.DataBind();
        ddList.Items.Insert(0, "-- Select --");
    }
}

Hope you get the idea...


Implementing a Trie in Python using lists alone

Exceptions are for exceptional (read 'rare','unexpected') edge cases

You are using exceptions as the default behaviour, this is not nice, instead functions should return values, remove TrieException("word not find") from search_word(word, trie) and instead return True if you find the word and False if you do not find it.

Confusing alias

branch = trie

You just confuse the reader, each thing should have one name only.


How do you cancel a sleep once it starts?  I would expect that calling .expireAt(nil) might accomplish that.  However, if @expireAt is nil, calcTimeLeft() crashes.

Alternatively, one might try to call .onExpiry(nil), but you don't handle @onExpiry being nil either.


Refactoring step 1, remove unnecessary variables and braces and return early

public bool CheckMobileSim(List<Mobile_Range> numberRange, string MobileNumber)
{
    if(numberRange == null)
        return;
    string NineDigits = MobileNumber.Substring(0, 9).ToString();
    long Number = Convert.ToInt64(NineDigits);
    for (int i = 0; i < numberRange.Count; i++)
        if ((Number >= numberRange[i].RangeStart && Number < numberRange[i].RangeEnd))
            return true;

    return false;
}

I realize that breaks with the "single point of return" wisdom but I'm not a big fan. When you have small functions like this one, it doesn't make all that much sense.

Refactoring step 2, with that cleaned up it's easy to see how this fits into a simple LINQ query

public bool CheckMobileSim(IEnumerable<Mobile_Range> numberRange, string mobileNumber)
{
    if(numberRange == null || String.IsNullOrWhitespace(mobleNumber))
        return false;

    var nineDigits = mobileNumber.Substring(0, 9);
    var number = Convert.ToInt64(nineDigits);

    return numberRange.Any(n => number >= n.RangeStart && number < n.RangeEnd);
}

Since this is a public method I added some checks and downcast List to IEnumerable, which is a looser contract and all you really need here.

By the way, .Net naming conventions are pascalCase for private and local variables CamelCase for public and protected. It's rare to use underscores.


is there a better way than replace to write this function?

-- One --

You can use a dictionary to hold your translation data:

mydict = {'1':'triangle', '2':'square', '3':'rectangle',
          '4':'pentagon','5':'hexagon', '6':'octagon','7':'circle'}

Now your list of replacement lines becomes simply:

for key, value in mydict.iteritems():
    name = name.replace(key, value)

another option would be:

for key in mydict:
    name = name.replace(key, mydict[key])

To make this part complete, consider also a tuple for holding your data as indicated in @larmans answer. See also comments in the answers. I think there are interesting hints about which could be the best alternative for different cases.

-- Two --

also remember you can do

2 <= total <= 5

instead of

total >= 2 and total <= 5

-- Three --

Note you dont need parenthesis in the if expressions. Just do this:

if total == 1:


Group list into elements with same value

You've tagged this linq so you're clearly aware of Linq, but this is not a Linq-like approach. The closest approximation in Linq is GroupBy, so that can serve as a model:

Instead of string property take Func<TSource, TKey>.
Instead of List<List<T>> (which, apart from anything else, violates the principle of coding to the interface instead of the implementation) return IEnumerable<IGrouping<TKey, TSource>> (or, if you don't care about the value itself, IEnumerable<IEnumerable<TSource>>).

Also, in Linq style, favour lazy implementation with yield return.

I would advise you to rewrite from scratch with those principles in mind.

But I must address one major problem in this code, lest you repeat it in the rewrite:

    for (int i = 0; i < inputs.Count(); i++)
    {
        var current = inputs.ElementAt(i);

This is absolutely the wrong way to iterate over an IEnumerable. The right way is

    foreach (var current in inputs)
    {

Otherwise if inputs is lazy you do far more work than necessary, and potentially execute side-effects more times than you might expect.

Also,

    if (previousSelector == null)

is problematic. What if this method is used with objects which actually have null as a value of the relevant property? I think the best approach is to use the current IGrouping: either initialise that to null and test whether it's null, or initialise it to a grouping with key default(T) and replace the special case with a special case which doesn't return an empty grouping.


You could perhaps look at separating the win condition by sticking it in another method then call it in ActionPerformed.

Outside of that, you could replace:

if(count % 2 != 0){
        letter = "X";
    } else {
        letter = "O";
    }

with a ternary operator such as:

letter =(count%2!=0)?"X":"O";

That's all I can think off the top of my head.


Deserializing multiple elements from XElement

Your initial revision is fine. If you take a look at the implementation at Reference Source you'll see that the XmlReader returned by CreateReader is lightweight and that calling Dispose on it is not necessary.

...
var customers = xml.Elements("Customers");
...

It seems a little strange that you pick elements of type "Customers" and deserialize them as Customer. They should be "Customer" in the XML if they represent a single customer each.


Disabling a form button while there's an http request running

Yes, your approach looks correct to me. I also had faced similar issues earlier in my project (before hooks were introduced) and had used setState for a boolean variable to enable and disable the button.

The thing which you need to keep in mind is look out for edge cases related to your business requirements. e.g. suppose a async validation is happening but API gave you 401 or some other status code (i.e. validation didn't happen properly but API gave some response), so should you be enabling the button for user to retry or the button should remain disable.

Hoping that I am able to explain you properly. Please revert if something is not clear to you.


The reader/command/connection fields of DBConnectivity are not really being used to represent state of DBConnectivity. This is obvious because of usage like:

dbConnectivity.command = new SqlCommand(salesQuery, dbConnectivity.connection);
dbConnectivity.dataReader = dbConnectivity.command.ExecuteReader();
while (dbConnectivity.dataReader.Read()) {...}

frankly, they should just be local variables:

var command = new SqlCommand(salesQuery, connection);
var dataReader = dbConnectivity.command.ExecuteReader();
while (dataReader.Read()) {...}

Additionally, in all uses, you are not correctly disposing your resources. The IDisposable contract is important: if something is IDisposable, then it is your job to make sure it gets disposed when done. So with the above example:

using(var command = new SqlCommand(salesQuery, connection))
using(var dataReader = dbConnectivity.command.ExecuteReader())
{
    while (dataReader.Read()) {...}
}

This using makes a huge difference, and ensures you don't drop connections etc on the floor when exceptions happen.

Personally, I would not advocate doing this type of work in a constructor - that is not intuitive. A static method that returns a populated instance, sure - or an instance method that populates an existing instance. But a constructor? not so clear.

I also suspect that you could benefit from the use of tooling to avoid boiler-plate code that is error-prone and not important to your actual work. For example, tools like dapper allow much simpler object population. For example:

public class DBConnectivity
{
    private readonly string connectionString;
    public DBConnectivity(string connectionString = null)
    {
        if(string.IsNullOrEmpty(connectionString))
        {
            connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
        }
        this.connectionString = connectionString;
    }
    public SqlConnection OpenConnection() {
        var conn = new SqlConnection(connectionString);
        conn.Open();
        return conn;
    }
    public List<MasterTableAttributes> GetMasterTableList()
    {
        using(var connection = OpenConnection())
        {
            const string sql = "SELECT Id as [FileId], FileName, Frequency, Scheduled_Time as [ScheduledTime] FROM MASTER_TABLE";
            return connection.Query<MasterTableAttributes>(sql).ToList();
        }
    }
}

Here the only useful state is the connection string, with a method that creates new connections. Note how this is used with using to create and dispose the connection, with "dapper" then taking the load for handling the data.

If you really wanted to pass this around, you can:

    public List<SomethingSalesEsque> SomeMethodOnSales(DBConnectivity dbConnectivity)
    {
        using(var conn = dbConnectivity.OpenConnection())
        {
            return conn.Query<SomethingSalesEsque>(someQuery).ToList();
        }
    }

From your code, I'm guessing you have:

class MasterTableAttributes
{
    public int fileId;
    public string fileName;
    public string frequency;
    public string scheduledTime;
}

this would preferably be:

class MasterTableAttributes
{
    public int FileId {get;set;}
    public string FileName {get;set;}
    public string Frequency {get;set;} // maybe an enum?
    public string ScheduledTime {get;set;} // datetime? timespan?
}


My first program in C. A simple command-line calculator

power() problems
double power() does not return a value.
Incorrect result when y is not a value in the int range.
Code attempts a linear power calculation: O(y).  Research Exponentiation by squaring.  It is faster and less precision loss.
double r parameter serves no purpose. Instead make a local double r variable.
A floating point power function is one of the most changeling functions to code well.  Rough cut below.

root() problems
double root() does not return a value.
Other problems like power().

It floating point, not fixed point
More informative to use exponential notation for large and small value than a fix-point format.
// printf("%0.1lf", res);
printf("%g", res);

Sample improved my_power() - unchecked
// Very rough code
double my_power(double x, double y) {
  double whole;
  double fraction = modf(y, &whole);
  if (fraction == 0.0) {
    double r = 1.0;
    double p = fabs(whole);
    while (p > 0) {
      if (fmod(p, 2.0)) {
        r *= x;
      }
      x *= x;
      p /= 2.0;
    }
    if (whole < 0) {
      r = 1.0 / r;
    }
    return r;
  }
  if (x == 0.0) {
    return 0.0;
  }
  if (x < 0.0) {
    return NAN;
  }
  return exp(log(x) * y);
}


You are right that this roll is biased.  Instead of using a fixed range and less-than for your rolls, you should just roll once and use specific ranges to choose which action is taken.  Something like:

int spinAttackChancePerTickMin = 0;
int spinAttackChancePerTickMax = 50;

int spinDefenceChancePerTickMin = 50;
int spinDefenceChancePerTickMax = 100;

int roll = Random.Range(0, 100);

if (roll >= spinAttackChancePerTickMin &&
    roll < spinAttackChancePerTickMax)
{
    StartCoroutine(SpinAttackTimer());
    continue;
}

StartCoroutine(DefenseSpinTimer());


The CHI uses many caching backends and you did not said which one you are using. Fastest is perl's internal arrays, then hashes and then any other implementations. CHI may use persistent files to caching, like Berkeley DB backend or one of mmap implementation to reduce memory usage. When you are using such caching to improve perfomance you may place cache files to tmpfs (or some of ramfs) on *nix systems (linux, *bsd).

So, when I'm storing a lot of data in cache and I need to reduce memory usage I prefer use BDB without CHI. Then I need speed and managing few data in cache I prefer perl's internal structures. In last case you need to remember that Perl uses optimistic memory allocation. Thats means that Perl reallocates and allocates new memory segments and never returns consumed memory back to the OS. It is very important when writing daemons and you need to limit somehow memory usage. In other cases you may use any caching system and do not worry about performance or memory usage. Just use Devel::NYTProf to find bottlenecks.


This is one of the beefs I have with online judging systems like this..... it is not testing the algorithm, or anything like that. Instead, consider doing the very last line like:

// the longest value will be 11 chars long because % 1000000007 + " "
StringBuilder sb = new StringBuilder(N * 11);
for (long l : A) {
    sb.append(l).append(" ");
}
System.out.print(sb.toString());

A single println is almost always N times faster than N printlns.

If that does not make it work in time, then consider reading the entire System.in in to a buffer, and parsing it from the buffer.