Traversing two trees until a common value has been found

Docstrings: You should include a docstring at the beginning of every method, class, and module you write. This will help documentation identify what your methods/classes/modules are supposed to accomplish.
Simplicity: Rather than dist = start_dist + end_dist then returning dist, you can simply return start_dist + end_dist. You can return the addition of the two values, rather than creating a variable to only use it once to return. This is a personal preference, but it helps reduce the number of variables in the program, which helps me; and may also help you.
Constants: Any constants in your program should be UPPERCASE. You only have one in your code, but you should keep in practice for when you write bigger programs.
Printing: You use print(..., ...) and print(f"...") interchangeably. You should stick to using only one for consistency sake. As my preference, I changed all of them to print(f"..."), but you change choose your preference.

Updated Code

"""
Traverses two objects that may share a common ancestor
"""

def get_distance(start, end):
    """
    Gets the distance from `start` to `end` in the trees
    """
    start_d = {
        'a': 'b',
        'b': 'c',
        'c': 'd',
        'd': 'x',
        'x': 'y',
        'y': 'z',
        'z': 'z'
    }

    end_d = {
        'z': 'y',
        'y': 'x',
        'x': 'd',
        'd': 'c',
        'c': 'b',
        'b': 'a',
        'a': 'a'
    }

    connected = False
    start_dist = 0
    end_dist = 0

    while True:
        print(f"Start: {start}")
        print(f"End: {end} \n")

        # Check whether a and b are the same, if so break
        if start == end:
            print(f"Found overlap: {end}")
            connected = True
            break

        # Check whether the next a value is the same as b, if so break and increase a_dist
        elif start_d[start] == end:
            print(f"Found overlap: {end}")
            start_dist += 1
            connected = True
            break

        # Check whether the next b value is the same as a, if so break and increase b_dist
        elif end_d[end] == start:
            print(f"Found overlap: {start}")
            end_dist += 1
            connected = True
            break

        # If for a and b all options are exhausted, break
        if start == start_d[start] and end == end_d[end]:
            break

        # If a is not exhausted, get its dict value and increase distance
        if start != start_d[start]:
            start_dist += 1
            start = start_d[start]

        # If b is not exhausted, get its dict value and increase distance
        if end != end_d[end]:
            end_dist += 1
            end = end_d[end]

    print(f"Connected: {connected}")
    return start_dist + end_dist

if __name__ == '__main__':
    DISTANCE = get_distance('b', 'y')
    print(f"Distance: {DISTANCE}")


C++ binary search tree, not using recursion

You Break the Rule of Three/Five

{
    Bst  tree1;
    tree1.add(5);
    tree1.add(6);

    Bst  tree2(tree1);  // You just made a copy.
                        // Even though there is no copy constructor!

    tree2.add(8);       // both trees have 8 in them!!!!
}

Both trees are a mirror of each other. Adding nodes to one also adds nodes to the other. Also if you add the appropriate clean up code this will cause a break.

This is all caused because the compiler generates a couple of methods automatically. These methods work perfectly most of the time. But if your class contains an "Owned" RAW pointer then it does not work like you would expect.

So the simplest solution is to disable these auto-generated methods. You can then fix them later when you understand what is going on (look up rule of three).

    // Add this to your class.
    Bst(Bst const&)            = delete;
    Bst(Bst&&)                 = delete;
    Bst& operator=(Bst const&) = delete;
    Bst& operator=(Bst&&)      = delete;

Your class Leaks

For every call to new there must be a corresponding call to delete

    BstNode* newNode = new BstNode();

I don't see any calls to delete in your code. I don't see a destructor in your code to handle the clean up. So Add a destructor that deletes the tree from the root down.

Interface

The insert function:

BstNode* insert(int data)

looks out of place for a public function. This looks like an internal function that is called when you know where to insert the data value. Best to just make this private.

Simlify your Code

    BstNode* newNode = new BstNode();
    newNode->data = data;
    newNode->left = nullptr;
    newNode->right = nullptr;
    return newNode;

This can be replaced with a single line:

    return new BstNode{data, nullptr, nullptr};

Finding the node to insert a value:

    // Personally I would write this using recursion.
    // Its a balanced tree the chance of blowing the stack are small.
    BstNode*& find(BstNode*& node, int value)
    {
        if (node == nullptr) {
            return node;
        }
        return (node->value <= value)
                  ? find(node->left,  value)
                  : find(node->right, value);
    }

    // But if you must implement it using a loop then
    // its not much harder to write (you just need to handle
    // pointers to pointers). But it does make slightly harder
    // to read (Which is why I prefer the recursion route).
    BstNode*& find(BstNode*& node, int value)
    {
        BstNode** loop = &node;
        while(*loop != nullptr) {
            loop = (*loop)->value <= value
                  ? &((*loop)->left)
                  : &((*loop)->right);
        }
        return *loop;
    }

    void add(int value)
    {
        BstNode*&  nodeToModifiy = find(root, value);
        nodeToModifiy = insert(value);
    }


How to have  elements with different links on each image?

Yes hacky!
This is very hacky as you are doing a media query the long way. Interpreting the resulting media aware DOM for a URL that you then manually parse.
Learn and use the API
There are many API's available to a modern browser environment. The general rule is if it can be done on the page via HTML/CSS there is an API that can do it in JavaScript.
I never use media queries as I serve to interrogated devices so I am not 100% up on media querie API's, but for static pages you can use matchMedia
Setting up media dependent links.
There are many ways to setup your page. But in code you can access media queries using matchMedia which returns the result of a media query as MediaQueryList
You can access an elements media attribute by name. for example if an image is clicked in your example HTML event.target.parentElement.querySelector("source").media
You can store the different links as data attributes.
I think the best approach is to pre-process the markup when it has loaded and just set the link references depending on the associated media query.
Example
The code checks each link (anchor element) for a source element and uses the source elements media attribute to do a media query.
Depending on the result of the media query it gets the appropriate data set item and set the link href property.
Each picture has a different media query. Hover to see link href (I have set title to show the link as example)

// do in page onload event
for (const link of linkedImages.querySelectorAll("a")) {
    const source = link.querySelector("source");
    if (source) {
        const isSmall = matchMedia(source.media).matches;
        link.href = isSmall ? link.dataset.linkSmall : link.dataset.linkNormal;
        link.title = link.href; // just for example
    }
}

        <picture>
            <source media="(max-width:  1700px)" srcset="https://i.stack.imgur.com/C7qq2.png?s=48&g=1">

        </picture>

        <picture>
            <source media="(max-width:  500px)" srcset="https://i.stack.imgur.com/C7qq2.png?s=48&g=1">

         </picture>


hexdigest returns a string

So you don't need to str(hash_mac()) each time. Even if it didn't, you would probably want to put the str call within that hash_mac function.
You're not using get_mac for any other purpose than hashing it.

You might thus want to encapsulate this functionality into hash_mac:

from uuid import getnode as get_mac

def hash_mac():
    """hash the MAC Address using sha256 algorithm"""
    mac = str(get_mac()).encode()
    return hashlib.sha256(mac).hexdigest()

You don't need to get a file open for that long.

You can close it as soon as you read its first line. As a bonus, you can also directly compare strings:

def main():
    with open('uid_file.cfg') as uid_file:
        first_line = uid_file.readline().strip()

    if hash_mac() == first_line:
        print('Match MAC and execute program here\n')
    else:
        print('MAC does not match! Exiting...')
        sys.exit(0)

You can feed error messages to sys.exit:

sys.exit('Mac does not match! Exiting...')

will print Mac does not match! Exiting... to stderr and exit the program with a status code of 1. Note that usually, a status code of 0 means success.
If you want to use it as a form of security, you should avoid giving hints of what to do to unauthorized persons:

if uid_file.cfg does not exist, a traceback saying it tried to open it will be printed
if content of the file mismatch, a hint is given such that it should contain a MAC address

You can try to avoid that with a generic error message such as Access denied:

def main():
    try:
        with open('uid_file.cfg') as uid_file:
            first_line = uid_file.readline().strip()
    except OSError:
        sys.exit('Access denied')

    if hash_mac() != first_line:
        sys.exit('Access denied')

    print('Match MAC and execute program here\n')

Lastly, it might be interesting to define this function as a check that you can easily disable while developping/testing:

import sys
import hashlib
from uuid import getnode as get_mac

def hash_mac():
    """hash the MAC Address using sha256 algorithm"""
    mac = str(get_mac()).encode()
    return hashlib.sha256(mac).hexdigest()

def check_secure_user():
    try:
        with open('uid_file.cfg') as uid_file:
            first_line = uid_file.readline().strip()
    except OSError:
        sys.exit('Access denied')

    if hash_mac() != first_line:
        sys.exit('Access denied')

def main():
    print('Match MAC and execute program here\n')

if __name__ == '__main__':
    check_secure_user()  # deactivate while developping
    main()


Excel Duplicate File name with different Revisions

Although this question is slightly off-topic I will give you a run down of your code. I will start with some bugs in your code, then make some general remarks about the coding style, explain what is probably causing your code to miss duplicates and, finally, propose an approach that removes all duplicates in one go.

Bugs

The bugs I referred to above are that you frequently refer to cells on the ActiveSheet instead to those on Sheet1 because you have omitted the dot in front.

Style

Now, let me say something about the coding style.

You should indent your code properly. In your code the start and end of if blocks and loops do not match up, which makes it very hard to read.
One of the best practices to improve readability of your code is to use meaningful names. E.g. LRow3 does not tell you at all what it is. (It containing 'row' I would expect it to be a Long, but actually it is a String. (I hope you declared it above the code you posted.)) As far as I can see it might better be called sometime like dataRangeString. If anybody else ever reads this again, or you in a few months, he will be grateful for the added readability.
This is not a major concern here, but try to follow the single responsibility principle, which basically tells you that a unit of code should do one and only one thing. E.g. the first for loop could be its own sub called SaveConcatenatedKeyInKeyColumn.
In the With block variable you make an implicit reference to the ActiveWorkbook. It is good practice to make that explicit. Generally, you should avoid implicit references and default members, because they hinder readability and hide subtle bugs.

For more help with the coding style you might want to have a look at Rubberduck. (Full disclosure, I am a contributer.)

Potential Cause of Problems

Now to what I think might be the problem with your code. When you are deleting rows, all rows below get shifted up. This makes you skip consecutive rows that should have been deleted.
To solve this, always remove rows bottom to top.

Alternative Approaches

The approach I want to propose is to sort first by filename (Key1) and then by version (Key2). All you have to do then is to go from bottom to top and remove every row where the row below it has the same filename in the filename column. Because you sorted by version as the second key, only the highest version survives.

Alternatively, you could use a Dictionary, which requires a reference to VBScript, to store the highest version seen so far in a first pass over your data. (Use Exists to see whether you have seen the filename before. If not, save the revision with the filename as key. If yes, compare the current revision for the filename to that in the dictionary and save it if it is higher.) In a second pass, from bottom to top, remove every row where the version is not the one in the dictionary.

The second approach is faster for large data sets since you do not have to sort. However, if you want to sort the filenames anyway, as your example suggests, there is no real performance advantage.


Things you did well:

Usage of static.
Using memset() instead of some for loops for initialization of your int[][].

Things you could improve:

User Experience:

You don't indicate to the user that they should enter a number first.

printf("Enter the number of test cases: ");

You don't indicate that the user should enter a string after then enter a number.

printf("Enter test case string: ");

Variables:

I don't expect dp will ever contain negative numbers:

static int dp[6101][6101];

You also don't need the full range of int.  Using a unsigned short will half your memory usage.

static unsigned short dp[6101][6101];

Always initialize your variables when you create them.

int tc = 0;

Readability:

You don't declare what main will return or take in as parameters.

main()

I know that when the type specifier is missing for what you will return, it defaults to an int.  You should still declare it for more readability.  Also, whenever you don't take in any parameters, declare them as void.

int main(void)

Your for loop is hard to follow.

for(int i=1;i<len;i++)
    for(int j=0,k=i;k<len;k++,j++)
        dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;

Braces will help, and will reduce the likelihood of you unintentionally adding bugs in the future.

for(int i=1; i<len; i++)
{
    for(int j=0,k=i; k<len; k++, j++)
    {
        dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;
    }
}

Don't use the ternary operator for longer statements.

dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;

This makes it hard to follow and understand what you are trying to do.  Just use the normal if-else statements.

if (s[j] == s[k]) dp[j][k] = dp[j+1][k-1];
else dp[j][k] = fmin(dp[j][k-1], dp[j+1][k]) + 1;

Use more space in your code.  Let it breathe a bit.  But don't go overboard.
Use more comments to explain your code.

Syntax/Styling:

You have some magic numbers in your code.

static int dp[6101][6101];

With the help of macros, we can easily get rid of them.

#define ARRAYSIZE 6101
static int dp[ARRAYSIZE][ARRAYSIZE];

Don't use the function min().

dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;

min() and max() functions are not included in standard C.  To make things simple for your code, use the standard math function fmin().

dp[j][k] = (s[j] == s[k]) ? dp[j+1][k-1] : fmin(dp[j][k-1], dp[j+1][k])+1;

You have an implicit conversion that loses integer precision:

int len=strlen(s);

You aren't converting your unsigned long that strlen() returns to an int.

int len = (int) strlen(s);

Use fgets() instead of scanf().  This way we can specify the maximum number of characters to be copied into our string (including the terminating null-character).

fgets(s, 6101, stdin);

You should always check for superfluous input and get rid of it.

while (getchar() != '\n');

Preprocessor:

Whenever you include functions such as scanf() and printf() that deal with input or output, you need included the standard I/O header.

#include <stdio.h>

Whenever you include functions that deal with strings, there is a good chance you will have to include the string header.

#include <string.h>

Whenever you include math functions, you need to include the math header.

#include <math.h>

Final Code:

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

#define ARRAYSIZE 6101

static unsigned short dp[ARRAYSIZE][ARRAYSIZE];
char s[ARRAYSIZE] = {0};
int main(void)
{
    int tc = 0;
    printf("Enter the number of test cases: ");
    scanf("%d",&tc);
    while (getchar() != '\n');
    while(tc--)
    {
            printf("Enter test case string: ");
        fgets(s, ARRAYSIZE, stdin);
        int len = (int) strlen(s);
        memset(dp, 0, sizeof dp);
        for(int i=1; i<len; i++)
        {
            for(int j=0, k=i; k<len; k++, j++)
            {
                if (s[j] == s[k]) dp[j][k] = dp[j+1][k-1];
                else dp[j][k] = fmin(dp[j][k-1], dp[j+1][k]) + 1;
            }
        }
        printf("%d\n", dp[0][len-1]);
    }
    return 0;
}


There's no need to collect all the arguments into a vector to ignore all but one. Just grab that one via nth.
Remove most of the explicit types and prefer inferring them instead.
Use expect instead of unwrap to provide a message when it fails. It took me 10 minutes to realize that the first argument had to be a filename and not the number of lines to read from standard input.
It's shorter to use expect instead of a panic! when you can.
Don't provide full type for collect; let the inner type be inferred with Vec<_>.
Use the iterator in the for loop instead of calling next manually.
Extract functions to give structure, add names, and isolate mutability.

use std::env::args;
use std::fs::File;
use std::io::Read;

fn read_input_file(name: &str) -> String {
    let mut input = String::new();
    let mut f = File::open(&name).expect("Unable to open the input file");
    f.read_to_string(&mut input).expect("Unable to read the input file");
    input
}

fn main() {
    let filename = args().nth(1).expect("Provide an input file as an argument");

    let input = read_input_file(&filename);
    let mut input = input.lines();

    let num_inputs = input.next().expect("No contents");
    let num_inputs = num_inputs.trim().parse().expect("First line in input not a number");

    for (i, line) in input.take(num_inputs).enumerate() {
        let mut score = 0;
        let moods: Vec<_> = line.chars().collect();
        let mut problems = Vec::new();

        for (j, &mood) in moods.iter().enumerate() {
            // the assumption is that you'll only request problems
            // that're the same mood that the grader is in reason
            // being that you can receive a maximum of 10 points and a
            // minimum of 5, whereas for the other mood it'll be a max
            // of 5 and a min of 0

            if problems.is_empty() {
                problems.push(mood);
            } else if problems.len() >= moods.len() - j {
                if problems.last() == Some(&mood) {
                    score += 10;
                } else {
                    score += 5;
                }
                problems.pop();
            } else if problems.last() == Some(&mood) {
                score += 10;
                problems.pop();
            } else {
                problems.push(mood);
            }
        }
        println!("Case #{}: {}", i+1, score);
    }
}

When profiling, it is very important to compile in release mode. You will also want to make sure you aren't including compilation time. I tend to split the compile and execute steps into two parts to be sure nothing extra is included:

$ cargo build --release
$ time ./target/release/gc3 A-large-practice.in

# ...snipped output...

real    0m0.022s
user    0m0.010s
sys     0m0.010s


I'm not quite sure what you are asking for, but I guess you are looking for a solution similar to this (not compiled nor tested):

#include <stdio.h>   /* sscanf */
#include <stddef.h>  /* NULL */
#include <stdbool.h> /* C99 bool type */

typedef enum
{
  TYPE_CHAR  = 'c',
  TYPE_INT   = 'd',
  TYPE_FLOAT = 'f',
  // etc
} Type_t;

/* I placed destination first to use the same parameter order as standard library
   functions (strstr for example). Note the const correctness for read-only parameters. */

bool FetchValueArray (void*       dest,
                      const char* source,
                      const char* name,
                      size_t      count,
                      Type_t      type)

{
  const char* strptr;                  /* Some string pointer (not sure what it does) */
  BOOL is_found;                       /* Is the name found? */

  if(dest == NULL)                     /* No need to do anything if this parameter is NULL */
  {
    return false;
  }

  strptr = strstr(source, name);
  is_found = strptr != NULL;           /* Boolean arithmetic */

  if(is_found)
  {
    size_t i;
    size_t item_size;
    const char format[2] = {'%', (char)type};

    switch(type)
    {
      case TYPE_CHAR:  item_size = 1; break;
      case TYPE_INT:   item_size = 4; break;
      case TYPE_FLOAT: item_size = 4; break;
    }

    for(i=0; i<count; i++)
    {
      sscanf(strptr, format, (char*)dest + item_size*i);
    }
  }

  return is_found;
}

EDIT:
Regarding array bounds checking. First you have to decide whether this is actually your concern or if you should leave it up the caller. Most commonly, you document every parameter in the .h file and state how the function should be called. If someone still decides to call it with incorrect parameters, it is then their own fault. That's how most C functions work and in this particular case, that's what I would recommend.

Since C does not store the array size together with the array as one single data type, you can't really pass an array size "safely" between the caller and a function, the caller is the one with the knowledge about the size, so you simply have to trust the programmer writing the caller.

You could write something like this

bool FetchValueArray(char dest[25], ...

but there are still no guarantees by the standard that this is safe. Some compilers will toss a warning if you try to pass anything but a fixed char array of 25 items to this function, but they don't have to. And we'd lose the generic type, so it isn't helpful.

You could do something like this, but I would not recommend it:

#define SIZE 25

typedef union
{
  char  char_array[SIZE];
  int   int_array[SIZE];
  float float_array[SIZE];

} GenericSafeArray_t;

This will allocate SIZE*sizeof(float), since float happend to be the largest type. So it is memory-ineffective and not particularly flexible either.


Using CSS grid to align content in a non responsive div

I think the CSS looks fine. To your questions

a.) It doesn't matter which container has the grid property. It's CSS. It's not semantic.

b.) I am not sure if it is considered a best practice, but a lot of people seem to use it this way. Just google CSS nested grid and you will get quite some articles and videos on that topic. For example this and this.

c.) Counter question: Why not? CSS doesn't add any semantic meaning to HTML. It's just for styling. So, IMHO as long as it works and is scalable/maintainable it's fine.


I'm reading all lines of another sheet and I paste the value that I want to the active sheet VBA

Off the bat it appears that you are looping through the entire sheet "MT950" twice.  Doing this once will improve the speed.  Also, the line you said it might be slow around appears twice in your code.

In your first loop you are running two comparisons, one using the If, Like, Then and then another right after using InStr(1, SearchString, swift, 1).  These can be combined into the following

For Line = 1 To LastLine
    SearchString = Sheets("MT950").Range("A" & Line).Value
    If InStr(1, SearchString, swift, 1) <> 0 and SearchString Like "-}{5:*" Then Count = Count + 1
Next Line

The second loop appears to be the same as the first only with more stuff happening once you get down inside of it.  I'd recommend merging these two loops, there doesn't seem to be a need to loop through all the rows twice.


assert() isn't meant for runtime errors like an invalid filename. It's meant to aid in debugging by catching logical errors. Essentially, it says, "There should be no possible way this statement can be false. If it is false, something about this program is invalid, so I need to blow up."

A good use of assert() here would be:

List* build_list(char* fileName)
{
    assert(fileName && fileName[0]);
    // Alternately (more verbose, but maybe more clear):
    assert(fileName != NULL && fileName[0] != '\0');
    // Another alternative, which gives a helpful message
    // if it fails
    assert(fileName && fileName[0]
        && "build_list(char* fileName) was given a null or empty fileName");

This way, if you write a function somewhere else that passes a null filename into build_list, you'll get notified of the programming error.

A runtime error such as a missing file is better handled by returning some kind of error. You could return NULL on error, or you could take a List* (or List**) as an argument and return an integer result (0 for success is typical).


If you are able to use Java 8 you can use streams:

List<String[]> list = IntStream.range(0, 3)
    .mapToObj(i -> new String[] { String.valueOf(i) })
    .collect(Collectors.toList());

Let's break it down:

IntStream.range(0, 3) gives you the values 0, 1 and 2
.mapToObj(i -> new String[] { String.valueOf(i) }) converts them to a string and puts them into a String[]
.collect(Collectors.toList()) collects the stream into a List<String[]>


OK, so I'm going to start with your DFS method.  You're right - you should be able to do it without those vars in the outer function.  You should be able to work out why - after all, you have vals in the outer layer of your BFS method.  Why?  Because your BFS uses a recursive helper function, so the vals are only used once (and could be discarded).

So your DFS function should really use recursion, but I suspect you may have rejected recursion because you couldn't see how visited would be properly preserved as a recursive function popped back and forth.  The answer is foldLeft.

def DFS(start: Vertex, g: Graph): List[Vertex] = {

  def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {
    if (visited.contains(v))
      visited
    else {
      val neighbours:List[Vertex] = g(v) filterNot visited.contains
      neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))
    }
  }
  DFS0(start,List()).reverse
}

I don't have space here to explain foldLeft, if you've never encountered it - maybe Matt Malone's blog post will help.  You can rewrite almost anything with foldLeft, although it isn't always a good idea.  Definitely the right thing to do here, though.  Notice that I completely dropped your result var since visited is the result, the way you are doing this.

My version of your DFS method is entirely functional, which is how Scala really wants to be used.  Note also the lack of braces and brackets in

val neighbours:List[Vertex] = g(v) filterNot visited.contains

It can be written

val neighbours:List[Vertex] = g(v).filterNot(visited.contains)

but the Scala style is to omit the brackets and braces except where essential.

Your BFS method is similarly over-populated.  I've slimmed it down a little without altering the basic way it works:

def BFS(start: Vertex, g: Graph): List[List[Vertex]] = {

  def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {
    val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct
    if (newNeighbors.isEmpty)
      visited
    else
      BFS0(newNeighbors, newNeighbors :: visited)
  }

  BFS0(List(start),List(List(start))).reverse
}

It still gives the same results.

The other big point to make is that while Scala is a functional language it is also an Object Oriented language.  Those DFS and BFS methods should belong to a graph object, preferably at least derived from a generic class.  Something like this:

class Graph[T] {
  type Vertex = T
  type GraphMap = Map[Vertex,List[Vertex]]
  var g:GraphMap = Map()

  def BFS(start: Vertex): List[List[Vertex]] = {

    def BFS0(elems: List[Vertex],visited: List[List[Vertex]]): List[List[Vertex]] = {
      val newNeighbors = elems.flatMap(g(_)).filterNot(visited.flatten.contains).distinct
      if (newNeighbors.isEmpty)
        visited
      else
        BFS0(newNeighbors, newNeighbors :: visited)
    }

    BFS0(List(start),List(List(start))).reverse
  }

  def DFS(start: Vertex): List[Vertex] = {

    def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {
      if (visited.contains(v))
        visited
      else {
        val neighbours:List[Vertex] = g(v) filterNot visited.contains
        neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))
      }
    }
    DFS0(start,List()).reverse
  }
}

And then you could do this:

scala> var intGraph = new Graph[Int]
scala> intGraph.g = Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3))
scala> intGraph.BFS(1)
res2: List[List[Int]] = List(List(1), List(2, 4), List(3))
scala> intGraph.BFS(2)
res3: List[List[Int]] = List(List(2), List(1, 3), List(4))
scala> intGraph.DFS(3)
res4: List[Int] = List(3, 2, 1, 4)

or this:

scala> var sGraph = new Graph[String]
scala> sGraph.g = Map("Apple" -> List ("Banana","Pear","Grape"), "Banana" -> List("Apple","Plum"), "Pear" -> List("Apple","Plum"), "Grape" -> List("Apple","Plum"), "Plum" -> List ("Banana","Pear","Grape"))
scala> sGraph.BFS("Apple")
res6: List[List[java.lang.String]] = List(List(Apple), List(Banana, Pear, Grape), List(Plum))


Go functions to create a directory if it doesn't exist

Create a directory if it doesn't exist.

  Don't report an error if the directory exists.

Isn't that a simple wrapper for the Go standard library os.Mkdir function?

For example,

// mkdir, like os.Mkdir, creates a new directory
// with the specified name and permission bits.
// If the directory exists, mkdir returns nil.
func mkdir(name string, perm os.FileMode) error {
    err := os.Mkdir(name, perm)
    if err != nil {
        if !os.IsExist(err) {
            return err
        }
    }
    return nil
}

  Personally I prefer the one line method.

In Go, we favor readability and simplicity for correct and maintainable code. Use the Go idiom for creating a file:

f, err := Create(fileName)
if err != nil {
    // handle error
}
defer f.Close()

For your usage, use a wrapper for the Go standard library os.Create function.

For example,

// createFT, like os.Create, creates the named file with mode 0666 (before umask),
// truncating it if it already exists.
// The file is created in the directory named in the FT_SOURCE environment variable.
func createFT(fileName string) (*os.File, error) {
    dirKey := "FT_SOURCE"
    dirName, ok := os.LookupEnv(dirKey)
    if !ok {
        err := fmt.Errorf("%s environmemt variable not found", dirKey)
        return nil, err
    }

    perm := os.FileMode(0666)
    err := mkdir(dirName, perm)
    if err != nil {
        return nil, err
    }

    f, err := os.Create(filepath.Join(dirName, fileName))
    if err != nil {
        return nil, err
    }
    return f, nil
}

Functions are used to encapsulate implementation details. Functions can also be used to hide complexity and "ugly" code.


I'm not usually harsh, but this code is a buggy mess. Sorry.

We don't review broken code on CodeReview, but I just can't help myself. As I said in a comment, this code is so broken that it actually ends up almost working correctly.

Well, except for the fact that data.g_current raises an exception, because you should be writing data['g_current'].

But let's ignore that and look at #compare_data:

def compare_data second_value, date
  # this is *always* false, since neither value is a number;
  # they're strings and a string can't be zero
  unless @today_value == 0 && second_value == 0

    # And this condition makes the one above completely redundant anyway
    if @today_value != second_value
      period = @result_data[date]

      # This *never* happens because (again) a string can't be zero.
      # But that's a good thing, because if it worked, and
      # @today_value was zero, while second_value was 1 or more
      # you'd end up adding 1 to :dec here, *and* adding 1 to
      # :inc in the else-block below
      period[:dec] += 1 if @today_value == 0

      if second_value == 0
        # this never happens either (same reason again)
        period[:inc] += 1
      else

        # this is the only line that'll ever actually do anything!
        # ... but it's broken.
        # You're comparing strings, not numbers, so in string terms,
        # "2" is greater than "10", "323" is less than "5" and so on,
        # and the branch will do the wrong thing. It just happens to
        # work if both values are single digit strings
        @today_value < second_value ? period[:inc] += 1 : period[:dec] += 1
      end
    end
  end
end

In other words: there are issues here.

Other stuff:

What you want is a method, not a class. What you seem to be going for is a straight folding/reduction of a data set (i.e. Array#inject).
You're setting an instance variable in a loop (@today_value), and relying on that in a method. This is, frankly, terrible. If anything, just pass it to the method as an argument. There's just a lot of really weird coupling and state-keeping going on, none of which should be happening.
#get_data should be idempotent. Right now, if you call it more than once, you'll just get larger and larger inc/dec values because you keep adding to the same @result_data hash. But again, you don't want a class anyway.
And #get_data is stranger still. You set @today_value again and again although it doesn't change in the inner each loop.
Fix your indentation
Don't call a class CompareData. Classes should be nouns; "compare data" is imperative. And don't call a variable init, and don't pluralize data since it's already plural.
Be consistent with your parentheses. You use them for #initialize, but you don't for #compare_data

Here's something that I think is closer to what you're actually trying to do

changes = values.inject({'g_yesterday' => {inc: 0, dec: 0}, 'g_week' => {inc: 0, dec: 0}, 'g_month' => {inc: 0, dec: 0}}) do |memo, datum|
  current = datum['g_current'].to_i
  memo.each do |key, hash|
    previous = datum[key].to_i
    if current < previous
      hash[:inc] += 1
    elsif current > previous
      hash[:dec] += 1
    end
  end
  memo
end

No class, no strange coupling or state-keeping. Just input and output.

Update: New code posted, and while my answer was already accepted, I might as well. The new code is thankfully working with numbers rather than strings, which helps, but most of my points above still stand. Looking at the #compare_data method again:

def compare_data second_value, date
  # just return if you don't want to run the rest of the code
  unless @today_value == 0 && second_value == 0

    # again: This condition makes the one above pointless
    # and again, just return instead of wrapping everything
    if @today_value != second_value
      period = @result_data[date]

      # Why are zeros treated differently? Isn't the point simply to figure
      # out what value is higher, and update inc/dec accordingly?
      # Why does one of the values being zero make it behave exactly
      # opposite of how it behaves if both values are non-zero?
      #
      #  today_value   |  second_value   |  Add 1 to...
      # ----------------------------------------------
      #  1  (highest)  |  0              |  :inc
      #  2  (highest)  |  1              |  :dec
      #
      # This doesn't make sense to me...
      if @today_value == 0 || second_value == 0
        @today_value > second_value ? period[:inc] += 1 : period[:dec] += 1
      else
        @today_value > second_value ? period[:dec] += 1 : period[:inc] += 1
      end
    end
  end
end


If you're writing a simulation, it's probably worthwhile to add some abstractions to your code so that you can free your mind to think at a more abstract level.  Ideally, I would like to see

L = list(until_total(stop_time, poisson_process(10)))

(Consider not calling list() if you just need an iterable and not a list.)

Here is one way to get there:

from itertools import takewhile
from random import expovariate

def poisson_process(rate):
    while True:
        yield expovariate(rate)

def until_total(limit, iterable):
    total = [0]                 # http://stackoverflow.com/q/2009402
    def under_total(i):
        total[0] += i
        return total[0] < limit
    return takewhile(under_total, iterable)

stop_time = next(poisson_process(1))
L = until_total(stop_time, poisson_process(10))

Also, consider using more meaningful identifiers:

customer_arrivals = poisson_process(10)
cashier_yawns = poisson_process(1)
customer_interarrival_times = until_total(next(cashier_yawns), customer_arrivals)


There are several quick improvements that can halve the time.

There is a redundant check where you first check a > b and then check b < a. Ignoring that the "continue" statement makes any check redundant  since if it doesn't match you'll fall past and continue anyway, it's also redundant because you're checking for the negative of a previous check. Well, an almost negative, you don't explicitly deal with a == b but I'm guessing you want to continue there not swap them, both are a valid result but swapping identical values is a waste.

Also a bunch of the time is taken filling the array. Rather than looping over a long array and calling append on each item, you can just set

value_list = range(len_of_list)

The other major optimisation is to not use recursion, the reason this improves performance here is because your comparison for finishing is a long operation that you have inside the loop, by making the function looping / iterative it is easy to move that outside the inner loop saving a large amount of time.

Also you have some funny logic around the last element, just looping (0, n-1) fixes that.

The last element MUST be in order after the first iteration, it gets pushed back every single time, so instead of looping (0, n - 1) you can actually loop (0, n - i - 1) where i is the iteration number.

You can remove the check_results call entirely and consider what it means to be "in order". Being in order means that no swaps have happened. That means that instead of looping over everything you can just track whether you've swapped anything. If you haven't then congratulations, everything is in order.

This saves a large amount of time since your "check_results" loops over the array doing comparisons which you were doing inside another loop (well, recursed call).

Below is my modification of your code to include the changes I have described. I have changed some variable names to more clearly show their new meaning.

import random
import time
import sys

value_list = []
# Create values
len_of_list = random.randint(8500, 10000)
value_list = range(len_of_list)
random.shuffle(value_list)

def timeit(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print "The function {.__name__} took {:.15f} seconds to finish.".format(func, time.time() - start)
        return result
    return wrapper

def custom_sort():
    has_swapped = True
    iteration = 0
    while has_swapped:
        has_swapped = False
        for index in range(len_of_list - iteration - 1):
                next_value = value_list[index + 1]
                if value_list[index] > next_value:
                    has_swapped = True
                    value_list[index + 1] = value_list[index]
                    value_list[index] = next_value
        iteration += 1
        if not has_swapped:
           print value_list

@timeit
def run():
    custom_sort()

run()

For reference, your code on my system executed in around 25-28 seconds depending on the random array length, my modified version executes in 12-14 seconds. I am sure there are further optimisations I have missed.


ConcurrentLinkedQueue to unmodifiable list

Lists.newArrayList will allocate a new list (as the name indicates) so there is no reason to wrap it in a Collections.unmodifiableList.

What you have is a defensive copy. This won't allow propagation of changes back to the queue, but requires you to get a new list each time you want an update.

If you still want a queue backed view then you should return Collections.unmodifiableCollection:

public Collection<MimeMessage> getMailsToSend() {
    return Collections.unmodifiableCollection(mailsToSend);
}

This has the downside that only way to get all items from a generic Collection is using the iterator or the toArray methods. Though each time you call it on them you get an up to date view (with the same caveats of the same methods of the queue).


public static void flagOfLiberia(Graphics g) {
    Expo.setBackground(g,Expo.black);
    for (int d = 1; d <= numDots; d++) {
        int x = Expo.random(0,1000);
        int y = Expo.random(0,650);

        if (x < 300 && y < 300)
            Expo.setColor(g,Expo.darkBlue);
        else if (y % 100 < 50)
            Expo.setColor(g,Expo.red);
        else
            Expo.setColor(g,Expo.white);

        drawDot(g,x,y);    // must be run inside the loop
    }
    Expo.setColor(g,Expo.white);
    Expo.fillStar(g,150,150,100,5);
    showName(g,"Liberia");
}

The above should be at least a little improvement. I used a modulus (%) to check every multiple of 100, seeing if the remainder is less than or greater than 50. If you desire a cutoff at 650, then a single if statement can be added before the modulus to check that y is below the threshold. Also, I placed the star after the for loop in order to execute it only once.


Python image sequence file concatenation

Many, many problems:

Low level dealing with strings. Python is a high-level programming language - don't reinvent the wheel. Regex and string methods now are replacing your low-level code in my rework of it. Good rule of thumb is to avoid any code that has a lot of array indexing in Python.
Sorting doesn't need a function if you use sorted
Long comprehensions and generators are usually unreadable and unmaintainable so avoid those at all costs. Especially avoid adding needless logic in them too.
Extension list is a constant so you might as well extract that to the top.
Simpler or more standard output could have made the code much simpler but it wasn't clear if that was the requirement.
Hardcoding args shouldn't be done when sys.argv and argparse are so easy to use.

tl;dr fixed code. Code could be a lot simpler if the output format was a bit more standard but you can probably modify the code with minimal effort:

#!/usr/bin/env python3

import os
import re
import sys

FILE_EXTS = [
    'exr',
    'jpeg',
    'jpg',
    'png',
    'tif',
    'tiff',
]

SEQUENCE_PATTERN = r'(.*)\.([0-9]+).(.{3,4})$'

def sequences_strigifier(sequences):
    output_string = ''
    for key, seq_info in sequences.items():
        if not seq_info:
            output_string += '{}\n'.format(key)
            continue

        if seq_info['start_index'] == seq_info['end_index']:
            output_string += '{}.{}.{}\n'.format(key,
                                                 seq_info['start_index_str'],
                                                 seq_info['ext'])
            continue

        output_string += '{}.{}.{}, [{}-{}]\n'.format(key,
                                                      seq_info['start_index_str'],
                                                      seq_info['ext'],
                                                      seq_info['start_index'],
                                                      seq_info['end_index'])

    return output_string.strip()

def find_image_sequences(directory):
    '''
    sequences get put into arrays like so:
    [x_folder, z_folder, [test_a.000.png, 0, 2], [test_b.000.tif, 0, 3], test_C.000.png]
    :return: [file1, file2, [first_file, seq_start, seq_end]]
    '''
    sequences = {}

    sorted_candidate_list = sorted(os.listdir(directory))

    for candidate_path in sorted_candidate_list:
        full_candidate_path = os.path.join(directory, candidate_path)
        if not os.path.isfile(full_candidate_path):
            sequences[candidate_path] = None
            continue

        matches = re.match(SEQUENCE_PATTERN, candidate_path)
        if not matches:
            sequences[candidate_path] = None
            continue

        filename = matches.group(1)
        sequence_index = matches.group(2)
        extension = matches.group(3)

        if not extension in FILE_EXTS:
            sequences[candidate_path] = None
            continue

        if not filename in sequences:
            sequences[filename] = {
               'ext': extension,
               'start_index_str': sequence_index,
               'start_index': int(sequence_index),
               'end_index': int(sequence_index),
            }
            continue

        sequences[filename]['end_index'] = int(sequence_index)

    return sequences_strigifier(sequences)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Usage: {} <dirname>'.format(sys.argv[0]))
        exit(1)

    print(find_image_sequences(sys.argv[1]))


Nested for-loop to create list of lists - Python

Using a pure Python approach, this is exactly the job for itertools.groupby. But for it to work efficiently, you need to sort your data by the same key you will group them by (i.e. the date). Since your first sort also sort by the third field, you need to sort your list by multiple attributes

I would also build a generator to help reuse code and separate the core of your computation from the testing code using if __name__ == '__main__'. Something along the lines of:

from operator import itemgetter
import itertools

def generate_ranks(sales_data):
    sorted_data = sorted(sales_data, key=itemgetter(0, 2), reverse=True)
    for date, group in itertools.groupby(sorted_data, key=itemgetter(0)):
        yield [date] + [entry[1] for entry in group]

if __name__ == '__main__':
    sales_data = [
        [201703, 'Bob', 3000],
        [201703, 'Sarah', 6000],
        [201703, 'Jim', 9000],
        [201704, 'Bob', 8000],
        [201704, 'Sarah', 7000],
        [201704, 'Jim', 12000],
        [201705, 'Bob', 15000],
        [201705, 'Sarah', 14000],
        [201705, 'Jim', 8000],
        [201706, 'Bob', 10000],
        [201706, 'Sarah', 18000],
    ]
    sales_ranks = list(generate_ranks(sales_data))
    print(sales_ranks)


Some suggestions (by far not complete as the other answer(s) show):

You don't need to specify the type twice:

protected List<Tree<T>> children = new ArrayList<Tree<T>>();
protected List<Tree<T>> children = new ArrayList<>();

Create a new parameter maxDepth to limit the function nesting level.
It should be set to a default value to follow the principle of least astonishment: Nobody would expect his program to crash just because he triggered the string conversion somehow.
With very big trees the nested function calls can become a problem.
But I wouldn't worry about it for two reasons:

The function is not named archiveTree. As a user, I wouldn't expect it to handle each and every scenario of a tree.
The default value maxDepth should reasonably prevent out of memory scenarios as long as the user doesn't manually provide disproportional values. If he does, it's his fault and not yours anymore.

You sometimes have inconsistent spacing, e.g.:

buildString(sb,prefix, true);
buildString(sb, prefix, true);

You could specify the capacity argument with a guessed value to the constructor of StringBuilder to prevent some unnecessary capacity allocations. However, as long as you haven't identified this as a noticeable bottleneck of your application, I would consider it to be premature optimization.


I'd replace the conditions with guard clauses. (Flattening Arrow Code)

function has_access() {
    if ( !is_user_logged_in() ) {
        return false;
    }
    $role = get_current_user_role();
    $admins = array(
        'Administrator',
        'Agent',
        'Contributor',
    );

    if (in_array($role, $admins)) {
        return true;
    }
    return false;
}


This perl script renames all files in a directory to have an equal amount of digits

As you suspect, this can be done in fewer lines, but it's not a one-liner.

use strict;
use warnings;
use diagnostics;

Always a good idea.  Consider use warnings FATAL => "all" so that you don't miss any.

my $filename = <STDIN>;

A command-line argument or environment variable is the typical way to do this, in Perl and most other languages.  Directory variables oughtn't be named $filename.

  my $dir = ( shift or $ENV{TIMELAPSE_DIRECTORY} or die "usage: $0 directory\n" );

chdir $filename or die "Couldn't change the directory: $!\n";
…
rename ($file, $new_name) or die "Couldn't rename the file: $!";

The fat-arrow => can replace a comma and improve readability in some cases.  Dropping parens is another good readability boost, when done judiciously.  Unless the line number where die occurred is interesting, suppress it by appending a newline to the message.  And finally, it's a good habit to include in error messages the data that produced them, as in:

 rename $file => $new_name or die "Couldn't rename '$file' to '$new_name': $!\n";

my @files  = <*>;
#gives a list of all filehandles in the given directory

Filenames, not filehandles.  It would be reasonable to filter this list to contain actual files, excluding directories:

my @files  = grep -f, <*>;

And maybe even by name:

my @files = grep { -f and /\.( png | jpe?g | tga )$/xi } <*>;

my $amount_of_digits = int( log($#files)/log(10) +1);

$#files is the largest index in that zero-based array.  With 10 files, the last is $files[9] and the math returns 1 instead of the 2 we need.  The size of the array is one bigger and retrieved as @files in scalar context (log() imposes scalar context for us, which is convenient).

width is a good name for this variable.

Avoid an uncaught exception by checking that @files is non-empty.

And the parens around int can be omitted.

die "nothing to do!\n" unless @files;
my $width = int log(@files)/log(10) + 1;

But this is still no good!  log(1000)/log(10) is 3 in Perl and in real life.  But int( log(1000)/log(10) ) is 2!   This happens because floating-point math is imperfect.  Luckily Perl will let us cheat by taking the length of a number that's been silently converted  to a string:

my $width = length scalar @files;

foreach my $file (@files){

for is the idiomatic alternative to foreach.

    if ($file =~ /(\d+)/){
        my $amount_of_padded_zeroes = $amount_of_digits - length($1);
        if($amount_of_padded_zeroes > 0){
            my $new_number =  '0' x $amount_of_padded_zeroes . $1;
            (my $new_name = $file) =~ s/$1/$new_number/;
            print "Changing name too: $new_name\n";

sprintf is the function to use for leading zeroes.  It can go right in the s/// replacement by using the /execute modifier.  If the replace fails, skip to next file.

             (my $new_name = $file) =~ s/(\d+)/ sprintf "%0${width}d" => $1 /e or next;

rename ($file, $new_name) or die "Couldn't rename the file: $!";

It's good practice to ensure you have something to do, and that you aren't overwriting an existing file here:

next if $new_name eq $file;
die "$new_name (from $file) already exists!\n" if -f $new_name;

print "Program completed. Press any key to continue.\n";
my $einde = <STDIN>;

I think you know how I feel about this.  Should you decide to keep it, only the Enter key will actually proceed.

Putting it all together:

use strict;
use warnings FATAL => 'all';
use diagnostics;

my $dir = ( shift or $ENV{TIMELAPSE_DIRECTORY} or die "usage: $0 directory\n" );
chdir $dir or die "Couldn't change directory to $dir: $!\n";
my @files = grep { -f and /\.( png | jpe?g | tga )$/xi } <*>;
die "nothing to do!\n" unless @files;
my $width = length scalar @files;

for my  $file (@files) {
    (my $new_name = $file) =~ s/(\d+)/ sprintf "%0${width}d" => $1 /e or next;
    next if $new_name eq $file;
    die "$new_name (from $file) already exists!\n" if -f $new_name;
    rename $file => $new_name or die "Couldn't rename '$file' to '$new_name': $!\n";
}
print "Program completed.\n"

Reader exercise: improve this program to number the files from 1 to n, even if the original numbers don't start at 1 or have gaps!


PHP page to edit a user account information and avatar

Security

Possibly Broken Authentication

if(!$user->is_logged_in()) {
    redirect('login.php');
}

[do important stuff]

Make sure that redirect dies. The header redirect you do use doesn't, and if the one of redirect doesn't either, an attacker could easily bypass this check, as a client does not have to follow a header redirect if they do not want to.

Possibly SQL Injection

You mostly use prepared statements, which is good. It's a bit surprising that you do not always use them though:

$edit = $db->prepare("UPDATE members SET user_avatar = :avatar WHERE username ='" . $_SESSION['username'] . "'");

Depening on your - current or future - limitations on username, this is open to SQL injection. You really should always use prepared statements, even if you think the data may be safe. If you need to think about this each time, you will eventually make a mistake.

Misc

your indentation is off, making your code harder to read.
you have quite a lot of comments which only describe what the code does. Most of them can simply be removed, others seem to be there for structuring your code (AVATAR, choosing the avatar, etc). Instead, add more classes/files and functions. Eg you could have a Avatar class, which has a function uploadAvatar (uploadAvatar would likely use a more generic uploadImage or uploadFile function stored in a more generic class).
your code is quite deeply nested, making it hard to read. If you follow the advice of adding more functions, you will already greatly reduce the nesting. Additionally, return early. So if you have checks at the beginning of a function, don't do if (cond) [do the complex thing], but instead if (!cond) return; [newline] [do the complex thing] (instead of just returning, you could return true/false, an error message, throw an exception, etc.
Error... is not a very informative error message.


Guttag's Finger Exercises: Enter 10 integers, find largest odd integer and print result

Python 2.x vs. Python 3.x

As a start, welcome to code review and since this is your first time here, well done, you did a good job here for a first post. One of the most confusing topics for beginner programmers is to choose which version of Python to learn. However there are more benefits to learn Python 3.x since it's the current version of Python and very soon there will be no future security or bug fixes for Python 2.x. and most of the developers nowadays are using Python 3.x, and as I'm familiar with the book you indicated, I know it's written in Python 2.x therefore I suggest you try to look things up and try to apply the same logic you encounter in exercises in Python 3.x (you will just be using a slightly different syntax).

Besides Python 3.x contains a bunch of new features that you'll eventually start using:

the print function
f strings
integer division
and many other features

Style

Here's a reference style guide (pep8) https://www.python.org/dev/peps/pep-0008/, the official Python guide to style you could read and here are a few comments about style:

If an assignment has a right hand side, then the equality sign should have exactly one space on both sides.

even=0

x=int(raw_input('Please enter an integer: '))

if x%2!=0:
Use inline comments sparingly.
An inline comment is a comment on the same line as a statement.
Inline comments should be separated by at least two spaces from the
statement. They should start with a # and a single space.
Use f-strings for better formatting.

ex: print(f'largest odd: {odd_num}')

The if elif else statements:

An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else statement following if.

The use of functions and lists:

You can use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.

You can also use lists when you have more than a few items to do operations on.
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ]

The code can be simplified as follows:

def get_odd_max(n):
    """Return maximum odd number from n numbers, print a message for no odds"""
    odds = []
    evens = []
    for _ in range(n):
        # the use of try and except to catch illegal types without stopping the code execution.
        try:
            number = int(input('Enter an integer: '))
            if number % 2 == 0:
                evens.append(number)
            if number % 2 != 0:
                odds.append(number)
        except ValueError:
            print('Expected int.')
    if odds:
        # f-strings for a cleaner code
        # usually a function does not print anything(it's for the sake of the example)
        print(f'Maximum odd value: {max(odds)}')
        return max(odds)
    else:
        print('No odds found.')
        return 0

if __name__ == '__main__':
    print(get_odd_max(10))


Overall, this looks good, but I think there are a few places it's still open to a little bit of improvement.

Consistency

You're somewhat inconsistent about the type you use for the size (and index into) a polynomial--you have a constructor that takes a size_t, but subscript operator that takes an int. I'd choose one type, and use it consistently. Lacking a really specific reason to do otherwise, I'd use size_t throughout (or see below, and use size_type instead--it's probably a better choice than either size_t or int).

This can also simplify your code a bit. For example, you subscript operator checks for an argument less than zero, but that simply can't exist with size_t.

Consider conforming to container interface

Right now, your Poly type can act quite a bit like a container (e.g., it has begin(), end(), and operator[] just like a container that supports random access iteration. It's fairly trivial to add a few more typedefs to make it a reasonably complete implementation:

typedef T value_type;
typedef T &reference;
typedef std::vector<T>::iterator iterator;
typedef std::vector<T>::const_iterator const_iterator;
typedef std::vector<T>::difference_type difference_type;
typedef std::vector<T>::size_type size_type;

The standard's requirements for containers are spelled out in §[container.requirements] (aka §23.2 in recent drafts), especially Tables 96, 97 and 98.

Use iterators where applicable

This is almost part of the previous point, but (I think) bears being pointed out separately.

Rather than defining begin() and end() to just return pointers, I'd define them to return iterators. I'd at least consider adding the rest of the normal rbegin(), cbegin(), crbegin() (and matching *end()) functions as well.

Use the right member functions

That leads directly to the point: once you've changed its argument to a size_t, your operator[] can be:

T & operator[](size_t i) {
    if (i >= sz)
        throw std::out_of_range{ "Poly::operator[]" };
    return coeff[i];
}

This, in turn, reduces to:

T & operator[](size_t i) {
    return coeff.at(i);
}

I'd also at least consider following the same path as vector, and providing a .at() that does bounds checking and an operator[] that doesn't.

Code arrangement

I'd rather see the two overloads of operator[] right next to each other in the code (without getSize() and operator+= between them). [Yes, this is a pretty minor point.]

Don't repeat yourself

Right now, you operator+= has two legs that start with nearly identical loops:

    if (...) {
        for (int i = 0; i < bsz; ++i)
            coeff[i] += b[i];
    }
    else {
        int i = 0;
        for (; i < sz; ++i)
            coeff[i] += b[i];

        // ...
    }

I'd rather eliminate that duplication. Personally, I'd probably do that by changing the order of operations a little bit. First, I'd resize my vector to the larger of the two sizes, then I'd do the addition:

coeff.resize(std::max(sz, bsz));
for (size_type i=0; i<sz; i++)
    coeffs[i] += b[i];

Alternatively, you could do something like this:

for (size_type i=0; i<sz; i++)
    coeffs[i] += b[i];
for (size_type i=sz; i<bsz; i++)
    coeffs.push_back(b[i]);

In this case, if sz >= bsz, the second loop won't execute (or: "will execute zero iterations"). To work with this, however, you also have to deal with the fact that it could index into a nonexistent element in the b. One way to deal with that would be to rewrite operator[] a bit to treat out of bounds accesses as legitimate, but with a zero coefficient:

T operator[](size_type i) {
    if (i > sz)
       return T{};
    return coeffs[i];
}

So this is basically observing that a polynomial like \$A + bX^2\$ can be treated as \$A + bX^2 + 0x^3 + 0x^4 + ...\$. Obviously this is mathematically fine--since we're giving 0 as the coefficient for any higher order terms, they don't affect the overall value. This way, the right-hand operand of our += can be treated as always having at least as many terms as the left hand operand.

If wanted to get even fancier, we could do roughly the same with T &operator[] as well, but that gets quite a bit trickier, since it would (potentially) have to reallocate the vector of coefficients. At least in my opinion, that's probably more trouble than it's worth (but, I'll repeat: I'd prefer to resize first, and be done with it--it keeps everything simple and neat).

Move Constructor

As far as your question about use of the move constructor goes, the answer to precisely the question you've asked ("I also want to be sure if the move constructor would be called during the addition operation.") is "no".

The move constructor won't (at least normally be called during an addition operation. Rather, it'll be used after the addition operation, to move value from the temporary that's created in the addition, into the destination being initialized from that addition. If you're assigning to that destination rather than initializing it, the move assignment operator will be used instead.

As far as the question you really intended to ask though: yes, these will be used to move the result of an addition into a destination. This is fairly easy to verify by changing your implementation a bit to add some instrumentation:

Poly(Poly &&src) : sz(src.sz), coeff(std::move(src.coeff)) {
    std::cout << "\nMove ctor\n";
}
Poly &  operator = (Poly &&src) {
    sz = src.sz;
    coeff = std::move(src.coeff);
    std::cout << "\nMove assign\n";
    return *this;
}

The result when running your main.cpp is:

4685
Move ctor

Move assign
468

Showing that yes, the move ctor and move assignment operator were actually used.


Program to evaluate powers of complex numbers

C has a built-in complex type and a cpow() function since C99.  You seem to be reinventing-the-wheel.

Only in rare circumstances should you use float.  In most cases, you should use double instead.

Exponentiation of complex numbers is better done using the polar representation:

$$z = r e^{i\theta}$$

where

$$\begin{align}
z &= a + i b \\
r &= \sqrt{a^2 + b^2} \\
\theta &= \arctan{\frac{b}{a}}
\end{align}$$

then

$$z^n = (r e^{i\theta})^n = r\,^n e^{i\ n \theta}$$

For non-trivial values of \$n\$, you would be better off converting to a polar representation, performing the exponentiation, and converting back to the Cartesian representation.


Adjust bootstrap dropdown menu based on page width

I came across this post searching for a fix to a slightly different problem. I have long entries in a drop-down menu that get cut off on small screen sizes.
I found that if I allow the content in the dropdown to wrap it automatically gets adjusted to the page width:

.dropdown-menu > li > a {
    white-space: normal;
}

If you don't want it to wrap if there is enough space, add no-wrap back in with a media query. Because it is so simple I figured I leave this here for others, even though it does not directly apply to the cascading dropdown in your example.


Refactor function that returns a comma Operator to pass jsHint

Simple answer:

var jThat = $(this).remove();
return jThat.attr("name") + "=" + jThat.val() + "&";

There's nothing wrong with calling .remove() right away; the element's still in memory so its attributes be still be accessed. As you said, the remove call is already executed in your code, before the rest.

Longer answer:
Don't write your own query string by concatenating stuff with "&" and "=". It's error-prone, a bother to deal with, and it also means you have to do the slice off the trailing "&" later (which, incidentally, you can do with just skuValues.slice(0, -1)).

jQuery has a $.param() function that's built for this sort of thing. Pass it an array of objects, each with name and a value property, and it'll make a properly encoded query string for you.

// no need to first store `$(".atcLoginRequired")` in a variable,
// and then check its length. If nothing was found, jQuery will
// just ignore the call to .on(). Same result as you checking, and
// and returning if length is zero.

$(".atcLoginRequired").on("submit", function (event) {
  var form          = $(this), // use a more descriptive name than "jThis"
      nextPageInput = form.find("[name='nextpage']"),
      skuValues     = form.find("[name$='_qty']").map(function () {
        var input = $(this).remove(); // again, more descriptive
        // return an object fit for jQuery's param() function
        return {
          name:  input.attr("name"),
          value: input.val()
        };
      }).get();

  // add the nextPage stuff, if there is any
  if( nextPageInput.val() ) {
    skuValues.push({
      name: "nextpage",
      value: nextPageInput.val()
    });
  }
  nextPageInput.val( $.param(skuValues) );
});

Overall, though, I'm wondering what the point is of stuffing a big query string into a hidden input. That's going against the grain. Why not send the inputs to the server as-is, and let it add a bunch of hidden inputs to the next page's form or something? Using an input to store other inputs seems like a kludge.

  What can I do to make this better in terms of readability, performance and extensibility ?

For readability, see above. Less code, more descriptive variable names. You can find better names than mine - I just went for simple ones.

Performance... well, there isn't a whole lot going on. It's not a complex algorithm. If you want performance, skip jQuery and go straight to the native DOM. Of course, that's a hassle to code, which is why jQuery is extremely useful.

Extensibility: In what way exactly? This is, I presume, not a library in itself. It's the end-goal code. So extensibility is sort of moot. But if you want to add more on-submit functionality (like, say, form validation), the first order of business is to not remove elements. If you do that, the next piece of code will just find an empty form. Validation would be sort of pointless if it comes after this code, as it's not going to find anything but a hidden input with a big query string as its value. And if you need to validate that input, you'll need to parse that string, just to get back to the individual values again.


Counting the longest increasing subsequence in an array of integers

Here is one comment about the readability of your code.

/* 1 means not used */
int used_flag[seq_size];

I allowed myself to change the "use" to "used", because it is more grammatically correct.

Now first of all, if "1 means not used", then you should name this array not_used_flag.

Alternatively, you can keep calling it used_flag, but let 0 denote the case of "not used".

If you choose the second option, then you can initialize the entire array upon declaration:

int used_flag[seq_size] = {0};

Please note that it doesn't yield better performance because it's a non-static local array.

Nevertheless, it does clean up your code a bit...

Another point is implied in a comment at the bottom of your code:

/* the initialization value of -1 is just to calibrate the system.
   it takes an extra loop around and gives a wrong result otherwise. */

It sounds like an ugly workaround for "an extra loop" that should not take place.

So I think that you definitely need to solve it properly instead of working around it.

Last issue (though possibly related to the previous one):

while (j < seq_size)
{
    ...
    temp_seq[j+1] = ...;
}

By entering the loop with j == seq_size-1, you'll be writing beyond the boundaries of temp_seq.

Your code might be working correctly for some input, but beware that it does look suspiciously unsafe.


Generating a selection box for the day of the month

I suggest to build a function which can be reused for the options:

function select_options($options, $selected = null) {
  $_options = '';
  foreach ($options as $value => $content) {
    $_options .= sprintf("<option value=\"%s\"%s>%s</option>\n", $value, $value == $selected ? ' selected="selected"' : '', $content);
  }

  return $_options;
}

And some PHP "magic" for the values generation but it is not really needed:

<?php $values = array_map(create_function('&$v', 'return sprintf("%02d", $v);'), range(1, 31)) ?>
<select name="checkInDay" tabindex="3" onchange="calcDay();" class="ffe selectform" id="checkInDate">
  <?php echo select_options(array_combine($values, range (1, 31)), 12) ?>
</select>

But more important than all: in a HTML template, use the PHP alternative notation.


Your escaping for the search term is not sufficient. Other characters than spaces might be in the user entered string, which also need to be escaped. Luckily, requests can do it all for you:

def rechercher_google(search_term, number_results, language_code):
    '''
    input: Nom de l'entreprise à siretiser, le nombre de page et la langue
    output: La page resultat dde google en html stocker au format raw html
    '''
    assert isinstance(search_term, str), 'Il doit etre en string'
    assert isinstance(number_results, int), 'DOit etre en chiffre'

    g_url = 'https://www.google.fr/search'
    params = {"q": search_term, "num": number_results, "hl": language_code}
    response = requests.get(g_url, params=params, headers=USER_AGENT)
    response.raise_for_status()
    return response.text, search_term

Note that I also followed Python's official style-guide, PEP8, and did not use spaces around the = for keyword arguments.

But the obvious improvement is not to parse the Google search results at all, but directly query the website you are interested in. If I understand it correctly, what you actually want to parse is:

url = "https://www.infogreffe.fr/recherche-entreprise-dirigeants/resultats-entreprise-dirigeants.html"
params = {"ga_cat": "globale", "ga_q"=search_term}
response = requests.get(url, params=params, header=USER_AGENT)

That website is not particularly fast either (some pages take 5s to load). But they will probably have worse bot protection than Google, which is a bit evil, but if your scraping is evil, you should not be doing it in the first place. Always read the terms & conditions of websites you want to scrape, so at least you know what you are doing. The Wikipedia page Search engine scraping has quite a lot of information about what Google is doing to prevent you from scraping their search result page too aggressively. In the same vein, you could try optimizing the wait time between the queries, which is currently 11 seconds. With some trial & error you might find a shorter time that also works.


Author class, with constructor validations and rich comparisons

Personally using a namedtuple is the best way to strip most of your code.

If you wish to be able to mutate your data, then inheriting from a list, rather than namedtuple, could be a better idea.
I'm not a fan of _validateid or _validate_author, just write them out in the constructor.

And so I'd personally change your code to:

from collection import namedtuple

class Author(namedtuple('AuthorBase', 'id first_name last_name')):
    def __new__(cls, id, first, last):
        if id < 1:
            raise ValueError('id is not a valid id')
        if not first:
            raise ValueError('first_name has not been set')
        if not last:
            raise ValueError('last_name has not been set')
        return super().__new__(cls, id, first, last)


Error Handling
You check whether the output file was opened correctly, but all you do is output a message (you don't even say what's wrong!) and then you keep on ignoring it. What if file.txt is a directory or read-only? I guess you haven't tested these cases. By default, throw an exception if you can't continue at some point. In this case, throw std::runtime_error("failed to open output file").
Loop Condition
You are reading until the line is empty. This is okay-ish, but why don't you just check whether c.empty() and then break from the loop? Another case is that the end of the input is reached. In that case, the streamstate is set to failed. I'm not sure what happens in getline() then (read the docs at cppreference.com), but if it just doesn't change the string passed by reference, you may end up in an endless loop.
As an alternative I would use getline(cin, c) as loop condition. If this succeeds, you have received a line which can then write to the output file. Otherwise, you either had an error or you reached the end of the input.
Closing Filestreams
If you didn't call fich.close(), when would it be closed? However, consider the possibility that the file can't be written fully. You'll never notice this, neither with your code nor if you let the destructor do its work. So, what I'd rather do there is a call to fiche.flush() followed by a check of the streamstate.
Efficiency
I wouldn't bother with that at the moment. Point is, you're still learning to walk, so don't try to run yet. Still, what you're doing is inefficient. Firstly, writing in size of lines is useless, because you're just moving bytes from one file to the other. Secondly, endl implies a newline and a flush. So this is not really a cheap operation! In addition, there is a lot of stuff going on in C++ IOStreams that there's a whole book about their internals. Lastly, copying files can sometimes be done more efficiently using OS features which will avoid looking at the data more than necessary.


Ruby on rails with active record perfomance

The #dups are probably unnecessary. If you unset the ID ActiveRecord already "thinks" that the object is new, and #save will create a new one in the DB. But the main bottleneck is probably the amount of DB queries generated. The easiest way to gain some performance in such cases is to wrap the whole block into a transaction. The best way would probably use bulk inserts (e.g. with a gem like https://github.com/zdennis/activerecord-import).

But if you've to do so many deep copies you also should rethink if you're using the right approach (or DB) here.


Fetch API is now supported by Firefox, Chrome and Opera, you could use it instead of the ugly XMLHttpRequest. How ironic, by the way, is using XMLHttpRequest to make a JSON reqest?

var data = {};

Since you likely won't be reassigning this variable, you could use const instead. The same is true for var xhr = new XMLHttpRequest();.

for (var i = 0; i < feedbackform.length; i++) {
    var input = feedbackform[i];
    if (input.name && input.value) {
        data[input.name] = input.value;
    }
}

First, that's a perfect use case for a for...of loop. Secondly, if you want to check if a string is empty, it's better to explicitly compare it with an empty string.

I would rewrite this loop like this:

for (let input of feedbackform) {
  if (input.name !== "" && input.value !== "") {
    data[input.name] = input.value
  }
}

feedbackform.send.disabled = true;

It's better to disable the whole form, instead of just the submit button. Did you know that you can submit a form by pressing Enter while focused in an input?

xhr.onloadend = function () {}

Oh come on, it's the 21st century! Why do you still use .onevent properties? You should totally drop that and try jQuery .addEventListener(). See addEventListener vs onclick.

You can also use an arrow function here.

I would rewrite it like this:

xhr.addEventListener("loadend", () => {
  // event listener code
})

if (xhr.status == 200)

Always use three-equals operator (===) for equality comparisons. See Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?.

Besides, 200 isn't the only status code which means that request was successful. There is for example status code 204—No Content. Therefore, you should be checking whether the status code is in 200-299 range:

if (xhr.status >= 200 && xhr.status < 300)

return false;

What purpose does it serve?


According to MSDN, all public and protected members of ConcurrentDictionary<TKey, TValue> are thread-safe and may be used concurrently from multiple threads. However, concurrency only applies to the individual actions performed on the instance of the ConcurrentDictionary. The situation will not get messy, if a thread is performing a write operation and an another thread is performing a read operation at the same time. But, there is no protection within the  ConcurrentDictionary class against the situation, when an information of the past is provided, that has since changed and because of that, an invalid operation is performed.

I do not see the reason of calling ContainsKey, since an another thread could remove that particular element between the ContainsKey and the Dictionary value accessor operations and KeyNotFoundException will be thrown.

if (_processingGateways.ContainsKey(request.GatewayId))
// the element could be removed right at this point during execution
    _processingGateways[request.GatewayId].WaitOne(); // KeyNotFoundException is thrown here
_processingGateways.TryAdd(request.GatewayId, new AutoResetEvent(false));

The key to your solution could be the TryGetValue method. It is going to lock the ConcurrentDictionary for reading and return the element (if it exists).

if (_processingGateways.TryGetValue(request.GatewayId, out var Gateway))
    Gateway.WaitOne();
_processingGateways.TryAdd(request.GatewayId, new AutoResetEvent(false));

(Disclaimer: code uses C#7.0 out variables)

Now your are secured against the exception.

If you inspect the code for possible deadlock situations, you might observe that it is possible, that Set gets executed before WaitOne. It is good to know, that the wait returns when all events are set and it does not matter, whether or not that happened before or after wait was called. Great, no deadlocks here!


Implementation
Your implementation is clean, robust and easy to understand. I suggest only small changes:

Declare multiplesSum as const to prevent accidental rebinding / overriding later on.
multiplesSum(n) should compute the sum of multiples of 3 or 5 up to and including n. Sum formulas are usually following this convention.
I prefer terminating statements with semicolons instead of relying on JavaScript's automatic semicolon insertion.

Algorithm
Your algorithm is simple and easy to understand, but comes with a linear runtime complexity of O(n).
An algorithm with constant runtime complexity O(1) exists. Here are some pointers in case you are stuck:

Given a positive integer n, how often do 3 or 5 fit into n? Division and Math.floor give the answer.
Arithmetic sequences such as 3 + 6 + 9 + ... have simple, explicit sum formulas.
By adding (3 + 6 + 9 + ...) + (5 + 10 + 15 + ...), you count some numbers twice, so you need to find and subtract those.


Returning the common divisors of two integers

I don't know your application, but it seems rather uncommon to me that one would want a list of all common divisors.

To optimize your code, you could use Euclid's algorithm to find the greatest common divisor of the two numbers; this is much faster than iterating through all numbers less than your arguments.  Even more, the common divisors of your two numbers happen to be the divisors of the greatest common divisor.  Thus, the two-step process of finding the greatest common divisor and then finding all divisors of that greatest common divisor will be faster than your current method, since it does not usually have to consider all numbers up to the smaller factor.

An optimization for finding factors of a number \$n\$ would be only to iterate up to \$\sqrt n\$, adding to the list any factor \$k\$ you find as well as \$n / k\$.  A separate idea would be to compute the prime factorization of \$n\$ and finding the factors from that.


Implement an algorithm to determine if a string has all unique characters

If I'd asked an interview question, and got this as an answer (at least as the first answer) I think my immediate reaction would be to consider it excessively clever.

To make much sense, along with the conditions you gave, I'd have had to specify that minimizing memory usage was absolutely crucial.

Under ordinary circumstances, I'd expect an answer something like this:

bool all_unique(std::string const &input) {
    std::map<char> temp(input.begin(), input.end());
    return temp.size == input.size();
}

...or something like this:

bool all_unique(std::string input) {
    std::sort(input.begin(), input.end());
    auto p = std::unique(input.begin(), input.end());
    return p == input.end();
}

There are, of course, variations on these themes (e.g., perfectly reasonable and acceptable to use unordered_set instead of set).

Either of these will work with a much wider range of inputs than you've specified. They will use more storage, but the amount they use is still too small to matter under any normal circumstances.

If somebody were going to craft a special-purpose set of their own, I'd normally expect them to start from std::bitset or std::vector<bool>. I guess if they insisted on starting with a native type to represent their bits, I wouldn't object too terribly much, but I'd be a little disappointed if they chose int for that type.

If you want a bag of bits, you should usually use an unsigned type.
If you want at least 32 bits, you should use a type that guarantees at least 32 bits (int only guarantees at least 16 bits).

As such, obvious choices would be unsigned long and uint32_t.


Advent Of Code 2017 Day 4 (part 1) in Functional Programming (FP)

I don't remember where I saw it (maybe one of your other posts) but I recently saw a technique for ensuring uniqueness of array elements - iterate over the elements and just return the equality of the current index to the value returned by calling Array.indexOf(). Using that technique here, Array.every() can be used to ensure each word is unique.

With that technique, there is no need to count the number of occurrences of each word and hence the reduction can be removed. Thus countDuplicate can be eliminated and onlyUniqueWords can be simplified like below:

const onlyUniqueWords = phrases => {
    const words = phrases.split(' ');
    return words.every((word, index) => words.indexOf(word) === index);
};

Here is a jsPerf comparing this technique with the original. The original appears to be ~83-86% slower.

In the snippet below (and the jsPerf mentioned above), I replaced the 3rd line (i.e. ...) with two lines similar to those in the problem description. The first inserted line has unique words and the second does not.

const INPUT =
`pphsv ojtou brvhsj cer ntfhlra udeh ccgtyzc zoyzmh jum lugbnk
vxjnf fzqitnj uyfck blnl impo kxoow nngd worcm bdesehw
aa bb cc dd
aa bb cc dd ee cc
caibh nfuk kfnu llfdbz uxjty yxjut jcea`;

const get = input => input.split('\n');
const onlyUniqueWords = phrases => {
  const words = phrases.split(' ');
  return words.every((word, index) => words.indexOf(word) === index);
};

const phrasesWithUniqueWords = get(INPUT).filter(onlyUniqueWords);
console.log("solution ", phrasesWithUniqueWords.length);

P.S. I feel like this technique could very easily apply to your subsequent post for the 2nd part of this...,
 but perhaps for the sake of varying ideas, I shall refrain from mentioning this in that post...


Simple but (hopefully) safe C nodes for data structures

It's very misleading that destroy_node (singular) actually recursively frees all nodes in the chain.

It's very weird that create_node allocates two nodes rather than one.  In fact, you do have a memory leak in your main():

first->next = second;

There, you have just overwritten the 42 node's next pointer without having freed it.

To answer this question…

// How necessary are these checks? Under which circumstances
// could this return NULL?
if (result == NULL) {
    return NULL;
}

If malloc() fails (because no more memory is available), it will return NULL.  Yes, it is good practice to check whether malloc() failed.  (In practice, if you are so low on memory that you can't even allocate a single linked-list node, it's very difficult to recover gracefully.  Your program is going to die, and there's not much you can do about it.)


Ok, after the hint from the comment it makes more sense for me. I felt a bit bad because of the wrong comment, so I have investigated this deeper.

As far as I see it, there is only one problem which I will explain in the next paragraph. But I have to admit, the implementation is rather complex because we have several layers of parallelization and locking with multiple data structures. It would need very carefully analysis to prove the correctness.

The problem I found is the remove method. You have implemented remove(int):

@Override
public V remove(int index) {
    writeLock.lock();
    try {
        return super.remove(index);
    }finally {
        writeLock.unlock();
    }
}

But you are using remove(Object):

public boolean remove(Key key, ListValue value) {
    final List<ListValue> list = values.get(key);

    if (list == null) {
        return false;
    }

    return list.remove(value);
}

Test case to show it:

    final int max = 500;
    final int maxThreads = 200;
    for (int i = 0; i < max; i++) {
        final int currentI = i;
        final List<Thread> threadList = new ArrayList<>();
        for (int j = 0; j < maxThreads; j++) {
            final int currentJ = j;
            threadList.add(new Thread(new Runnable() {
                @Override
                public void run() {
                    map.add(currentI, currentJ);
                    map.remove(currentI, currentJ);
                }
            }));
        }
        for (final Thread thread : threadList)
            thread.start();
        for (final Thread thread : threadList)
            thread.join();
    }

    if (map.getEntrySet().size() != max)
        System.err.println("entryset size should be: " + maxThreads + " is:" + map.getEntrySet().size());

    for (final Entry<Integer, ConcurrentList<Integer>> entry : map.getEntrySet()) {
        final ConcurrentList<Integer> value = entry.getValue();
        if (value.size() != 0)
            System.err.println("value size should be: " + 0 + " is:" + value.size() + ", value: " + value);
    }

This can easily be solved, if you just implement the remove(Object) method:

@Override
public boolean remove(final Object o) {
    writeLock.lock();
    try {
        return super.remove(o);
    } finally {
        writeLock.unlock();
    }
}

This errors could be avoided if you use one of the following patterns:

Use a synchronized list here, Vector (not recommended), CopyOnWriteArrayList or Collections.synchronizedList
Use encapsulation, rather then extension. Do not extend ArrayList, use implements List and use a member field with the backed up data structure. This will be in the end, nearly the same as using Collections.synchronizedList, but you could avoid the mutex and use the ReantrantLocks if you really need it

As already partly mentioned in my comment. To get the code running, I had to change the generic identifier Value to ListValue at some places, it looked like they were mixed up.


Creating a sorted hash counting the occurrences of a number in an array

Not sure which viewpoint this would be, but this is what I came up with:

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}]

Update: I'm not thrilled with this, but this one sorts by the occurrence count, descending.

Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}.sort_by {|a| a[1]}.reverse]


I totally agree with liuyu that a proper in-memory database like sqlite3 will be much more efficient and useful than what you have here.

But just reviewing your code as it is:

There's no documentation. How are we supposed to use this class?
There are no test cases. You could use the doctest module to make your example code into a runnable test case.
You don't follow the Python style guide (PEP8). In particular, if you kept to the maximum line length of 79 columns, then we could read your code here without having to scroll the window.
From is a poor name: it doesn't clearly communicate the meaning of the class. An instance of the From class represents an table of records, so I would give the class a name like Table.
Unless you have a particular reason to make an old-style class, you should write:

class From(object):

so that you get a new-style class which is portable to Python 3. See "new-style and classic classes" in the docs.
Instead of providing methods length to get the length of the table, and get to get the table itself, why not make your class into a sequence? That is, instead of length you'd provide __len__ and instead of get you'd provide __iter__ and __getitem__. Then callers could just iterate over your From items in the usual way:

for record in From(...):

If you derived your class from the abstract base case collections.Sequence, you'd also get __contains__, __iter__, __reversed__, index, and count methods for free.
It would be most natural to return each record as a collections.namedtuple object, so that the caller can refer to the columns by name:

for record in From(...).select('description', 'count'):
    print('Part: {0.description}. Number: ${0.count}'.format(record))

The special case in get seems like a bad idea. It is generally best for functions to have simple and clear specifications. If you want a convenient method for returning a single column as a list, then you should write that as a separate method.
The index method on a list has to scan along the whole list comparing with each element in turn. You should consider building a dictionary in which you can look up the column name and get its index. (Or if you use namedtuple you can write getattr(row, column).)
There's very little error checking. For example, in __init__, wouldn't it be worth checking that the array has the right number of columns?
There are a couple of problems with your unique method: (i) The comment should be a docstring; (ii) by using a dictionary you don't guarantee to get the records out in the order they went in. I would use collections.OrderedDict to ensure that order of rows is preserved.

So I'd write something like this:

from collections import namedtuple, OrderedDict, Sequence

class Table(Sequence):
    """Table(name, data, columns) represents a 2-dimensional table of data
    whose column names are given by the columns argument.

        >>> from operator import attrgetter
        >>> planets = Table('Planet', [
        ...     ('Mercury',   58,    88),
        ...     ('Venus',    108,   225),
        ...     ('Earth',    150,   365),
        ...     ('Mars',     228,   687),
        ...     ('Jupiter',  779,  4333),
        ...     ('Saturn',  1433, 10759),
        ...     ('Uranus',  2877, 30799),
        ...     ('Neptune', 4503, 60190)],
        ...     ('name', 'semi_major_axis', 'period'))

    Iterating over the table yields the rows as namedtuple objects:

        >>> max(planets, key=attrgetter('semi_major_axis'))
        Planet(name='Neptune', semi_major_axis=4503, period=60190)

    You can filter the table to get a subset of the rows:

        >>> planets.filter(lambda p: p.period > 10000)
        ... # doctest: +NORMALIZE_WHITESPACE
        Table('Planet',
              [Planet(name='Saturn', semi_major_axis=1433, period=10759),
               Planet(name='Uranus', semi_major_axis=2877, period=30799),
               Planet(name='Neptune', semi_major_axis=4503, period=60190)],
              ['name', 'semi_major_axis', 'period'])

    Or select a subset of the columns:

        >>> planets.select('name')
        ... # doctest: +NORMALIZE_WHITESPACE
        Table('Planet',
              [Planet(name='Mercury'),
               Planet(name='Venus'),
               Planet(name='Earth'),
               Planet(name='Mars'),
               Planet(name='Jupiter'),
               Planet(name='Saturn'),
               Planet(name='Uranus'),
               Planet(name='Neptune')],
              ['name'])

    If you just want the values from a column, use the column method:

        >>> ' '.join(planets.column('name'))
        'Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune'

    """
    def __init__(self, name, table, columns):
        self.name = name
        self.columns = list(columns)
        Row = namedtuple(self.name, self.columns)
        self.column_set = set(self.columns)
        self.table = [Row(*row) for row in table]

    def __len__(self):
        return len(self.table)

    def __getitem__(self, key):
        return self.table[key]

    def __iter__(self):
        return iter(self.table)

    def __repr__(self):
        return '{0}({1.name!r}, {2!r}, {1.columns!r})'.format(
            self.__class__.__name__, self, list(self))

    def column(self, column):
        """Generate the values in the given column."""
        assert(column in self.column_set)
        for row in self:
            yield getattr(row, column)

    def filter(self, condition):
        """Return a new Table containing only the rows satisfying
        condition.

        """
        return Table(self.name, filter(condition, self), self.columns)

    def where(self, column, value):
        """Return a new Table containing the rows from this table for which
        the given column has the given value.

        """
        assert(column in self.columns)
        return self.filter(lambda row: getattr(row, column) == value)

    def whereNot(self, column, value):
        """Return a new Table containing the rows from this table for which
        the given column does not have the given value.

        """
        assert(column in self.columns)
        return self.filter(lambda row: getattr(row, column) != value)

    def select(self, *columns):
        """Return a new Table consisting only of the given columns of this
        table.

        """
        assert(all(c in self.columns for c in columns))
        return Table(self.name,
                     ((getattr(row, c) for c in columns) for row in self),
                     columns)

    def unique(self, *columns):
        """Return a new Table containing one row for each unique combination
        of values in the given columns. (If there are multiple rows
        with the same combination of values, the last one is
        included.)

        """
        assert(all(c in self.columns for c in columns))
        result = OrderedDict((tuple(getattr(row, c) for c in columns), row)
                             for row in self)
        return Table(self.name, result.values(), self.columns)


The code is simple to understand and does what it needs to do. Just some remarks:

Whenever you use the ECB cipher mode, you must justify in written form why you use it. This is because this cipher mode can reveal patterns in your plain text.
Converting the encrypted bytes to an UTF-8 string doesn't make sense. You should better print them in hex or base64.
Your code contains duplicates. You could extract that code into a method:

private AesCryptoServiceProvider CreateProvider(byte[] key) {
    return new AesCryptoServiceProvider {
        KeySize = 256,
        BlockSize = 128,
        Key = key,
        Padding = PaddingMode.PKCS7,
        Mode = CipherMode.ECB
    };
}

You made the Encrypt method public, but Decode is private. I don't see a reason for this asymmetry.