This is my first review, so please bear with me. I'll start with atm.rb:

require_relative 'account'

account = Account.new

loop do
  # This is totally opinion, but I think doing this by joining a string array looks neater.
  # puts "What you want to do?\n1- Deposit\n2- Withdraw\n3- Check balance\n4- Check statement\n5- Exit"
  puts "What you want to do?"
  options = [
    "1- Deposit",
    "2- Withdraw",
    "3- Check balance",
    "4- Check statement",
    "5- Exit"
  ]
  puts options.join("\n")
  # These two lines can be condensed into one
  # option = gets.chomp
  # case option
  case gets.chomp
  when '1'
    puts "How many dollars do you want to deposit?"
    # You could merge these lines into account.deposit(get.chomp.to_f)
    amount = gets.chomp.to_f
    account.deposit(amount)
  when '2'
    puts "How many dollars do you want to withdraw?"
    # You could merge these lines into account.withdraw(get.chomp.to_f)
    amount = gets.chomp.to_f
    account.withdraw(amount)
  when '3'
    puts "You have #{account.balance} USD."
  when '4'
    puts account.statement.join("\n")
  when '5'
    break
  else
    "Wrong option. Try again."
  end
end

This is generally fine, just a couple things that I'd prefer for readability. I have larger ideas for structure for the other two files.

For the Transaction class, you really don't need the @type instance variable if it can only be :deposit or :withdraw. You can really just make that information be held in the sign of @amount. If @amount > 0, it's a deposit, and if @amount < 0 it's a withdraw. So, with that in mind, here's my revised version:

class Transaction
  # This was an attr_accessor. These attributes don't need to be editable, only readable.
  attr_reader :amount, :timestamp

  def initialize(amount)
    @amount = amount.to_f
    @timestamp = Time.now.getutc
  end

  def to_s
    # @amount is an instance variable, and so I added the "@" before it
    # You don't really need type here, but if you want it, use the next line:
    type = @amount > 0 ? "deposit" : "withdraw"
    "#{@timestamp} - #{type} - #{@amount} USD"
  end
end

And now, we move to the final file, account.rb:

require_relative 'transaction'

class Account
  def initialize
    @transactions = []
  end

  def balance
    # With our modifications to Transaction, we can do this more simply
    # @transactions.inject(0) { |sum, transaction| sum + transaction.value }
    @transactions.map(&:amount).sum
  end

  # In the next 2 methods, we don't to pass type anymore.
  # We can also remove the private add_transaction method, because it doesn't really serve any purpose. If you wanted to modify the transaction creation process, you should do it in Transaction#initialize.
  # I've also added optional type handling, for fun

  def deposit(amount)
    # add_transaction(amount, :deposit)
    @transactions << Transaction.new(amount)
  end

  def withdraw(amount)
    # add_transaction(amount, :withdraw)
    @transactions << Transaction.new(-amount)
  end

  def statement
    # This can be simplified with the map(&:to_s) syntax
    # @transactions.map { |transaction| transaction.to_s }
    @transactions.map(&:to_s)
    # You may also want to make the call to #join here, instead of in the main loop, because a statement sounds like it should be a string.
  end
end

Edit:

You could also get rid of the Transaction#to_s method and instead modify the Account#statement method to be:

class Account
  def statement
    @transactions.map do |t|
      type = t.amount > 0 ? "deposit" : "withdraw"
      "#{t.timestamp} - #{type} - #{t.amount} USD"
      # Personally, I like the extra line for readability, but
      # you could also write it as:
      # "#{t.timestamp} - #{t.amount > 0 ? 'deposit' : 'withdraw'} - #{t.amount} USD"
    end
  end
end


Search and filter in MVC3 Razor using Linq

Just put if, not else if so you can have a cumulative multi criteria search, and one condition in every if.

So every condition is easy to read, and if more than one criteria is filled, they will cumulate fine.

if (!String.IsNullOrWhiteSpace(searchString))
   books = books.Where(b => b.Name.ToUpper().Contains(searchString.ToUpper());

if (!String.IsNullOrWhiteSpace(searchGender))
   books = books.Where(b => b.Gender == searchGender);

if (String.IsNullOrWhiteSpace(searchHand))
   books = books.Where(b => b.Handedness == searchHand);


My minesweeper implementation in Javascript

Here are my personal thoughts:

Naming:

it's probably better to have placeBombs instead of initBombs, because you have a function called placeBomb.
Sometimes you use i and j , others you use x and y, it's better to be consistent.

Structure:

You should have a state field with constants indicating the state of the cell instead of various fields set to true or false.
you don't really need to look for the value inside of an hash to get the value of a cell. You can have a two dimensional array and reference the cell directly. This also means that you can remove the getFieldId function.

Something like this, for example:

var states = {
    MARKEDBYPLAYER: 1,
    DISCOVERED: 2,
    UNTOUCHED: 3
};

var boardSize = 16;
var cells = new Array(boardSize);

for(var x=0; x < boardSize; x++) {
    cells[x] = new Array(boardSize);
    for(var y=0; y < boardSize; y++) {
        cells[x][y] = {};
        cells[x][y].state = states.UNTOUCHED;
        cells[x][y].hasBomb = true;
        cells[x][y].neighbourNumber = null;
  }
}

if (cells[0][1].hasBomb) {
    console.log('Player has lost')
}

In generateBoard you have a bunch of instruction that would read better if you had just a call to a function that sets the required values.

Something like this:

function setDomCell(domCell, x, y, cellSize, cellFontSize) {
  domCell.id = x+'x'+y;
  domCell.style.width = cellSize;
  domCell.style.height = cellSize;
  domCell.style.fontSize = cellFontSize;
  domCell.setAttribute('x', x);
  domCell.setAttribute('y', y);
  domCell.addEventListener('click', reveal, true);
}

function generateBoard(){
  var domRow, domCell;

  for(var y=0; y<boardHeight; y++){
    domRow = document.createElement('tr');
    domBoard.appendChild(domRow);
    for(var x=0; x<boardWidth; x++){
      domCell = document.createElement('td');
      setDomCell(domCell, x, y, cellSize, cellFontSize);
      domRow.appendChild(domCell);
    }
  }
}

It would be even better if you had on object to take care of that, but take it one step at a time.

In the start function you have a switch to lookup values based on another value.

I'd say that's what a hash is for:

  var sizeVars = {
    'small': {
      boardWidth: 10,
      boardHeight: 10,
      cellSize: '48px',
      cellFontSize: '32px',
      bombsNumber: 16
    },
    'medium': {
      boardWidth: 20,
      boardHeight: 20,
      cellSize: '32px',
      cellFontSize: '16px',
      bombsNumber: 70
    },
    'large': {
      boardWidth: 30,
      boardHeight: 30,
      cellSize: '16px',
      cellFontSize: '8px',
      bombsNumber: 160
    }
  }

  var chosenSize = document.getElementById('size').value;
  console.log(sizeVars[chosenSize].boardWidth);


Finding median of 3 elements in array, and sorting them

You seem to specify that it will only be 3 elements in the title of the question, but your input shows you input more than 3 every so often. Your sorting "algorithm" (a lot of swaps) is quite naïve in that sense - for examples of some sorting algorithms that you could implement, take a look at Wikipedia's article on Sorting Algorithms. No need to understand all of them - some get quite complex!

However, you don't have to write a sorting algorithm yourself to use one! Java has some built in for you.

import java.util.Arrays; // or java.util.Collections if you are using ArrayList etc
Arrays.sort(my_array); // this will sort your array for you, using the Quicksort algorithm

As @JS1 mentioned, your formula for finding the center is wrong, and should be

int center = start + (end - start) / 2;

And with that, you can simply return the center index of the array, since it's all sorted now!

public static int medianOfThree(int[] sample, int start, int end) {
    Arrays.sort(sample);
    return sample[start + (end - start) / 2];
}

...Unless the array has a length that is an even number. Then the median formula is a little different:

public static int medianOfFour(int[] sample, int start, int end) {
    Arrays.sort(sample);
    int medianRightIndex = start + (end - start) / 2;
    int medianLeftIndex = medianRightIndex - 1;
    return (sample[medianRightIndex] + sample[medianLeftIndex]) / 2;
}

However, unless you are specifying a range in the array (e.g. you only wanted the median of the first 3 elements), you don't need to specify the start and end parameters at all. start can be 0 and end can be sample.length. Again, this is only if you want the median of the entire array. For a specific subset, you'd still use start and end parameters.

Now we have arrived to:

public static int median(int[] sample) {
    Arrays.sort(sample);
    int median = 0;
    int index = sample.length / 2;
    if(sample.length % 2 == 0) {
        median = (sample[index] - sample[index - 1]) / 2;
    } else {
        median = sample[index];
    }
    return median;
}


Finding longest list in list of lists in Python

Note that your code iterates over paths twice: once to calculate the max length,
and one more time to find all elements that have the max length.

It would be better to iterate only once,
keeping track of the max value, and the item that had the max value.
At the end of the iteration (single pass),
return the item that had the max value.

You can code this algorithm yourself,
and in many programming languages you would have to.
In Python,
the max built-in takes a key parameter,
to perform such "max by" operation.
The key parameter must be a one-argument function.
For each item in the collection,
the function will receive the item,
and should return a value that will be used as the rank of the item.

In your example, the rank of each item is its length.
That gives this simple pythonic code:

max(paths, key=lambda coll: len(coll))

... which gets even simpler with η-reduction to just (thanks @Gareth!):

max(paths, key=len)


Inserting and updating record using LINQ by calling a common function

I would probably pass in the customer log as a parameter to the method and then have it deal with just the database insertion.  If you wanted to keep a InsertOrUpdate type of approach I would branch on perhaps something like the object ID if it has one.  This way you can have a variety of ways that your object is created and the method is only responsible for the persistance of that object not also it's creation and populating.

A couple of problems I see in your approach:

The method is doing too many things.  It's responsible for querying for your record, instantiating the record and populating as well as performing the persistance.
The method has too many dependencies.  It looks like you have made it subject to both an external UI component in the .Text objects as well as the database layer.  What happens if you had multiple ways of populating the object.  You would have to duplicate this method?

Something like this (without knowing a bit more of your setup):

// a method higher up the chain
void CreateCustomerLog()
{
   Data_Customer_Log record = new Data_Customer_Log();
   record.cCustomerType = NewCustomerddlCustomerType.Text;
   record.cBranchName = NewCustomerddlBranchName.Text;
   record.nBranchNo = Convert.ToDecimal(Global.gBranchNo);

   InsertOrUpdate(record);
}

void UpdateCustomerLog(string applicationNo)
{
   Data_Customer_Log record = GetCustomerLog(applicationNo);

   if(record == null)
   {
      // handle record not existing here or filter it up the chain
   }
   else
   {
      InsertOrUpdate(record);
   }
}

Data_Customer_Log GetCustomerLog(string applicationNo)
{
   return (from cust in
           dt.Data_Customer_Logs
           where cust.cApplicationNo.Equals(applicationNo)
           select cust).SingleOrDefault();
}

Data_Customer_Log InsertOrUpdate(Data_Customer_Log record)
{
    if(record.ID > 0)
    {
       return Insert(record);
    }
    else
    {
       return Update(record);
    }
}

Data_Customer_Log Insert(Data_Customer_Log record)
{
    // TODO: perform insertion and throw exception if there is a problem
}

Data_Customer_Log Update(Data_Customer_Log record)
{
    // TODO: perform update and throw exception if there is a problem
}

I would probably point out that these methods would probably be in different classes.  For example the Update, Insert and/or Get might be in some sort of repository class.  The CreateCustomerLog and UpdateCustomerLog might be at the higher level, maybe your UI level as it interacts directly with the UI elements.

Just my thoughts.


OraTest is not a useful name. Call it OracleToCSVWriter or something like that.

Mind the naming of variables etc: oda is not very descriptive - adapter would maybe be better.

Hardcoded username/password is rarely a good idea.

Why do you convert to string in this line?:

IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));

I think the below would be sufficient:

sb.AppendLine(string.Join(",", row.ItemArray));

Even for such a small piece of code it is a good idea to split it up in meaningful parts (maybe: private string GetConnectionString() {...}, private DataTable LoadData(OracleConnection connection) {...}, WriteData(DataTable data) {...})

You should dispose OracleCommand, OracleDataAdapteras well as DataTablejust as you dispose OracleConnection.

When writing to file, I would write directly to a stream, instead of first collect all data in memory:

    using (StreamWriter writer = new StreamWriter("<Path>", false, Encoding.Unicode))
    {
      foreach (DataRow row in table.Rows)
      {
        writer.WriteLine(string.Join(", ", row.ItemArray));
      }
    }

That said You should be aware that when writing a CSV file, string and other data may contain commas (,)  and that could break the column layout, so you'll have to encapsulate strings in quotation marks, which will complicate the writing a little bit. A way to go could be something like:

        writer.WriteLine(string.Join(", ", row.ItemArray.Select(i => i is string? $"\"{i}\"" : i)));

or maybe:

writer.WriteLine(string.Join(", ", row.ItemArray.Select(i => $"\"{i}\"")));

(Not fully tested!)


This method satisfies two concerns:

mark users as active
return the last status of inactivity

This should be two separate methods so as to not violate SRP and enable checking of that status without resetting it.

wasUserInactive should be isUserInactive and just return userInactive;. Additionally there should be a method resetting the inactive status to false.

Don't introduce quantum behaviour in your code, where observing a state changes it!


Some notes:

if boolean then true else false end -> boolean.
UserRelation.where(user_id: self.id).where(with_user_id: user.id) -> UserRelation.where(user_id: self.id, with_user_id: user.id)
active_record_collection.count > 0 -> active_record_collection.exists?
I don't understand why you have to check both ways, a "coach - student" relationship looks unidirectional.

Anyway, if you set up the coach_students association, you may write something like this:

def coach_of?(user)
  coach_students.where(with_user_id: user).exists? ||
    user.coach_students.where(with_user_id: self).exists?
end


Macro to generate an enum and an array of strings

Most macro solutions are not readable nor maintainable. You should avoid macro solutions like this.

The best way is to not use macros at all:

typedef enum
{
  ZERO,
  ONE,
  TWO,
  THREE,
  NUMBERS_N
} numbers_t;

static const char* NUMBER_STR[NUMBERS_N] =
{
  [ZERO]  = "ZERO",
  [ONE]   = "ONE",
  [TWO]   = "TWO",
  [THREE] = "THREE",
};

puts(NUMBER_STR[1]); // prints ONE

This code is perfectly readable and it maintains the integrity between the enum and the array well. It only has one small problem and that is code repetition.

Code repetition should be avoided, but programmers tend to exaggerate how bad it is. It is rarely ever so bad that it justifies turning your whole program into "macro hell".

The reasons why code repetition should be avoided is that is leads to typo-like bugs and problems with maintenance. However, while a "macro hell" solution might rule out the typos, it makes the code difficult to maintain and the increased complexity increases the chance of other more serious bugs.

Famous quote by Brian Kernighan:

  Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?

That being said, there are valid cases where you must centralize data in one place, particularly when maintaining existing code that shouldn't be changed more than necessary. The macro you posted is a flavour of "X macros", which is the preferable way to write such macros - "messy in a standardized way" so to speak. X macros is about defining a list of data as you do, but to pass on that data to localized macros embedded into the code itself. To rewrite the above code with X macros, you'd do:

#define NUMBER_LIST \
  X(ZERO)           \
  X(ONE)            \
  X(TWO)            \
  X(THREE)          \

typedef enum
{
  #define X(name) name,
    NUMBER_LIST
  #undef X
  NUMBERS_N
} numbers_t;

static const char* NUMBER_STR[NUMBERS_N] =
{
  #define X(name) [name] = #name,
    NUMBER_LIST
  #undef X
};

puts(NUMBER_STR[1]); // prints ONE

The advantage here is the flexibility to apply the same data in different ways, on case-by-case basis. A macro such as #define X(name) [name] = #name, is cryptic by itself, but when given the context of the surrounding array initializer list, one can easier understand the meaning. "X macros" can also be used to manually unroll loops:

#define X(name) puts(NUMBER_STR[name]);
  NUMBER_LIST
#undef X

This is equivalent to iterating over the array and printing all items, but the loop is unrolled and we end up with a number of puts calls.


Stitching together badly formatted log files

Without knowing exactly your data structure, I have to guess that it looks like this:

data <- data.table(a = c('1,1,1,4,6',
                         '1,2,3,4,',
                         '',
                         '1,2,3,4,',
                         '1,2,3,4,5'))

If it is correct, then your desired operations could be done like this:

#############################################
#Removing empty rows.
data <- data[data[[1]] != '']

#Removing rows where there is no data in the 5th column.
retain <- str_detect(trimws(data[[1]], which = 'both') ,".+,.+,.*,.*,.+")
data <- data[retain, ]

#This replaces the first 4 commas with a tab-delimiter.
for(i in 1:4) data[[1]] <- str_replace(data[[1]], ",", "\t")

#This splits the row into 5 seperate columns, always.
dNew <- as.data.table(tstrsplit(data[[1]], "\t", fixed = T))
dNew
#    V1 V2 V3 V4 V5
# 1:  1  1  1  4  6
# 2:  1  2  3  4  5

The main problem is that you are using lapply where it is not needed.


You should try to find the O(1) algorithm for this problem, instead of using your current O(M) algorithm.

For example, given the input 9 500000001, your program takes 2.3 seconds (on my laptop) to run through the half-billion integers between 999999999 and 500000001. Whereas, using the relatively obvious O(1) algorithm, it takes 0.007 seconds.

Since this looks like homework and/or a Project Euler–type problem, I won't give the spoiler here.

Stylistically,

Prefer to write out std::cin, std::cout, etc., instead of wasting space at the top of the program with a bunch of using directives. It's shorter, cleaner, and (most importantly) more idiomatic to qualify names at the point of use instead of relying on using directives to pull them into scope.
Your function validNums uses exceptions for control flow, which is frowned upon in C++. Prefer to make it a function returning bool, and have its caller do something sensible (such as print an error message) if the given numbers aren't valid.
You have a named abstraction for largestNumber, when that could just as well have been a named local variable int largestNumber = pow(...);.
You don't have a named abstraction for produceTheActualAnswer; instead, you inline a complicated test if (answer = divisbleBy(largestNumber(num1), num2)) straight into main. This makes it unnecessarily difficult to switch out your bad old algorithm for a new and better one.
Putting an assignment inside an if condition is supremely bad style — so bad that both GCC and Clang (and probably MSVC too) will emit a warning on this code. You should write either

int answer = produceTheActualAnswer(num1, num2);
if (answer != 0) {
    ...
} else {
    ...
}

or, if you really want to use "interesting" features of C++, you might write

if (int answer = produceTheActualAnswer(num1, num2)) {
    ...
} else {
    ...
}

But I don't recommend the latter.

You should also consider taking your num1 and num2 parameters via the command line, instead of reading them from stdin:

int main(int argc, char **argv) {
    if (argc < 3) {
        // maybe read them from stdin anyway
    } else {
        int m = std::atoi(argv[1]);
        int n = std::atoi(argv[2]);
        int answer = f(m, n);
        if (answer != 0) { ... } else { ... }
    }
}

This makes it easier to test your code quickly from the command line, and also makes it easy to time ./a.out 9 500000001 to see if you've beaten my 0.007 seconds yet. ;)


I'd start with very minor issues.

Usually underscore isn't used in C# names, PascalCase and camelCase are usually preferred (see max_log_per_source). Functions are usually PascalCase (then, for example, isBlocked should be IsBlocked).

Private fields (like requests) do not need any special prefix but you'd better (for clarity) to use a prefix (for example _) or access them like this.requests.

I do not see any extension point in your class then it should be marker sealed.

Fields you initialize only in ctor and that aren't supposed to be changed should be marked readonly: private readonly ConcurrentDictionary<string, LinkedList<DateTimeOffset>> requests;.

In isBlocked() you do not really need haslist local variable. It may be simplified to (you're already doing this in ForgiveSource()):

LinkedList<DateTimeOffset> list;
if (!requests.TryGetValue(source, out list))
    return false;

If you're using C# 7 code might be further simplified:

if (!requests.TryGetValue(source, out var list))
    return false;

ForgiveSource() and HandleRequest() seem to work in concert however I'd change calling logic to avoid to add an entry when login is valid.

This code:

if (condition) {
    // Something
    return;
} else {
    // Something else
}

Can be simplified, you don't need an else here:

if (condition) {
    // Something
    return;
}

// Something else

I find that usually list.Count == 0 is much much clearer than list.Count < 1.

To me a type declared as ConcurrentDictionary<string, LinkedList<DateTimeOffset>> is a missing opportunity to introduce a separate specialized class. More than that you have a thread-safe ConcurrentDictionary and an inner LinkedList which is not. Why don't you introduce a MultiMap<string, DateTimeOffset> type? It's a pretty common data structure to reuse. Also you may wrap it (or extend it) into your own LogInAttemptsCollection (which will be thread-safe). In this way you might separate logic ("list logic" from "is blocked" logic)

Is limit a dynamic parameter which will change for each request? If not then you may consider to move it to a property (or to a readonly field set in ctor).

Why HandleRequest() has an out parameter and a void return type? out parameters should be avoided, when possible, and in this case you just need to change return type to bool.

One note: I feel removeOld() algorithm is way too complex (in general, not for its implementation). Is any reasoning behind this?


Better way to query and pass the elements to conditional operator in Javascript

Interesting question;

You can make this code slightly less efficient (however, the user will never notice), and so we can just attach listeners to everything.

const addClickEventListeners = () => {

  const addListener = (button) => button.addEventListener('click', someFunction, false);

  document.querySelectorAll('[name="multiple_choice"]').forEach(addListener);
  document.querySelectorAll('[name="true_false"]').forEach(addListener);
  document.querySelectorAll('[name="multi_answers"]').forEach(addListener);

};

This should behave the same way as far as I can tell.

You could also create your buttons that require someFunction with a css class dedicated for that selection or even better with a data attribute for that purpose. Then you just query on that and attach the listener.


C++ - printing a binary tree vertically, Depth first

The order in which you're traversing the tree is a simple pre-order traversal. If you can use recursion, it's a much easier way to do this traversal:

void preorder(node *root) {
    if (root == nullptr)
        return;
    std::cout << root->val << " ";
    preorder(root->left);
    preorder(root->right);
}

Other than that, your code currently has undefined behavior--in main you don't seem to be allocating any actual nodes for your tree. You're just taking an uninitialized pointer (root) and overwriting whatever happens to be in the memory it points at. To get something meaningful, you need to allocate your nodes.

I'd probably add a constructor to node to make construction a little easier:

struct node {
    int val;
    node *left, *right;

    node(int val) : val(val), left(nullptr), right(nullptr) {}
};

Then main would look something like this:

int main() {
    node *root = new node(5);
    root->left = new node(3);
    root->left->left = new node(7);
    root->left->right = new node(8);
    root->right = new node(4);
    root->right->left = new node(9);
    root->right->right = new node(1);
    preorder(root);
    // possibly code here to delete the nodes of the tree.
}


Parsing users from a list of commands for email notifications

Critique

First, note that you are misusing tr when you do tr "\n" ", \s".  In tr string1 string2, string1 is supposed to be at least as long as string2, as each character in string1 is translated into the corresponding character in string2.  (If string1 is longer than string2, the last character found in string2 is duplicated until string1 is exhausted.)  Therefore, tr "\n" ", \s" is equivalent to tr "\n" ",", which produces a comma-separated output with no spaces — in contradiction to your sample output.

The dangling ; echo "\n" at the end is awkward.  You're now running two pipelines whose outputs happen to appear one after the other, rather than producing one output stream.  That means that the output merely looks right on screen.  You can't pipe or redirect the whole thing, though, unless you run the two pipelines in a subshell, like ( awk … | tr -d … | tr … ; echo "\n" ).

Suggested solution

awk '{ print $NF }' /tmp/foo | xargs echo will get you mostly there.  By using xargs, you automatically get unquoting behaviour.  (The way xargs handles quoting is not quite the same as the way SQL handles quoting, but in most cases, it's probably close enough.)  The echo command will produce one line of output, ending with a newline.

The only thing remaining is to insert a comma before each space.  For that, I would use | sed -e 's/ /, /g'.  (If you just want commas and no spaces, you can use tr ' ' , instead.)

In summary, do

awk '{ print $NF }' /tmp/foo | xargs echo | sed -e 's/ /, /g'


Generating an HTML table with colspan and rowspan from a one-dimensional array

I really wanted to find a purely functional solution to this problem, but I wasn't able to.  Nevertheless, your basic idea is pretty simple, and can be made even shorter and more declarative:

// Cell calculations as pure data.  "cells" is the variable containing
// all cells, which we are filling in
var width     = 3,
    numCells  = input.reduce((m,x) => m += x.rowspan + x.colspan -1, 0),
    cells     = new Array(numCells).fill(false),
    dummy     = { dummy: true},
    addAcross = (i,n) => R.times(j => cells[i+j+1] = dummy, n),
    addDown   = (i,n) => R.times(j => cells[i+(j+1)*width] = dummy, n),
    nextIndex = () => cells.findIndex(x => !x);

 // Everything happens here.  We fill in "cells" with the real
 // cells and dummy cells for the span cells

 input.forEach(x => {
   var i = nextIndex();
   cells[i] = x;
   addAcross(i, x.colspan-1);
   addDown(i, x.rowspan-1);
 })

// HTML View Helpers
// Once we have the data, just split the array into subarrays
// for each row, and filter out the dummy cells.  In this format
// constructing the html itself is trivial

var rows = R.splitEvery(width, cells).map(r => r.filter(x => !x.dummy)),
    asTd = c => `<td rowspan=${c.rowspan} colspan=${c.colspan}>${c.value}</td>`,
    asTr = row => `<tr>${row.map(asTd).join('')}</tr>`,
    asTable = rows => `<table border=1>${rows.map(asTr).join('')}</table>`;

document.querySelector('body').innerHTML = asTable(rows);

Note: I used one ramda library function just to break the array into subarrays.  Lodash has a similar one, but I prefer ramda.

Here's a working bin of the final solution:
http://jsbin.com/nimuca/2/edit?js,output


Model class representing a financial calculator

Are my constants defined in the correct location in my Model class's implementation file?

It is impossible to tell.  Where a variable needs to be declared is entirely dependent upon its intended scope.

If a variable is used only within a single block (within an if, else, or loop, or anything else of this nature), it should be declared within that block.
If a variable is used only in a single function, it should be declared in that function.
If a variable is used in multiple functions in a file, it should be declared in the .m file so it can be seen throughout the file, but not within other files in the project.
If a variable is used in multiple files, it should be declared in a .h file so that it may be imported across the multiple files.

  Even though the compiler does not force me to, would it be better to declare my private methods in the class extension? I want to make sure I'm following best practices.

There's no particular need to declaring methods in class extensions in Objective-C.  I don't know of any real benefit to doing so.

  Now that the Model's instance methods have been changed to class methods, should I change the public calculateValuesWithMonthlyRevenue: method to a class method as well?

This one can't be changed, at least not quite as easily.  You can't refer to a class's instance variables within a class method.

Perhaps what you should do is instead change it to more of a factory method that might look a bit like this:

+ (instancetype)calculatedValuesForMonthlyRevenue:(CGFloat)monthlyRevenue {
    return [[self alloc] initWithValuesForMonthlyRevenue:monthlyRevenue];
}

- (instancetype)initWithValuesForMonthlyRevenue:(CGFloat)monthlyRevenue {
    self = [super init];

    if (self) {
        _calculatedPay = [MMCalculator calculateYourPay:monthlyRevenue];
        _calculatedSavingsForStuff = [MMCalculator calculateSavingsForStuff:monthlyRevenue];
        _calculatedSavingsForProfitFormula = [MMCalculator calculateSavingsForProfitFormula:monthlyRevenue];
        _calculatedSavingsForTaxes = [MMCalculator calculateSavingsForTaxes:monthlyRevenue];
    }

    return self;
}

  Any other general comments are welcome.

The class name, MMCalculator needs some work.  This does a more specific job then a regular calculator.  This is more like a personal finance calculator if anything.

  Any other general comments are welcome.

You really shouldn't represent money with floating point numbers.

Instead, you should probably create a class for holding money.

Money.h

@interface Money

@property (readonly) int dollars;
@property (readonly) int cents;

+ (instancetype)moneyWithDollars:(int)dollars cents:(int)cents;
- (instancetype)initWithDollars:(int)dollars cents:(int)cents;

@end

Money.m

@implementation Money {
    long long _totalCents;
}

- (int)dollars {
    return _totalCents/100;
}

- (int)cents {
    return _totalCents%100;
}

+ (instancetype)moneyWithDollars:(int)dollars cents:(int)cents {
    return [[self alloc] initWithDollars:dollars cents:cents];
}

- (instancetype)initWithDollars:(int)dollars cents:(int)cents {
    self = [super init];

    if (self) {
        _totalCents = cents + (100 * dollars);
    }

    return self;
}

@end

The class could be rounded out with various math methods as well.


Generating lists of sequences of specified lengths

Your function seems very well suited to the Clojure iterate function, which takes a function that turns state into state:

(def shifts [5 5 5 5 5 2 2 5 5 5 5 5 2 2])
(def total-shifts (apply + shifts))
(def genes (vec (range total-shifts)))

(defn transition [[answer shifts-remaining genes-remaining]]
  (let [[num-shifts & more-shifts] shifts-remaining
        [genes-in-day rest-of-genes] (split-at num-shifts genes-remaining)]
    [(conj answer genes-in-day) more-shifts rest-of-genes]))

(->> (iterate transition [[] shifts genes])
     (drop (count shifts))
     ffirst)


You arrive at the answer by counting 20 at a time.  That's 11639628 iterations of the main loop — and many recursive calls to calculate().

A more efficient and satisfying approach would be to use the Euclidean Algorithm to compute LCMs.

Note that an int is not guaranteed to be large enough to hold the result.  I suggest using long everywhere.

#include <iostream>

long gcd(long a, long b) {
    while (b) {
        int prevB = b;
        b = a % b;
        a = prevB;
    }
    return a;
}

long lcm(long a, long b) {
    return a * (b / gcd(a, b));
}

int main() {
    long result = 20;
    for (long number = result - 1; number > 1; --number) {
        result = lcm(result, number);
    }
    std::cout << result << '\n';
}


Extending on @yuri's answer, if you don't have any information relative to the state of "sortedness" of the numbers, quicksort is almost certainly a better option.  If you happen to know that the numbers are almost sorted, it would be more efficient to use insertion sort at that point.  Writing a sorting algorithm as an exercise is fine, but you're likely going to want to prefer to use Collections.sort than write your own unless you have a specific reason not to.

A few other tips:

IntArray is not a typical variable name in Java.  Variable names should start lowercase.
There's really no reason to use two Scanner instances.  You can use the same instance to read the initial array amount as well as each value.
While we're at it, there's no reason to specify the number count.  The program would be more robust if you simply used a List (ArrayList implementation would work best here) and added values until you receive a non-number input like "end".
Generally static class members should really only exist to define constants in your class, and not hold state.  Everything in your program is static, so you don't require state except for the Scanner instance.  Normally you'd simply pass Scanner instance as a parameter to the static method, but you're only using it in the one method getIntegers so you could just instantiate Scanner only in the scope of getIntegers rather than use it as a parameter or class member.
There is already a simple means to print out contents of a List:  List.toString.
In the off chance that an exception is thrown by Scanner (or any stream), we surround the reading with a try.. finally to ensure that no matter what, the scanner instance is closed properly.
Note that I maintained use of List rather than convert to an array.  This is mostly because ultimately an array is only required to print out.  We can accomplish everything we need using List, and most professional programmers tend to prefer the use of List over arrays except for specific circumstances.

Applying the changes above, we get the following:

public class Main {
    public static void main(String[] args) {
        List<Integer> intList = getIntegers();
        intList = sortIntegers(intList);

        printIntegers(intList);
    }

    public static List<Integer> getIntegers() {
        System.out.println("Please provide integers and 'done' when finished.");

        List<Integer> values = new ArrayList<Integer>();
        Scanner scanner = new Scanner(System.in);
        try {
            while(scanner.hasNextInt()) {
                values.add(scanner.nextInt());
            }
        } finally {
            scanner.close();
        }

        return values;
    }

    public static List<Integer> sortIntegers(List<Integer> list) {
        Collections.sort(list, Collections.reverseOrder());
        return list;
    }

    public static void printIntegers(List<Integer> list) {
        System.out.println(list.toString());
    }
}


1. Review

Code is easier to test (and measure the performance) if it's organized into functions or classes. In this case you have persistent data (W, H, grid, legal, start_pos) that's shared between the various parts of the code, so a class would be the best way to go here.
It would be simpler to write:

EMPTY_SPACE_SYMBOLS = '.'
STARTING_POINT_SYMBOLS = 'Ss'

since Python can iterate over the characters in a string just as easily as over the items in a list.
Assertions should be reserved for detecting programming errors, and not used for reporting problems with the input. That's because assertions can be disabled via the -O option to the Python interpreter, or the PYTHONOPTIMIZE environment variable. For the errors in this code, you should raise exceptions.
It's more general to have a method format_solution that returns a string, rather than a function print_solution that prints it. That way the caller has the option of deciding what to do with it.
Instead of:

[OBSTACLE_SYMBOL for _ in range(self.w)]

write:

[OBSTACLE_SYMBOL] * self.w

Instead of building str_grid from result_grid and then formatting the former, just format result_grid directly:

'\n'.join(' '.join(str(item).ljust(3) for item in row)
          for row in result_grid)

The number "3" only works for small enough puzzles. To make the formatting work in the general case, it should be one more than the maximum number of digits in any number in the path, that is:

len(str(len(path) + 1)) + 1

extend is only called from one place in the code, so it would make sense to inline it at that point.
Coordinates are r and c in some places in the code, and x and y in other places. It would be better to be consistent.

2. Revised code

import time

EMPTY_SPACE_SYMBOLS = '.'
STARTING_POINT_SYMBOLS = 'Ss'
OBSTACLE_SYMBOL = 'X'
DIRS = [(-1, 0), (1, 0), (0, 1), (0, -1)]

class HamiltonSolver:
    """Solver for a Hamilton Path problem."""

    def __init__(self, grid):
        """Initialize the HamiltonSolver instance from a grid, which must be a
        list of strings, one for each row of the grid.

        """
        self.grid = grid
        self.h = h = len(grid)
        self.w = w = len(grid[0])
        if any(len(row) != w for row in grid):
            raise ValueError("Grid is not rectangular")
        self.start = None
        self.legal = set()
        for r, row in enumerate(grid):
            for c, item in enumerate(row):
                if item in STARTING_POINT_SYMBOLS:
                    if self.start is not None:
                        raise ValueError("Multiple starting points")
                    self.start = (r, c)
                elif item in EMPTY_SPACE_SYMBOLS:
                    self.legal.add((r, c))
        if self.start is None:
            raise ValueError("No starting point")

    def format_solution(self, path):
        """Format a path as a string."""
        grid = [[OBSTACLE_SYMBOL] * self.w for _ in range(self.h)]
        for i, (r, c) in enumerate(path, start=1):
            grid[r][c] = i
        w = len(str(len(path) + 1)) + 1
        return '\n'.join(''.join(str(item).ljust(w) for item in row)
                         for row in grid)

    def solve(self):
        """Generate solutions as lists of coordinates."""
        target_path_len = len(self.legal) + 1
        paths = [[self.start]]
        while paths:
            path = paths.pop()
            if len(path) == target_path_len:
                yield path
            r, c = path[-1]
            for dr, dc in DIRS:
                new_coord = r + dr, c + dc
                if new_coord in self.legal and new_coord not in path:
                    paths.append(path + [new_coord])

PUZZLE_GRID = '''
......
.SX...
...X..
.....X
......
XX....
......
'''.split()

def main():
    start_time = time.time()
    n_solutions = 0
    puzzle = HamiltonSolver(PUZZLE_GRID)
    for solution in puzzle.solve():
        if n_solutions == 0:
            print(puzzle.format_solution(solution))
            print("First solution found in {} s"
                  .format(time.time() - start_time))
        n_solutions += 1
    print("{} solution{} found in {} s"
          .format(n_solutions, '' if n_solutions == 1 else 's',
                  time.time() - start_time))

if __name__ == '__main__':
    main()

3. Speeding it up

Each time extend is called, the list of paths under consideration is extended by up to four new paths, each of which is a copy of the current path plus one new grid coordinate. As the search progresses, this results in many paths being created and stored (up to 20 paths in the example from the post).

But in a depth-first search it should be only be necessary to remember a single path at a time, together with the current position in the iteration over the four directions. (This is the "stack of iterators" pattern.)
The code checks to see if the new coordinate is available by calling new_coord in self.legal and new_coord not in path. But path is a list, and testing for membership in a list is not efficient (Python has to compare the new coordinate with every item in the list). For efficient membership testing you need a set.

In this case the code already has a set of legal coordinates. So we can remove a coordinate from this set when we add it to the path, and add it back to the set when we backtrack. This means we only need one membership test, and it also means that the path is complete when the set of legal coordinates is empty.
We can speed up the inner loop by caching method lookups like path.append in local variables.

The revised solve method looks like this:

def solve(self):
    """Generate solutions as lists of coordinates."""
    path = [self.start]
    dirs = [iter(DIRS)]

    # Cache attribute lookups in local variables
    path_append = path.append
    path_pop = path.pop
    legal = self.legal
    legal_add = legal.add
    legal_remove = legal.remove
    dirs_append = dirs.append
    dirs_pop = dirs.pop

    while path:
        r, c = path[-1]
        for dr, dc in dirs[-1]:
            new_coord = r + dr, c + dc
            if new_coord in legal:
                path_append(new_coord)
                legal_remove(new_coord)
                dirs_append(iter(DIRS))
                if not legal:
                    yield path
                break
        else:
            legal_add(path_pop())
            dirs_pop()

On the example from the post this is more than 2½ times as fast as the original code.

Update You asked in comments how this works. Well, the list path contains the current path reached in the search. The list dirs is the same length as path, and each element is an iterator over the list DIRS. Each iterator remembers where we got to in the list of directions at that point in the search, so that when we backtrack we can pop the dirs list and then continue iterating from where we left off.

The control flow is slightly tricky. When the path is extended it reaches the break statement, which breaks out of the for loop (bypassing the else) and so goes back to the top of the while loop, picking up the new coordinates that we just added to the path. But when no further progress can be made, the for loop runs out of directions and enters the else clause. This causes  path and dirs to be popped and then the while loop picks up from the previous point reached in the search.

I hope that's clear. If you're still not quite sure, step through the code in the Python debugger so that you can see exactly what it's doing.


I think your algorithm is fast enough to get accepted. Contest times are sometimes not well calibrated for python speed.

One part that could be optimized is splitting the string and converting it to integers, which is now creating a new string for every number, possibly up to \$10^5\$ strings. Since the string is always gonna be 1-digit numbers separated by spaces, you could instead iterate on the string without parsing it or converting it to integers.

Something like:

str = "1 2 3 4"
for index in range(0, len(str), 2):
  num = str[index]
  # use num here


The reason why the filter is slow is because by calling lambda, the groupby objects are then iterated over in Python. In this case there are 70000 ID groups and so that can take some time.

One way to avoid this would be to count the number of non-nan values and the number of total values per ID in pandas, then mask your data like that. This keeps everything vectorized in Pandas.

So you could find IDs containing nans,

contains_nan = data.groupby("ID")["dt"].count() != data.ID.value_counts().sort_index()

Note that to compare the two series, the indices for the two series must be the same, so we sort it. Then you can filter just IDs not containing nan and apply the mask:

ids_without_nan = contains_nan[~contains_nan].index
data = data[data.ID.isin(ids_without_nan)]

Benchmarking this method results in:

81.1 ms ± 5.46 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

versus using filter:

17.7 s ± 396 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


Wrapper for boolean type to reduce the use of if statements

Approach

The approach is interesting, but doesn't seem practical or actually useful.

I think that you need more justification for this than simply stating that you want to use less if-statements.

Especially since you essentially still have the if-structure, just with a different syntax:

// your code:
findElement("el").ifTrue(() -> doSomething).orElse(() -> doSomethingElse)

// regular if, one line (which I would not recommend, it's more difficult to read than multi-line):
if (findElement("el")) doSomething; else doSomethingElse;

// standard if:
if (findElement("el")) {
    doSomething;
} else {
    doSomethingElse;
}

If there are other reasons for your approach, you need to make them clear. But this is definitely not a good replacement for general-purpose if statements.

And if you use this throughout a project, you have dependencies to this custom wrapper everywhere. Removing it later will be a lot of work. You will also need to wrap each return value from libraries and the standard APIs (which will be ugly in itself), or your code will consist of a mixture of standard ifs and your approach, which will not help readability.

Readability

Your approach is already more difficult to read than the standard approach, and with anything except a simple function-call, your approach would be even less readable:

// your code:
findElement("el").ifTrue(() -> {doSomething; doSomething2; doSomething3;}).orElse(() -> doSomethingElse; doSomethingElse2;)

// standard:
if (findElement("el")) {
    doSomething;
    doSomething2;
    doSomething3;
} else {
    doSomethingElse;
    doSomethingElse2;
}

You can of course also make your version multi-line, but that doesn't make matters much better:

findElement("el").ifTrue(() -> {
    doSomething;
    doSomething2;
    doSomething3;
}).orElse(() -> {
    doSomethingElse;
    doSomethingElse2;
})

You are still recreating the if-structure, just with a worse syntax.

Performance

I did not profile your approach, but in many situations, the extra cost of the additional function calls for the simplest of basic expressions will be noticeable.

Misc

I would recommend curly brackets even for one-line statements. They do make code easier to read, and can prevent bugs.
I would always use this when accessing fields, it makes it clearer where values come from.
Do you really need the value field and if in OrElse? I would assume that an else should always be executed.


Executing an SQL command on a number of files

if (fileList != null)

You can reduce nesting (which is usually a good thing) by turning this into

  if (fileList == null) { return; }

The same applies to

if (File.Exists(file))

It's better to have

if (!File.Exists(file)) { continue; }

But even better then this would be to filter the list before you start processing it:

fileList.Where(File.Exists)

Checking the fileList for null is an indicator that some other part of the code might be implemented in a wrong way_. In C# we prefer to have an empty list rather then a null.

Parallel.ForEach

Have you already tried the Parallel.ForEach? It would greatly simplify your code:

Parallel.ForEach(fileList.Where(File.Exists), fileName =>
{
    // process the file
});

This method has a lot of overloads so you'll probably find something that suits your needs.

With one of them you could for example create a connection for each parallel loop and dispose it at the end of the processing.

Here's a bigger example that might work for you. This will use the same connection for several files.

try
{
    var parallelOptions = new ParallelOptions
    {
#if DEBUG
        MaxDegreeOfParallelism = 1
#else
        MaxDegreeOfParallelism = Environment.ProcessorCount
#endif
    };

    var parallelLoopResult = Parallel.ForEach
    (
        source: fileList.Where(File.Exists),
        parallelOptions: parallelOptions,
        localInit: () => new
        {
            Connection = /* init the oracle connection*/
        },
        body: (fileName, loopState, i, local) =>
        {
            // process the file
            // use the local.Connection
            return local; // pass the connection to the next loop
        },
        localFinally: local =>
        {
            local.Connection.Dispose();
        }
    );
}
catch (AggregateException ex)
{
    // handle exceptions
}

See this question on SO, it compares your solution with Parallel.ForEach:

Parallel.ForEach vs Task.Factory.StartNew


[...] it misbehaves in some subtle or pathological cases.

I may have identified a pathological case...

Caveat When Using Bitwise Shifting

This pertains to the following line:

var begin_right = begin + (size >> 1);

Using bitwise shifting to efficiently multiply or divide by a factor of two carries a risk when extremely large numbers are involved. size >> 1 will stop behaving predictably when size exceeds 2147483647.

This is fine if you don't expect to be sorting arrays of such magnitude, but you might as well double that range by using an unsigned bitwise shift (>>>), allowing you to shift any positive number up to 4294967295.

If you want to be safe with arrays even longer than that, you can use Math.floor(size/2) although that will negatively impact performance.

Here's a fiddle to demonstrate: http://jsfiddle.net/akxbLej5/1/


Depends on how you want to improve it, there's number of ways to go. For instance:

Procedural vs OO code - Extendability

If you wish to extend your game, add new functionalities, make it one game among many that users can play, you'd better switch from current programming style to more modularized one.

Right now that code is contained within "main" method. It's quite common for first programs, to be like that. It's rather procedural programming - you give the computer instruction after instruction. While easy to follow, it's problematic when you try to expand such code or maintain it. It's also mind-numbing to read, making it hard to modify properly.

You may want to modularize it somewhat:

group instructions together into procedures / functions
more related procedures into classes
leave in main as few things as you can

This is obviously very short answer to very large topic, but do ask if you're interested. You would then have to model the program using objects.

For me that would be number 1. Even over syntax.

Syntax & Cleaning

Tools help

Intellij IDEA has a menu called Analyze. If you select Inspect code there, you'll notice a few pointers, along with explanation.

Additionally, there is Checkstyle and FindBugs, they also offer lots of pointers.

Heed earlier advice

Giving credit where it's due, I also completely agree with sje397's comment. Let me quote it here:

  Fix indenting. Fix variable names (firstName isn't holding a first
  name). You don't even need to enter the loop if the answer is 'no' or
  the value us 'cheater'. The | symbol is 'binary or' - you want ||. You
  can use boolean vars to store the results of your calls to equals.
  That's a start :)

Less sparse code

Less empty lines. Your code is very sparse which makes it harder to read.

Initializing many variables need not happen in different lines.

    boolean running, guessed, realInt;
    running = guessed = realInt = true;

Rename number to answer.

It's not just a number, it's a game answer.

Read on String comparison

You're using equals for it. There's also equalsIgnoreCase which in most cases is preferred.

Yoda conditionals?

Some folks don't like Yoda-conditionals.

"value".equals(variable) -> variable.equals("value").

Choose your own flavour.

DRY

Keep your code DRY, that is Don't Repeat Yourself. Often you use same conditions in your flow-control instructions (if, while...).

Cheat codes

You have two cheat codes. One is to input -5, the other is to answer starting question with "cheater". Both serve same purpose, the game reveals the number. If so, why not collapse to ifs into one? Because the code executed in is the same.

Checking user input

Note: this code is changed using pointers above.

| -> ||
equals -> equalsIgnoreCase
less parens, cut those redundant

You may want to shorten them to functions. This is easy to do in IDE. Select ("yes".equalsIgnoreCase(firstName) || "cheater".equalsIgnoreCase(firstName)) and - if you use Eclipse, press Alt+T, this opens refactoring window. Choose extract method, name your method 'yesOrCheater' and proceed. In Intellij the shortcut is Ctrl+Alt+M.

Then

if (guessed && ("yes".equalsIgnoreCase(firstName) || "cheater".equalsIgnoreCase(firstName))) {

becomes

if (guessed && yesOrCheater(firstName)) {

Usability

Here is my game log:

want to play the game? Yes/No: yes
I have chosen a random value
Have a go at guessing it
5
Plsease try again
4
Plsease try again
65

# [some tries later]

Plsease try again
3
I have chosen a random value
Have a go at guessing it
2
[...]
Plsease try again
5
I have chosen a random value
Have a go at guessing it

Firstly... please. If I'm to read that word that often, please, write it well. ;-)

Also, how can I quit? I'm bored, I want to quit.

When I guessed right, don't just skip to next game, let me know it wasn't an error in the code, that I "won". ;-)

Finally, random value is a very broad term. Decimals? Negatives? 1:10? -100 gazillions : 98 gazillions? When I read this, I had unpleasant feeling about it, how long do I need to guess?

Testability

You may want to add tests or verifications that your game progresses as you intend it to. Using assert with JVM flag, or some test library (TestNG over JUnit, my personal preference). But that's also a large topic, perhaps for next time.


Using an alternative for a switch/state-based custom parser

Although you didn't share MatchReplacePair I assume it holds the Strings that were loaded from the file. So in fact you read all the file's contents into memory.

Starting with Java 7, this can be achieved in one method call:

List<String> lines = Files.readAllLines(file.toPath());

then, you can skip the state machine implementation and just iterate over the list

if (lines.size() % 3 != 0) {
   // Incorrect file contents
}
Iterator<String> itr = lines.iterator();
// the above check ensures you can iterate over three lines safely
while (itr.hasNext()) {
  itr.next(); // ignore separator line? or you can verify if you wish
  list.add(new MatchReplacePair(itr.next(), itr.next()));
}

This also eliminates the need for clone() which was used as constructor replacement.


Ruby agreement is to use snake_case to name methods and variables, and not javaCase. While you could say it's a matter of taste, it's so common in Ruby world you would do better to just stick with it. Ruby programmers also tend to push for initializing arrays like this:

polyArray = []

Your PolynomialElements class is not how you use OOP. It has accessor, but what you pass to them aren't parts of its state - those are arguments for printElement. More proper abstraction would be to make it hold an array of coeficients, and iterate over it to form a string.

class Polynomial
  attr_accessors :coeficients # I think this is a proper name for elements (?)

  def initialize coeficients_array = [0] # default value, just in case
    coeficients = coeficients_array
  end

  def to_s
    coefficients.each_with_object("").with_index do |(coef, str), idx|
      # ...
    end
  end
end

Than, you could use it like:

polynomial = Polynomial.new poly_array
puts polynomial.to_s

Notice that you don't need to operate on array of characters - Ruby string allows you to work in the same way, just use append instead of push, and then you just print/puts it instead of printing each character separately.

Generally speaking, you barely ever need to keep track of index of iteration manually with Ruby. This:

num = numString.to_i
while num > 0
  puts "Enter a value for the Polynomial "
  value = gets
  polyArray.push(value.chomp)
  num -= 1
end

could be much better written as

num_string.to_i.times do
  # ...
end

Ruby way to do (potentially) infinite loop would be:

loop do
  polyArray = []
  # ...
  cont = gets
  break if cont.chomp != "y"
end

This seems more readable, as we directly talk to our loop itself by breaking it, instead of using variable as a "middleman".
Also notice how initializing array inside a loop eliminates need for clearing it.


I know that this code was posted more than three years ago and you have likely learned many things since then but I'd rather not see it be a zombie any longer... so here we go:

In general the code looks okay. There aren't too many repeated blocks. There are a few suggestions I have to tidy up the code.

Cache DOM references - instead of querying for collections like $('img') multiple times, do that once the DOM is loaded, store the collection in a variable and then reference the variable instead of re-querying.

var images
$(window).load(function() {

    images = $('img');
    images.each(function () {

and later in the resize callback:

.on('resize', function () {

    clearTimeout(sizeTimer);

    sizeTimer = setTimeout(function () {

        images.each(function () {

unused variable: img this variable doesn't appear to be used anywhere after it is created: var img = new Image();. Perhaps that is left from a side venture in the code...
Don't repeat code this may only be achievable with advanced function manipulation so I wouldn't expect you to do this in one of your first projects but the code that exists in the callback function on the resize event executed for each image could be abstracted out to a separate function:

function setAttributesOnImage() {

    var $this = $(this),
        _imgWidth = $(this).width(),
        _imgHeight = $(this).height();

    $this.attr({
        'width' : _imgWidth,
        'height': _imgHeight,
        'src': '//placehold.it/' + _imgWidth + 'x' + _imgHeight
    });

}

Then that function can be used in the load callback, utilizing Function.prototype.apply():

image.src = $(this).attr("src");
setAttributesOnImage.apply(this);
$this.wrap('
').closest('.image').css({

    'max-width': _naturalWidth,
    'max-height': _naturalHeight

});

This means _imgWidth and _imgHeight don't have to be declared again in the load handler, since the call to setAttributesOnImage() handles that.

And also in the resize callback:

  .on('resize', function () {

    clearTimeout(sizeTimer);

    sizeTimer = setTimeout(function () {

        images.each(setAttributesOnImage)
    }, 250);

Also, that last timeout callback could be simplified, using Function.prototype.bind() to create a Partially applied function:

sizeTimer = setTimeout(images.each.bind(images, setAttributesOnImage), 250);

Snippet

Expand the snippet below to see simplified code.

/* Goal:

 1. add wrapper around .topic contents (wrapInner) onDocReady
 2. add wrapper around images (wrap) onDocReady

 3. dynamic width & height attributes on images (attr) onLoad & resize
 4. dynamic queryString on img.src (URL adds ?width=###&height=###) onLoad & resize (for demo purposes I'm using "placehold.it") this is only needed for content images in the DOM.

 5. real width & height of image set to parent as max-width/height onLoad
 6. debounce/throttle resize events

*/

$(function () {

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

        var $this = $(this),
            ifMedia = $this.find('.media');

        $this.wrapInner('
');

        if (ifMedia.length) {
            $this.addClass('media-support');
        }
        if ($this.hasClass('media-support')){
            $('.media-support:odd').addClass('inverse');
        }
    });

});
function setAttributesOnImage() {

  var $this = $(this),
      _imgWidth = $(this).width(),
      _imgHeight = $(this).height();

  $this.attr({
    'width' : _imgWidth,
    'height': _imgHeight,
    'src': '//placehold.it/' + _imgWidth + 'x' + _imgHeight
  });

    }
var sizeTimer;
var images;
$(window).on('load', function () {
  images = $('img');

    images.each(function () {

        var $this = $(this),
      image = new Image(),
            _naturalWidth = this.naturalWidth,
            _naturalHeight = this.naturalHeight;

        image.src = $(this).attr("src");
        setAttributesOnImage.apply(this);
        $this.wrap('
').closest('.image').css({

            'max-width': _naturalWidth,
            'max-height': _naturalHeight

        });

    });

}).on('resize', function () {

    clearTimeout(sizeTimer);

    sizeTimer = setTimeout(images.each.bind(images, setAttributesOnImage), 250);

});
* {
    box-sizing:border-box;
}
html{background-color:#ecf0f1;}
body{max-width:1200px;color:#34495e;}
.content{max-width:800px;}
body,.content{margin:0 auto;}
h2{font-size:2rem;margin-bottom:15px;line-height:1;}
p{font-family:sans-serif;line-height:1.55}

img {
    display:block;
    max-width:100%;
    height:auto;
}
.topic:nth-of-type(odd) {
    background-color:#cde
}
.topic:nth-of-type(even) {
    background-color:white
}
.media{
    position:absolute;
    transform:translateX(-100%)
}
.content{padding:35px 25px}
@media (min-width:540px){
    .content {
        height:350px;
        padding:0;
    }
    .content:after {
        clear:both;
        content:'';
        display:table;
    }
    .image {
        background-position:center center;
        background-size:cover;
        background-repeat:no-repeat;
        width:100%;
        padding-bottom:30%;
    }
    .copy{
        padding-left:25px;
        padding-right:25px;
        position:relative;
        top:50%;
        transform:translateY(-50%);
    }
    .media-support .copy {
        width:50%;
        float:left;
    }
    .media-support.inverse .copy {float:right}

    .media-support .media {
        width:50%;
        transform:translateX(0);
        float:right;
        height:100%;
        position:relative;
    }
    .media-support.inverse .media {float:left}
    figure {
        margin:0;
    }
    .media .image, .media img, .media div {
        position:absolute;
        bottom:0;
    }
    .media-support:not(.inverse) .image,
    .media-support:not(.inverse) img{
        left:0
    }
    .media-support.inverse .image,
    .media-support.inverse img{
        right:0;
    }
    .media .undock {
        position:absolute;
        bottom:50%;
        transform:translateY(50%);
    }
    .media-support .media .image > img {
        width:100%;
        height:auto;
    }
}

This is a section heading

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

This is a section heading

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

This is a section heading

Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.

Morbi in sem quis dui placerat ornare. Pellentesque odio nisi, euismod in, pharetra a, ultricies in, diam. Sed arcu. Cras consequat.

&nbsp;


The first thing I noticed about your code, is that you don't clearly have a movie category. I did find these methods on Movie after a while

public int getPriceCode() {
    return priceCode;
}

public void setPriceCode(int arg) {
    priceCode = arg;
}

I believe the getter would better be renamed to getCategory(). I would also completely remove the setter. It's really unlikely for a movie to change categories, so it should only be set during construction.

It might also be worth writing a specific class Category to list all possible categories. An enum would be the most natural here, but this might be awkward with the requirement:

  with the ability to add new categories of movies.

If it's no problem to recompile the code with a new movie (as I expect is the case in this example program) then the enum is still the better choice here.

public enum Category {
    CHILDREN, REGULAR, NEW_RELEASE;
}

This also changes the Movie class to this:

public class Movie {
    private final String title;
    private final Category category;

    public Movie(String title, Category category) {
        this.title = title;
        this.category = category;
    }

    public Category getCategory() {
        return category;
    }

    public String getTitle() {
        return title;
    }
}

Notice that I also added final to the fields to make it clear that a movie instance is immutable. Immutability is nice to have.

The other thing I didn't expect in your code is that the Customer class is responsible for calculating the "statement".

If I wanted to add a new category to the code, I wouldn't expect that I need to change the Customer class as well.

There are 2 major ways to solve this smell. Either put the "statement" calculations into a specialised class. Or add category specific calculations to that category.

Let's take a look into the second option since this might not be trivial if you're not used to working with enums in java.

I would implement it like this:

public enum Category {
    CHILDREN {
        @Override
        public int calculateRent(int daysRented) {
            int result = 75;
            if (daysRented > 3)
                result += (daysRented - 3) * 75;
            return result;
        }
    }, REGULAR {
        @Override
        public int calculateRent(int daysRented) {
            int result = 100;
            if (daysRented > 2)
                result += (daysRented - 2) * 75;
            return result;
        }
    }, NEW_RELEASE {
        @Override
        public int calculateRent(int daysRented) {
            return daysRented*150;
        }
    };

    public abstract int calculateRent(int daysRented);
}

This way, we can simplify the statement() in Customer to:

public String statement() {
    double totalAmount = 0;
    int frequentRenterPoints = 0;

    String returnVal = "Rental record for : " + this.getName() + ".....\n";

    for(Rental rental : rentals){
        double thisAmount = rental.getMovie().getCategory().calculateRent(rental.getDaysRented());

        frequentRenterPoints ++;
        if ((rental.getMovie().getCategory() == Category.NEW_RELEASE) && rental.getDaysRented() > 1) {
            frequentRenterPoints ++;
        }

        returnVal += "\t" + rental.getMovie().getTitle() + ": " + thisAmount + "\n";
        totalAmount += thisAmount;

    }

    returnVal += "Amount owed is: " + totalAmount + "\n";
    returnVal += "You have earned " + frequentRenterPoints + " frequent renter points";

    return returnVal;
}

With this change, adding a new Category only changes a single class (the enum).

Some other things to point out that I improved in this method:

foreach

Since java 5 I believe, there's a specialised way to loop over all itmes in a collection. The syntax here is for(Rental rental : rentals) which reads as "for each rental in rentals".

meaningful names

I renamed your each variable to rental. If you read this later on in the method it's more clear that it's the rental you're talking about.

comments are clutter

Comments are rarely useful. A comment should never be added to say what some line of code does. The only exception being a javadoc for methods (because you usually look at the javadoc from outside the class if you're interested in what that method does that it's name doesn't already tell you).

If you really need a comment to be able to understand some line(s) of code, you should either rename variables/methods in that line or extract a method with a name that clearly says what happens.

Always put {}

You should put curly brackets after each for/if/else/...
This is to prevent really difficult to debug mistakes like this:

if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) && each.getDaysRented() > 1)
            System.out.println("Added bonus frequenterpoints");
            frequentRenterPoints ++;

All I did was add a print to see if anyone had bonus points added. But this innocent looking change cause EVERYONE to get a bonus point independent of the if check.

Most IDE's can be configured to automatically add the braces for you.

edit: making rentalpoints dependant on category as well.

Since the ammount of rental points depends on the category too, let's add another method in that enum. Since it only changes for a new release, I would add a default implementation that returns 1 and override this in the NEW_RELEASE. The new Category enum now looks like this:

public enum Category {
    CHILDREN {
        @Override
        public int calculateRent(int daysRented) {
            int result = 75;
            if (daysRented > 3)
                result += (daysRented - 3) * 75;
            return result;
        }
    }, REGULAR {
        @Override
        public int calculateRent(int daysRented) {
            int result = 100;
            if (daysRented > 2)
                result += (daysRented - 2) * 75;
            return result;
        }
    }, NEW_RELEASE {
        @Override
        public int calculateRent(int daysRented) {
            return daysRented*150;
        }

        @Override
        public int calculateFrequentRenterPoints(int daysRented) {
            if(daysRented > 1){
                return 2;
            } else {
                return 1;
            }
        }
    };

    public abstract int calculateRent(int daysRented);
    public int calculateFrequentRenterPoints(int daysRented){
        return 1;
    }
}

Now there's one more principle that I too have to get used to. It's the tell, don't ask. This is violated inside the statement method.

What we're doing is asking a rental for it's movie, then asking the movie for it's category and then once more asking the rental for the number of days rented. And then do the same asking for the frequent renter points.

This is too much asking. It would make more sense to just tell rental to calculate the price and then return the result. This way we only ask for one thing.

If we move those 2 methods to the Rental class istead, then our statement method will turn to this:

public String statement() {
    double totalAmount = 0;
    int frequentRenterPoints = 0;

    String returnVal = "Rental record for : " + this.getName() + ".....\n";

    for(Rental rental : rentals){
        frequentRenterPoints += rental.calculateFrequentMoviePoints();

        double thisAmount = rental.calculateRent();
        returnVal += "\t" + rental.getMovie().getTitle() + ": " + thisAmount + "\n";
        totalAmount += thisAmount;
    }

    returnVal += "Amount owed is: " + totalAmount + "\n";
    returnVal += "You have earned " + frequentRenterPoints + " frequent renter points";

    return returnVal;
}

For completeness sake here's the new Rental class as well:

public class Rental {
    private Movie movie;
    private int daysRented;

    public Rental(Movie movie, int daysRented) {
        this.movie = movie;
        this.daysRented = daysRented;
    }

    public int getDaysRented() {
        return daysRented;
    }

    public Movie getMovie() {
        return movie;
    }

    public int calculateRent() {
        return movie.getCategory().calculateRent(daysRented);
    }

    public int calculateFrequentMoviePoints() {
        return movie.getCategory().calculateFrequentRenterPoints(daysRented);
    }
}

This actually makes a lot more sense. A Customer only knows that it can ask a rental for the price and points, it doesn't need to know how those are calculated.

A Rental needs to know who to ask for the actual price or points, and has the information needed to calculate those (in this case, the number of days rented).

A Category contains category - specific calculations. Adding a new category means only implementing a new field in the enum. No other classes need to be changed.

Your idea of putting it into subclasses of movie (eliminating the Category class altogether) would work too. It's even better for the Rental class since it doesn't need to know that there exist such a thing as different categories of movies.

The only reason I would not go for this solution is the reason to change a Movie class. If your name is just an identifier for the movie, and no other info about the movie is stored in that class than I would completely agree with this being a good solution. Except that I would change the name to something else. (If only I could find a decent name for that specific concept ... naming things is hard). Let's give it the not so awesome name RentableMovie for now.

That would mean a Customer has a bunch of Rentals.
Each of those rentals has a number of days and a RentableMovie.
That RentableMovie contains specific ways of calculating the price and points. It only contains 1 identifier for the movie. Or we could introduce a new MovieInformation class so that the RentableMovie can point to all information about the movie, without knowing what exactly is in it.

This would work as well :)
So you can choose what feels best to you.


Calling many web services asynchronously

I'm not all that familiar with async/await (I really need to get going on this), but I find your code pretty clear, except why the magic number  5 is being used for an initialCount.

I like your usage of var, but the comments are a little redundant, they say nothing much that the code doesn't already tell.

It would have been nice to see the actual code in place of the placeholder comments in the try block - I'd expect to see a method call here; if that comment stands for code that actually implements what's described, you need to factor it out.

Also I would have indented the async task's body, but that's more of a nitpick.

I would probably also have introduced a var validOrders = orders.Where(order => !order.HasError); to make the foreach loop clearer. Not sure I like x for a name in the lambda: try to use meaningful names everywhere.


Your query isn't right, and in my opinion, your schema doesn't make sense either.

What is the purpose of the sub-select in your query?  Is your query not equivalent to

SELECT *
    FROM `translations_urls` AS `t`
    GROUP BY `url_gb`
    ORDER BY iso = 'GB' DESC, `order` ASC, `url_gb` ASC;

Furthermore, what do you intend to achieve with GROUP BY?  You aren't using any aggregate functions in your output columns.  In fact, with a sane database engine (e.g. PostgreSQL), such a query would generate an error like

  ERROR:  column "t.id" must appear in the GROUP BY clause or be used in an aggregate function

Your schema seems awkward to me, for several reasons:

The url_gb column implies that GB is the original language, which, as you stated, is no longer a valid assumption.
The use of url_gb to identify a translation's original results in a normalization problem.  If the URL of a UK-English document changes, you have to update the url_gb of all of its translations.

Furthermore, translations should have language codes, not country codes.  (An exception would be if you were "translating" legal contracts, in which case you want a different document per country.)

One solution is to make a self-referential table that could form a tree of documents:

CREATE TABLE `documents`
( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT
, `order` INT(10) NOT NULL COMMENT 'Sort order'
, `iso` VARCHAR(6) NOT NULL COMMENT 'ISO language code'
, `url` VARCHAR(127) NOT NULL COMMENT 'URL'
, `controller` VARCHAR(127) NOT NULL COMMENT 'Controller the URL refers to'
, `action` VARCHAR(127) NOT NULL COMMENT 'Action the URL refers to'
, `translated_from` INT(10) UNSIGNED COMMENT 'id of document from which this was translated'
, PRIMARY KEY (`id`)
, UNIQUE INDEX `iso_url` (`iso`, `url`)
, FOREIGN KEY (`iso`) REFERENCES `translations_languages` (`iso`)
, FOREIGN KEY (`translated_from`) REFERENCES `documents` (`id`)
)
ENGINE=InnoDB;

Another approach, which I prefer, is to distinguish between documents and their translations.  The advantage of this is that you can nominate one of the translations as the canonical original, to prevent recursion, which is harder to deal with in SQL.

CREATE TABLE `documents`
( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT
, `order` INT(10) NOT NULL COMMENT 'Sort order'
, `canonical` INT(10) UNSIGNED COMMENT 'Canonical (original) translation'
, `controller` VARCHAR(127) NOT NULL COMMENT 'Controller the URL refers to'
, `action` VARCHAR(127) NOT NULL COMMENT 'Action the URL refers to'
, PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

CREATE TABLE `translations`
( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT
, `document_id` INT(10) UNSIGNED NOT NULL
, `iso` VARCHAR(6) NOT NULL COMMENT 'ISO language code'
, `url` VARCHAR(127) NOT NULL COMMENT 'URL'
, PRIMARY KEY (`id`)
, UNIQUE INDEX `document_id_iso` (`document_id`, `iso`)
, UNIQUE INDEX `url` (`url`)
, FOREIGN KEY (`iso`) REFERENCES `translations_languages` (`iso`)
)
ENGINE=InnoDB;

ALTER TABLE `documents`
    ADD FOREIGN KEY (`canonical`) REFERENCES `translations` (`id`);

An annoyance with this schema is the mutual foreign key relationship.  To add a document, you would first have to insert a document with NULL as the canonical translation, then insert the first translation, then update the document with the id of the first translation.

With the latter schema, a query to preferentially return English versions, falling back to a canonical text in another language, would be:

SELECT *
    FROM `documents` AS `d`
        INNER JOIN `translations` AS `t`
            ON `t`.`document_id` = `d`.`id`
    WHERE
        `iso` = 'en' OR
        (`iso` <> 'en' AND `t`.`id` = `d`.`canonical`);


Ok, so there's two different things here:

Hover effects (fade in/out)
Actions

Now, #1 is the same for all three elements, and thus shouldn't need to be repeated in code. But #2 is expressly different for each button, which means it probably shouldn't mixed with the hover effects.

Aside: Speaking of duplication, your CSS is full of it too. You should look into that. You should also avoid naming things for how they look. E.g. add-item-red is fine until that item is no longer red; usually it'll have some purpose other than being red. Its color is a presentation detail. Name stuff for what it does, not how it looks.

Anyway, these days (read: modern browsers), I'd probably just use CSS transitions to handle the hover effect; no javascript necessary. For instance:

div {
  background: green;
  padding: 0.3em;
  display: inline-block;
  transition-duration: 0.5s;
}

div:hover {
  opacity: 0.4;
}

Hover

But since this is about jQuery, here's how I'd handle it with a common class name for all the buttons (which, incidentally, I'd use <button> tags for), and jQuery's appropriately named .hover() event handler.

$(".fade").hover(function () {
  $(this).fadeTo('fast', 0.4);
}, function () {
  $(this).fadeTo('fast', 1.0);
});
body { background: black; }

button {
  border: none;
  padding: 1em;
}

#helloButton   { background: green; }
#goodbyeButton { background: red; }
#clearButton   { background: white; }

<button type="button" id="helloButton" class="fade">One</button>
<button type="button" id="goodbyeButton" class="fade">Two</button>
<button type="button" id="clearButton" class="fade">Three</button>

Now, you're using mouseenter combined with mouseout. But that's not really "symmetrical". The opposite of mouseenter is mouseleave (and the opposite of mouseout is mouseover). The enter/leave events are originally Internet Explorer-only events which jQuery has replicated, and they behave differently than the standard over/out events with regard to nested elements. jQuery's docs have a discussion of this and a demo to illustrate. It happens to work in your case, but it's a bit like saying that the opposite of multiplying is subtracting; it just happens to work out for certain numbers, but that doesn't make it right.

Next, there's the click actions. You're adding those inside the mouseenter event. This is a big no-no. It means that every time you mouse over a button, a new click event handler gets added! You just don't notice it because you're inserting and re-inserting the same element. But if you mouse over the red button 3 times before clicking it, the effect is that you're clicking it 3 times because now you've got 3 separate but identical event handlers attached.

Yet another reason to keep the actions separate from the hover effects.

You can either attach the event handlers to an element by its ID (as below), or you can use some other means of linking an element to an action.

$(".fade").hover(function () {
  $(this).fadeTo('fast', 0.4);
}, function () {
  $(this).fadeTo('fast', 1.0);
});

var hello = $("

").text("Hello").css({background: "green"});
var goodbye = $("

").text("Goodbye").css({background: "red"});

$("#helloButton").on("click", function () {
  $("#output").prepend(hello);
});

$("#goodbyeButton").on("click", function () {
  $("#output").prepend(goodbye);
});

$("#clearButton").on("click", function () {
  $("#output").empty();
});
body { background: black; }

button {
  border: none;
  padding: 1em;
}

#helloButton   { background: green; }
#goodbyeButton { background: red; }
#clearButton   { background: white; }

<button type="button" id="helloButton" class="fade">One</button>
<button type="button" id="goodbyeButton" class="fade">Two</button>
<button type="button" id="clearButton" class="fade">Three</button>

You'll notice a few things here:

I'm prepending the elements to the output div, rather than inserting them next to it. This makes more sense to me since now, all the output is, well, in the output. Not beside it. And it means I can just call empty to clean up.
I'm constructing the elements using jQuery rather than with strings of HTML. I generally don't like a ton of hardcoded HTML in my JS. I also don't need IDs for them, because, again, I just need to call empty.

I might go a step further and add the elements in the HTML itself, and simply hide them until needed, which would be even simpler in a lot of ways, and keep the JS free of hardcoded elements of any kind.

In the end, I'd probably replicate your code with something like this:

$("#helloButton").on("click", function () {
  $("#hello").show();
});

$("#goodbyeButton").on("click", function () {
  $("#goodbye").show();
});

$("#clearButton").on("click", function () {
  $("#output").children().hide();
});
body { background: black; }

button {
  border: none;
  padding: 1em;
  display: inline-block;
}

.fade { transition-duration: 0.5s; }
.fade:hover { opacity: 0.4; }

#helloButton   { background: green; }
#goodbyeButton { background: red; }
#clearButton   { background: white; }

#hello { background: green; }
#goodbye { background: red; }

#output p { display: none; }

<button type="button" id="helloButton" class="fade">One</button>
<button type="button" id="goodbyeButton" class="fade">Two</button>
<button type="button" id="clearButton" class="fade">Three</button>

Hello

Goodbye

It doesn't make the paragraphs switch places, but I don't think that's the most salient feature either, to be honest.


Most efficient way in C++ to strip strings

A few thoughts which come to my mind, without having actually profiled your code:

Try passing std::string as reference-to-const to avoid a copy (in case your std::string implementation is not Copy-On-Write).
Reserve space in the std::string by calling reserve.
Avoid calling std::string::length repeatedly, memorize the value.
Avoid indexing the string repeatedly, use an iterator instead.

For what it's worth, you could try a different (more functional) way to implement this function. Some may consider this idiomatic, other will find it harder to read. Your call -maybe just for the fun of it, to see how it performs (remember to enable optimizations!):

#include <algorithm>
#include <functional>
#include <locale>
#include <string>

std::string strip( const std::string &s ) {
    std::string result;
    result.reserve( s.length() );

    std::remove_copy_if( s.begin(),
                         s.end(),
                         std::back_inserter( result ),
                         std::not1( std::ptr_fun( isalpha ) ) );

    return result;
}


Code to join filesystem path strings in PHP

Seems like the problem has been over thought.  This would be how I would write it.

<?php

//$args = func_get_args();
$args = array('foo/', '/bar', 'fiz');

$paths = [];

foreach ($args as $arg) {
    $paths[] = trim($arg, DIRECTORY_SEPARATOR);
}

$paths = array_filter($paths);

echo DIRECTORY_SEPARATOR . join(DIRECTORY_SEPARATOR, $paths);

I don't see any need to leverage any exclusive PHP 5.6+ features to solve this.


Generic function that accepts both Actions and Func's as parameters

Try to avoid using magic values. This one is a hack to avoid writing 2 methods.

private HttpResponseMessage TryCatch(Action action)
{
    return TryCatch(() => { action(); return "ActionToFunc"; });
}

You are better of splitting your methods. Dispatch error handling to its own method ResolveStatusCode to avoid boiler-plate error handling. In addition, perform argument checks. Since your method is private, I would favor Debug.Assert over ArgumentNullException.

    HttpResponseMessage TryCatch(Action operation)
    {
        try
        {
            Debug.Assert(operation != null, "invalid usage of API");
            operation();
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception error)
        {
            return Request.CreateResponse(ResolveStatusCode(error));
        }
    }

    HttpResponseMessage TryCatch<T>(Func<T> func)
    {
        try
        {
            Debug.Assert(func != null, "invalid usage of API");
            var result = func();
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        catch (Exception error)
        {
            return Request.CreateResponse(ResolveStatusCode(error));
        }
    }


Well, Promises are designed so that you won't have to nest at all! You can think of Promises as try-catch-finally statements. And the nice thing about Promises is that if you return a promise inside then, the next chained then waits for that promise instead of the original. Here's a simplified version of your code (assuming I understood it correctly).

// Call the async function #1
return this.getCustomer().then(
  function(credentials) {
    // Success for async function #1

    // You can return promises. It will be listened to in the next .then()
    return $http.post(CONSTANT_VARS.BACKEND_URL + '/auth/logout', {
      username: credentials.username,
      customer: credentials.customer
    });

  }
).then(
  function(data) {
    // Success callback for async function #2 (the POST request)

    // We can also return a newly rejected promise to fail the next then
    // Or send back the promise of your remove operation
    // $.Deferred().reject().promise(), Deferred is read-write, Promise is read-only
    return data.error ? new Promise.reject() : LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_CUSTOMER);

  },
  function(error) {
    // Fail callback for async function #2 (the POST request)

    cleanLocalForage();
  }
).then(
  function() {
    // Success callback for async function #3 (the remove)

    cleanLocalForage();
  },
  function(err) {
    // Fail callback for async function #3 (the remove)

    console.log(err);
  }
);

The return value is either a resolved or rejected promise, depending on the result of the entire chain. If the entire thing resolves, the return is a resolved promise. If it rejects, then it returns a rejected promise. You can also recover from a reject by returning a promise. If that promise resolves, the next chain resolves and so on.

It's the main reason why it's called "then". It's like "Do this, then what?". The idea of the promise is to be some sort of linear flow-control mechanism, to avoid nested callbacks and proxy deferreds.

As for the other function, assuming logout is an async operation, you can do it like:

BetSlipFactory.removeSlip(slip).then(null, function(err) {
  console.log(err);
  return AuthFactory.logout();
}).then(function() {
  $location.path('/');
});


Sequence Generator from previous max sequence based on certain conditions

Dim unique_string1, unique_string2, unique_string3 As String

Variables declared without the As keyword are declared as a variant.  In the line above unique_string3 is declared as a String, unique_string1 an unique_string2 are variants.

The original posted code use Range("J2:J20000" & jr).  jr was being concatenated to the end of "J2:J20000".  The post has been edited and corrected.

W is missing from the formula

INT(w2:20000))

getAddress = .Cells(i, 23).Address
Range(getAddress).Value = nextn

Use .Cells(i, 23).Value = nextn instead.  This will qualify the ranges to the worksheet instead of the ActiveSheet,

Sheets("Docs").Evaluate("MAX(IF((J2:J20000=""" & x & """)*(K2:K20000=""" & y & """)*(O2:O20000=""" & z & """),INT(w2:20000)))")

It is better to change the worksheets codenames for easy reference.
VBA Codenames:
Sheet (document) modules have a property called CodeName, which is how the object is know internally to VBA. Indeed, if this feature is used by the developer, VBA code can always refer to a sheet (worksheet or chart), even if the sheet is renamed from Excel by a user. For example:

A worksheet is named 'Sales-2012'
Sheet CodeName is 'Sales'
User renames the worksheet to 'Sales-2013'

Use the Worksheet's Evaluate method instead of the Application's.

Refactored Code

Here is a rough rewrite of the OP's code:

Option Explicit

Sub NewSequence()
    Dim JobIds As Variant
    JobIds = GetUniqueValues("J")

    Dim Deps As Variant
    Deps = GetUniqueValues("K")

    Dim Job_Nos As Variant
    Job_Nos = GetUniqueValues("O")

    With wsDoc
        Dim LastRow As Long
        Rem Make sure that this refers to the longest used column
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        Const BaseFormula As String = "MAX(IF((J2:J@LastRow=""@jobid"")*(K2:K@LastRow=""@dep"")*(O2:O@LastRow=""@job_no""),INT(w2:w@LastRow)))"

        Dim Formula As String
        Dim Id As Long
        Dim Department As Long
        Dim JobNumber As Long
        Dim i As Long

        For Id = 0 To UBound(JobIds)
            For Department = 0 To UBound(Deps)
                For JobNumber = 0 To UBound(Job_Nos)
                    For i = 2 To LastRow
                        Formula = Replace(BaseFormula, "@LastRow", LastRow)
                        Formula = Replace(Formula, "@jobid", JobIds(Id))
                        Formula = Replace(Formula, "@dep", Deps(Department))
                        Formula = Replace(Formula, "@job_no", Job_Nos(JobNumber))
                        .Cells(i, 23) = 1 + .Evaluate(Formula)
                    Next
                Next
            Next
        Next

    End With
End Sub

Private Function GetUniqueValues(ColumnName As Variant) As Variant
    Dim Target As Range
    With wsDoc
        Set Target = .Range(.Cells(2, ColumnName), .Cells(.Rows.Count, ColumnName).End(xlUp))
    End With

    Rem If there are no values then exit the function
    Rem The calling method should test if the return value is an array using isArray()
    If Target.Row = 1 Then Exit Function

    Rem Range.Value will return an 1 based range of values it the Range contains multiple cells
    Rem A Range that contains a single cell then it will return a single scalar value
    If Target.Count = 1 Then
        Rem Return the single value wrapped in a zero based array
        GetUniqueValues = Array(Target.Value)
        Exit Function
    End If

    Rem Typically a Scripting.Dictionary is used to return an unique lists
    Dim list As Object
    Set list = CreateObject("Scripting.Dictionary")

    Rem assign an 1 based array of values from the Target range to an array
    Dim Values As Variant
    Values = Target.Value

    Dim Item As Variant

    Rem Use For Each controls to iterate over the Values array
    For Each Item In Values
        Item = Trim(Item)
        If Not list.Exists(Item) And Len(Item) > 0 Then list.Add Key:=Item, Item:=Item
    Next

    Rem Return a zero based array from the Dictionary
    GetUniqueValues = list.Keys
End Function

I changes the Doc tab codename to wsDocs for the code above.  Thanks Peter T!


Removing random repeated guesses from brute force program

I think that your problem is the use of randomisation - it's not really a brute-force attack if you are guessing.

If it were a 4-digit combination lock you would start at 0000 and then try 0001 and 0002 and so on. That's the brute-force approach. I suggest that you employ exactly the same approach with your password cracker. It should be the same algorithm, but rather than 10 posibilities in each slot you have 26.


Counts the number of times a particular character, such as e, appears in a file

If you are using java 8 you can use streams.

Also IMO for this kind of functionality a static method would me more appropriate.

 public static long countCharacter(Path path, char lookFor) throws IOException {

     try (Stream<String> stream = Files.lines(path)) {

         return stream.flatMapToInt(String::chars)
                      .filter(c -> c == (int) lookFor)
                      .count();
     }
 }


Passing objects to functions safely and efficiently

It doesn't feel natural to initialize a Doge with a fixed age:

Doge::Doge(){
    cout << "Doge Constructor" << endl;
    itsAge = 5;
}

It would be more natural to make age a mandatory constructor parameter:

Doge::Doge(int itsAge): itsAge(itsAge) {
    std::cout << "Doge Constructor" << std::endl;
}

The copy constructor doesn't actually copy anything.
Either remove it, or implement copying, for example:

Doge::Doge(Doge& other){
    std::cout << "Doge Copy Constructor" << std::endl;
    this->itsAge = other.itsAge;
}

This function is declared to return a Doge *, but it returns nothing:

Doge * Function( Doge * theDoge){
    cout << "In Function" << endl;
    cout << "Scott is now " << theDoge->GetAge() << endl;
}

This raises a compiler warning, at least with g++.

You probably implemented the destructor just to see when it gets called.
That's fine, for testing.
When you're done, just remember to remove it if it's not needed.


Fast import of numbers stored in a CSV file

In C++, we usually avoid malloc - in this case, you could use a std::vector< double > in stead. Doing this, you will allow the user of your code to use RAII in stead of manually managing the allocated memory. You cal tell the vector how much to allocate by initializing it with the right size. The compiler will apply return value optimization to avoid copying the vector (by constructing it into the return value) so you shouldn't worry too much about that.
You don't preserve the values of m and n. I don't know if this is intentional but if you don't want to burden your client code with lugging it around, consider a struct or a class to carry it, and the values you read, around.
You don't check the return values of the methods you call on the fstream - you should.
You'd probably be better off reading the values from the fstream directly into the array, rather than reading them into a buffer, copying that buffer into a stringstream and then reading them from the stringstream to convert. You can save the use of the stringstream (and therefore eliminate it altogether).

Example program:

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

using namespace std;

struct Data
{
        Data(unsigned int width, unsigned int height)
                : width_(width)
                , height_(height)
                , data_(width * height)
        { /* no-op */ }
        unsigned int width_;
        unsigned int height_;
        vector< double > data_;
};

Data split(istream &is, unsigned int width, unsigned int height)
{
        Data retval(width, height);
        double d;
        int i(0);

        while (is >> d)
        {
                retval.data_[i++] = d;
                is.ignore(1, ',');
        }

        return retval;
}

int main()
{
        const char *test_string = ""
                "2.83, 31.26, 2354.3262, 0.83567\n"
                "12.3, 35.236, 2854.3262, 0.83557\n"
                "32.3, 33.26, 2564.3262, 0.83357\n"
                "27.3, 3.2869, 2594.3262, 0.82357\n";
        const unsigned int width = 4;
        const unsigned int height = 4;
        stringstream ss(test_string);
        Data data(split(ss, width, height));
        copy(data.data_.begin(), data.data_.end(), ostream_iterator< double >(cout, " "));
}