Dynamic programming to solve two printers with different speeds

Your BestTime method looks great. The nextpage variable is never used, so it doesn't really matter which direction the loop goes. I'd be curious why you are using a decrementing loop, but it doesn't matter which direction you use in the grand scheme of things.

Choosing Double because Integer gives you overflow seems misleading. At first I thought "oh good, it handles decimal rates, like 2 1/2 pages per minute". The algorithm looks like it should work for floating point, though.

If you only want to support integral types, you can use Long or ULong. Based on the test cases you provided, Long is sufficient.

myTimes(0) + X and myTimes(1) + Y are calculated twice. For this scale of number it's not a huge performance loss. But if you were extending this to BigInteger levels, you could calculate them both once and assign the number if needed.

This is the kind of optimization that would require benchmarking before deciding if it is worthwhile.

A Const for delimeters won't work because System.Environment.NewLine is read only property that is not available at compile time. There are a couple of alternatives:

use a ReadOnly field instead of Const
use vbNewLine instead of System.Environment.NewLine

Note, this will (possibly) be different functionality.

However, you only use delimeters in one spot, so a method variable like you currently have is fine.

You did a good job separating the algorithm from input/output. You could take it further by wrapping input handling in its own function outside of Main.

If this weren't for a "competition" style of programming, I would recommend a parameter for the input file name so that the user can change it. I'd also strongly encourage a separate parameter for output. Right now, the user needs to perform an extra step before running your program a second time.

Additionally, you could use more descriptive variable names than X, Y, and N. It matches the competition specs so it's perfect in this instance. But for a long term program I would recommend something like printerXSpeed or numberOfPagesToPrint. The caveat is you never know when that one off function you write gets put in production for years.


Line 105 is a typo. The indentation suggests its only executed if output is not null.

But it's actually unrelated to the if statement.

You should always use curly braces even if execution is only 1 line long. This goes for all statements: while, if, do, etc.


How to approach separation of layers mapping response to model in Angular app?

I made some good experience with the following approach. Its more code, but it helped the other developers in the team (and especially the new ones) to get a good grip and a fast start.
As always, many roads, choose the one that fits best in your context, they all have drawbacks. :-)
First i describe the expected data from the Backend
export interface AddressJSON{
  street: string,
  city: string
};

export interface UserJSON{
  id: number,
  name: string,
  address: AddressJSON
}

That helps to understand what to expect from the backend. Also its easier to track mapping problems (for example a Java LONG that is stored in a JavaScript NUMBER => Number has a smaller value range)
Then i create the FE models and if the mapping between backend and FE is easy, then i add converter methods
class Address {
  public street: string;
  public city: string;

  constructor(street: string, city: string){
    this.street = street;
    this.city = city;
  }

  public toJSON(): AddressJSON{
    return {
      street: this.street,
      city: this.city
    }
  }

  public static fromJSON(address: AddressJSON): Address{
    return new Address(address.street, address.city);
  }
}

class User {
  public name: string;
  public address: Address;
  private readonly id: number;

  constructor(id:number){
    this.id = id;
  }

  public toJSON(): UserJSON {
    return {
      id: this.id,
      name: this.name,
      address: this.address.toJSON()
    }
  }

  public static fromJSON(user: UserJSON): User{
    const newUser: User = new User(user.id);
    newUser.name = user.name;
    newUser.address = Address.fromJSON(user.address);
    return newUser;
  }
}

As you can see the entities can be stacked.
One reason i choose classes over interfaces for my entities is that i can move functionality directly to the entities.
And, i can FORCE the way this entity has to be used. For example i can disallow the creation of a artificial user without an id.
It reduces the risc for later changes. And it enforces a deeper understanding of the business requirements behind those entities.
On the over side its much more work at the start.
Most people who didn´t liked this approach hated the extra work, that you have to invest. The people who liked it, mostly highlighted the better understanding of the business requirements and the possibly to enforce correct usage.


Finding pairs of numbers within A that add up to N

If you had a sorted array of n numbers, then finding pairs that sum to N should take O(n) time.

Sorting should take O(n log n) time.

O(n log n + n) is O(n log n).  That's better than O(n2).  Therefore, you would be better off sorting the array first.


I don't know if you can, depending on your real world needs... but if you can convert the TaskItems Dictionary to a List of KeyValuePairs like this...

public List<KeyValuePair<string, Item>> TaskItems = new List<KeyValuePair<string, Item>>
{
    new KeyValuePair<string, Item>( "ItemA", new Item() {} ),
    new KeyValuePair<string, Item>( "ItemB", new Item() {} ),
    new KeyValuePair<string, Item>( "ItemC", new Item() {} ),
};

Then you can use the ForEach() exstension method to reduce the loop code to...

if (this.RunPerItem)
{
    TaskItems.ForEach(I => Tasks.ForEach(T => T(this, I.Value)));
}
else if (this.RunPerTask)
{
    Tasks.ForEach(T => TaskItems.ForEach(I => T(this, I.Value)));
}

If you couple that with @Steven Jueris' idea of splitting them into their own methods, your code will be very clean.


You could also implement this with async-await but I thought this would be a more efficient implementation.

When performance matters, don't guess, measure. When it doesn't matter (which is 97 % of the time according to some), write code that is readable and maintainable.
Why do you think small increase in efficiency (most likely less than 1 ms) would matter here, when the retry interval is probably going to be hundreds of milliseconds or more (and can't effectively be less than 15 ms)?

Func<bool> retryFunc

Consider adding another overload that allows you to retry async functions (i.e. Func<Task<bool>> retryFunc).

CancellationToken cancellationToken

It might make sense to make this an optional parameter, some users might not need cancellation.

int retryInterval

I think it would be better to use TimeSpan here, that way both your code and the code of your users becomes more clear. If you want to keep using int, document very clearly the unit used, possibly by even renaming the parameter to something like retryIntervalMs.

You don't want to be the next Mars Climate Orbiter.

When the CancellationToken is canceled, why do you wait for the timer tick to cancel the returned Task? You could use Register() to make sure the Task is canceled as soon as the CancellationToken is.

if (!taskCompletionSource.Task.IsCompleted)

What's the purpose of this check? If it's because you're worried that retryFunc might run longer than retryInterval, then I think your logic is flawed. When I have an operation that takes 1 minute to run and I ask for retry after 5 seconds, I probably don't want to have 12 instances of the operation running at the same time.

You could achieve this by using Change().

And even when you want this behavior, you should probably also switch to using TrySet versions of the TaskCompletionSource methods, to avoid unnecessary exceptions.

if (cancellationToken.IsCancellationRequested)
{
    taskCompletionSource.SetException(new TaskCanceledException("RetryAsync cancelled"));
}

This way, the Task will be in the Faulted state. To get it to the correct Canceled state, use SetCanceled().

//// Once the task is complete, dispose of the timer so it doesn't keep firing.
tcs.Task.ContinueWith(t => timer.Dispose(),
                      CancellationToken.None,
                      TaskContinuationOptions.ExecuteSynchronously,
                      TaskScheduler.Default);

This closure is important also because it keeps the Timer rooted, so it prevents it from being GCed prematurely. I would expand the comment to explain that.

(Also, why are you using four slashes for a comment? Two are enough.)


Writing out a tree of Tnodes with words as values in alphabetical order

Improvements / details:

Your naming is a bit odd. Tnode is not a very descriptive name. TreeNode seems out of context, as the type is actually the tree itself, not a node.

I suggest renaming TreeNode to just Tree and Tnode to TreeNode instead.

That count parameter seem to be the child count of a given node. It can be used to determine the height of the tree. It is not implemented properly for this purpose though.

I prefer placing private methods and data at the end of the class declaration. Public data and methods should appear at the top, as this is what users of the interface care about when reading the file. Also, it is better to separate the class in declaration and definition. The declaration usually goes in a header file (.h/.hpp).

Wouldn't be a bad idea renaming the recursive helper methods of the tree to make the use of recursion more explicit. You could append _recursive to the name. E.g.: traverse() => traverse_recursive().

Tnode should have a formal constructor to properly initialize its data.

Refactored code:

I took the liberty of applying these changes to your code. Following is the result:

// tree.h:

struct TreeNode {

    std::string word;
    int numChildren;

    TreeNode* left;
    TreeNode* right;

    TreeNode(const std::string& word)
        : word(word), numChildren(0), left(nullptr), right(nullptr) { }
};

class Tree {

public:

    Tree();
    Tree(const std::string& word);

    void add(const std::string& word);
    void traverse();
    int get_num_nodes() const;

    ~Tree();

private:

    TreeNode* add_recursive(TreeNode* n, const std::string& word);
    void traverse_recursive(TreeNode* n);
    void destroy_recursive(TreeNode* n);

    TreeNode * root;
};

// tree.cpp:

Tree::Tree()
    : root(nullptr) { }

Tree::Tree(const std::string& word)
    : root(new TreeNode(word)) { }

void Tree::add(const std::string& word) {
    root = add_recursive(root, word);
}

void Tree::traverse() {
    traverse_recursive(root);
}

int Tree::get_num_nodes() const {
    return root->numChildren + 1; // +1 to count the root as a node
}

Tree::~Tree() {
    destroy_recursive(root);
}

TreeNode* Tree::add_recursive(TreeNode* n, const std::string& word) {
    if (n == nullptr) {
        n = new TreeNode(word);
    } else if (word < n->word) {
        n->left = add_recursive(n->left, word);
        n->numChildren++;
    } else if (word > n->word) {
        n->right = add_recursive(n->right, word);
        n->numChildren++;
    } else {
        n->word = word;
    }

    return n;
}

void Tree::traverse_recursive(TreeNode* n) {
    if (n == nullptr) {
        return;
    }

    // Extended printing to visualize more info:
    std::cout << "Node => " << n->word << ", numChildren: " << n->numChildren;
    if (n->left != nullptr) {
        std::cout << ", left: "  << n->left->word;
    }
    if (n->right != nullptr) {
        std::cout << ", right: " << n->right->word;
    }
    std::cout << "\n";

    traverse_recursive(n->left);
    traverse_recursive(n->right);
}

void Tree::destroy_recursive(TreeNode* n) {
    if (n == nullptr) {
        return;
    }
    destroy_recursive(n->left);
    destroy_recursive(n->right);
    delete n;
}

// main.cpp:

int main()
{
    Tree tree;

    tree.add("hello");
    tree.add("C++  ");
    tree.add("world");
    tree.add("foo  ");
    tree.add("bar  ");
    tree.add("baz  ");

    tree.traverse();

    std::cout << "num nodes: " << tree.get_num_nodes() << std::end; // prints "num nodes: 6"
}


Bash script to find included files in C code

... so what's going on?

$ (grep ^#include file.c | grep -o '"[^"]\+"' | read -a myarr; echo $myarr)
(nothing is printed)
$ (grep ^#include file.c | grep -o '"[^"]\+"' | mapfile myarr; echo $myarr)
(nothing is printed)

Why doesn't this work? Because "each command in a pipeline is executed in its own subshell". As the page explains, you could enable the lastpipe option to have the last element of the pipeline run in the current process. (The page doesn't mention that this will only work when you use it in a script, where job control is not active (as mentioned here). It won't work in an interactive shell.)

Keep pipelines as short as possible

It's good to use the fewest possible processes in pipelines.
Multiple grep in a pipeline are points to look at with suspicion.
You can make the first grep work a little harder,
using a stricter pattern, and then you can achieve the same result with 2 processes instead of 3:

grep '^#include .*"' file.c | cut -d'"' -f2


Program to take a number from 0 to 9 as input

This can be rewritten using regular expression \s*(\d)\D* (zero or more whitespace characters, a single digit, zero or more non digit characters. If I understand correctly, heading and trailing spaces are ok, 2ff is ok but ff2 is not ok and 23 is not ok either.
int input_number() {
  static const std::regex valid_number("\\s*(\\d)\\D*");
  string data;
  std::smatch matches;
  while (true) {
    cout << "Input: ";
    if (getline(cin, data) &&
          std::regex_match(data, matches, valid_number)) {
        return stoi(matches[1]);
    }
    cerr << "Invalid number, try again!" << endl;
  }
}

The exception on parsing should never be thrown, regular expression takes care to feed only valid number as the input. The initial version contained try/catch construct to catch it anyway and assert false but this idea is probably over-engineering.


I like your solution. You usually see it done with while/for loops that substract multipliers instead of taking the quotient/remainder. Some notes about your code:

ROMAN.reduce(self) { |number, (divider, letter)|. In a multiline block is idiomatic to use do/end.
Prefer building an array + join at the end, that appending to a string. Not that it matters with those sizes, but in general it's the recommended way (+= in a string is typically O(n^2), << on an array is O(n)).
inject is a functional abstraction. While you can perform in-place updates within the block, it will break the assumption of many readers. One solution is to encapsulate the output within the state (using a hash, for example).

I'd write:

class Fixnum
  ROMAN = {...}

  def to_roman
    ROMAN.reduce(number: self, result: []) do |state, (divider, letter)|
      letter_multiplier, remainder = state[:number].divmod(divider)
      new_result = state[:result] + [letter * letter_multiplier]
      {number: remainder, result: new_result}
    end[:result].join
  end
end

Note that this is a state machine: it iterates over an input with an initial state, on each loop the state is updated, and the result is the final state.


Best way to manage a device information class

I think you should have :

A constructor taking device_id, device_type and home as an argument.
a static method doing the file handling and calling the constructor previously defined.

This would make your code more modular, easier to test and would put different independent things (device creation and file handling) in different places.

I'd also like to point out that at the moment, your constructor does create a non-properly-initialised device when the file does not exist. It would probably be much better not to create it at all (and return null ?) if we don't have the required information to do so.

Also, and this is not relevant to your question but there's not real need for 2 variables XML_DIRECTORY_ON_DEVICE and ROOT_DEVICE_XML_FILE if you are always going to call them together. It might be just as easy to have "XML_PATH".


Repetition. Always a sign that something could be improved. DRY (Don't repeat yourself) is the mantra here.

Magic Numbers. Passable for one-off code, but can get in the way if you wish to maintain or extend the code.

I will deal with the magic numbers first (and you'll see why when I address the repetition)

You have Dim score(10) as decimal where there is no real reason for 10 except that it is a nice number. We can fix this (may seem superfluous at first, but it is a good habit) by the following:

Const numOfInputs as Long = 10 ' You can always call it what you like, but make it sensible and descriptive
Dim score(numOfInputs) as decimal

Now, if you wanted to work with 12 numbers you only have to change the assignment of numOfInputs. You have two areas of repetition. Addressing the main block:

For iterator as Long = 0 to numOfInputs - 1 ' 0 based array.
    Console.WriteLine("Enter the score (input number " & iterator & ")")
    score(iterator) = Console.ReadLine
Next iterator

See how I was also able to "personalise" the prompt string! Now if you want to do something else in here, you only have to fix the code once, and not ten times.

Addressing the output. There are a couple of ways to do this. One of those is to set up another loop, loop through the array and then use the output. But we already have the exact same loop that we would use to add them all up.

Const numOfInputs as Long = 10 ' You can always call it what you like, but make it sensible and descriptive
Dim score(numOfInputs) as decimal
Dim finalCount as decimal = 0 'OK, the default value is 0 but I like to be explicit
For iterator as Long = 0 to numOfInputs - 1 ' 0 based array.
    Console.WriteLine("Enter the score (input number " & iterator & ")")
    score(iterator) = Console.ReadLine
    finalCount += score(iterator) ' simply add up the items as we go along.
Next iterator

As you can see, I have now put in place finalCount so that we can add up as we go along - which is what I would have done if I had it in a separate loop anyway.

Oh, and now you can print it out through Console.WriteLine(finalCount).

Key lessons

Loop rather than repeat. Much easier to maintain
Reuse loops where you can - it is much more efficient. Think about your program logic so you can be efficient with loops.
Replace magic numbers with variables (constants) that are defined somewhere logical. Much easier to replace a well-named constant only once than trying to find that 10 and then working out if that needs to change to 12 or if it really is 10.


Moving business logic towards the domain object as a design pattern

First, I would like to say thank you for asking this question, because this is the type of situation that average enterprise devs face every day and being able to recognize that something doesn't "feel" right even though all the rules are followed is a good indicator that you're on the right track for figuring out what is going to be a good implementation and what isn't.

Getting to the code, from an overall perspective I would recommend the pattern of creating services in front of your domain layer, instead of your domain objects being fed into services that are dependencies of util/helper classes. An app layer can construct a domain Document object and pass it to a DocumentService, but encapsulating a DocumentService behind something that the app layer doesn't interact with could become hard to maintain.

A DocumentService could deal with saving the Document to the database, and as it's saving, it can then check for duplicates. Whether it checks for duplicates inline in the  method or it calls another duplicate-checking object/util to do this is up to how big the method gets and how many different things the service is doing in the method.

Looking at your existing code, I'd recommend not getting too dogmatic about "one role, one responsibility--one class!" because it can be argued that documentService.SaveDocument(document) also has one responsibility (having to check for duplicates is superfluous--it's not part of the public contract of this method, although it may require a dependency or two passed in to the constructor).

I think when you have a DocumentService inside a very specific class used for a very specific purpose, it's a bit of a smell, because your DocumentService starts seeming like a bit of a Swiss army knife you start including inside all document-related objects, because hey, it's where document-related things go!

After all of that, if you implement according to my advice, your Document may remain a glorified property bag (though I would remove the properties like IsDuplicate from the Document. They don't belong on a domain entity. IsDuplicates should be refactored most simply to a boolean hasDuplicates or duplicatesExist as a local variable inside a method that has a responsibility to check for duplicates). And I think it's okay if it stays that way for now if your domain is not very fleshed out. It would be worse to put responsibilities/functionality on a domain object that didn't belong, because that's the type of problem that once is in place is really hard to break out because it's in such critical spot.

I would recommend focusing on your domain objects as smart entities first. That will help keep your mental model of them as a business object, but keeping the "smart" aspect in mind will allow you to apply "smart" logic to your objects. For example, if you have a one-to-many relationship between your objects, how does your domain track changes between these objects? If a child object assigns its parent reference, the parent object should have a reference to the child in its collection of children. So you might implement that by writing a "smart" setter so that when an Order assigns its Customer property, the Customer property adds it to its Orders collection if it doesn't exist. I think that's more in line with a domain object that is still an "entity" of sorts. Of course, there's definitely more that comes with the evolution of an application, but I'd start there.

For the time being, I'd focus on having intuitive services sitting in front of your domain, so the application layer can call these services, using domain objects to communicate by constructing them and passing them in to the services or having them returned from the services, or both.


I need some suggestions to speed up my array manipulation code

Speed You say you want the program to run more quickly, but it looks pretty good to me already. Are you really processing such a huge number of giorni objects that the function doesn't run fast enough? (It's possible, but it sounds unlikely.) But there are some improvements that could be made.
indexOf vs object You use indexOf to find the position of the day in the days array. This has O(n) complexity; the interpreter searches through the array indicies one-by-one until it finds a match. It would be less computationally expensive to use an object mapping day names to their indicies, then look up the name on the object, in a single operation.
Conditional values Inside the .map, the only part that changes between the if and else is the giorno property. To do this more efficiently and concisely, use the conditional operator instead:
return {
  id: g.id,
  giorno: momentToday <= dayIndex
    ? moment().isoWeekday(dayIndex)
    : moment().add(1, 'weeks').isoWeekday(dayIndex),
};

. Or, since it you don't actually care about the id properties, you can remove them entirely, and just use an array of times.
Moment Moment is a non-trivial library (and even it recommends to use modern APIs instead, like Date). If speed is an issue, you could use the native Date object instead.

const giorni = [{
  id: 1,
  giorno: 'lun', // Monday; turns into Mon 28 Sep
  orari: ['12:00', '13:00']
}, {
  id: 2,
  giorno: 'mer', // Wednesday: turns into Wed 23 Sep
  orari: ['12:00', '13:00']
}, {
  id: 2,
  giorno: 'ven', // Friday: turns into Fri 25 Sep
  orari: ['15:00', '17:00']
}];
const dayIndiciesByDayName = Object.fromEntries(
  ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab']
    .map((name, i) => [name, i])
);

const todayDayIndex = new Date().getDay(); // Zero-indexed and starts at Sunday
const todayDayOfMonth = new Date().getDate();
const inputDays = giorni.map(({ giorno }) => giorno);
const itemDates = giorni.map((g) => {
  const itemDayIndex = dayIndiciesByDayName[g.giorno.toLowerCase()];
  // Below will be 0 to 6:
  const itemDayDifferenceFromToday = (itemDayIndex - todayDayIndex + 7) % 7;
  const itemDateObj = new Date();
  itemDateObj.setDate(todayDayOfMonth + itemDayDifferenceFromToday);
  return itemDateObj;
});
const output = itemDates
  .sort((a, b) => a - b)
  .map((date) => {
    const match = date.toString().match(/(\w+ )(\w+) (\d+ )/);
    return match[1] + match[3] + match[2];
  });
console.log(output);


Grabbing city names and numbers from a CSV file

Leave out the square brackets:

^\d+\s+[A-Z]+\s+

Square brackets are used for "character classes", like

[A-Z]

which matches exactly one letter out of the range A to Z.

\d already is a class: all the numbers.


Script for adding a set of form fields on clicking an Add More button

Put the php code outside the form, run it once and create a variable with the options, something like:

$dropDownList = '<select name="vat" id="find" data-required="true"><option value="">Select Vat</option>';

$query = mysqli_query($con, "SELECT * FROM `tax_vat` ");
while ($row = mysqli_fetch_array($query))
{
$dropDownList .= '<option value="' . $row['vat_rate'] . '">' . $row['vat_description'] . '</option>';
}

$dropDownList .= '</select>';

Now, in your form you just need to <?php echo $dropDownList?> where you want the drop down to appear.

For your javascript you could do something like this:

var dropOption = "<?php echo $dropDownList?>";

And modify the append() html data like this:

$(InputsWrapper).append('
<input id="find" type="text" name="item[]">	<input id="find" type="number" name="qty[]">	<input id="find" type="number" name="price[]">	<input id="find" type="number" name="discount[]">	'+dropOption+'	<input id="find" type="number" name="total[]" readonly >
');

Hope this helps.


Converting raw thesaurus data into nice JSON file

Welcome to Code Review!

The current code looks clean enough. Since it will be a command line utility, I'd suggest taking up the argparse or click. argparse is a python inbuilt module, so your end package will not have a dependency other than the dictionary files.

The json package provide the method json.dump which can write directly to a file. No need to have extra memory consumption.

Instead of using print statements, I'd go with logging builtin module with possibly multiple handlers, if you want to stream logs to console or file etc.


Not too bad.

You do not export Rational' from the module so no outside code can make one directly
numer and denom will conflict with a similar function name in any other code which imports your module. Perhaps rational'Numer and rational'Denom?
See http://www.haskell.org/tutorial/numbers.html for a good intro to numbers in Haskell. You missed the Fractional class which defines div, recip, and fromRational.
Why are rationalSub and rationalDiv not defined like add and mult? Be consistent.
In rationalSignum your comment says the reader would expect a 0 or 1 Int but the return needs to be of the Rational' type and then you actually return 0 or 1. Be consistent and return Rational' 0 1 and Rational' 1 1
rationalFromInteger could be rationalFromInteger = (flip Rational') 1
I would define reduce like this

reduce (Rational' n 0) = divByZero n
reduce (Rational' n d) = Rational' (n `div` common) (d `div` common)
  where common = (gcd n d) * (signum d)


Reading strings into a vector, without using namespace std

I'll assume that you've read Why is using namespace std considered bad practice? so you understand the reasons that this can cause problems for your code.  I'm not going to address that any further in this answer.

You have alternatives, that reduce the risk compared to using namespace std; at file scope:

Selectively import names you're going to use, in the scope you're going to use them:

#include <string>
#include <vector>
#include <iostream>

int main()
{
    using std::string;
    using std::vector;

    string text;
    vector<string> svec;

    while (std::cin >> text)
        svec.push_back(text);

    for (vector<string>::size_type i = 0; i < svec.size(); i++)
        std::cout << svec[i]  + " " << svec[i].size() << "\n";

    return 0;
}

This is an important technique when using free functions such as begin() and end() in generic code, where you want the std:: implementations to be available, but for argument-dependent lookup to prefer a more specific (local namespace) override if available.
Reduce the need to actually write typenames, with greater use of auto.  For example, your output loop can be

for (const auto& element: svec)
    std::cout << element << " " << element.size() << "\n";

Using auto more liberally can be very helpful when you decide that a method needs to be generic; you won't need to trawl through it updating the types to match the new signature.

As an aside, note that some namespaces (e.g. std::literals and its contained namespaces) are intended to be imported with a using namespace directive; you may still want to restrict their scope to just that part of your code that needs it, though - and never in a header file!


I'm going to try to avoid raging about the data table based data access layer because I doubt a random person on the internet is going to change the direction of your project. So, let's look at your SQL query:

SELECT Date,
       Shift
FROM   ScheduleList
WHERE  ID = @ID
  AND  MONTH(Date) = @Month
  AND  YEAR(Date) = @Year

I've removed the extra brackets because they were just adding noise. This query could easily be changed so you could add a covering index to your schedule list table:

SELECT Date,
       Shift
FROM   ScheduleList
WHERE  ID = @ID
  AND  Date > @Date
  AND  Date < DATEADD(MONTH, 1, @Date)

Combined with an index on the Date and Id columns which also includes Shift and your query will be much faster.

CREATE INDEX IX_ScheduleList_Id_Date on your_schema.ScheduleList
(
    Id,
    Date
) INCLUDE (Shift)

I'd be more inclined to do this though:

SELECT Date,
       Shift
FROM   ScheduleList
WHERE  ID = @ID
  AND  Date > @StartDate
  AND  Date < @EndDate

This way you can search for schedule list in any window of time, not just one month at a time.

Having said that, what I'd actually do is return the employee list with their schedules at the same time - SQL is a relational database: it's good at joining related data together.

(SQL typed into browser and I'm rusty so it might not be 100% right).


Computing max t such that tanh(pi*sinh(t)/2) <1

I don't have any suggestions for making the code faster (other than pre-computing at compile-time, which I assume isn't an option for you), but I do have some general observations on the code style.

Instead of bringing definitions of the std and boost names at global scope, they can be isolated in the functions that use them (still with using, so ADL will continue to work the same as in the original code):

#include <cmath>
#include <boost/math/constants/constants.hpp>

template<class Real>
Real g(Real t)
{
    using std::tanh;
    using std::sinh;
    using boost::math::constants::half_pi;
    Real tmp = half_pi<Real>()*sinh(t);
    return tanh(tmp);
}

template<class Real>
Real g_inv(Real x)
{
    using std::asinh;
    using std::atanh;
    using boost::math::constants::two_div_pi;
    return asinh(two_div_pi<Real>()*atanh(x));
}

Standard C++ provides nexttoward(), which can be used in place of boost::math::float_prior:

template<class Real>
Real find_max_t()
{
    using std::isnormal;
    using std::nexttoward;

    static const Real ONE{1};

    Real x = nexttoward(ONE, 0);
    Real t_max = g_inv(x);
    while (!isnormal(t_max))
    {
        x = float_prior(x);
        t_max = g_inv(x);
    }
    // This occurs once on 100 digit arithmetic:
    while (!(g(t_max) < ONE))
    {
        x = nexttoward(x, 0);
        t_max = g_inv(x);
    }
    return t_max;
}

Unfortunately, the Boost numeric types don't provide any nexttoward(), so you may be stuck using boost::math::float_prior after all.  :-(

The benchmark code can now be separable:

#include <iostream>
#include <benchmark/benchmark.h>

template<class Real>
static void BM_max_t(benchmark::State& state)
{
    Real t_max;
    while(state.KeepRunning())
    {
        benchmark::DoNotOptimize(t_max = find_max_t<Real>());
    }
    std::cout << "t_max = " << t_max << std::endl;
}

#include <boost/multiprecision/float128.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
BENCHMARK_TEMPLATE(BM_max_t, float);
BENCHMARK_TEMPLATE(BM_max_t, double);
BENCHMARK_TEMPLATE(BM_max_t, long double);
BENCHMARK_TEMPLATE(BM_max_t, boost::multiprecision::float128);
BENCHMARK_TEMPLATE(BM_max_t, boost::multiprecision::cpp_bin_float_50);
BENCHMARK_TEMPLATE(BM_max_t, boost::multiprecision::cpp_bin_float_100);

BENCHMARK_MAIN();


This confuses me:

name.val() === nameVal

The variable nameVal is equal to the value attribute of name. And, the calling val() on name returns the value attribute of name so of course they are going to be equal.

I may be missing something here, but I think this is unnecessary.

Long chunks of mush like this:

(name.val() === nameVal || name.val() === '' || name.val().length < 3) ? name.addClass(error) : name.removeClass(error);
            (comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) ? comment.addClass(error) : comment.removeClass(error);
            (!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);

and this:

!(name.val() === nameVal || name.val() === '' || name.val().length < 3) &&
            !(comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) &&
            validateEmail(email.val())

are in no way whatsoever readable. You need to either

Break this up. Maybe everything here is not necessary.
Split this into variables and check with the variables.

I think you should go with the first option, because these can be simplified:

1:

As I stated above, having

name.val() === nameVal

is unnecessary. You can just remove this.

2:

The value "" is called a falsey value. That means that "" can be treated as though it were false.

So, for example, this here:

name.val() === ''

can be reduced to:

!name.val()

Constantly calling the .val function on these elements in each of your conditionals is inefficient. You should store the result of .val() in a variable, and just use that for the conditionals (I think nameVal should already hold the .val() for name).

Now, for example, one of your conditional chunks becomes:

( !nameVal || nameVal.length < 3) ? name.addClass(error) : name.removeClass(error);

(! commentVal || commentVal.length < 3) ? comment.addClass(error) : comment.removeClass(error);

(!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);

Where commentVal is comment.val() and nameVal is name.val()


Producing and comparing maximum sub array sum algorithms

tl;dr: This is pretty good! A few bugs and weird edge cases, and you can be more Pythonic – no code is perfect – but I like what you’ve done.

Is this Pythonic?

There are several things you could do to make this more Pythonic:

Rather than describing functions using a comment above the definition, use a docstring – that’s the preferred way to document functions in Python.
Rather than iterating over the indexes of an array, it’s better to iterate over the elements. It’s the difference between (bad):

for index in range(len(myarray)):
    element = myarray[index]
    do_stuff_with_element()

and (good):

for element in myarray:
    do_stuff_with_element()

If you need both the index and the element, then you should use enumerate().
Indentation should be four spaces, not two.
Look at list comprehensions; they’re very useful. For example, they can reduce your generate_array() function to one line:

def generate_array(count, lower_bound, upper_bound):
    """
    Generates a random array of integers.
    """
    return [random.randint(lower_bound, upper_bound) for _ in range(count)]

Are these accurate implementations of the algorithms?

max_subarray_cubic()

Because all your ranges start at 1, but Python indexes lists at 0, this function doesn't seem to include the first element in the array.  For example:

>>> max_subarray_cubic([1, 2, 3, -100])
5

but taking the first three elements gives a larger sum of 6.  Adjusting the ranges to range(len(array)) seems to fix the problem.

max_subarray_quadratic()

I haven't spotted any bugs in it; this seems to work correctly.
As I explained above, you could make the inner loop more Pythonic by iterating over the elements, like so:

for elem in array[i:]:
    current += elem
    maximum = max(current, maximum)

max_cross_sum()

There should be something in the docstring to explain how to use the low/mid/high arguments; I had to guess and I think I got it wrong. [I didn't realise this was a helper function for max_subarray_div_conquer when I first read it.]
It's quite unusual to see a variable name with a trailing underscore in Python programs. Good job for not overriding the builtin function (a common mistake among new programmers), but you should try to pick a better variable name rather than just appending an underscore.
When the last argument of range() is -1, I prefer to use reversed(), because I think it's easier to read. Combining with my advice above, your first loop becomes:

for elem in reversed(array[low:mid]):
    sum += elem
    # do stuff with elem

max_subarray_div_conquer()

When this function is first called, I have to pass in the length of the array as arguments, which could cause a problem if I pass in incorrect values. I'm repeating information provided by the first argument.

It would be better to check if the user passes in any values, and if not, compute them based on the length of the array:

def max_subarray_div_conquer(array, low=None, high=None):
    if low is None:
        low = 0
    if high is None:
        high = len(array)

I'm using a default argument of None to check whether the user passed anything in; if they didn't, I'll work it out myself.

max_subarray_kadane()

If I pass this function an empty list, it hits an exception in the first line:

Traceback (most recent call last):
  File "tmp/subarrays.py", line 89, in <module>
    function_timer(max_subarray_kadane, [], "kadane")
  File "tmp/subarrays.py", line 76, in function_timer
    print("Maximum sub sum for the %s algorithm: %s" % (policy, function(array)))
  File "tmp/subarrays.py", line 63, in max_subarray_kadane
    current = maximum = array[0]
IndexError: list index out of range

You should check that I've passed in more than just an empty list at the start of this function. You might still want to raise an exception – a ValueError seems appropriate here – but it should provide a more informative message about why something has gone wrong.

You might want to look at doing the same for the rest of your functions: although they don't throw an exception, they tell me that the maximum subarray sum of an empty list is -inf. Does that seem sensible? Is there a meaningful largest subarray sum of an empty list?

How's the running time function?

The function itself is fine. The fact that you have to special case the divide and conquer algorithm is a little annoying, but that can be addressed by removing the need for additional arguments – see above.
One weakness with the mechanism is that you only check the results once, and for a single array. It’s possible that you could get an array which plays to one algorithm's strengths, or a call is unlucky and takes unusually long time.

You'd get more accurate results if (a) you tested with a variety of arrays, and (b) you repeated and averaged the results.
Your test code is in the top-level of the file, which means it will be run whenever this file is executed – whether directly as a script, or imported as a module. A better construction is to put this code inside if __name__ == '__main__', which means it will only be called if the script is run directly.

That allows you to import functions from this file without any of this timing code being called.


Card class

Specify the access modifiers of the class and members properly.
Use proper names for members:

class  Card{
    Suit s;
    Rank r;

for example:

public class  Card{
    private Suit suit;
    private Rank rank;

print() method

It's better to only create a String representation of an object and return that. You override toString() method which will be used implicitly if the object has to be converted to a String.

It's good practice to override toString() for all custom classes, because this is where people will look for when searching for a String representation of the object. You called it print(), or was it info()? , who knows? Your future self? Probably not. toString() is the way to go.

Your current approach appears to be more convenient, but actually causes some trouble like duplicated code:

System.out.print("Rank: "+c.getRank()+" Suit: "+c.getSuit()+"\t");
System.out.println("Card: "+card.getRank()+" Suit: "+card.getSuit());

Card.toString() could look like this:

@Override
public String toString()
{
    return "rank: " + rank + "\t suit: " + suit;
}

CardDeck is pretty much a collection of a number of cards. CardDeck.toString() could look something like this:

@Override
public String toString()
{
    String result = cards.size() + " cards:" + System.lineSeparator();
    for (Card card : cards)
    {
        result = result.concat(card + System.lineSeparator());
    }

    return result;
}

Here's what both classes look like so var with a little example program:

Card.java

public class  Card
{
    private Suit suit;
    private Rank rank;

    public  enum  Suit
    {
        Spade , Heart , Diamond , Clubs
    }

    public enum Rank
    {
        ACE(1) , TWO(2), THREE(3), FOUR(4), FIVE(5) , SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN (10), JACK(11), QUEEN (12), KING(13);

        int priority;

        Rank(int s)
        {
            priority = s;
        }

        public int getPriority()
        {
            return priority;
        }

        public Rank getRankByPriority(int p)
        {
            switch (p)
            {
                case 1: return Rank.ACE;
                case 2: return Rank.TWO;
                case 3: return Rank.THREE;
                case 4: return Rank.FOUR;
                case 5: return Rank.FIVE;
                case 6: return Rank.SIX;
                case 7: return Rank.SEVEN;
                case 8: return Rank.EIGHT;
                case 9: return Rank.NINE;
                case 10: return Rank.TEN;
                case 11: return Rank.JACK;
                case 12: return Rank.QUEEN;
                case 13: return Rank.KING;

                default: return null;
            }
        }
    }

    Card(Rank rank, Suit suit)
    {
        this.rank = rank;
        this.suit = suit;
    }

    Rank getRank()
    {
        return rank;
    }

    Suit getSuit()
    {
        return suit;
    }

    @Override
    public String toString()
    {
        return "rank: " + rank + "\t suit: " + suit;
    }
}

CardDeck.java

import java.util.ArrayList;

public class CardDeck
{
    private ArrayList<Card> cards;

    CardDeck()
    {
        cards = new ArrayList<>();

        for(Card.Suit s: Card.Suit.values())
        {
            for(Card.Rank r: Card.Rank.values())
            {
                cards.add(new Card(r,s));
            }
        }
    }

    public static void main(String[] args)
    {
        CardDeck deck = new CardDeck();

        System.out.println(deck);
    }

    @Override
    public String toString()
    {
        String result = cards.size() + " cards:" + System.lineSeparator();
        for (Card card : cards)
        {
            result = result.concat(card + System.lineSeparator());
        }

        return result;
    }
}

result (excerpt):

$ java CardDeck
52 cards:
rank: ACE    suit: Spade
rank: TWO    suit: Spade
rank: THREE  suit: Spade
rank: FOUR   suit: Spade
rank: FIVE   suit: Spade
rank: SIX    suit: Spade
rank: SEVEN  suit: Spade
rank: EIGHT  suit: Spade
rank: NINE   suit: Spade
rank: TEN    suit: Spade
...

shuffle() method

A method is a block of code that operates on an object. Your shuffle() method might work on an optional parameter which is entirely independent from the CardDeck object. The part of the method that operates on an arbitrary ArrayList<Card> should be static.

public void shuffle(ArrayList<Card> c){
        if(c==null){
            Collections.shuffle(cards);
        }else{
            Collections.shuffle(c);
        }

    }

Thus splits into:

public static void shuffle(ArrayList<Card> cards)
{
    if(cards!=null)
    {
        Collections.shuffle(cards);
    }
}

public void shuffle()
{
    Collections.shuffle(cards);
}

The second one makes a lot of sense, but the static version does not. What's the point of calling this method directly when you already have Collections.shuffle()?

Also, the static version has nothing to do with the CardDeck class whatsoever. It should not be a member of CardDeck, but either Card or better a separate class with utility functionality named CardUtils for example. But again, there's no real point in having that functionality that does not add anything to Collections.shuffle(). Delete it.

deal() method

I have no idea what this is doing by only looking at it. There are so many card games and all have their own ways to deal cards. Does every player get the same number of cards? Or are all cards distributed to a number of players?

Trying your code it looks like the later is true.

The problem with this method is that it does not return anything. It only prints the piles of card out, without any chance to do anything with them. Instead, provide a useful return value you can work with.

One such return value could be CardDeck. There's a bit of functionality already in there, so why not reuse that? Add a constructor to be able to pass a Collection of cards to it:

CardDeck(Collection<? extends Card> cards)
{
    this.cards = new ArrayList<Card>(cards);
}

When dealing the cards, there's no real point in dealing them one by one. You know how many cards each player receives and should just get that many from the shuffled cards. Think about it like every player takes a certain number of cards from the deck.

public ArrayList<CardDeck> dealAllCards(int numberOfPlayers)
{
    ArrayList<CardDeck> playerHands = new ArrayList<>(numberOfPlayers);
    ArrayList<Card> shuffledDeck = new ArrayList<>(cards);

    int cardsPerPlayer = shuffledDeck.size()/numberOfPlayers; // to be subtracted by 1 after dealing remaining cards
    int remainingCards = shuffledDeck.size()%numberOfPlayers;

    Collections.shuffle(shuffledDeck);

    for (int player = 0; player < numberOfPlayers; ++player)
    {
        if (player == remainingCards)
        {
            --cardsPerPlayer; // all remaining cards dealed
        }

        CardDeck hand = new CardDeck(shuffledDeck.subList(0, cardsPerPlayer + 1));
        shuffledDeck.removeAll(hand.cards);

        playerHands.add(hand);
    }

    return playerHands;
}

The full code now looks like this:

Card.java did not change, see above

CardDeck.java

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class CardDeck
{
    private ArrayList<Card> cards;

    public static void main(String[] args)
    {
        CardDeck deck = new CardDeck();

        ArrayList<CardDeck> playerHands = deck.dealAllCards(5);

        for(CardDeck playerHand : playerHands)
        {
            System.out.println(playerHand);
        }
    }

    CardDeck()
    {
        cards = new ArrayList<>();

        for(Card.Suit s: Card.Suit.values())
        {
            for(Card.Rank r: Card.Rank.values())
            {
                cards.add(new Card(r,s));
            }
        }
    }

    CardDeck(Collection<? extends Card> cards)
    {
        this.cards = new ArrayList<Card>(cards);
    }

    public ArrayList<CardDeck> dealAllCards(int numberOfPlayers)
    {
        ArrayList<CardDeck> playerHands = new ArrayList<>(numberOfPlayers);
        ArrayList<Card> shuffledDeck = new ArrayList<>(cards);

        int cardsPerPlayer = shuffledDeck.size()/numberOfPlayers; // to be subtracted by 1 after dealing remaining cards
        int remainingCards = shuffledDeck.size()%numberOfPlayers;

        Collections.shuffle(shuffledDeck);

        for (int player = 0; player < numberOfPlayers; ++player)
        {
            if (player == remainingCards)
            {
                --cardsPerPlayer; // all remaining cards dealed
            }

            CardDeck hand = new CardDeck(shuffledDeck.subList(0, cardsPerPlayer + 1));
            shuffledDeck.removeAll(hand.cards);

            playerHands.add(hand);
        }

        return playerHands;
    }

    public void shuffle()
    {
        Collections.shuffle(cards);
    }

    @Override
    public String toString()
    {
        String result = cards.size() + " cards:" + System.lineSeparator();
        for (Card card : cards)
        {
            result = result.concat(card + System.lineSeparator());
        }

        return result;
    }
}

full example output:

$ java CardDeck
11 cards:
rank: FOUR   suit: Clubs
rank: FIVE   suit: Heart
rank: FOUR   suit: Spade
rank: ACE    suit: Heart
rank: EIGHT  suit: Heart
rank: SIX    suit: Heart
rank: JACK   suit: Spade
rank: EIGHT  suit: Diamond
rank: JACK   suit: Clubs
rank: QUEEN  suit: Clubs
rank: TWO    suit: Spade

11 cards:
rank: SEVEN  suit: Heart
rank: NINE   suit: Spade
rank: SEVEN  suit: Diamond
rank: SEVEN  suit: Clubs
rank: SIX    suit: Clubs
rank: ACE    suit: Clubs
rank: KING   suit: Heart
rank: SEVEN  suit: Spade
rank: FIVE   suit: Clubs
rank: FOUR   suit: Diamond
rank: TEN    suit: Diamond

10 cards:
rank: KING   suit: Clubs
rank: TEN    suit: Clubs
rank: ACE    suit: Diamond
rank: QUEEN  suit: Spade
rank: SIX    suit: Diamond
rank: FIVE   suit: Spade
rank: EIGHT  suit: Spade
rank: QUEEN  suit: Heart
rank: FOUR   suit: Heart
rank: KING   suit: Diamond

10 cards:
rank: THREE  suit: Clubs
rank: EIGHT  suit: Clubs
rank: THREE  suit: Diamond
rank: KING   suit: Spade
rank: TWO    suit: Clubs
rank: JACK   suit: Heart
rank: THREE  suit: Spade
rank: THREE  suit: Heart
rank: JACK   suit: Diamond
rank: TWO    suit: Diamond

10 cards:
rank: NINE   suit: Heart
rank: NINE   suit: Clubs
rank: TEN    suit: Heart
rank: ACE    suit: Spade
rank: NINE   suit: Diamond
rank: TEN    suit: Spade
rank: FIVE   suit: Diamond
rank: QUEEN  suit: Diamond
rank: TWO    suit: Heart
rank: SIX    suit: Spade

further improvements from the comments

Thanks @Boris!

  String.concat is conventionally written as +; this is never used in a loop - a StringBuilder (or StringWriter) is used instead.

That's right. CardDeck.toString() could look like:

@Override
public String toString()
{
    StringBuilder result = new StringBuilder(cards.size() + " cards:" + System.lineSeparator());
    for (Card card : cards)
    {
        result.append(card + System.lineSeparator());
    }

    return result.toString();
}

This is great, because it also helps readability. It's not just some String, but a StringBuilder, which is a bit more self-documenting.

Given that cards is immutable (no public acces and not private changes), this String could even be built beforehand and cached in a private member. As I don't think the toString() method will be called in such quantities that it would make a significant difference, I leave such and further optimisations of the method to the interested reader.

  Your deal method is very inefficient; List.removeAll will call remove on each of the elements, which is in turn going to loop through the List to find the element; this is O(n*k) - very bad. Instead use List.subList.clear() after you create the CardDeck for the player.

True, I was more concerned about being close to the real world situation that the code is modelling, that is: tacking a number of cards from a set of cards.

How to solve that problem? Not at all. They say it's clever to solve a problem, but wise to avoid it. Let's simply not remove anything at all.

Instead, move the parameters for subList(), which essentially has the same effect. The improved version of dealAllCards() could look like this:

public ArrayList<CardDeck> dealAllCards(int numberOfPlayers)
{
    ArrayList<CardDeck> playerHands = new ArrayList<>(numberOfPlayers);
    ArrayList<Card> shuffledDeck = new ArrayList<>(cards);

    int cardsPerPlayer = shuffledDeck.size()/numberOfPlayers; // to be subtracted by 1 after dealing remaining cards
    int remainingCards = shuffledDeck.size()%numberOfPlayers; // #cards is not a multiple of #players

    Collections.shuffle(shuffledDeck);

    int firstCardIndex = 0;
    int lastCardIndex = 0;

    for (int player = 0; player < numberOfPlayers; ++player)
    {
        if (player == remainingCards)
        {
            --cardsPerPlayer; // all remaining cards dealed
        }

        lastCardIndex = firstCardIndex + cardsPerPlayer + 1;

        playerHands.add(new CardDeck(shuffledDeck.subList(firstCardIndex, lastCardIndex)));

        firstCardIndex = lastCardIndex;
    }

    return playerHands;
}

shuffledDeck is just a local temporary helper to hold the shuffled cards, after all.


"Find the Min" challenge on Facebook Hacker Cup

1. Improving your code

If you used if __name__ == '__main__': to guard the code that should be executed when your program is run as a script, then you'd be able to work on the code (for example, run timings) from the interactive interpreter.
The name func is not very informative. And there's no docstring or doctests. What does this function do? What arguments does it take? What does it return?
func has many different tasks: it reads input, it generates pseudo-random numbers, and it computes the sequence in the problem. The code would be easier to read, test and maintain if you split these tasks into separate functions.
Reading all the lines of a file into memory by calling the readlines method is usually not the best way to read a file in Python. It's better to read the lines one at a time by iterating over the file or using next, if possible.
When computing the result, you keep the whole sequence (all \$n\$ values) in memory. But this is not necessary: you only need to keep the last \$k\$ values (the ones that you use to compute the minimum excluded number, or mex). It will be convenient to use a collections.deque for this.
Similarly, it's not necessary to build the set of the last \$k\$ values every time you want to compute the next minimum excluded number. If you kept this set around, then at each stage, all you'd have to do is to add one new value to the set and remove up to one old value. It will be convenient to use a collections.Counter for this.

Applying all of these improvements results in the code shown below.

import sys
from itertools import count, islice
from collections import Counter, deque

def pseudorandom(a, b, c, r):
    """Generate pseudo-random numbers starting with a and proceeding
    according to the linear congruential recurrence
    a -> (b * a + c) % r.

    >>> list(islice(pseudorandom(34, 37, 656, 97), 10))
    [34, 71, 82, 4, 28, 43, 16, 84, 78, 50]

    """
    while True:
        yield a
        a = (b * a + c) % r

def mex(c):
    """Return the "mex" (Minimum EXcluded) number in the Counter c.

    >>> mex(Counter(range(10)))
    10
    >>> mex(Counter([2, 3, 0]))
    1

    """
    for i in count():
        if c[i] == 0:
            return i

def iter_mex(k, it):
    """Generate the sequence whose first k values are given by the
    iterable `it`, and whose ith value (for i > k) is the "mex"
    (minimum excluded number) of the previous k values of the
    sequence.

    """
    q = deque(islice(it, k))
    for m in q:
        yield m
    c = Counter(q)
    while True:
        m = mex(c)
        yield m
        q.append(m)
        c[m] += 1
        c[q.popleft()] -= 1

def nth_iter_mex(n, k, a, b, c, r):
    """Return the nth value of the sequence whose first k values are
    given by pseudorandom(a, b, c, r) and whose values thereafter
    are the mex of the previous k values of the sequence.

    """
    seq = iter_mex(k, pseudorandom(a, b, c, r))
    return next(islice(seq, n, None))

def main(f):
    cases = int(next(f))
    for i in xrange(cases):
        n, k = map(int, next(f).split())
        a, b, c, r = map(int, next(f).split())
        print('Case #{}: {}'.format(i, nth_iter_mex(n - 1, k, a, b, c, r)))

if __name__ == '__main__':
    main(sys.stdin)

2. Timing

Python comes with the timeit module for timing code. Let's have a look at how long the program takes on some medium-sized test instances:

>>> from timeit import timeit
>>> timeit(lambda:nth_iter_mex(10**5, 10**2, 34, 37, 656, 97), number=1)
1.6787691116333008
>>> timeit(lambda:nth_iter_mex(10**5, 10**3, 34, 37, 656, 97), number=1)
16.67353105545044
>>> timeit(lambda:nth_iter_mex(10**5, 10**4, 34, 37, 656, 97), number=1)
143.31502509117126

The runtime of the program is approximately proportional to both \$n\$ and \$k\$, so extrapolating from the above timings, I expect that in the worst case, when \$n = 10^9\$ and \$k = 10^5\$, the computation will take about five months. So we've got quite a lot of improvement to make!

3. Speeding up the mex-finding

In the implementation above it takes \$Θ(k)\$ time to find the mex of the last \$k\$ numbers, which means that the whole runtime is \$Θ(nk)\$. We can improve the mex finding to \$O(\log k)\$ as follows.

First, note that the mex of the last \$k\$ numbers is always a number between \$0\$ and \$k\$ inclusive. So if we keep track of the set of excluded numbers in this range (that is, the numbers between \$0\$ and \$k\$ inclusive that do not appear in the last \$k\$ elements of the sequence), then the mex is the smallest number in this set. And if we keep this set of excluded numbers in a heap then we can find the smallest in \$O(\log k)\$.

Like this:

import heapq

def iter_mex(k, it):
    """Generate the sequence whose first k values are given by the
    iterable `it`, and whose ith value (for i > k) is the "mex"
    (minimum excluded number) of the previous k values of the
    sequence.

    """
    q = deque(islice(it, k))
    for m in q:
        yield m
    excluded = list(set(xrange(k + 1)).difference(q))
    heapq.heapify(excluded)
    c = Counter(q)
    while True:
        mex = heapq.heappop(excluded)
        yield mex
        q.append(mex)
        c[mex] += 1
        old = q.popleft()
        c[old] -= 1
        if c[old] == 0:
            heapq.heappush(excluded, old)

Now the timings are much more satisfactory:

>>> timeit(lambda:nth_iter_mex(10**5, 10**2, 34, 37, 656, 97), number=1)
0.2606780529022217
>>> timeit(lambda:nth_iter_mex(10**5, 10**3, 34, 37, 656, 97), number=1)
0.2634279727935791
>>> timeit(lambda:nth_iter_mex(10**5, 10**4, 34, 37, 656, 97), number=1)
0.32929110527038574
>>> timeit(lambda:nth_iter_mex(10**6, 10**5, 34, 37, 656, 97), number=1)
3.5652129650115967

However, we still expect that when \$n = 10^9\$ and \$k = 10^5\$, the computation will take around an hour, which is still far too long.

4. A better algorithm

Let's have a look at the actual numbers in the sequence generated by iter_mex and see if there's a clue as to a better way to calculate them. Here are the first hundred values from a sequence with \$k = 13\$ and \$r = 23\$:

>>> list(islice(iter_mex(13, pseudorandom(34, 37, 656, 23)), 100))
[34, 5, 13, 10, 14, 1, 3, 8, 9, 0, 12, 19, 2, 4, 6, 5, 7, 10, 11, 1,
 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13,
 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10,
 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0,
 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5]

You should have noticed a pattern there, but let's lay it out in rows of length \$k + 1 = 14\$ to make it obvious:

[34, 5, 13, 10, 14, 1, 3, 8, 9, 0, 12, 19, 2, 4,
 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,
 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,
 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,
 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,
 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,
 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4,
 6, 5]

You can see that the first \$k + 1\$ values are different, but thereafter each group of \$k + 1\$ items from the sequence is identical (and moreover is a permutation of the numbers \$0, \ldots, k\$).

Let's check that this happens for some bigger examples:

>>> it = iter_mex(10**5, pseudorandom(34, 37, 656, 4294967291))
>>> next(islice(it, 10**5, None))
0
>>> s, t = [list(islice(it, 10**5 + 1)) for _ in xrange(2)]
>>> s == t
True
>>> sorted(s) == range(10**5 + 1)
True

Let's prove that this always happens. First, as noted above, the mex of \$k\$ numbers is always a number between \$0\$ and \$k\$ inclusive, so all numbers in the sequence after the first \$k\$ lie in this range. Each number in the sequence is different from the previous \$k\$, so each group of \$k + 1\$ numbers after the first \$k\$ must be a permutation of the numbers from \$0\$ to \$k\$ inclusive. So if the (\$k + 1\$)th last number is \$j\$, then the last \$k\$ numbers will be a permutation of the numbers from \$0\$ to \$k\$ inclusive, except for \$j\$. So \$j\$ is their mex, and that will be the next number. Hence the pattern repeats.

So now it's clear how to solve the problem. If \$n > k\$, element number \$n\$ in the sequence is the same as element number \$k + 1 + n \bmod (k + 1)\$.

The implementation is straightforward:

def nth_iter_mex(n, k, a, b, c, r):
    """Return the nth value of the sequence whose first k values are
    given by pseudorandom(a, b, c, r) and whose values thereafter
    are the mex of the previous k values of the sequence.

    """
    seq = iter_mex(k, pseudorandom(a, b, c, r))
    if n > k: n = k + 1 + n % (k + 1)
    return next(islice(seq, n, None))

and now the timings are acceptable:

>>> timeit(lambda:nth_iter_mex(10**9, 10**5, 34, 37, 656, 4294967291), number=1)
1.6802959442138672


If you don't need to print out results in order, you can inverse the logic and compute power value first, and check if the result equals to sum of digits. It's super fast:

using System;

public class Program
{
    private const int MaxCount = 25;

    public static void Main(string[] args)
    {
        var c = 1;
        for (var i = 2; i < 100; i++)
        {
            for (var j = 2; j < 1000; j++)
            {
                var pow = (long)Math.Pow(j, i);
                var sum = SumOfDigits(pow);
                if (sum != j)
                {
                    continue;
                }
                Console.WriteLine($"{c}: {pow} = {sum} ^ {i}");
                c++;
                if (c > MaxCount)
                {
                    break;
                }
            }
            if (c > MaxCount)
            {
                break;
            }
        }
        Console.ReadLine();
    }

    private static long SumOfDigits(long value)
    {
        long sum = 0;
        while (value != 0)
        {
            sum = sum + (value % 10);
            value = value / 10;
        }

        return sum;
    }
}

Please note loop limit values are arbitrary, large enough to satisfy requirement of 25 results.


const-correctness
use references in favor of pointers where possible
The fact that you leave the obligation to free the memory that you allocate to the caller is generally not a good practice
a common pattern in your code is that you have pointers to arrays and their length - why not make a structure to bundle them up?
try to make use of iterators and range-based-for-loops when you don't really need the index (which you don't in your example)
since we don't really care about the type of the elements in a vector space you could use templates to generalize your algorithm

And just to see if it would be possible, I tried to come up with a compile-time version of the algorithm:
template<typename T>
struct pair
{
    T first;
    T second;
};

template<std::size_t N, typename T>
struct cvp
{
    pair<T> pairs[N];
};

template <typename T, size_t NV, size_t NW>
auto get_cvp(const T (&vs)[NV], const T (&ws)[NW])
{
    cvp<NV*NW, T> result;
    auto it_pairs = std::begin(result.pairs);
    for (const auto v : vs) {
        for (const auto w : ws) {
            *(it_pairs++) = {v, w};
        }
    }
    return result;
}

you can try the code here: https://godbolt.org/z/e8GvEf


Should this be written with exception handling instead of nested if-thens?

Maybe simple loop logic can serve your purposes better. If what you want is to ignore the rest of the loop body if a condition is met, the continue statement will follow immediately with the next iteration.

foreach (string fileName in updateList.fileNameList())
{
    updatesForFile = updateList.updatesForFile(fileName);
    hyperlinkEntry = hyperlinkList.getHyperlinkEntry(fileName);
    if (hyperlinkEntry == null)
    {
        updatesForFile.markResultAllRows("File not found on server");
        continue;
    }
    hyperlink = hyperlinkEntry.hyperlink;
    if (updatesForFile.updateNeeded())
    {
        if (!po.checkout(hyperlink))
        {
            updatesForFile.markResultAllRows("checked out to other user");
            continue;
        }
        downloadPath = downloadFolder + fileName;
        downloadResult = dl.download(hyperlink, downloadPath);
        if (downloadResult == false)
        {
            updatesForFile.markResultAllRows("download failed");
            continue;
        }
        file = new FileObject(xlApp, downloadPath, updatesForFile);
        if (file == null)
        {
            updatesForFile.markResultAllRows("unable to open");
            continue;
        }
        foreach (FeatureUpdate featureUpdate in updatesForFile.getFeatureUpdateList())
        {
            resultValue = featureUpdate.getColumnValue("result");
            if (!resultValue.Contains("updated"))
            {
                file.update(featureUpdate, updateMethods.lowFeatureLength);
                updatesForFile.markResult(featureUpdate.getIndex(), "updated");
            }
        }
        file.close();
        updateList.save();
    }
}

If what you need is to exit altogether when a condition is met, then I'd favor return, maintaining the same logic as the continue example. This would also give a lot more flexibility to refactor your code into functions and even probably use of kind of error codes, if it gets to that point.

Exceptions are very useful, but they are very expensive, so unless you don't really care about the performance of this code, I'd favor a solution based in flow control any day of the week.


Arduino code for multi button state change detection

Not a review, but an extended comment.

This is a very common problem. Polling the bunch of event sources is easy to implement, but it leads to the flaws you've discoverd. The only way out is to abandon polling, and switch to interrupts. In your case, consider to

    attachInterrupt(digitalPinToInterrupt(pin), ISR, RISING);

for each pin you are interested in, during setup. The ISR shall push a pin which triggered it into a queue. Then the loop would pick the pin numbers from the queue, and do whatever is relevant.

Be careful with synchronizing the queue between the ISR and the main line. Solving the synchronization is hard, but very enlightening.


Prime Number Generator algorithm optimization

You say you have implemented a Sieve of Eratosthenes but the code doesn't do
what I understand from the Wiki page.  Maybe you have changed it now, as your
comment to Loki's comment implies.

Here are a few extra comments to add to those from @LokiAstari

Use of unsigned is not necessary or desirable. Just use int unless there
is good reason for an unsigned (e.g. when you have a bitmap or similar)
You repeat the expression n - m + 1 several times. Although the compiler
will optimise this away, the reader has to read it each time.  Best to put
such an expression into a constant, e.g.:

 const int range = n - m + 1;

Variables i and t are functionally unused.
main takes argc/argv parameters. Also, it is normal not to do all the work
in main, although for a small program like this that is perhaps irrelevant.
Your initial if clause might be better inverted to avoid the indentation
caused.  Also note that it is easy to mistake the precedence of operators, so
brackets are safer:

if ((n - m > 10000000) || (m >= n) || (m < 0) || (n > 1000000000)) {
    // print an error
    exit(1);
}

In general it is better to use functions to aeparate parts of a program into
small units that are easily tested or otherwise verified.  The overhead of a
function call is often zero (the compiler can optimise the call away). So
some of your loops could be extracted into functions - but only if using a
function is 'makes sense' (which takes experience to decide).
The Sieve of Eratosthenes doesn't really need any division.  It is probably
better to compute all primes from 2 upwards and then just print the ones
requested rather than trying to start at the specified minimum bound.
Nested loops are in my opinion best avoided.
You say you used short names to keep the program short.
But even your short names are not well
considered.  For example, the first loop uses j as a loop variable to
initialise the sieve: access to the sieve uses a[j].  The following loop
uses j as a loop variable but it is never used to access the sieve -
instead the inner loop uses k as a variable: if (a[k] % j == 0.....
Maybe this is nit-picking but consistency is an important aspect of
programming.  Note also that loop variables are often best defined in the
loop:

for (int i = 0; i < range; ++i) {
    etc
}

Here is my attempt at the sieve, for what it is worth:

#include <stdio.h>
#define SIZE 1000000

static void prime_set(char *sieve, int n, size_t size)
{
    for (int i = n + n; i < (int) size; i += n) {
        sieve[i] = 1;
    }
}

static int prime_next(char *sieve, int n, size_t size)
{
    for (int i = n + 1; i < (int) size; ++i) {
        if (!sieve[i])
            return i;
    }
    return 0;
}

static void prime_print(const char *sieve, int min, int max)
{
    for (int i = min; i < max; ++i) {
        if (!sieve[i]) {
            printf("%d\n", i);
        }
    }
}

int main(int argc, char **argv)
{
    const int min = 1;
    const int max = SIZE;
    int prime = 1;
    char sieve[SIZE] = {0};

    while ((prime = prime_next(sieve, prime, SIZE)) != 0) {
        prime_set(sieve, prime, SIZE);
    }
    /* remaining zeros in sieve are primes */
    prime_print(sieve, min, max);
    return 0;
}


Select input that is generated and populated with options

A few minors:

Your spacing is a bit inconsistent (e.g. missing spaces here completeSelect{ and here $this->setIn=$val;)

Your naming convention is a bit inconsistent as well. I don't do much PHP but class names are usually PascalCase. You should decide whether your methods should be camelCase or PascalCase (you have buildOptions vs BuildSelect).

You have a typo here select_brwoser - should probably be select_browser

Your interface into the class is not quite clear. You build your options on construction yet the method to do so is public. Am I supposed to call it again - if so under which circumstances? If the class is immutable (e.g. you can't add more values for the options) then why not simply build the entire select in the first place and cache it?
A possible change would be to make the buildXYZ methods private and build on construction (assuming the class is immutable) and have public getXYZ methods instead which return the cached value for the options or the select respectively.


How could this constructor code be improved?

Why -init... should be declared to return id

Imagine you have class A and its subclass B sharing the same designated initializer, initWithString:.

@interface A : NSObject
-(A *) initWithString: (NSString *) string;
@end

@interface B : A
-(B *) initWithString: (NSString *) string;
@end

As you can see, the declarations have a conflicting return type, which unavoidably causes a compiler warning. You can trivially fix it by changing the methods to return id, which, given Objective-C dynamic typing, doesn't change anything about how these methods work. So it has become a well-established, but not as well-understood, tradition.

Why class initializers should use self rather than the class name

As you correctly noticed, using JGProduct instead of self will allocate an instance of JGProduct for any subclass, which is not what you want in 99% cases.

Why write +[JGProduct productWithIdentifier:]?

Most of the time, it's just a shortcut to alloc, init and autorelease to make calling code more readable. However, these initializers may be much more complicated and more efficient when implemented in class clusters. When you write a class cluster, you have one public superclass and several private subclasses. In such cases the superclass's alloc has to return a placeholder object which will allocate and instantiate an object of the right subclass in its init... implementation. The class initializer, on the other hand, can immediately return an already inited object of the right subclass.


The major problem here is using imprecise floating point values. Not only does it slow the entire process (minor quibble), but it will produce incorrect results once the values pass the integral cutoff of the field width. If you truly want to allow calculations approaching infinity (or what? 24 bits?) you need to switch to BigInteger which can model "exact" integers of any size.

  Okay, they probably cap out at a very, very large number...much larger than doubles, but will likely last past the life of your PC.

This issue is so critical to the correctness of the solution that I'll leave it to stand on its own and leave any other review issues for others.


Per the Capitalization Conventions on MSDN, types, methods, and properties should be PascalCasemeaning they start with an uppercase letter.

  Func<byte, byte> validate = (grade) =>
  {
    if (grade > 100)
      throw new ArgumentOutOfRangeException("grade can`t be more than 100");
    else
      return grade;
  };

There is no reason to use a Func here. Just use a normal method, like this

private byte Validate(byte grade)
{
    // the method body can go here
}

  public byte kor
  {
    get { return kor; }
    set { kor = validate(value); }
  }

Have you tested this code? The getter and setter both look like a StackOverflowException (via infinite recursion) to me. You need a backing field, like this

private byte kor;
public byte Kor
{
    get { return kor; }
    set { kor = Validate(value); }
}

It's uncommon to use byte instead of int, even if you know your data will fit in a byte. Only optimize for size if you know that you need to do so.


The first thing that stands out here to me is that you should be using __get_item__ and __set_item__, and __repr__ instead of get-key, set-key-value and print_hashmap. This will opt you into the syntax of collections in python where you use d[key] to get a key, d[key] = val to set a value, and print(d) to print it. This may seem trivial, but the fact that python lets containers you have written to feel as nice as base ones is a large part of why Python is such a natural feeling language as opposed to something like Java, where this style would be considered correct.


A WinAPI C++ program for printing the master boot record of the hard drive

Idiomatic is relative. I guess it's a coding style you could find in older code-bases (and many winapi based applications are rather old), but you wouldn't write C++ like this today. Consider for instance:

#include <iostream>
#include <iomanip>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <array>

constexpr std::size_t MBR_SIZE = 255;
constexpr std::size_t BYTES_PER_COLUMN = 4;
constexpr char LINE_DELIMITER = '\n';
constexpr const char* COL_DELIMITER = " ";

int main() {
    std::array<unsigned char, MBR_SIZE> mbr;
    std::iota(std::begin(mbr), std::end(mbr), 0); // filling it for testing purposes

    std::cout << std::hex << std::setfill('0');
    std::size_t index = 0;
    std::transform(std::begin(mbr), std::end(mbr), std::ostream_iterator<int>(std::cout, COL_DELIMITER), [index](auto c) mutable {
        if (index++ % BYTES_PER_COLUMN == 0) std::cout << LINE_DELIMITER;
        std::cout << std::setw(2); // setw must be applied for each output
        return c;
    });
    std::cout << std::endl;
}

In a dozen of lines you get the same result as printMBR and its two auxiliary functions (at least I believe so, I haven't had the chance to run your code), which are longer and more complicated.

To be more specific about your code:

don't declare a variable before you're ready to define it, and don't define it before you're ready to use it.
don't std::move your return value, it prevents copy elision
don't declare free functions static, it's a java thing
inside ReadMBR there's a char* buffer = new char[MBR_SIZE]; you don't use afterwards
I'm not a fan of that many using directives; prefix the names with std:: and be done with it, unless you prefer to set up aliases: then using string = std::string is clearer
use standard algorithms, such as std::copy, std::accumulate, etc (in headers <algorithm> and <numeric>) or range-base for loops (for auto item : sequence) instead of "raw" loops. For instance, charToHex could be written

like this:

std::string s;
for (auto nibble : { (c >> 4) & 0xf, c & 0xf })
    s += fourBitsToString(nibble);
return s;

or:

char lo = c & 0xf;
char hi = (c >> 4) & 0xf;
char chars[] = {hi, lo};

return std::accumulate(std::begin(chars), std::end(chars), std::string(), [](auto init, auto elem) {
    return init += (fourBitsToString(elem));
});

And, on a more aesthetic note, a four-bits aggregate can be called a half-byte or a nibble.


I'd second TopinFrassi's answer, that this is a more or less sensible approach, and the implementation is excellent. However, there are some potential issues, which I'll expand from craftworkgames' comments and your response. Because I can't really find anything that needs criticism in how it's written, this will be entirely design focussed.

There are two central issue in passing an interface that claims it can provide

IDbSet<TEntity> Repository<TEntity>() where TEntity : class;

You're promising an awful lot
You're exposing this outside of directly data-access related code (even if it's in service classes, these classes are unlikely to all be directly DA related except perhaps in a very small application)

And the problems this can cause are:

Exposing much more than a consumer needs. Any class that only needs to deal with SalesReps shouldn't also be passed a way to perform arbritrary crud operations on Customers. This is a violation of the Interface Segregation Principle.
Difficulty of mocking. An interface that can provide a lot means a lot to mock. It's likely that you'll be able to narrow down what actually needs to get mocked in individual tests, but often the practicality of that is having to couple to implementation details of the SUT which you aren't really trying to test, which makes your tests more brittle.
A leaky abstraction. Abstractions are about more than just being able to swap implementations, which means even if you have no interest in doing that, a leaky abstraction is still a problem. In this case you're exposing the big EF gotcha to every class who ever has to deal with entities: IQueryable. It does a good impression of IEnumerable, but then throws exceptions for a lot of arguments to its LINQ extensions which IEnumerable would happily process. Having to remember that code will need to be converted into SQL is not an issue you should expose throughout your service layer.
A lack of entity-specific methods. In addition to giving all your service classes too many general methods, you may also be giving them not enough specific methods. It's quite likely that you'll have queries or commands for a particular entity type which you'll want to do in several places- including across several service classes- but which are long/complex enough that repeating the entire query or command would be a DRY violation.

Resolving

That last problem is the one that screams out most for a particular answer, so let's start out with that. Say we've written a service class with a private method that does a complex query for us. Now we're writing another service class, and though the functionality isn't that similar, we find ourrselves needing the same query that was in that private method.

We do the obvious thing and pull the query out into its own class:

public class FirstFooService()
{
    public FirstFooService(IUnitOfWork unitOfWork, FooQueryHelper queryHelper) { //... }

    //...
}

public class SecondFooService()
{
    public SecondFooService(IUnitOfWork unitOfWork, FooQueryHelper queryHelper) { //... }

    //...
}

But now this really seems like a mess. We're relying on two different things- the unit of work and the query helper- to do our data access, at two different levels of abstraction. Which level do we actually want?

Well, I think the answer is straightforward. We added FooQueryHelper specifically because we found ourselves wanting that abstraction over accessing the IUnitOfWork directly. Moreover, if we look at the problems above, FooQueryHelper can solve all four of them. It solves 1,2 and 4 by its nature, and it can simply solve 3 by keeping its return types as IEnumerable rather than IQueryable, and by not exposing any methods which take an arbitrary Func or Expression to use as a filter.

All that remains is to extract the IUnitOfWork methods that we consume onto FooQueryHelper, narrowing them and making them more specific to keep them at the right abstraction level when possible. You can probably see the punchline coming- what we actually end up with isn't FooQueryHelper, but FooRepository. This can follow the standard generic repository pattern you'll find described all over the place. If you look back at the root problems, you can see these are solved too: now everything relies on a much smaller, more targeted interface, and data access concerns are kept in data access classes, rather than spreading out to every service that cares about entities.

Conclusion

But what about KISS? Possibly you were already aware of the generic repository, and you wanted to avoid it because of its apparently needless complexity and indirection. Well, yes, as always there's the tradeoff- in a small, simple application, at what point does further SOLIDifying your code consume more development resources than it'll ever buy you back? That's a judgement call you'll have to make. But hopefully I've given some reasons beyond just "So I can swap my ORM" for why you might pick this more complex pattern.

Also note that the generic repository is, at its core, not actually all that complex or bulky to implement. It really starts out as just a thin wrapper over IDbContext. But don't be misled! A repository should not just be an adapter from IDbSet to an interface you control, it should be a full-blown abstraction layer! So if you do find yourself adding more methods, that's probably vindicating the choice of that pattern.


Assigning array keys based on the values of another array

PHP provides functions to parse CSV files and strings line-by-line.

$file = ...
$headers = fgetcsv($file);
$lines = array();
while (($line = fgetcsv($file)) !== false) {
    $lines[] = array_combine($headers, $line);
}


It's been a long time since I've heard the terms BCD or Binary Coded Decimal. Keep in mind that BCD was primarily a hardware encoding of integers provided by one particular manufacturer of main frame computers. There were computer performance issues when using BCD.
The best way to implement a BCD number would be an array of 4 bit integer values.
One good habit the code demonstrates is that all if statements and loops wraps the code in braces ({ and }). Thank you for that!
Magic Numbers
There are Magic Numbers in the void printBits(unsigned long number) function (32, 9, 17, 25, 5, 13, 21 and 29), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Unused Header Files
The program includes limits.h and string.h but the contents of these files are not used by the code in the program. In the case of string.h it might be better to remove the #include. In the case of limits.h it might be better to use the limits provided. It is better to not include files that aren't being used since this will decrease the size of the code being compiled and might improve build times. The #include directive literally copies the header file into the intermediate file that is compiled after the C pre-processor is run.
Algorithm
It might be better to prompt the user for the number to be converted rather than use argv as the source of the input. Even if argv continues to be the source of the input, it would be better to check argc to see if there are enough arguments and either prompt the user for a number in screen input, or report an error and quit.
Readability
The some of the functions (printBits and convertBinaryToBCD) might be easier to read if there was vertical spacing in the functions.
Off by One Bug
As noted by @1201ProgramAlarm there is an off by one bug in void printBits(unsigned long number), the code is accessing one invalid memory location bit_position[32] and ignoring bit_position[0].
It is also not clear why bit_position is 32 bits rather than 64 bits, since the code is primarily using unsigned long rather than unsigned int.


Speed optimization for transparent gradient blend algorithm

There are a number of things you could do to make this faster and better.

Use a pointer rather than array references

The code currently computes a pixelIndex and uses it as in pixelValue = pixelBuffer[pixelIndex], but what's actually happening is that each pixel is visited in order.  The code can be sped up quite a bit with just this one change.

pixelValue = *pixelBuffer;
// .. do processing
++pixelBuffer;   // advance to the next pixel

Avoid shifting

Right now, the code masks off the pixel value for each color and then shifts it, does calculations and then shifts it back into place.  Those shifts are not needed.  Instead of this:

const uint8_t backR = (BACKCOLOR & 0x00FF0000) >> 16;
R = (pixelValue & 0x00FF0000) >> 16;
pixelBuffer[pixelIndex] = (uint32_t)((A << 24) | ((R & 0xFF) << 16)
    | ((G & 0xFF) << 8) | (B & 0xFF));

The code could instead do this:

const uint32_t maskR = 0x00FF0000;
const uint32_t backR = BACKCOLOR & maskR;
R = *pixelBuffer & maskR;
*pixelBuffer++ = (uint32_t)((A << 24) | (R & maskR)
    | (G & maskG) | (B & maskB));

Use same-sized constants

Using a mix of uint8_t, uint32_t and unsigned short constants makes the compiler work much harder with all of the implicit transformations.  Better would be to use all the same size, such as uint32_t, the same as your pixel data.  The code generated by the compiler may be simpler, smaller and faster as a result.

Move loop invariants out of the loop

Compilers can often perform this optimization for you, but it's good to give them a hint.  This code computes this each time through the inner loop:

R = (R * A + backR * (OPAQUE - A)) / OPAQUE;

But A, backR and OPAQUE don't change within that loop, so better would be to calculate backR * (OPAQUE - A) as part of the outer loop.

Use named constants

This isn't a speed issue, but instead of using the constant 0x00FF0000 multiple places, it's better from a maintenance standpoint to turn that into a named constant maskR to avoid errors.  Alternatively, one could create a function or macro that does the masking.

Be careful with signed vs. unsigned

The loop counters x and y are declared as int values, and they're compared to width and gradientHeight, but are you ever really going to want negative numbers for any of those?  It seems to me that they'd be better as unsigned.

Is BACKCOLOR really 0?

More of the math could be eliminated if BACKCOLOR is really always supposed to be zero.  I assumed instead, that it might be set to some other color, and so I left it in place.

Declare variables as late as possible

Rather than using the old C-style of declaring all variables at the top of a function, use the modern C++-style and declare variables as late as possible.  Doing so can sometimes help the compiler figure out register allocation, resulting in faster, smaller code.

Putting it all together

When all of these are applied, the resulting code is shorter, cleaner and faster:

#define maskR(x) (x & 0x00FF0000)
#define maskG(x) (x & 0x0000FF00)
#define maskB(x) (x & 0x000000FF)

void sectionAlphaGradient2(uint32_t* pixelBuffer,
    const unsigned width, const unsigned gradientHeight)
{
    const uint32_t OPAQUE = 255;
    const uint32_t BACKCOLOR = 0x00000000;
    const uint32_t backR = maskR(BACKCOLOR);
    const uint32_t backG = maskG(BACKCOLOR);
    const uint32_t backB = maskB(BACKCOLOR);

    for (unsigned y = 0; y < gradientHeight; y++)
    {
        uint32_t A = (uint8_t)((OPAQUE * y) / gradientHeight);
        uint32_t shiftedA = A << 24;
        uint32_t altR = backR *(OPAQUE - A);
        uint32_t altG = backG *(OPAQUE - A);
        uint32_t altB = backB *(OPAQUE - A);
        for (unsigned int x = 0; x < width; x++)
        {
            uint32_t R = (maskR(*pixelBuffer) * A + altR) / OPAQUE;
            uint32_t G = (maskG(*pixelBuffer) * A + altG) / OPAQUE;
            uint32_t B = (maskB(*pixelBuffer) * A + altB) / OPAQUE;
            *pixelBuffer++ = shiftedA | maskR(R) | maskG(G) | maskB(B);
        }
    }
}

Results

On my machine, a 64-bit Linux box running g++ 4.8.3 and using test code with an 8000 by 6000 pixel buffer, I get the following results:

original: 240977 microseconds
improved: 125714 microseconds


Understanding my permalink service tests

Naming

Good names are very important for readability. For example, this:

testPermalinkServiceA_createPermalinkWithoutValidation_permalinkWithAllFilesAndWithoutValidation

is just way too long a name.

You can reduce it's size by removing all references to permalinks (it's in the PermalinkServiceTest class, so it's assumed that the tests test permalinks). It's also not very clear what the A stands for, but it seems to be only necessary because the tests need to be executed in a specific order, which doesn't seem like a good idea

The name also contains more duplication, as it contains WithoutValidation twice.

A shorter name might be testCreateLinkAllFilesNoValidation, or even just allFilesNoValidation (if that accurately described what is tested, which I'm not sure it does; It's hard to say without the actual code, but I'm eg unsure what allFiles are, or how they are used in the test).

Tests building on each other

I don't really like how the tests seem to build on each other; I would prefer if each test is self-contained.

Self-contained tests seem a lot more stable and maintainable, and would also result in easier to understand code. If you are worried about duplication, just extract that code to a method.

This would also get rid of many of the fields, which I think also results in nicer code.

Misc

Many of your tests don't actually contain any tests, why is that?


Counting the number of elements in a sorted array

I want to find a solution [whose] algorithm time complexity is lower than O(n).

You'll have to be more specific. What you asked for literally isn't possible; but sometimes people use "big-O" notation loosely, either out of laziness or because they haven't yet been exposed to the notation expressing their intended precise gradations of meaning.

Notice that if I give you the input

1 2 3 4 5 6 7 8 9 10 11 12 13 ...

then you must output

number of 1 is 1
number of 2 is 1
number of 3 is 1
number of 4 is 1
...

— that is, if the size of the input is n, then the worst-case size of the output is O(n). Printing those O(n) bytes of output will take O(n) time just by itself. Anything else the program does (besides print its output) can only make the overall program slower, not faster.

On the above worst-case input, your "repeated binary search" algorithm runs in O(n log n) time, which is worse than O(n).

Now, if you're not concerned about worst-case inputs, but merely with the average input... well, then you'd have to define a notion of "the average input". You'll have to come up with some model of what kinds of input you expect. One way to do this is to come up with an algorithm for generating inputs, and then treat it as your model. For example:

def get_random_input(n):
    return sorted([random.randrange(n) for i in xrange(n)])

Or:

def get_random_input(n):
    return sorted([random.randrange(100) for i in xrange(n)])

On these two different models, your algorithm performs very differently. On the latter, you do well: O(log n). On the former, you do poorly: O(n log n).

This is kind of like asking for a compression algorithm that compresses all possible inputs. You can get compression for some inputs only at the expense of others; the art is deciding which kinds of inputs are "interesting" and which can safely be blown up. In this case, you can get sub-O(n) performance for some inputs only at the expense of others; the art is deciding which kinds of inputs are "interesting", which is to say, deciding on a model for your "average" or "expected" input.

EDIT: My analogy above is flawed, as indicated by LinMa's comments below this answer. See, if you can get O(log n) performance on your "expected" inputs while blowing up the "unexpected" inputs by only a constant factor (e.g. "O(n) plus a constant number of comparisons" or "O(n) times two"), then you can keep your algorithm's worst-case big-O "constant" while improving the best-case.

Hope this helps!


(non-Clojure-specific) Gain performance, sure. Use packed array of odds, where index i represents value 2i+1. Then you don't have to deal with evens, which are all non-prime a priori (except the 2 of course). Then you can increment by 2*p for a prime p to find its odd multiples twice faster.

For a non-marked index i, the prime p is p = 2*i+1, its square is p*p = (2i+1)(2i+1) = 4i^2 + 4i + 1 and its index is (p*p-1)/2 = 2i^2 + 2i = 2i(i+1) = (p-1)(i+1). For the value increment of 2*p, the index increment on 2x-packed array is di = p = 2i+1.


Performance

The main problem seems to be that you're checking each monster and item for each console position. If cameraSize is 80, that means you're checking each monster and item 80 x 80 = 6400 times.

Just draw the map first, and then loop through your monsters and items (once) and draw them if they're within view.

Other notes

You're using a lot of getter methods: GetX(), GetY(), ReX(), ReY(). In C# properties are normally used instead of getter/setter methods.

ReX and ReY are not very descriptive names. Obviously we're dealing with coordinates here, but what does that Re prefix mean?

Since you're dealing with 2D coordinates quite frequently, it could be useful to create a separate Position class for that, with X and Y properties and perhaps some overloaded operators (+, -) and utility methods (int DistanceTo(Position other), and so on).

Calling Console.Write(elem) invokes elem's ToString method. Personally I'd give those monster and item classes a public char Appearance { get; private set; } property, and turn that write call into Console.Write(elem.Appearance), to make it more obvious what's going on, and so I don't have to abuse a ToString method.

Monstro and Item class

These notes refer to the classes you posted in the chat:

new Random() gives you a pseudorandom number generator that's seeded based on the current time. Because each monster has its own Random instance, they will likely move in the exact same way if you create multiple monster instances at the same time (or close enough).

Your movement code can be simplified: if you use a offsetX and offsetY variable, which are set based on the chosen direction, then you don't need that switch-case statement anymore.

Making Item responsible for its own placement is quite inflexible. Just give its constructor an x and y parameter, and let the map-generating/loading code figure out where to place items.

Randomly picking spots until you find an empty one should work just fine if there's plenty of space, but large maps with few empty spots will cause a lot of retries. It'll even loop indefinitely if there is no empty spot available.

SetPickedUp can be simplified to pickedUp = argPickedUp. Or just use a property instead.

Map.CheckTile is not a very descriptive name. Map.IsTileEmpty is more obvious.

You don't need those StringBuilders in your ToString methods. Just return appearance.ToString() or GetType().Name directly.

More notes

Making Item and Monstro abstract implies that you've got several classes that inherit from them. I assume that each different item has a class of its own? That makes sense if different items actually have different behavior, but if they only have different stats, then a single Item class is sufficient. Since Item has an attack, defense, health and rarity field, it can already be used for a variety of different items: weapons (attack), armor (defense), health potions (health).

In larger games, such data is often stored in csv or Excel files, which makes it easy for game-designers to adjust items without the help of a programmer. In your case that's probably not worth the effort, but you can still create a 'table' of item data in code. For a one-man project that's just as easy to modify, and still saves you a ton of useless classes:

var itemBlueprints = Dictionary<string, Item> {
    { "Sword", new Item(5, 0, 0, 0.05, '|') },
    { "Shield", new Item(0, 2, 0, 0.08, 'o') },
    { "Potion", new Item(0, 0, 5, 0.12, '+') },
};

You'll want to add a Name property to the Item class so you can still determine an item's name (the type name no longer tells you what it is). That's more flexible than using a type name anyway.

The above code could be made a little more readable by using optional and named parameters:

new Item("Sword", attack: 5, rarity: 0.05, appearance: '|');
new Item("Shield", defense: 2, rarity: 0.08, appearance: 'o');