A little next combination program in C++

using std::cout;, while better than including the entire namespace, is still worse than simply using the std:: prefix. If typing it annoys you too much, you can just make a macro in your editor to type it for you when you press a certain key combo.

Overall this looks much more like a C program than a C++ one. Assuming your algorithm works as intended you can take some steps to make this more C++ idiomatic?

Replace the array with a vector and get rid of raw pointers.
Enforce const when possible.
Drop return 0 from main because the compiler will generate it for you. This refers excplicitly to the return 0 at the end of main. Exiting from main by reaching the end automatically returns 0. So adding the return statement is just duplicate code.
Prefer prefix over postfix operator.
Move the logic into a class so you don't have to pass everything on every call to nextCombination.
You can overload operator<< to print the current line.
Eliminate magic numbers.

Keeping all this in mind, the rewrite could look something like this:

#include <iostream>
#include <iterator>
#include <vector>

class Combinatorics {
public:
    Combinatorics(std::vector<int> const& v, int const& n, int const& r)
        : elements{v}
        , n{n}
        , r{r}
    {}

    friend std::ostream& operator<<(std::ostream& os, Combinatorics const& obj);

    bool next() {
        int lastNotEqualOffset = r - 1;
        while (elements[lastNotEqualOffset] == n - r + (lastNotEqualOffset + 1)) {
            --lastNotEqualOffset;
        }
        if (lastNotEqualOffset < 0) {
            return false;
        }
        ++elements[lastNotEqualOffset];
        for (int i = lastNotEqualOffset + 1; i < r; ++i) {
            elements[i] = elements[lastNotEqualOffset] + (i - lastNotEqualOffset);
        }
        return true;
    }

private:
    std::vector<int> elements;
    int n;
    int r;
};

std::ostream& operator<<(std::ostream& os, Combinatorics const& obj) {
    std::copy(obj.elements.begin(), obj.elements.end(), std::ostream_iterator<int>(os, " "));
    return os;
}

int main() {
    constexpr int n = 7;
    constexpr int r = 3;
    int total = 0;
    Combinatorics combinatorics{{1, 2, 3}, n, r};
    do {
        std::cout << combinatorics << "\n";
        ++total;
    } while (combinatorics.next());
    std::cout << total << "\n";
}

You simply pass all your data into the constructor upfront and then call next until every repetition has been done. (I kept n and r because they are used in the math context, normally you should try to avoid short variable names like that).


Recurrent action on concurrent collection

Your Stop method does not actually stop the timer. This is

really counter-intuitive
wastes CPU

There is also a racing condition. If someone calls Stop in-between those two lines:

           if (!this.IsStopped)
            this.Start();

the Stop call will be ignored. The moral of the story: just take the lock.

Timer implements IDisposable. So you should call Dispose when you no longer need it (in Stop method, for example.)

I would refactor actionOnItems into a public event.

int for time period is ambiguous and limiting. I can not use your class, if I want to send updates every 0.5 seconds, and I can easily make an error by assuming, that int represent milliseconds. You can eliminate those problems by replacing it with TimeSpan.

Edit: Also your AddRange method rises some red flags. I assume it is not an atomic operation, and you add items to the bag one by one. What will happen, if AddRange is called right before Interlocked.Exchange(ref this.items, new ConcurrentBag<T>()); ? Do you think the new items will go to the new bag or to the old one? How is your extension method synchronized with the rest of your code? You are walking on the really thin ice here. If you have a limited experience with multi-threading, I suggest you start simple. Remove ConcurrentBag, use regular list, but lock every single access point (both  public AND private, methods AND properties). Once this is working, test if it meats your performance requirements. If it does, leave it at that. There is no point in fighting over nanoseconds if

You do not actually need those nanoseconds

and

You get an extremely bug-prone code as a result


Adding support to Busybox vi for reading file from stdin

Can be slightly smaller
I was able to shrink your function a little by combining the two calls to text_hole_delete into one call.  I'm not sure what compiler options you are using, but when I used gcc -Os on a 32-bit x86 target, it saved 16 bytes.  Here is the modified code:
int fd_insert(int fd, char *p)
{
    int size       = BUFSIZ;
    int cnt        = 0;
    int total      = 0;
    int unusedSize = 0;
    int ret        = 0;

    do {
        total += cnt;
        p     += text_hole_make(p + total, size);
        cnt    = full_read(fd, p + total, size);
    } while (cnt == size);

    if (cnt < 0) {
        status_line_bold_errno("can't read from fd");
        ret        = cnt;
        unusedSize = total;
    } else {
        total     += cnt;
        ret        = total;
        p         += total;
        unusedSize = size - cnt;
    }

    // shrink unused space
    if (unusedSize)
        text_hole_delete(p, p + unusedSize - 1, NO_UNDO);
    return ret;
}


Efficient String permutations calculation in Java

Why are you giving as parameter to permutations a permutationsList, that you will both mutate and return? The purpose of this method is to generate the permutations of the given input; it shouldn't need to take any list as parameter, and should just return the result. (Also, node that this method is only called by giving it a new array list, which hints that it isn't really needed).

Also, why does it take a StringBuilder as parameter? This method doesn't try build a String with it, it just get its length and the character at a given index. So pass it a String.

Therefore, consider this instead:

private static List<String> permutations(String input) {
    List<String> permutationsList = new ArrayList<>();
    // ...
    return permutationsList;
}

And with this small change, we can clarify the code more. We would have

List<String> permutationsList = new ArrayList<>();
if (input.length() == 0 || input.length() == 1) {
    permutationsList.add(input);
} else {
    // ...
}
return permutationsList;

(We don't need to call toString() anymore since the argument is now a String). The first part handles the base condition of the recursion. Notice that it builds a new list, only to add a single element to it and return it directly. Instead, we can use the optimized Collections.singletonList(o) which directly returns a list containing the single given element. Now we can have:

if (input.length() == 0 || input.length() == 1) {
    return Collections.singletonList(input);
}
List<String> permutationsList = new ArrayList<>();
// ...
return permutationsList;

No need for an else-clause, and the use of the early return saves one level of indentation and adds to clarity.

Then, we can move on to the scope of the variables. So far, the code is:

char prefix;
StringBuilder substring;
for (int i=0; i<input.length(); i++) {
    prefix = input.charAt(i);
    substring = new StringBuilder(input).deleteCharAt(i);
    // ...
}

Why declare the variables outside of the for loop? They are only used inside of it; variables should have the tighter scope possible. Instead, consider:

for (int i=0; i<input.length(); i++) {
    char prefix = input.charAt(i);
    StringBuilder substring = new StringBuilder(input).deleteCharAt(i);
    // ...
}

which saves in lines of code, makes sure prefix and substring have a minimal scope and is overall clearer.

Finally, the inner for loop calculates String.valueOf(prefix) each time, when the result will always be the same.

char prefix = input.charAt(i);
// ...
for (String str : permutations(substring)) {
    permutationsList.add(String.valueOf(prefix) + str);
}

This could be done a single time and reuse the result with

String prefix = String.valueOf(input.charAt(i));
// ...
for (String str : permutations(substring)) {
    permutationsList.add(prefix + str);
}

With all that, the end result is:

private static List<String> permutations(String input) {
    if (input.length() == 0 || input.length() == 1) {
        return Collections.singletonList(input);
    }
    List<String> permutationsList = new ArrayList<>();
    for (int i = 0; i < input.length(); i++) {
        String prefix = String.valueOf(input.charAt(i));
        String substring = new StringBuilder(input).deleteCharAt(i).toString();
        for (String str : permutations(substring)) {
            permutationsList.add(prefix + str);
        }
    }
    return permutationsList;
}

Other comments:

permutateString is a wrong name. The word "permutate" doesn't exist, it should be "permute". But actually, even that would be a wrong name: the method doesn't actually permute the given String. It prints the permutations of it. The difference is that, with a method named permuteString, one would expect it to return the permutations, except this one doesn't, since it prints them. Consider renaming it printPermutationsOf.
If you worry about the memory and time efficiency of the algorithm, then you're likely not using the right tool here. Building all the permutations will be memory intensive (with all the objects to build), and very slow (complexity is O(n!), where n is the length of the String). It is only practical for short Strings: there are already more than 3 millions permutations for a String of length 10. Depending on the use-case, you will either want to filter some of them, or even use a completely different approach that doesn't require building any permutations.


Public property, backing up by a private field, with caching and null checking inside

Good thinking about the caching and efficiency. I have two minor suggestions

1 - Enforce SRP (single responsibility principal), which basically states (according to Robert C. Martin) that in the world of "Clean Code" classes must have one reason to change for better maintainability, which is one of the concerns you had in your question. So to apply this to your case, the class that contains the Profile property need not be changed if you decide to change the signature of the ProfileFacade.Instance.GetMainProfileByType method, or maybe choose another method to populate the Profile. So maybe refactoring that code out of the class would be a good idea. Here is what I mean by that:

private Profile _individualProfile;
public Profile IndividualProfile
{
    get
    {
        if (_individualProfile != null) return _individualProfile;

        return (_individualProfile = ProfileFacade.Instance.GetIrnicProfile() ?? Profile.NullProfile);
    }
}

As you can see in the code snippet I used the short hand null check using the ?? null-coalescing  operator.

2 - NULL object pattern. Basically define the neutral state (or NULL state) of your object inside the object itself, benefiting from not changing the calling code if ou decide to redefine what the NULL means for your object. In my code snippet I added Profile.NullProfile which is defined as such:

public class Profile
{
    public string FirstName { get; set; }
    // Other properties here
    public static Profile NullProfile
    {
        get
        {
            return new Profile
                        {
                            FirstName = String.Empty,
                            // etc...
                        };
        }
    }
}

Other than that... Good work!


Handling session resources in MY_Controller with Codeigniter

You don't really need to check for is_logged_in.  If you destroy/build the session data correctly all you should care about is "Does a user id exist in the session?", then you can let your main controller handle the rest.

class MY_Controller extends CI_Controller{

    //here we just build some constants to check against values
    //in the permissions array
    const PERM_READ = "read";
    const PERM_EDIT = "update";
    const PERM_DELETE = "delete";

    //here we let the main controller take care of our auth/permissions/roles etc
    //first check if a user id exists in the session
    //if so assign a user, group, permissions and check for authentication where
    //you need it ( ie: child controllers)

    protected $_user, $_group, $_permissions = array();

    public function __construct(){
        parent::__construct();

        //check for a user id in the session
        $this->user = ( $this->session->userdata('uid') )
                    ? User::find_by_id( $this->session->userdata('uid') )
                    : NULL;

        //if user exists assign permissions and group
          if ($this->user !== NULL) {
              $this->_assign_group();
              $this->_assign_permissions();
              $this->_check_for_banned_users();
          }

    }

    protected function _assign_group() {
        return $this->group = $this->user->group->name;
    }

    // {["read", "update", "delete"]}
    protected function _assign_permissions() {
        return  $this->permissions = json_decode($this->user->permissions);
    }

    protected function _check_for_banned_users() {
        if ($this->group === 'banned') {
            show_error('You have been banned from this website!');
            return;
        }
    }

    protected function _can_read(){
        return (bool) ( in_array( self::PERM_READ, $this->permissions) );
    }

    public function _can_edit(){
        return (bool) ( in_array( self::PERM_EDIT, $this->permissions) );
    }

    public function _can_delete(){
        return (bool) ( in_array( self::PERM_DELETE, $this->permissions) );
    }
}

This might give you some idea, as your user table won't look like that, I'm sure.

Now, you have control over any child classes.

class some_child extends MY_Controller{

     public function __construct(){
         parent::__construct();
     }
     public function show_something(){

          if($this->is_ajax_request()){
              if($this->user && $this->_can_read()){
              //yes a user exists and is logged in,
              //yes he has permission to read from this section
              $this->load->view('some_view');
              }
          }
          else
             show_404();
     }
}

Just be careful to destroy your session properly.

function logout(){
    $this->session->set_userdata(array(
         'uid'  => 0,
         //any others you created upon user login
    ));
    return (bool) $this->session->sess_destroy();
}


Extension methods for translation engine

This is a horrible misuse of extension methods.  The only thing worse (and I'm sure you'll see it) is (n+5).Translate(...).  You're absolutely correct - the starting point for the mistake is in thinking of the integer as the base object for the translation.  There are a number of well-understood patterns for handling localization, and this isn't any of them.  Since we're talking C#, there's the obvious resource technique, but there are others as well.  The GNU Project pioneered the _("blah blah blah") mechanism, where the default string serves as a key in a locale-specific table of replacements (along with the Windows OS and MS Office, this is one of the most prevalent and successful translation systems).  And then there's the tried-and-true dictionary-indexed-by-a-named-constant (often an enum member), often encapsulated behind a Language class with a Translate(...) method.


Two versions of Word Break II - exhaustive combinations

The first solution

There's a bug in the first loop:

    for w in wdict:
        if s.startswith(w):
            if len(s) == len(w):
                ans.append(w)
                return ans
                ^^^^^^^^^^ should not do this!
            st.append((w, 0, [w]))

It's not correct to return when one of the words is the same as the sentence,
because there might be other words to compose that sentence.
At it is, the program produces incorrect result for the input:

"foobar"
["foobar", "foo", "bar"]

The first loop duplicates some of the logic of the second loop.
You can remove the first loop completely if you initialize st like this:

st = [('', 0, [])]

This solution is much slower than the second,
because unlike the second,
it doesn't do anything to avoid repeated computation of sub-problems.
For example, if the input string is "foobar" + some_very_long_string,
and the word list has "foo", "bar", and "foobar", then the sentences for some_very_long_string will be computed twice at least, for the "foo bar" and "foobar" prefixes.

The second solution

The posted code is broken, probably you copy-pasted a work-in-progress version:

result_of_rest = helper(s[len(word):], wordDict, memo)

This line references the nonexistent function helper,
and the nonexistent variable wordDict.
The fix is easy enough:

result_of_rest = inverse_helper(s[len(word):], wdict, memo)

Next time please make sure to post working, verified code!

This solution implements memoization manually.
Python has a cool technique to make this easier,
using lru_cache from the functools package.
In a nutshell,
all you need is a function with hashable arguments,
and then you can simply annotate it with @lru_cache to benefit from easy memoization.

from functools import lru_cache

def word_break_helper(text, wdict):
    @lru_cache(maxsize=128)
    def helper(s):
        res = []
        for word in wdict:
            if not s.startswith(word):
                continue
            if len(word) == len(s):
                res.append(word)
            else:
                for sentence in helper(s[len(word):]):
                    res.append(word + ' ' + sentence)
        return res

    return helper(text)

Use better names

The names used in both solutions are quite poor.

I don't know what's "inverse" about these solutions.
Sure, the first one uses a stack, to which it appends and pops values,
but it's not really important anyway.
So I don't get "inverse" in these names.

res, and ans are poor as well. Why not naturally sentences?

wordDict doesn't follow Python naming conventions (should be snake_case).

Further improving performance

Although it doesn't seem to be important in this puzzle,
looping over the list of supported words to find possible prefixes would be inefficient with a large number of words.
You could use a more efficient data structure to retrieve potential prefix words without iterating over all the supported words.


This code is pretty well written, although there are a few things that really bug me a little.

First off, inline comments, like the one you've positioned inside that for loop, are eyesores to look at. Preferably, comments should stay on their own separate lines.

Secondly, your naming could be improved. For example, what does the variable cen do? It's name doesn't give any hint as to what it does, nor do it's contained items, a and b. Variable names should be descriptive, and describe the purpose of a variable, all while not being too long, or too short.

Finally, use braces around your if statements. Have you ever heard of the "goto fail" bug? That's what happened in a bug with Apple SSL. The error, in question, looked something like this:

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;  /* MISTAKE! THIS LINE SHOULD NOT BE HERE */

Just use braces. They'll prevent all sorts of mistakes from occurring, and they'll make things look clearer overall as well.


C# static class holding list of member class instances

I think your tokens <fromUnit> and <toUnit> should be public static readonly string fields, instead of being hard-coded the way they are. This turns eventDescriptions into something like this:

private static string[] eventDescriptions = new string[8]
{
    FromUnitToken + " walked",
    FromUnitToken + " waited",
    FromUnitToken + " inquired",
    FromUnitToken + " allured " + ToUnitToken,
    FromUnitToken + " persuaded " + ToUnitToken,
    FromUnitToken + " bribed " + ToUnitToken,
    FromUnitToken + " hired " + ToUnitToken,
    FromUnitToken + " attacked " + ToUnitToken,
};

And then the Event constructor can do something like this:

    description = description.Replace(EventLog.FromUnitToken, _fromUnit.GetComponent<UnitData>().firstName + " " + _fromUnit.GetComponent<UnitData>().lastName);
    description = description.Replace(EventLog.ToUnitToken, _toUnit.GetComponent<UnitData>().firstName + " " + _toUnit.GetComponent<UnitData>().lastName);

The description field is problematic though:

public string description;

Instance fields shouldn't be public - that's breaking encapsulation, anyone that can use an Event instance can do whatever they want with that value. Better encapsulate it:

private readonly string description;
public string Description { get { return description; } }

Fields initialized from constructor should be marked readonly if that's the intent - it makes the intent clearer.

In AddEvents, you're adding events, and then removing whatever exceeds your max capacity:

events.Add(new Event(_fromUnit, _toUnit, _actionType));

if (events.Count > maxEventsInLog)
{
    while (events.Count > maxEventsInLog)
    {
        events.RemoveAt(0);
    }
}

Looks like you want some First In, First Out data structure - a List just isn't practical for that - consider using a Queue<Event> instead.


Appending unique data to a postgres table

First of all I don't know Python, so I will try my best.

For the first portion of code, why do you put 7 days as offset? If the file delays more than 7 days your script will crash. I would do a SQL query for that. One like this:

Select max(report_date) from table;

and now you have the latest date.

For the second part your code seems ok, but personally I don't see the reason to update the whole month every day, that will be problematic.

For me, the best solution is find the latest date, I gave you the query up there, and after that advance day by day looking for files up to today.


Find whether two (or 'n') particular values are present in a binary tree

Reading the title, you want a solution that covers N values. Looking at your code, it doesn't meet that expectation. Not do I see you writing all variants from 1 to N.

As API, you have 2 options: compile time N or runtime.
If you go for the compile time, use variadic templates in the call. Otherwise, go for std::vector. As I always mess up the ..., I'll continue with the vector.

Your current approach makes good use of cache locality. Really interesting if the tree is big. Alternatively, you could check each element 1 by 1, really good for a big number of values if you expect a lot of miss matches.

What I would suggest is the following:

bool CheckIfValuesPresentInTree(Node* root, const std::vector<int> & n) {
     auto f = std::vector<bool>{};
    f.resize(n.size(), false);
    IsPresent(root, n, f);

    return std::all_of(f.cbegin(), f.cend());
}

void IsPresent(Node* p, const std::vector<int> &n, std::vector<bool> &f) {

    if (!p) {
        return;
    }

    for (size_t i = 0; i < n.size(); ++i)
    {
      if (p->data == n[I])
           f[I] = true;
    }

    IsPresent(p->left, n, f);
    IsPresent(p->right, n, f);
}

About your question on whether to stop searching once everything if found. Ain't an easy question, given the existing API, I wouldn't bother as it might be more expensive to check.

It can however be done by changing the way you indicate if the value is found. Instead of using the bool, you could use the n to keep track of values you still need to search.

void IsPresent(Node* p, std::vector<int> &n) {

    if (!p) {
        return;
    }

    for (auto it = n.cbegin(); it != n.cend(); /**/)
    {
      if (p->data == *it)
           it = n.erase(it);
     else
           ++it;
    }

    if (n.empty())
        return;

    IsPresent(p->left, n);

    if (n.empty())
         return;
    IsPresent(p->right, n);
}

The advantage of this, is that the amount of values you are checking reduces while searching. The check on whether you need to terminate becomes really cheap, at the expense of some bookkeeping.


!!! Use this at your own risk. Fiddling with user's packages is scary business !!!

You can monkey-patch the builtin import statement and upon encountering ModuleNotFoundError install whatever dependency is missing. Here is a small example for a script.py. You can of course extend this to feature multiple files or dynamically use the file given as input.

import builtins
import pip
old_import = __import__

def my_import(name, globals=None, locals=None, fromlist=(), level=0):
    if globals["__name__"] == "script":
        try:
            return_args = old_import(name, globals=globals, locals=locals,
                                    fromlist=fromlist, level=level)
        except ModuleNotFoundError:
            builtins.__import__, temp = old_import, builtins.__import__
            pipcode = pip.main(['install', name])
            if pipcode != 0:
                builtins.__import__ = temp
                raise
            else:
                return_args = old_import(name, globals=globals, locals=locals,
                                    fromlist=fromlist, level=level)
                builtins.__import__ = temp
    else:
        return_args = old_import(name, globals=globals, locals=locals,
                                fromlist=fromlist, level=level)

    return return_args

builtins.__import__ = my_import

import script

and the script.py is your custom script:

import os
from time import time

import argh  # this should be installed

print(time())

Note: People sometimes do things like:

try:
    import optional_module
except ImportError:
    pass  # optional all cool

Above code patches import itself. If you remove the if that limits install powers to script you allow recursive installation for everything that is imported. Ever. Even if it is an optional dependency for a 4th level dependency test case of script pip will try to install it.


Counting standard deviation from parsed XML file

Be careful with instation of same object multiple times for same use- as it may change in use. If and when the first instantiation will be disposed, however, depends. The Java runtime environment traces references, so as long as there are any references to an object in use, the object won't be disposed. Note that the dispose itself does not happen immediately, but sometimes later, the next time when the garbage collector is run. But that is independent from the semantics of the code discussed, thats only a question of memory and performance.
I would use a HashMap for the Data Structure to count deviation.
Such as this example:

  HashMap hm = new HashMap();
  // Put elements to the map
  hm.put("Zara", new Double(3434.34));
  hm.put("Mahnaz", new Double(123.22));
  hm.put("Ayan", new Double(1378.00));
  hm.put("Daisy", new Double(99.22));
  hm.put("Qadir", new Double(-19.08));


There's no better way than creating a temporary dictionary to quickly update the contents of the entire file the way you want. However you can speed things by not using csv.DictReader and csv.DictWriter because they require building a separate temporary dictionary for each row processed.

Here's a more efficient version based on that supposition that also effectively updates the file "in-place". Note that the order of the rows in the file will be changed as a result of storing them temporarily in the dictionary. If that's important, use a collections.OrderedDict instead.

Also noteworthy is that it would be even more efficient to use @user3757614's suggestion, and instead do a less complicated mydict.update(temp_dict) (and then write mydict.items() out as the updated version of the file). If you want to preserve mydict, just make a copy of it first and then update that with temp_dict's contents.

import csv
import os

mydict = {
    "name2" : "pass2",
    "name3" : "pass3"
#     ...
}

csv_file = 'users.csv'  # file to be updated
tempfilename = os.path.splitext(csv_file)[0] + '.bak'
try:
    os.remove(tempfilename)  # delete any existing temp file
except OSError:
    pass
os.rename(csv_file, tempfilename)

# create a temporary dictionary from the input file
with open(tempfilename, mode='rb') as infile:
    reader = csv.reader(infile, skipinitialspace=True)
    header = next(reader)  # skip and save header
    temp_dict = {row[0]: row[1] for row in reader}

# only add items from my_dict that weren't already present
temp_dict.update({key: value for (key, value) in mydict.items()
                      if key not in temp_dict})

# create updated version of file
with open(csv_file, mode='wb') as outfile:
    writer = csv.writer(outfile)
    writer.writerow(header)
    writer.writerows(temp_dict.items())

os.remove(tempfilename)  # delete backed-up original


Compare two columns and fill in a third column

This is how I understand the requirements

Before

After

Column A is required (implied by how last row is determined)
Light red = group 1 (AAA); dark red = missing months for group 1
Light blue = group 2 (AAB); dark blue = missing months for group 2
If current record is in the same as group as previous don't update columns AT and AU

About the posted code

I found the logic a bit convoluted and hard follow (or maintain)

Indentation is inconsistent
Naming convention doesn't provide many clues for intent, examples:

MissingMonth() should be FindMissingMonths() or ShowMissingMonth()
temp1 and temp2 don't imply anything helpful, yet temp2 is critical
Usual loop counters are i, j, k (nesting hierarchy) - probably i was used at some point, then removed
LastRow (local variable names) should start with a lower case letter

temp1 is not needed
wSheet is assigned but in the LastRow assignment wSheet is not used:

LastRow = ThisWorkbook.Sheets("Source Data").Cells(Rows.Count, "A").End(xlUp).Row

should be

LastRow = wSheet.Cells(wSheet.Rows.Count, "A").End(xlUp).Row
in sub CheckMissingMonth(), parameter TempMonth is not used
there are too many interactions with the sheet, especially when calling CheckMissingMonth() and they cause slowness

This is how I would improve it for compactness and maintainability (and a bit for performance):

Version 1

Option Explicit

Public Sub findMissingMonths()
    Const JAN = 9   'start column
    Dim lastRow As Long, i As Long, j As Long, k As Long, miss As String, rng As Range
    Dim prevAS As String, mths As String, mthArr As Variant, lastMonth As Byte

    With ThisWorkbook.Sheets("Source Data")
        Set rng = .Range(.Cells(1, JAN), .Cells(1, JAN + 11)) 'get all months from headers
        mths = Join(WorksheetFunction.Transpose(WorksheetFunction.Transpose(rng)))
        mthArr = Split(mths)    '"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"

        lastMonth = UBound(mthArr)
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For i = 2 To lastRow                'check colAS (continue only if new group)
            If .Range("AS" & i).Value2 <> prevAS Or Len(prevAS) = 0 Then
                miss = mths                 'working string to remove the month from
                For j = 2 To lastRow        'check colAT
                    prevAS = .Range("AS" & i).Value2    'remember previous val in colAS
                    .Range("AT" & i).Value2 = prevAS
                    For k = 0 To lastMonth  'del month from full str as needed
                        If .Range("AS" & j).Value2 = prevAS Then
                          If Len(.Cells(j, JAN + k).Value2) > 0 Then
                            miss = Replace(Replace(miss, mthArr(k), ""), "  ", " ")
                          End If
                        End If
                    Next k
                Next j
                .Range("AU" & i).Value2 = Trim(miss)    'commit to cell
            End If
        Next i
    End With
End Sub

.

To optimize for performance I would eliminate all range interactions except for moving all data to memory and, at the end, placing it back on the sheet. This requires a bit more effort and code but the benefit is exponential

Here is another version optimized for speed, and this is the flow at high level:

move all data to array (variant)
create a nested dictionary that will keep track of each month value for each group:
AAA

Jan = Present (boolean)
Feb = Missing
Mar = Present
...

AAB

Jan = Missing
Feb = Missing
Mar = Present
...

first loop:

read all groups from col AS (also in memory as a smaller variant array)
initialize all values to False

second loop:

read all months' data and update all dictionary values to True as needed
update col AT and AU as needed (from dictionaries to array)

write all array data back to the sheet

Example (including all helper functions in the same module):

Version 2

Option Explicit

Private Const MONTHS As String = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
Public Sub showMissingMonths()      'in VBE set reference to "Microsoft Scripting Runtime"
    Const COL_I     As Long = 9     'Month columns I to T (9 to 20)
    Const COL_AS    As Long = 45    'Work columns AS to AU (45 to 47)
    Dim ws As Worksheet, arr As Variant, missing As String
    Dim i As Long, j As Long, lastRow As Long, unique As Dictionary
    Set ws = ThisWorkbook.Sheets("Source Data")
    arr = ws.UsedRange              'copy the used range to array
    lastRow = UBound(arr)           'first dimmension of the 2D array
    Set unique = getUnique(ws.UsedRange.Columns(COL_AS).Offset(1).Resize(lastRow - 1))
    If unique.Count > 0 Then
        For i = 2 To lastRow        'by row, determine if each month contains a value
            For j = 0 To 11
                If Not unique(arr(i, COL_AS))(arr(1, COL_I + j)) Then
                    unique(arr(i, COL_AS))(arr(1, COL_I + j)) = Len(arr(i, COL_I + j)) > 0
                End If
            Next
        Next
        For i = 2 To lastRow        'update colAU with missing month, only if new group
            If i = 2 Or arr(i - 1, COL_AS) <> arr(i, COL_AS) Then
              missing = vbNullString
              For j = 0 To 11
                If Not unique(arr(i, COL_AS))(arr(1, COL_I + j)) Then
                  missing = missing & arr(1, COL_I + j) & ", "
                End If
              Next
              arr(i, COL_AS + 1) = arr(i, COL_AS)
              If Len(missing) > 0 Then arr(i, COL_AS + 2) = Left(missing, Len(missing) - 2)
            End If
        Next
    End If
    ws.UsedRange = arr              'commit back to range
End Sub

Private Function getUnique(ByRef rng As Range) As Dictionary
    Dim arr As Variant, i As Long, ub As Long, d As Dictionary, val As String
    arr = rng
    ub = UBound(arr)
    getNewDict d        'each group value contains a dictionary with all months
    If ub > 0 Then
        For i = 1 To ub
            val = arr(i, 1)
            If Len(val) > 0 Then If Not d.Exists(val) Then Set d(val) = getMonthDict
        Next
    End If
    Set getUnique = d   'returned dictionary can be empty
End Function

Private Sub getNewDict(ByRef d As Dictionary, Optional ByVal ignoreCase As Boolean = False)
    If Not d Is Nothing Then Set d = Nothing
    Set d = New Dictionary
    d.CompareMode = IIf(ignoreCase, vbTextCompare, vbBinaryCompare)
End Sub

Private Function getMonthDict(Optional ByVal ignoreCase As Boolean = False) As Dictionary
    Dim arr() As String, m As Variant, d As Dictionary
    getNewDict d
    arr = Split(MONTHS)
    For Each m In arr
        d(m) = False
    Next
    Set getMonthDict = d
End Function

PS. In a working module I'd declare all variables on separate lines, use longer and more meaningful names, and add more vertical white-spaces

PS1. Performance measurements:

Tests duration

1,000 records

As posted:29.672 sec
Version 1:53.320 sec
Version 2:0.047 sec

10.000 records

As posted:60.45  min (3,627.328 sec)
Version 1:109.30  min (6,558.547 sec)
Version 2:0.297 sec

100.000 records

Version 2:3.094 sec
Version 2:3.242 sec
Version 2:3.234 sec

1 Million records

Version 2:32.234 sec
Version 2:32.164 sec
Version 2:32.336 sec


Complexity

It looks to me that even with this simple function, the complexity inside takes you for a ride. You don't have it under control. The reason is obvious: You try to do too much in one function.

If your program can set two flags, it can also choose between different functions: One for simple resizing, one for resizing while keeping the aspect ratio the same, etc. As you can guess there could be some overlap between these function. Therefore:

Classes

Classes are the ideal structures to put these multiple functions in, we call them 'methods', and let them share some common code. Let me give an example, that does some of the things that your function does, and some it doesn't:

function greatestCommonDivisor($int1,$int2)
// return greatest common divisor, euclidean algorithm
{
   if ($int2 == 0) return $int1;
   else return greatestCommonDivisor($int2,$int1 % $int2);
}

class ImageHandle
{
  private $outputSize;
  private $originalSize;

  public function __construct($width,$height)
  // constructor, set initial size
  {
    $this->setSize($width,$height);
    $this->originalSize = $this->getSize();
  }

  public function getSize()
  // get the Size of the rectangle
  {
    return $this->outputSize;
  }

  public function setSize($width,$height)
  // set the Size of the rectangle
  {
    $this->outputSize = ['width' => $width,'height' => $height];
    return $this;
  }

  public function resetSize()
  // go back to the orginal size
  {
    $this->outputSize = $this->originalSize;
    return $this;
  }

  private function computeAspectRatio($width,$height,$prefix = '')
  // return the aspect ratio as two numbers, with prefix
  {
    $divisor = greatestCommonDivisor($width,$height);
    $name    = ($prefix == '' ? 'aspect' : $prefix.'Aspect');
    return [$name.'X' => intdiv($width,$divisor),
            $name.'Y' => intdiv($height,$divisor)];
  }

  public function getAspectRatio()
  // return the aspect ratio as two numbers for set size
  {
    extract($this->getSize());
    return computeAspectRatio($width,$height);
  }

  public function setAspectRatio($newWidth,$newHeight)
  // set a new aspect ratio while keeping within the current width and height
  {
    extract($this->getSize());
    extract(computeAspectRatio($newWidth,$newHeight,'new'));
    if ($newAspectX > $aspectX) $height = $width*$newAspectY/$newAspectX;
                           else $width  = $height*$newAspectX/$newAspectY;
    return $this->setSize($width,$height);
  }

  public function rescaleSize($maxWidth,$maxHeight)
  // rescale, while keeping aspect ratio the same
  {
    extract($this->getSize());
    $newWidth  = $maxWidth;
    $newHeight = round($maxWidth*$height/$width);
    if ($newHeight > $maxHeight) {
      $newWidth  = round($newWidth*$maxHeight/$newHeight);
      $newHeight = $maxHeight;
    }
    return $this->setSize($newWidth,$newHeight);
  }

  public function echoInfo($title)
  // just here for this example, should be removed
  {
    echo $title.': ('.implode(',',$this->getSize()).
                 ') '.implode(':',$this->getAspectRatio()).'
';
    return $this;
  }

}

$test = [[ 480,  360, 1440, 1080],
         [1920, 1440, 1440, 1080],
         [ 480,  360, 1920, 1080],
         [3840, 2880, 1920, 1080]];

foreach ($test as $data)
{
  $image = new ImageHandle($data[0],$data[1]);
  $image->echoInfo('Orginal')
        ->setSize($data[2],$data[3])
        ->echoInfo('Set')
        ->resetSize()
        ->rescaleSize($data[2],$data[3])
        ->echoInfo('Rescale')
        ->resetSize()
        ->setAspectRatio($data[2],$data[3])
        ->echoInfo('Aspect Ratio');
  echo '
';
}

When ran this returns:

Orginal: (480,360) 4:3
Set: (1440,1080) 4:3
Rescale: (1440,1080) 4:3
Aspect Ratio: (480,360) 4:3

Orginal: (1920,1440) 4:3
Set: (1440,1080) 4:3
Rescale: (1440,1080) 4:3
Aspect Ratio: (1920,1440) 4:3

Orginal: (480,360) 4:3
Set: (1920,1080) 16:9
Rescale: (1440,1080) 4:3
Aspect Ratio: (480,270) 16:9

Orginal: (3840,2880) 4:3
Set: (1920,1080) 16:9
Rescale: (1440,1080) 4:3
Aspect Ratio: (3840,2160) 16:9

Ok, when you're not used to classes this might seem like killing a fly with an atomic bomb. I agree. But bear with me. I didn't call this class ImageHandle for nothing. You could extend this class to include other methods, mine are just examples, or an image loader and image saver, and much more.

However, notice the relative simplicity of each method: They don't get overburdened with functionality, so they stay relatively simple. Each one performs a single task.

Just like in your function, you could apply more than one method to change the size, but I found that to be a bit useless. Nevertheless, it will work.

PS: I intentionally left out the comments I normally put in my classes, this example is already quite long. You don't need them anyway, it isn't rocket science. :-)

PS2: I made this class slightly harder to understand, because I'm now using an array to store width and height. Some methods get very short, which is nice, but in others I use extract() to get at the data in the array. This is a method I often use. Arrays can be useful, but if you're not used to them they make it harder to read the code. Sorry for that.


Dynamic association generation in ActiveRecord

I think the query of the database would only happen once in production mode (the class would get cached, in development mode, the class gets reloaded every request that references a Customer object). You can confirm this by setting:

config.log_level = :debug

in your production.rb file and seeing if the query runs more than once. It might be worth having an after_save callback for FieldDef that does the same thing as the "FieldDef.find_each do |field|" block you have so you don't have to restart the server when new FieldDefs are created.


You can probably do something like this as well:

Files.lines(path)

It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list and write to the output file.

This answer gives you a functional programming approach. Most part of the method is self-explanatory.

Files.write(
            Paths.get(outFile),
            Files.lines(Paths.get(path))
                .sorted(String::compareToIgnoreCase)
                .collect(Collectors.toList())
    );


Scraping the full content from a lazy-loading webpage

Code Flow:

you are redefining links on every iterations of the while loop - you basically need to do it once
as a while loop exit condition, we can use the fact that there are line numbers in the company list grid - we can simply wait for the number 1000 to show up while scrolling
I would also create a class to have the driver and WebDriverWait instance shared across the class instance methods
instead of a hardcoded 3 second delay, use an Explicit Wait with a condition of the last line number to change - this would be much faster and reliable overall

Code Style:

posts variable name does not actually correspond to what it is - name it company_link instead
Name and Web violate PEP8 Python naming guidelines
process_links should be process_link - since you are processing a single link at a time. And, actually, we can name it get_company_data and let it return the data instead of printing it

Locating Elements:

don't use XPaths to locate elements - they are generally the slowest and the least readable
for the company links, I'd better use a more readable and concise ul.company-list > li > a CSS selector
in the process_links method you don't actually need a loop since there is a single company being processed. And, I think, you can generalize and return a dictionary generated from a company web page data dynamically - data labels to data values

Here is the modified working code:
from pprint import pprint

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class Fortune500Scraper:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.wait = WebDriverWait(self.driver, 10)

    def get_last_line_number(self):
        """Get the line number of last company loaded into the list of companies."""
        return int(self.driver.find_element_by_css_selector("ul.company-list > li:last-child > a > span:first-child").text)

    def get_links(self, max_company_count=1000):
        """Extracts and returns company links (maximum number of company links for return is provided)."""
        self.driver.get('http://fortune.com/fortune500/list/')
        self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul.company-list")))

        last_line_number = 0
        while last_line_number < max_company_count:
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

            self.wait.until(lambda driver: self.get_last_line_number() != last_line_number)
            last_line_number = self.get_last_line_number()

        return [company_link.get_attribute("href")
                for company_link in self.driver.find_elements_by_css_selector("ul.company-list > li > a")]

    def get_company_data(self, company_link):
        """Extracts and prints out company specific information."""
        self.driver.get(company_link)

        return {
            row.find_element_by_css_selector(".company-info-card-label").text: row.find_element_by_css_selector(".company-info-card-data").text
            for row in self.driver.find_elements_by_css_selector('.company-info-card-table > .columns > .row')
        }

if __name__ == '__main__':
    scraper = Fortune500Scraper()

    company_links = scraper.get_links(max_company_count=100)
    for company_link in company_links:
        company_data = scraper.get_company_data(company_link)
        pprint(company_data)
        print("------")

Prints:
{'CEO': 'C. Douglas McMillon',
 'CEO Title': 'President, Chief Executive Officer & Director',
 'Employees': '2,300,000',
 'HQ Location': 'Bentonville, AR',
 'Industry': 'General Merchandisers',
 'Sector': 'Retailing',
 'Website': 'www.walmart.com',
 'Years on Fortune 500 List': '23'}
------
{'CEO': 'Warren E. Buffett',
 'CEO Title': 'Chairman & Chief Executive Officer',
 'Employees': '367,700',
 'HQ Location': 'Omaha, NE',
 'Industry': 'Insurance: Property and Casualty (Stock)',
 'Sector': 'Financials',
 'Website': 'www.berkshirehathaway.com',
 'Years on Fortune 500 List': '23'}
------
...


Guess-the-number game by a Python beginner

This is a good first stab at a guess the number game.

Here's a few things:

You should be learning/using Python 3 instead of Python 2. So far the only difference for you will be raw_input becomes input and print "foo" becomes print("foo").
The line tries = tries doesn't do anything meaningful. You don't need it
You should put all of this inside a function called main and then at the bottom you run it with this (tests if this script is being run standalone):

if __name__ == '__main__':
    main()

You do int(guess) a lot. This is something that can fail (if someone types abc for example). You should do it once and check for failure.

try:
    guess = int(guess)
except ValueError:``
    print('Guess must be between 0 and 25')
    # ask for another guess

It's a good idea to comment. That's a fantastic habit to get into. However, you run the risk of over-commenting. And that is more distracting than having too few. As a rule, don't explain what, explain why. More concretely, "check to see if a user guessed the right number" is obvious from the if guess == secret_number:. Finding a balance is a skill, but if you work on it and read good quality open source code, you'll pick it up.
When you do your range check, you can do it in a much more pythonic way. Instead of checking guess < 0 or guess > 25, you can do if not 0 <= guess <= 25
tries = tries + 1 can be tries += 1
You don't need to escape ' inside a " (so "Congratulations you\'ve won!" can be "Congratulations you've won!")

The overarching issue you have though is most of your logic is duplicated in several different places. This becomes a problem if you want to, say, change the number range from 0-25 to 0-50. You'd need to change that in 6 places. What happens if you miss one? Then your game will break in weird ways.

What's the solution? Look to pull out duplicate logic like this into smaller, manageable chunks. In this case, it's helpful to identify the steps of your game.

Generate a secret number
Collect a guess from the user
If the user guessed the secret or more than 10 attempts have been made, end, else go back to 2

One easy thing you can pull out is "collect a guess from the user." You can do this in a function that gets the number, converts it to an int (handling the exception), and checking it is within range.

LOW, HIGH = 0, 25

def get_guess():
    while True:
        try:
            guess = int(input(f'Guess a number between {LOW}-{HIGH}: '))
        except ValueError:
            print('Please enter a number')
        else:
            if LOW <= guess <= HIGH:
                return guess

            print(f'Number must be between {LOW} and {HIGH}')

Now you can use get_guess() when you need to guess the guess from the user without having to add any extra control structures (like wrapping everything in a while) or duplicate any logic.

Now, when using get_guess() you can concern yourself with fewer facets of the game. Namely, checking the number of attempts and if the guess was correct:

from random import randint

MAX_ATTEMPTS = 10

def main():
    secret = randint(LOW, HIGH)

    for _ in range(MAX_ATTEMPTS):
        guess = get_guess()

        if guess == secret:
            print('You win!')
            break
    else:
        print('Too many attempts; you lose.')


The only good thing about this code is your desire to invent. It is a very good desire, only ones possessing it make good programmers. You just made the very first step towards inventing your own database, just like every aspiring newbie programmer does. And that's a very good sign per se.

Everything else about this code - let me be frank - is bad. From the main idea to the minute syntax issues. To outline some misconceptions:

The premise. I know, I know, you have a million reasons not to use a relational database. All of them are wrong though. Beside an aspiration, a good programmer possesses a thing called common sense. Which is bound to tell them that generations of programmers created and polished a thing called a relational database for a reason.
the above leads to the number of consequences:

scalability. By no means it is good for any project you would call "large". All these manual loops in the memory will become unbearably slow. A good database never loads the entire file in the memory, it reads a file by chunks. And uses indexes to speed up all the operations dramatically.
race condition. With your database you will learn the hard way such things like file locking and a race condition. In concurrent environments a file must be locked when operated with, in order to prevent other files from accessing it. Or it will lead to data corruption and other unwanted consequences.
features. SQL is one of the greatest inventions of the last century. In a relatively short sentence that is close to natural English it lets us to do the data filtering, ordering, aggregation. How many lines of code you will have to write to get the overall salary for all employees? Grouped by departments? For the certain period? It's just a single line in SQL mind you.

naming. What do remove(), delete() and destroy() functions do? Can you tell from looking at them used in the code?
OOP. Not to mention the ancient constructor definition (it was discouraged from using for decades!), the overall class structure is flat. It's just a collection of functions. There is no delegation, no abstraction, no separation of concerns. At least there should be two classes, one operating at the filesystem level and one operating at the single json file level.
syntax in general. Again, it seems to be inevitable for many people to pass such a stage, trying to make a code easier to write, making names gibberish as a result. It takes time to realize that reading is much more important than writing, and such names as p(), $d and such is a blasphemy. Every variable and method should have a meaningful name.
if (count($r) == 1) return $r[0]; is my favorite. I learned the hard way that such a magic will lead to a situation when your code expects a 2-dimensional array of rows but gets just a single row. It's funny to see the result when you are trying to loop over it and then access distinct fields inside each element. there must be explicit methods to get you certain result types, you want to look at PDOStatement for inspiration
error reporting. at least for json_encode() you have to implement a wrapper that will produce a meaningful error message

function jsonDecode($json, $assoc = false)
{
    $ret = json_decode($json, $assoc);
    if ($error = json_last_error())
    {
        throw new Exception(json_last_error_msg(), $error);
    }
    return $ret;
}


Count number of ways to construct binary search tree with n elements

The number of trees can be expressed in the closed form \$\frac{\binom{2n}{n}}{n+1}\$, and due to \$\binom{2n}{n} = \frac{4n - 6}{n} \binom{2(n-1)}{n-1}\$ the result is computed in linear time.

I would not ask such question in face-to-face interview (unless the position requires in-depth knowledge of combinatoric and graph theory).


Any better way to copy from Readable to OutputStream?

Well, last night I came up with that. I am pretty satisfied with it right now but would be happy to see if I am still missing something.

This solution does not rely on implementation details any more and provided streams are left open as the general contract demands it.

public static void copy(@Nonnull Readable src, @Nonnull @WillNotClose OutputStream dest, @Nullable Charset destCharset) throws IOException {
    CharBuffer charBuf = CharBuffer.allocate(CHAR_BUF_SIZE);

    while (src.read(charBuf) != -1) {
      charBuf.flip();
      copy(charBuf, dest, destCharset);
      charBuf.clear();
    }
}

public static void copy(@Nonnull CharBuffer src, @Nonnull @WillNotClose OutputStream dest, @Nullable Charset destCharset) throws IOException {
    copy(safeCharset(destCharset).encode(src), dest);
}

public static void copy(@Nonnull ByteBuffer src, @Nonnull @WillNotClose OutputStream dest) throws IOException {
    int len = src.remaining();
    int totalWritten = 0;
    byte[] buf = new byte[0];

    while (totalWritten < len) {
        int bytesToWrite = Math.min((len - totalWritten), BYTE_BUF_SIZE);

        if (buf.length < bytesToWrite) {
            buf = new byte[bytesToWrite];
        }

        src.get(buf, 0, bytesToWrite);
        dest.write(buf, 0, bytesToWrite);
        totalWritten += bytesToWrite;
    }
}


I start my intention in head and body.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title> Checking Different Headings | Isnt it fun?</title>

This is big

This is also good

This is also good

This is also good

This is also good

This is small

I also keep my tag tight–no spaces between text and tag.


Increase performance of a method which finds the element removed from an array

I think that the best option would be to sort the array, am I right?

Not exactly. You could sort it and reduce the complexity using a binary search to O(n log(n)). But you could much better by copying the array into a HashSet and getting O(n) assuming no perverted distribution (the worst case hash table access is O(n), but occurs very rarely).
The search itself could be even faster, when using two sorted arrays. As all the  data come from a Set, there are duplicates.  So whenever the element of the first array at a given position equals to the element of the other array at the same position, you know that you're before the removed element. Using a binary search you can get a complexity of O(log(n)). However, producing the the second array costs O(n), so you don't gain anything w.r.t. the O-notation.
Review
private static final Set<Integer> SET = Sets.newTreeSet(Arrays.asList(1, 3, 5, 7));

This is fine for the test data, but then you should define another constant for unsorted, too.
private static int checkElementRemoved(final int[] unsorted) {
    Integer elementRemoved = null;
    for (Integer number : SET) {
        if (!arrayContains(unsorted, number)) {
            // O(n^2) complexity
            elementRemoved = number;
            break;
        }
    }
    return elementRemoved;
}

You're not checking anything. Call it find... or alike. Don't use useless variables. It all can be reduced to
private static int checkElementRemoved(int[] unsorted, Iterable<Integer> set) {
    for (Integer number : set) {
        if (!arrayContains(unsorted, number)) {
            // O(n^2) complexity
            return number;
        }
    }
    throw new WhateverException();
}

Your code secretly throws a NullPointerException when unboxing elementRemoved. This is pretty bad. Throwing NPE explicitly would be much better, but NPE is not the right exception here. Letting your method return an Integer would be better, but only postpone the problem. Actually, IllegalArgumentException sounds right, as it's not allowed to pass an array missing no element.
In any case, you should pass SET as an argument, so that your method is more usable.
private static boolean arrayContains(final int[] unsorted, final int number) ...

This is no better than Arrays.asList(unsorted).contains(number). But as already said, create a HashSet and use it for speed.


Some things I spot on the fly:

Lack of documentation. PHPDoc works well, every method, every class, every file should have a DocBlock.
Naming conventions. It's considered good naming convention to have methodNames() and $variableNames in camelCase, but ClassNames and ObjectNames in UppercaseCamelCase.
Code style. Conforming to a single code style is great. Conforming to an established standard is awesome!. Check out the PSR Code style standards page.
On the newElement method, preg_split is redundant. explode by ; or = is enough, and is faster!
Last but not least, if the entire file is PHP (without embedding HTML), it's considered safe (and even recommended!) to omit the closing ?> at the end of the file. This helps with line break and whitespace issues.

I'll continue editing as I explore more.


Find the sum along root-to-leaf paths of a tree

You are treating res and curList as if they are Globals, and, since they are globals, there is no reason to return ret in the function at all.

As a result of this, your code is not re-entrant (you can only have one method calling your pathSum at any one point in time).

The right solution to this is to pass the curList and ret values as parameters to the method, convert it to private, and create a new public method which creates the instances as you need them.....

public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> curList = new ArrayList<Integer>();
    pathSum(root, sum, curList, res);
    return res;
}

private void pathSum(TreeNode root, int sum,
            ArrayList<Integer> curList, ArrayList<ArrayList<Integer>> res) {
    ....
    ** change the methods called as part of the recursion too**
    ....
}

That is the big structural change, but I would recommend more:

methods should not return specific List implementation types unless those types have special features you need. your method should return List<List<Integer>> and not ArrayList<ArrayList<Integer>>
convert curList to an array of int[], and the return valye of the system to List
you do the calculation sum-root.val in multiple places. Firstly, it should be spaced properly: sum - root.val, and secondly, you should save it as a variable once, and re-use that variable in the places where it currently is a function

About the complexity

you ask if worst case is \$O(n^2)\$ ... no, it is not.

Worst case is \$O(n \log(n))\$. This is my reasoning:

the depth of a binary tree is about \$\log(n)\$.
The deepest a binary tree can be is depth n, but, in that case there is only one possible solution, so the complexity will be two \$O(n)\$ operations, one to scan the single deep branch, and another to copy the array.
the worst case is actually a fully-balanced tree where every leaf node matches the intended sum, in which case the number of solutions is proportional to \$O(n)\$, but the actual copy to the array will be of \$O(log(n))\$ elements

So, My assessment is \$O(n \log(n))\$

Feel free to debate this... I am not 100% certain....


Loading a file in vim via piped output of ag

You could simplify the vim call like this:

vim $(ag '\.where\(.*\)' app | sed -nE '$s/([^:]*):([0-9]*):.*/+\2 \1/p')

That is, no need for the awk to print the matched filename and line number in reverse, you can reverse in the sed, and also prefix the number with + there.

I dropped the tail -1, by using the -n flag of sed to not print output by default, added $ in front of the s/// command to apply for only the last line of input, and the /p flag to print after substitution.
Although this has the benefit of eliminating a tail process in the middle, it has the disadvantage that it's a bit harder to understand. So you can put back tail -n 1 (more portable than tail -1) if you prefer.

I also changed the obsolete `...` to $(...).


Naming:

name and surname are somewhat unclear in what they specifically mean. The "actual" purpose of these variables is to serve as "root" of the trie. Incidentally I'd rename ancestor to rootin all the usages in your code, simply because I'm more used to it. YMMV :)
I'd rename name and surname to nameRoot and surnameRoot.

Simplifications:

Initialize private fields that are not dependent on constructor arguments in the field declaration to save on space and complexity.
Use Comparator.comparing and thenComparing to simplify your comparator.

I personally also prefer to not leave too much space between fields.

private final Node name = new Node();
private final Node surname = new Node();
private static final Comparator<Record> comparator = Comparator.comparing(Record::getName)
    .thenComparing(Record::getSurname).thenComparing(Record::getNumber);

Note that I also changed the comparator to be static. It could also do with a better name, but I'm coming up empty right now...

Possible Trie Optimizations:

Currently your trie is using a lot of memory. It's not quite as bad as it could be, but considering that names are very much non-uniform, you will have a lot of "degenerated branches", where the branching factor is very low, if not 1 for "long" stretches of the data structure.

These long stretches of basically linked lists can be collapsed by sacrificing a WORD of memory to store how many characters you can skip before the next actual branching.

Currently Node does not support this in any way.

The traversal during add can be simplified a bit with computeIfAbsent like so:

for (final char c: str.toCharArray()) {
    final Node child = node.children.computeIfAbsent(c, Node::new);
    child.records.add(record);
    node = child;
}

This simplification pretty quickly vanishes when you implement the optimization mentioned above (or rather it becomes somewhat complicated).


Scraping data from tables connected to each dot on a map

Some key things to take into account when using selenium:

if you have an id of an element - use it - it's the fastest way to locate an element
wait.until() returns a WebElement with most of the Expected Conditions - there is no need to find the element again if you want to use the element you've been waiting for
WebDriverWait() can be instantiated once per driver and reused
time.sleep() waits have to be avoided - they are making the code slower than needed most of the time, they are unreliable and not tied to any condition on a page, and sometimes the delay you set is not enough

You don't have to click through every circle on the map
We can seriously improve on web-scraping speed by extracting the "token" (let's call it this way) from the iframe URL and then making a REST API request to a specific endpoint with the data using requests:
from urllib.parse import parse_qs, urlparse

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://acwi.gov/monitoring/vm/programs/vm_map.html")

wait = WebDriverWait(driver, 10)

# get the token from the frame src
frame = wait.until(EC.presence_of_element_located((By.TAG_NAME, 'iframe')))
token = parse_qs(urlparse(frame.get_attribute("src")).query)['webmap'][0]

driver.close()

# parse data
response = requests.get("http://www.arcgis.com/sharing/rest/content/items/{token}/data?f=json".format(token=token))
data = response.json()

for item in data["operationalLayers"][0]["featureCollection"]["layers"][0]["featureSet"]["features"]:
    coordinates = item["geometry"]["x"], item["geometry"]["y"]
    attributes = item["attributes"]

    print(coordinates, attributes["MPN"])


Can't you change:

if ( !string.IsNullOrEmpty(curFilter.Filter)) {
  ..Lots of code..
}

to

if ( string.IsNullOrEmpty(curFilter.Filter)) {
  i++;
  continue;
}

?
This saves you one indent. (The else clause becomes redundant)

Also I would most likely swap around the if statements for isNumeric and the IN and NOT IN (and their corresponding contents). If only because the two function calls:

if (!Compare(curFilter.Expression, Convert.ToDouble(column), Convert.ToDouble(curFilter.Filter))) {
  return false;
}

and

if (!Compare(curFilter.Expression, column, curFilter.Filter)) {
  return false;
}

look very similar, so imo it's better to group them together. (Though this is mere aesthetics)

Other than that I'm looking at some more fundamental changes if you really want to tidy up the structure. But that goes beyond the scope of this post. (I'm at work at the moment, I know, bad excuse. See what other people have to say.)


Optimizing a nested for loop over JS array of objects

You can use some built in functions instead of the for loops.

var result = A2.filter(e => A1.includes(e.value));

I can't say if this is much faster, since those functions still loop through the arrays. You'll have to time this with some large input to test.

Be aware that Internet Explorer doesn't support .includes or arrow functions. IE friendly version:

var result = A2.filter(function(e) {return A1.indexOf(e.value) !== -1});


Very nice code in general! Here are a few points, though:

Think about using os.makedirs instead of os.mkdir. The former allows creating nested directories (so os.makedirs("~/long/new/path") will create all other folders in betweetn as well, if needed).

You should never have a bare except. This prevents you to e.g. CTRL-C to abort the program, since it will also be caught. Use at least except Exception, which all normal exceptions inherit from (but not some special exceptions like pressing CTRL-C).

In general it is usually not the best idea to have a lot of string addition. You could use format instead in repo_formatter:

def repo_formatter(scheme):
    base_url = scheme['github_repo']['address'].replace('github.com', 'raw.githubusercontent.com')
    return '{}/master/colors/{}.vim'.format(base_url, scheme['name'])

You have some very obvious comments in your code, especially in download. Comments should explain why you do something and not what. The latter should be obvious from your code! And in that function it is really easy to follow what happens, because you have chosen appropriate variable names :)


Here are my suggestions:

Get rid of the anonymous functions. They are notoriously difficult to test. I am hoping that you have written the test cases. If not, now would be a good time to try writing these tests.
There is either a documentation or implementation bug where you want the timeout to be 10s (10000ms) but are actually using a value of 10*10000ms which is 100s.
Rather than calling a method directly on require('http'), I'd like it if you import it the way you have imported request.
You are always sending back a response code of 200. You should wait till after the request has finished fetching the page and set the status code accordingly unless you have some way of serving the right content (using a cahed copy, for example).

Other than that, I think that you have the actual functionality pretty much nailed down.


Two variants of a db_create_resources(…) function

There's no specification. What does this function do? What arguments should I pass? What are the preconditions on db_file? (It looks as if I might have to fill in some of the fields, but which ones?)
"resources" is spelled thus.
The function does not check the preconditions.
Mixing fopen and db_close seems confusing and error-prone. fopen should be paired with fclose, and db_close should be paired with db_open.
If the call to fopen fails, it looks as if you lose information about the cause of the error. fopen can fail due to permissions (EACCES), lack of disk space (ENOSPC), missing directory (ENOENT), and so on, but these all get converted to ERR_IO.
The function uses db_file->metadata to hold a pointer to some memory, but this memory is not actually used by the function, and by the end of the function the memory is freed and the pointer set to NULL. It seems wrong to use the db_file structure this way. If db_create_logic needs some temporary memory, it should allocate it itself (and preferably in a local variable, not in the db_file structure).
The cleanup logic for db_file->metadata appears twice. This is a bad idea: if you changed it in one of the places, would you remember to change it in the other? Consider refactoring the error handling code to look like this:

enum error_codes
db_create_resources(const char* db_filename, struct pictdb_file* db_file)
{
    enum error_codes e;

    db_file->metadata = calloc(db_file->header.max_files,
                               sizeof *db_file->metadata);
    if (db_file->metadata == NULL) {
        e = ERR_OUT_OF_MEMORY;
        goto fail_calloc;
    }

    db_file->fpdb = fopen(db_filename, "wb");
    if (db_file->fpdb == NULL) {
        e = ERR_IO;
        goto fail_fopen;
    }

    e = db_create_logic(db_filename, db_file);
    db_close(db_file);
fail_fopen:
    free(db_file->metadata);
    db_file->metadata = NULL;
fail_calloc:
    return e;
}


Checking if IDs in array are not null and adding them into new array

Since the property names are sequential, you can just put it into a for loop:

function reSelectTags(view) {
    var val, term_ids = [];
    for (var i = 1; i <= 3; i++) {
        val = view["term_id_" + i];
        if (val != null) {
            term_ids.push(val);
        }
    }
    console.log(term_ids);
}

You can also just put repeated code into a local function:

function reSelectTags(view) {
    var term_ids = [];

    function pushVal(name) {
        if (view[name] != null) {
            term_ids.push(view[name]);
        }
    }
    pushVal("term_id_1");
    pushVal("term_id_2");
    pushVal("term_id_3");
    console.log(term_ids);
}


Calculating revenue from roller coaster rides

One of the suggestions I would make is to improve your input handling. You don't handle invalid integers well at all.

string input = "invalid int";
int numAvailablePlaces = 0;

while (!int.TryParse(input, out numAvailablePlaces))
{
    Console.WriteLine("Please enter a valid integer for the number of places available.");
    input = Console.ReadLine();
}

And similarly for the other int's you grab. (You could also do them all in one loop.)

This method:

private static int CountDirhamsEarnedInOneOperation(int numAvailablePlaces, LinkedList<int> numPeopleInEachGroup)
{
    //Each passenger pays one dirham to take the ride once.
    int dirhamsEarned = 0;
    int numGroupsInQueue = numPeopleInEachGroup.Count();

    while (numPeopleInEachGroup.First() <= numAvailablePlaces && numGroupsInQueue > 0)
    {
        dirhamsEarned += numPeopleInEachGroup.First();
        numAvailablePlaces -= numPeopleInEachGroup.First();
        numPeopleInEachGroup.AddLast(numPeopleInEachGroup.First());
        numPeopleInEachGroup.RemoveFirst();
        numGroupsInQueue--;
    }

    return dirhamsEarned;
}

Does too much. Break the inside of that while loop to a new method.

Other than that, there's little to say in my opinion.


Adding new or existing tags to a blog post

Take a step back and look at your code. Do the different classes/objects ha ve Single responsibility? Or is the same class responsible for adding posts, managing tags and coupling a tag to a post?

I think it is time to go back to the drawing board and see what you actually want/need.

Then every class you write should only have a single responsibility. e.g. representing a comment or a TaggableComment class that extends the Comment class and adds the ability to add and remove tags.

Also make sure that a Class shouldn't have to know how to handle the creation of other objecs. Using the 'new' operator inside a class methods is bad practice. If you would like to change the way a Tag is constructed, you will now have to change the Comment class aswell, not useful.

Look into some programming patterns, A really good read is: http://addyosmani.com/resources/essentialjsdesignpatterns/book/ I know, it's not php but javascript. But moest of the patterns there also apply to php, it's the idea behind the patterns that will help you


Search for solutions to quartic diophantine equation

This looks like a bug:

if (LHS == RHS && (arrA[a] != arrB[b] != arrC[c] != arrD[d]))

The operator != returns a boolean result. Its Associativity is also left to write. so the above is equivalent to:

if (LHS == RHS && (((arrA[a] != arrB[b]) != arrC[c]) != arrD[d]))

So:

arrA[a]         != arrB[b]     =>  true or false
(true or false) != arrC[c]     =>  true or false  (so usually true)
true            != arrD[d]     =>  true or false  (so usually true)

LHS == RHS && true             =>  Looking for LHS == RHS

This is a bad way of writing a nested loop:

while (d < 430000)
{
    if (a == 430000)
    {
        a = 0;
        b++;
    }
    if (b == 430000)
    {
        a = 0;
        b = 0;
        c++;
    }
    if (c == 430000)
    {
        a = 0;
        b = 0;
        c = 0;
        d++;
    }
    if (d == 430000)
    {
        break;
    }
    LHS = arrA[a] + arrB[b] + arrC[c];
    RHS = arrD[d];
    // stuff
}

Just write:

for(int a = 0; a < 430000; ++a) {
    for(int b = 0; b < 430000; ++b) {
        for(int c = 0; c < 430000; ++c) {
            for(int d = 0; d < 430000; ++d) {
                LHS = arrA[a] + arrB[b] + arrC[c];
                RHS = arrD[d];
                // stuff
            }
        }
    }
}

There is no point looping over all the values.

if a^4 + b^4 + c^4 > 430000^4 then there is no point in running through the d loop as you will never find the value.

There is no point in checking all values of d. If you must use a search arrD then do a binary search of the array. This will vastly reduce the number of items checked in the innermost loop. Alternatively just find the cube root of the result using a maths function.

 double root = std::pow(LHS, 1.0/4.0);
 double base = std::floor(root);
 if (floor * floor * floor * floor == LHS) {
     break;
 }

I am not convinced that calculating and saving all the powered values is going to save time. Also  you don't need to save the same result four times. Rather than have arrA and arrB and arrC and arrD have a single array arr. It is the index into the array that is important.

Also don't manually allocate this space with new use a vector<double>.

The question is a memory lookup faster than or slower than doing 4 multiplications (or callling std::pow(x, 4)). That is something you will need to time and find out.


What constructor implementaton follows best practice in Java

no one from them, this should be standard or base

EDIT: added DefaultCloseOperation for Top-Level Container

import javax.swing.*;
import java.awt.*;

public class Painter {

    private JFrame frame;
    private JPanel headerPanel;
    private Drawing_panel ;

    public Painter() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setTitle("Paint drawing demonstration");

        //new Center_frame(frame);
        //no reason for create another new JFrame look for
        //JDialog instead of JFrame, if you needed multiplayed
        //view then check CardLayout, is very easy for use

        headerPanel = new JPanel();
        headerPanel.add(new JLabel("The drawing panel is below"));

        dp = new Drawing_panel();

        frame.add(headerPanel, BorderLayout.NORTH);
        frame.add(dp, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Painter p = new Painter();
            }
        });
    }
}


Summing some datum for requests in each domain that fall in a date range

This is a case where a foreach loop might work better.  Your LINQ query iterates for your data several times.  Where as a foreach loop and a dictionary, should be able to accomplish this in one loop.  Something like this:

Dictionary<string,int> query = new Dictionary<string, int>();
foreach(var r in Results)
{
    if(r.RequestType.Id == Id && r.DateFrom >= sDate && r.DateTo <= eDate)
    {
         if(query.ContainsKey(r.Data_1))
         {
             query[r.Data_1] += int.Parse(r.Data_2);
         }
         else
         {
             query.Add(r.Data_1, int.Parse(r.Data_2));
         }
    }
}

While there is a Dictionary lookup for each item it should be more than offset by calculating the sum on the fly rather than at the end.


C++ class for a flag register in a Chip8 emulator

I see some things that may help you improve your program.

Avoid writing this

The overuse of this clutters the code and makes things harder to understand.  For example, the current code contains this:

void setFlag(Flag flagToSet) {
    this->state = this->state | flagToSet;
}

It's much easier to read and understand if written instead like this:

void setFlag(Flag flag) {
    state |= flag;
}

Think about the user

Consider actually using this class.  For example, to appropriately set the ZF flag we'd have to do something like this:

if (result == 0) {
    flags.setZF();
} else {
    flags.unsetZF();
}
return flags.checkZF();

That's way too much code for just one flag!  Here's what I'd rather write:

return flags.Z(result == 0);

Use const where practical

I would expect that checking the value of a flag shouldn't alter any flag.  To assure the reader of the code that this is the case, the functions should be marked const.  This also tells the compiler to make sure that 1) the code implementing the function does not alter the associated object and 2) the code calling the function can be a const object.  See this for a more detailed and rigorous explanation.

Simplify your code

Rather than having to go through another level of indirection, for such simple functions, I would remove the private methods.  To use the syntax I advocated earlier, here's one way to write a pair of functions:

bool C() const {
    return state & CF;
}
bool C(bool val) {
    if (C() != val) {
        state ^= CF;
    }
    return val;
}

You could even get crazy with preprocessor macros and write this:

#define FLAGIZE(x) bool x() const { return state & x ## F; } \
    bool x(bool val) { if (x() != val) state ^= x ## F; return val; }

    FLAGIZE(C)
    FLAGIZE(P)
    // etc.

This macro is just a shortcut to writing all of those functions out by hand.

Consider multithreading

It may be convenient at some point to have multiple threads setting flags simultaneously.  If that's the case, you want to make sure they don't overwrite, so either using something like std::atomic_uchar would provide a simple way to support such use.

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.


Printing a sequence of numbers using two alternating threads

I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:

public synchronized void run() {
    while (i < 10) {
        try {
            notify();
            System.out.println(Thread.currentThread().getName() + " prints " + i);
            i++;
            wait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.

Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.


I think it is mostly fine as it is. I would declare variables at the level they are actually needed, not before. Also, xAxis = TILE_WIDTH_AND_HEIGHT + xAxis; can be written as xAxis += TILE_WIDTH_AND_HEIGHT.

i and v are not very good variable names (too short, and they don't fit together). What does v even stand for? vertical? In that case, I would use vertical and horizontal.

TILE_WIDTH_AND_HEIGHT would be shorter as TILE_DIMENSION.

You could restructure it like this if you want to:

    for (int y = 0; y < 3; y++) {
        for (int x = 0; x < 3; x++) {
            shapeRenderer.rect(SPACE_BETWEEN_TILES + TILE_DIMENSION * x, SPACE_BETWEEN_TILES + TILE_DIMENSION * y, 10, 10);
        }
    }

The performance loss from transforming additions to multiplications should be fine in most cases.


An additional point to the ones mentioned by @palacsint is the check for the object removal:
according to the challenge:

  If the operation is remove and the number x is not in the list, output
  "Wrong!" in a single line

your code does not check for that: here is what you have:

if(items.size()<=1)
            {
              result[i]=-1;
            }
else .....

You are marking wrong when the list has a single item or is empty. Obviously this is not what the challenge requires. Therefore, you should discard this "if" block and only check the return value from the remove on the list:

boolean ok= items.remove((Integer)x[i]);
if (!ok){
  result[i]=-1;
}


I don't like c-style of declaring all the variables at the start of a function (which is a necessity in c, not in c#). It's better to define them closer to where they are used.

I suggest not to define your types explicitly, use var instead such as:

var tierAmtInt = 300;

You'll see the benefits when you want to modify or refactor stuff. This one looks like a good read on that: https://softwareengineering.stackexchange.com/questions/42863/explicitly-defining-variable-data-types-vs-using-the-keyword-var

For taxRateDec1/2/3, you can perhaps consider using array or sth similar.

If you really want to be perfectionist, you can consider passing all these variables as parameters or read from somewhere else. Just consider one day these rates changing, would you like to modify the code and recompile?

Last but not least, these variables are actually constants, consider putting 'const' keyword whenever necessary..


Selecting an enum for a payment transaction

You're using the wrong tool for the job.

If there's ever going to be a loan that I will pay an amount to every week for 2 years, you're gonna have to write a script to generate the code for you, because doing it by hand would suck. You'd have to write code for 204 different enum values, including the switch cases.

If you had to map months to strings, you could have given your enums values, e.g.

enum Month {
    JANUARY(1, "January", "JAN"),
    FEBRUARI(2, "February", "FEB"),
    ...

    private int number;
    private String name;
    private String shorthandName;
    Month(int month, String fullName, String shortName){
        number = month;
        name = fullName;
        shorthandName = shortName;
    }
    //add getters....
}

Like that.

But what you have here is more like an object. You have two values to keep track of, and they are not related. This doesn't lend itself to an enumeration as you'll need to create each combination by hand.

For that, I recommend using value objects. An example of a value object is a String. It's an immutable object of which you cannot change the value.

So consider making a class like so:

class InstallmentTransaction {
    private final int installments;
    private final boolean interest;

    private static final Map<Integer, Map<Boolean, InstallmentTransaction>> instances = new HashMap<>();
    private static final Object lockObject = new Object();

    private InstallmentTransaction(int installments, boolean interest)
    {
        this.installments = installments;
        this.interest = interest;
    }

    public static InstallmentTransaction getInstance(int installments, boolean interest){
        synchronized(lockObject){
            Map<Boolean, InstallmentTransaction> map = instances.get(installments);
            if(map == null){
                map = new HashMap<>();
                instances.put(installments, map);
            }
            InstallmentTransaction instance = map.get(interest);
            if(instance == null){
                instance = new InstallmentTransaction(installments, interest);
                map.put(interest, instance);
            }
            return instance;
        }
    }

    //getters go here
}

I didn't implement the full thing, that's something you'll have to do, but this will give you the benefit of object equality combined with the ability to reference instances (getInstance(12, false)).

I also opted for Integer here, because that's the format you store numbers in. Even if the API only exposes Strings, that doesn't mean you are stuck using Strings. ""+int will give you a String, and Integer.parseInt("") will give you an integer.

synchronized is used to prevent there being two threads both calling getInstance at the same time and creating two objects for the same values.

The upsides of this approach are that it automatically supports all values of installments and interest.

The downside is that if you have a lot of values, you risk filling up your memory with all of them. You don't have this, though, as right now it's going to be 24 values (12 months * 2). For Android development, it might not even matter - apps don't have the same active duration as server applications do.


This should do the trick:

http://jsfiddle.net/XjdTX/11/

I changed the
...
 to use a class instead. This will allow you to have multiple slide shows functioning off the same code, as shown in the jsFiddle. For toggling through the pics, the pic class is used and cycles based on the index of the clicked image.

There is also code in the jsFiddle that will fade the images instead of just toggling their visibility.

$(document).ready(function() {

    $('.slideframe').each(function() {

        var $pics = $(this).find('.pic'),
            max = $pics.length;

        $pics.on('click.slideframe', function(e) {
            var idx = $pics.index(this);
            if (idx < 0) {
                return false;
            }
            $(this).hide();
            $pics.eq(++idx % max).show();
        });
    });
});


Handling overwriting of unique Dictionary values

As far as your question is concerned, I'm not sure either choice is best, but if you had to choose one or the other, I would let them overwrite an existing one.

Consider that right now the user has no way to override a workday with a new one directly, so they would have to call GetWorkday to get a reference to it, and then change the properties of that object.

I think the best option would be to provide an overload that takes a Boolean that allows the user to determine if they want to overwrite a value:

public void SetWorkday( Workday value, bool overwrite)

Also, you haven't provided them with any way to RemoveWorkday, which might be a helpful addition.

For code reviewing thoughts, what are the fields DayStart and DayEnd for? I thought a workday was just a single day? Seems like it should just have a Date field.

In your get workday method, you could add a break; when you find the day you're looking for (since you don't need to keep searching):

foreach( KeyValuePair<DateTime, Workday> pair in ScheduledDays)
{
    if( pair.Key.Date == date.Date)
    {
        result = pair.Value;
        break;
    }
}

In your SetWorkday method, I think you only need to pass in a Workday object, not a DateTime key. The reason is that a Workday already has a DateTime associated with it, and looking at your code, it seems like it's an easy entry point for a bug where someone passes in a key whose date is different than Workday.DayStart:

foreach( KeyValuePair<DateTime, Workday> pair in ScheduledDays)
{
    if( pair.Key.Date == value.DayStart.Date)  // <- Comparing the workday date value
    {
        ScheduledDays[key] = value;            // <- But setting it using the key value
        scheduled = true;
        break;
    }
}

Also, in a few places you are checking if a key exists, and if it does you use assign the value using the index, but if it doesn't then you call the Add method. This is unnecessary - you can use the index assignment syntax for both. This will simplify your code. Here are 3 examples of different options and the simplified syntax:

// Overwrites
public void SetWorkday(Workday value)
{
    ScheduledDays[value.DayStart.Date] = value;
}

// Allows Overwriting
public void SetWorkday(Workday value, bool overwrite)
{
    if (ScheduleDays.ContainsKey(value.DayStart.Date) && !overwrite)
    {
        throw new WorkdayOverwriteException();
    }

    ScheduledDays[value.DayStart.Date] = value;
}

// Does not allow overwriting
public void SetWorkday(Workday value)
{
    if (ScheduleDays.ContainsKey(value.DayStart.Date))
    {
        throw new WorkdayOverwriteException();
    }

    ScheduledDays[value.DayStart.Date] = value;
}


Variables, references and pointers - Write the function zero (...) so that the following code works correctly

This isn't too complicated, so there isn't that much to say. Your code is perfectly clear, but there are a couple things that could be improved.

using namespace std;

This is okay-ish for beginning programming classes, but using namespace std should usually be avoided. See Why is “using namespace std” considered bad practice?

void zero(int &);

You could just not forward declare the function, and instead just define the function here. It's a little less code to write. It comes down to preference

int main(void) {

Don't use void to say that a function takes no arguments. It's a C-ism, and should be avoided in C++. Just write int main() {.

int main(void) {
    ...

    return 0;
}

There's no need to have a return 0; at the end of main(). For the specific case of the main function, return 0; is implied at the end of the function.


The code uses pos=queue[0] and queue.remove(pos). Instead, you could use pos=queue.pop(0). Be aware that popping from the front isn't really efficient, it's O(n), which is bad for big lists.
You could use the fact that you can assign to two variables at once: x, y = queue.pop(0). This removes pos completely, fewer variables are easier to understand.
You pass a maze and the start position to the BFS. However, the queue and others are global. That's very bad design. Keep things in as small a scope as possible. You can always return a tuple from a function if a single value is not sufficient, if that was the reason.
What are len(maze[0]) and len(maze)? Call those width and height and compute them at the start of the function to answer that question.
The if-clause in the loop has too many conditions at once, which is really hard to read. There's nothing wrong with a continue when the computed position was already visited, just to illustrate one check that could be extracted.
parent[neighbor] = pos is done at two places. Do that exactly once when you first visit a new place.
visited seems to be the list of places that were already visited. The type is a Python list, but a set would be a more suitable datatype for that, unless the order of the elements matters.


Not so similar...

Just because the method bodies "look similar" doesn't make them similar. It's better to think in terms of purpose instead. The two methods are for completely different things. They are not similar, and good to be separated.

In functional languages you could use a "walk" method to iterate over all cells of the board and use a callback function to act on each cell. You could emulate that behavior in Java, but the code will get more complex, and I'm not sure it will be worth it in this example.

Robustness

Do you intend to initialize the board more than once in the lifetime of the object? If not (probably), then move the initialization to the constructor.

Writing style

You should use camelCase for naming, for example initializeBoard instead of initialize_board.

It's recommended to use braces with ifs, for example:

if (x == 0) {
    board[x][y] = (char)y;
} else {
    board[x][y] = '~';
}

It's better to print a newline using println:

System.out.println();
// instead of: System.out.print("\n");


The formatting is all over the place, which is distracting and makes the code hard to read.

The suffix Impl in TreeNodeImpl is unnecessary, as are the rec prefixes for recSize and recHeight.

It's not clear why newTreeNode should exist; this looks like work that should be done in a constructor.

Neither of the imports java.util.LinkedList and java.util.TreeSet are used and should be removed.

Having recSize and recHeight take a node as a parameter leads to strange-looking code like node.recSize(node).

The biggest problem though is that successive calls to recHeight will return different values.


Inefficiencies

Your iteration is wasteful for several reasons

You generate every product of two 3-digit numbers, which will not be reaped until the calculation is finished.
You start at the lowest end of a large range, when the desired result is clearly going to be near the top end.
You keep iterating after the largest number has been found
You are iterating over nearly twice as many results as you need to, because of duplicate products

Just to prove the final point:

scala> (for (i <- 100 to 999; j <- i to 999) yield (i * j)).size
res0: Int = 405450

(for (i <- 100 to 999; j <- i to 999) yield (i * j)).sorted.distinct.size
res1: Int = 227521

for (i <- 100 to 999; j <- i to 999 if i * j == 100000) yield (i, j)
res2: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((125,800), (160,625), (200,500), (250,400))

Improvements

The first point can easily be addressed with iterators, since you only need to traverse each range once. As to the others...

You could look for a way to start at the top of the range and work down, in such a way that each iteration tests the next lowest product of two 3-digitnumbers.  If you could think of a way to do that recursively, you could safely return as soon as you found a palindromic number.  But consider this:

There are only 999 6-digit palindromic numbers
It is trivial to generate a sequence of them in descending order
Testing a decreasing sequence of potential divisors, starting at 999, can be abandoned as soon as palindrome / divisor > 999
The search can stop as soon as palindrome % divisor == 0

As long as the target number is near the top of the range (which of course it will be), working backwards like this will involve much fewer operations,  which makes this cheaper even with the higher cost of modulo division.

Here's a simple attempt:

def ps = for (i <- Iterator.from(9, -1) take 9;
              j <- Iterator.from(9, -1) take 10;
              k <- Iterator.from(9, -1) take 10;)
              yield (i + 10 * j + 100 * k + 1000 * k + 10000 * j + 100000 * i)

ps find {p =>
  Iterator.from(999, -1) take 900 takeWhile (p / _ < 1000) exists (p % _ == 0)
}

If you are not happy that this only looks at the 6-digit palindromes and worry that the highest palindrome might be in the 5-digit range, laziness means that it is cheap to append 5-digit palindromes to the 6-digit iterator:

// Lazily generate all 999 palindromic 6-digit numbers in reverse order
def ps6 = for ((i <- Iterator.from(9, -1) take 9;
                j <- Iterator.from(9, -1) take 10;
                k <- Iterator.from(9, -1) take 10)
              yield (i + 10 * j + 100 * k + 1000 * k + 10000 * j + 100000 * i)

// Even more lazy generation of the 5-digit palindromes
def ps5 = ps6 map (i => (i / 1000) * 100 + i % 100)

// Put them together.  Iterator ++ is lazy
def ps = (ps6 dropWhile (_ > 999 * 999)) ++ (ps5 takeWhile (_ > 9999))

There are ways to do this without modulo arithmetic and/or even fewer iterations.  While my simple solution addresses the first 3 inefficiencies I listed, it is iterating rather more than is needed (mitigated significantly by working down from the top). Maybe you can improve on this from here.