HTML5 style

I'm not sure if there's a standard for HTML formatting.
I think it usually depends on the team.
You might be interested in Google's style guide for HTML.

It seems logical to indent  and  deeper than ,
so instead of:

<!DOCTYPE html>

Simple Hours:Minutes Adder

This would be better:

<!DOCTYPE html>

Simple Hours:Minutes Adder

HTML5 validation

In HTML5, the <input> tag should not have a closing </input>.
The first <input> tag here violates that:

<input id="input_text" type="text"></input>
<input id="add_button" type="button" value="add">
<input id="pop_button" type="button" value="pop item">

There are some other HTML5 violations, for example missing <title>.
Use a validator to catch these.

JavaScript style

Indenting using two spaces is a very common practice, so that's good.

In general your JavaScript style seems fine, clean, easy to read.
Some minor violations:

pointless return; at the end of updateTotalDisplay
total = total + entries[i] can be simplified to total += entries[i]
instead of setting totaltimetext to output_prefix + formatTime(total), it would be better to have output_prefix in the HTML document, and only update the changing part, in a dedicated field

Use booleans

Instead of this:

  if (1) { //add validation, input must be hh:mm

Better use proper booleans:

  if (true) { //add validation, input must be hh:mm

But even better would be to replace the comment with a function call:

function is_valid(hhmm) {
   //implement validation, input must be hh:mm
   return true;
}

var hhmm = input_text.value.split(":");
if (is_valid(hhmm)) {

Improving the logic

Instead of re-summing the minutes stored in entries,
it would be more efficient to keep track of the running total,
and simply add the newly added number of minutes.

Improving formatTime

Instead of:

  if (mm >= 0 && mm < 10) {

It's generally more readable to arrange the terms in increasing order:

  if (0 <= mm && mm < 10) {

But actually, the 0 <= mm seems pointless.
It's reasonable to expect that this function will receive already validated number of minutes (0 or positive).

The function could also use better variable names,
and some string operations can be written simpler,
and some a variable can be eliminated:

function formatTime(total_minutes) {
  var hours = Math.floor(total_minutes / 60);
  var minutes = total_minutes % 60;
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  return hours + ':' + minutes;
}


Create a C style char** from a C++ vector

Since you already have a std::vector<std::string>, it's much simpler to let that own the memory, and build a parallel std::vector<char*> which just keeps pointers into the original strings. The only difficulty is ensuring this isn't used after the owning vector goes out of scope.

The simplest implementation is something like:

std::vector<char*> strlist(std::vector<std::string> &input) {
    std::vector<char*> result;

    // remember the nullptr terminator
    result.reserve(input.size()+1);

    std::transform(begin(input), end(input),
                   std::back_inserter(result),
                   [](std::string &s) { return s.data(); }
                  );
    result.push_back(nullptr);
    return result;
}

where the caller is responsible for managing the lifetimes of the two vectors. You get the required char ** by calling result.data().

If you want to avoid the potential lifetime problems, you can write a class to own both vectors for you so their lifetimes are synchronized.

Note that I deliberately haven't taken the vector by const ref, because execve takes an array of pointers to non-const char, but it doesn't mutate the contents so there's no need to make a copy. This lack of const-safety is common in old C interfaces.

PS. I didn't force myself to use transform when a simple loop would do hoping for some magic optimization. I used transform instead of a simple loop because it more clearly expressed the semantics of my code.

A "simple" loop is a powerful multipurpose language construct which could do anything. By comparison transform is a simple, special-purpose algorithm, and much easier to reason about as a consequence.

Not least, since I had to take a non-const reference to the argument despite having no intention of mutating it, anything that makes it easier to see at a glance that no mutation is possible, is helpful.


How best to differentiate boolean values in a long list?

Is this more like what you're after?

var TPORGatheredData = new[]
        {
            // Add all values in the logical order that you want them
            "Reference",
            "Title",
            "Status",
            "Status.State",
            //...omitted for brevity
            "Description",
            "ClosureText"

        }.ToDictionary(x=>x,x=>true);

        // This is significant
        TPORGatheredData["Description"] = false;


The logic behind this section seems to be a little off.

for p, s in self.ploys.items():
    for i in [i for i,n in enumerate(s) if umove in n]:
        del self.ploys[p][i]

When you delete the value at self.ploys[p][i] this essentially means that:

self.ploys[p][i + 1] is now at position self.ploys[p][i]
self.ploys[p][i + 2] is now at position self.ploys[p][i + 1]
etc

Because the comprehension in the second line finds the indices to the original array, all the proceeding deletes will delete the element 1 index ahead of their target, the next delete will be 2 ahead, and so on.

To fix this you can just iterate through the loop backwards.

for p, s in self.ploys.items():
    for i in [i for i,n in enumerate(s) if umove in n][::-1]:
        del self.ploys[p][i]

Along with that, I think it would help readability to give variables in your loop meaningful names.

It's much less cryptic as:

for ploy_index, soln_list in self.ploys.items():
    for soln_index in [i for i, soln in enumerate(soln_list)
                      if umove in soln][::-1]:
        del self.ploys[ploy_index][soln_index]

I notice is that in PlayUser you write the following.

while umove not in grid or (umove in self.umoves or
    umove in self.cmoves):
    ...

These brackets are a little confusing. When line length is a concern, you should put the entire expression in brackets or use the \ continuation. And although not explicitly in PEP8, I think it also looks better to add extra indentation to easily identify the condition from the logic.

while (umove not in grid or
       umove in self.umoves or
       umove in self.cmoves):
    ...


Should I Move Methods To A Different Class

Well, Your code looks good, and your suspicion seems right. I would agree with you. My reasoning is that your objects should be modeled after the problem rather than the data base schema. Here I would say that the other getTbl* methods are actually getters on particular animals. So it makes sense to move them to Animal class and rename the getTbl* methods accordingly, i.e getAnimalVaccinationList.

I would also recommend to refactor all these methods so that the db connect, and processing are in a different method,

public static ArrayList<Integer> runDbQuery(String query, String field) throws DbException {
    try {
      CC_H2 db = new CC_H2();
      db.Connect(Variables.getStrConn(), Variables.getStrUser(),
            Variables.getStrPassword(), "Embedded");
      ResultSet rs = db.query(query);
      ArrayList<Integer> lst = new ArrayList<Integer>();
      while (rs.next()) {
        lst.add(new Vaccination(rs.getInt(field)));
      }
      db.Disconnect();
      return lst;
    } catch(SpecificException e) {
      // Do not throw exception, process the exception and throw
      // some thing relevant to your program.
      throw new DbException(e);
    }
}

and use this in other methods to avoid repetition. I would also recommend moving the getTblHerd to another class - say Herd because it has an independent identity other than db_tables.

Here is an example of using the above method

public static ArrayList<Note> getTblNotes(int intID) throws DbException {
    String query = "Select NOTE_ID FROM tblNotes WHERE NOTE_HERD_ID = "
                    + intID + " ORDER BY Note_Date DESC";

    ArrayList<Note> alNotes = new ArrayList<Note>();
    for (Integer i : runQuery(query, "NOTE_ID")) {
        alNotes.add(new Note(i));
    }
    return alNotes;
}


Disclaimer: not an android developer....

Thoughts on the Problem

A few thoughts, right off the top.

  In this connection i have an integer field named as state.
  the state value is : 1 for connecting, 2 for connected and 0 for failed

First - that should probably be implemented as an enum, rather than as an integer

Second - that suggests that you are trying to implement a state machine (unsurprising; you are trying to implement a login protocol, and protocols almost always demand state machines).  I'd encourage you to refactor the code and make the state machine explicit; you might want to consider stateless4j as part of the implementation.

Third - doInBackground() needs to be checking for cancellation.  Normally, I would expect that check to be the condition in the while loop.

while (! isCancelled()) {
    if (connection.getState() == ImConnection.LOGGING_IN) {
        ...
    }
}

With the while loop written the way that you have it, it looks as though you are busy spinning while waiting for the state to change.  I'm not keen on that at all; Thread.sleep(), SystemClock.sleep(), something to free up CPU to do the work.  I'd probably go with Thread.sleep() myself, since I would want this worker thread to respond quickly to the cancel() command (which almost certainly interrupts() the running thread).

It's not really clear to me that you need the cancellation to be running on a timer separate from the CheckSignInTask - why not have the task check the time out itself? (If because Reasons[tm], those reasons should be clearly documented in the code so that the next coder to come along doesn't get too clever).

Style notes

What's the point of assigning a member variable if you are only using it in one place?

        protected Boolean doInBackground(IImConnection... params) {
        try {
            IImConnection connection = params[0];

Also, it's disconcerting that you are passed an array of connections, but you only ever manipulate the first one?

public class TimeOut implements Runnable {
        private AsyncTask task;

        public TimeOut(AsyncTask task) {
            this.task = task;
        }

You planning on changing what task you are timing out later?  Of course not.  So make that explicit

public class TimeOut implements Runnable {
        private final AsyncTask task;
        ...

Try to avoid magic numbers

handler.postDelayed(timeOut, 60 * 1000);

Is that a minute?  A thousand hours? 60 millenia?

handler.postDelayed(timeOut, TimeUnit.MINUTES.toMillis(1));

or even better

final long LOGIN_PROTOCOL_TIMEOUT = TimeUnit.MINUTES.toMillis(1);
handler.postDelayed(timeOut, LOGIN_PROTOCOL_TIMEOUT);


Set value to multiple selector on condition

The first and most simple thing to do, in this case, is to drop that if. Duplicated code always smells:

const isProduct = dataType === "product";
$(".type_product").val(isProduct ? 1 : 0);
$(".type_category").val(isProduct ? 0 : 1);
$(".type_modifier").val(isProduct ? 1 : 0);
$(".type_variant").val(isProduct ? 0 : 1);

Note the use of === instead of ==. Note that you may write $(".type_product, .type_modifier") to reduce number of lines but I find it pretty odd because I'm aggregating selectors for objects with different content (and I'm updating their value, not their style). Just my opinion, anyway.

If this is everything you need then I'd keep it as simple as possible but what if logic is more complex? Let's introduce a function: val() accepts it as parameter:

$(".type_product").val(calculateTypeField);
$(".type_category").val(calculateProductField);

And so on. Those functions can be as complex as required (and you introduce some separation between your view and its view model. For even more complex cases you may also have a dictionary:

{
    'product': calculateProductField
}

To use together with a data-field attribute to map the function to the function which calculates it:

<input type="hidden" name="type_product" value="" data-field="product" />

(of course you need to write few JavaScript lines to do this _mapping__)


Parallel factorial algorithm using std::thread

Firstly, some issues with API usage. Using raw std::threads is generally not the way you want to go with this sort of thing: prefer to use std::async. This also means you don't need to pass in by reference for updates, as it can return a value. The other big win from this is that you don't need to lock and perform an update in the thread that is running the calculation; this can be done independently.

Firstly, let's modify the threaded_factorial function:

constexpr static auto threads = 4U;
constexpr static auto test = 325253U;

namespace mp = boost::multiprecision;

mp::cpp_int thread_fact(unsigned num, int start)
{
    mp::cpp_int n = start;
    for (auto i = start + threads; i <= num; i += threads) {
        n *= i;
    }
    return n;
}

To call this, we setup some arrays for the std::futures that will be returned, as well as an array of partial results.

std::array<std::future<mp::cpp_int>, threads> futures;
std::array<mp::cpp_int, threads> results;
for (auto i = 1; i <= threads; ++i) {
    futures[i - 1] = std::async(std::launch::async, thread_fact, test, i);
}
for (auto i = 0; i < threads; ++i) {
    results[i] = futures[i].get();
}

Now, the step where you combine these is actually pretty expensive. Multiplying two numbers that are of this magnitude will be time consuming; let's launch the multiplications in separate threads as well:

std::future<mp::cpp_int> x = std::async([&results]() -> mp::cpp_int { return results[0] * results[1]; });
std::future<mp::cpp_int> y = std::async([&results]() -> mp::cpp_int { return results[2] * results[3]; });
auto x_val = x.get();
auto y_val = y.get();
auto z = x_val * y_val;

Making these changes, this runs in a bit under 10 seconds for me. In fact, from the profile graph, most of that time is spent doing the combining.

Others have pointed out that further algorithmic improvements are possible if you need more speed.


Scraping and analyzing recent articles on bitcoin

The @ variable prefix should only be used inside a class to denote instance variables. That said, for a script like this, you might like to wrap all the logic in a class (or rather a module since you don't need multiple instances).

Use string interpolation. So instead of

DateTime.now.to_s + " : " + me.to_s

you can write

"#{DateTime.now} : #{me}"


Changing state of a light (Uncle Bob's light switch problem)

Welcome to the world of programming where you never know exactly when you're done because the client doesn't know precisely what they want!

The business solution is to this problem is to first sit down with the client, write down a proposal about some precise interpretation of what should happen. Have the client agree with this interpretation and sign it. Then implement this exactly as proposed.

Then later on when the client tests your code they're either happy (yay, we're done!) or they are not. If they're not you write down what they want to change and make them pay for it again. Happy times! (for you at least, the client doesn't like paying again for something "you should have known" in the first place).

Extra note: sometimes a client asks for something that cannot work. They might only realise the contradiction after you explained what exactly happens and offer them 2 possible ways that achieve 1 of the 2 things they ask for. In such a case you let the client decide which of the 2 is more important.

To write working code we first need to know which exact result we want to get.
Here's the current problem more precisely:

1) If 2 (or more) different switches are flipped within a certain time (half a second) of each other, ignore one of them and change the state of the light.
2) If a switch is flipped twice in rapid succession the second flip should not be ignored.

Question: If (1) and (2) happen within half a second, should the light change state?

My answer would be: If a switch is flipped once within half a second, the light should change state (compared to half a second earlier) irregardless of other switches.

Solution 1:

One possible solution is to modify the implementation of the switches themselves. If a switch is first in state off, and then flipped on, it will still say it's off for half a second. Only if it has remained on for half a second will it say it's turned on. This solves the problem of flipping the same switch twice in rappid succession ... with the downside that a light state will change at the earliest half a second after a switch is flipped. This is something the client has to agree on.

If the client agrees on that change, the lightLogic can remain exactly the same as in Bob's solution since that correctly handles the remaining requirement of ignoring multiple switches flipping "simultaniously".

This kind of solution is often used to prevent flickering in oversensitive keys. Consider a switch that has a bad contact. If switched halfway, it might rappidly say ON>OFF>ON>OFF even though you only flicked it once. Looking at a change from a small delay before makes sure that it will only fire once in such cases as intended.

Solution 2:

Alternatively if you require that the light switches on immediatly after a single switch is flipped, you'll have to do it differently.

Let's say the light is switched from off to on. For the next 500 milliseconds, under which condition should the light be switched back off? -> If ALL switches are back to what they were when the light was still off.

This looks similar to your idea, but only looking at the penultimate state isn't enough. If switch A is flipped, and then switch B is flipped 4 times, the light should still be ON because of switch A.

An idea would be like this (note not tested):

int currentTime = millis();
if (currentTime - lastChangeTime <= 500) { // might be considered simultanious
    if(currentSwitchState == initialSwitchState) { //all switches back to initial state
        light.state = initialLightState;
        lastChangeTime = 0; //respond to any new flip after this as if it was new.
    } // else light stays as it is now
} else {
    if (currentSwitchState != previousSwitchState) { // start new case
        light.state = !light.state;
        lastChangeTime = currentTime;
        initialSwitchState = previousSwitchState;
    } // else nothing changed
}
previousSwitchState = currentSwitchState; //always update latest known state


Find the first non-recurring character in string

The code is too convoluted and unreadable for such a simple task

seems is a dictionary where the values are (first index, occurrences) pairs.  That's an unconventional data structure.  You'd be better off with two separate dictionaries.
seems is a weird variable name.  What does it mean, anyway?
Why is the index = len(string) statement necessary?

This solution is less cluttered, and more clearly expresses the idea that you are counting the characters, then finding the first unique one.

from collections import Counter

def first_uniq_char(s):
    counts = Counter(s)
    return next((i for i, c in enumerate(s) if counts[c] == 1), -1)


Testing, vetting, and redundancy.

First you have not clearly defined the requirement. Base64 is an encoding used to convert bit/byte streams for safe transport. It is not the same as n-based number systems.

I will assume you want n-based number systems

Your code does not do a conversion that makes any sense at all, you should test your code before you release it.

Anyways, the easy solution up to base 36 is:

if(base <= 36){
    value = parseInt(number, base);
}

but I don't think that is what the lesson is designed to teach. So here is my assessment, and it would be a fail as it stands.

Throw Error objects not strings.

When you throw you should always throw an error object. One of the appropriate Error object types see the MDN documentation for Error.

You may not be handling the thrown errors and if the error handler does not expect a string it to may throw an error attempting to access non existing properties.

Compound declaration with assignment.

Generally I don't like compound declarations that have assignments, though I do make exception to last item assignment. I find it even less readable if you are inconsistent in the use.

Example of compound declaration and assignment:

// Bad
var a = 0, b = 1, c;
// or
var a = 0,
    b = 1,
    c;

// Good
var a, b, c;
a = 0;
b = 1;

You have:

// bad one line is compound and then you have a single
const numberOriginal = number, baseOriginal = base;

const negative = number < 0;

You should have:

const numberOriginal = number;
const baseOriginal = base;
const negative = number < 0;

Dont create needless noise.

You create the const baseOriginal and assign it the value of base yet at no point do you modify base before you use baseOriginal making it redundant. This just adds complexity where it is not needed making code harder to read and modify.

Show you understand let, var, and const

There is much debate about the use of let, var, and const with some schools of though opting for the use of only let and const.

The problem with this is that when I look at code I am in part assessing the writer's level of expertise and if I see a declaration out of place I wonder if that coder knows what he/she is doing. Once I lose trust in the code the marks fall off much quicker.

I understand that some teach the use of let instead of var - no harm done, right? No!!! var and let create very different behaviours and you should use them appropriately. Creating a block-scoped variable in function scope is incorrect. If you declare in-function scope then you should use var to show you know you are using function scope.

If the variable is never modified you should use const and you should place it as high as possible in the scope that it is needed.

Use let only inside blocks (With the exception of for loops)

Vars are hoisted and thus you should put var declarations where they are declared, first lines after the function declaration. If you don't then it is hard to know what has been defined, and the person reading the code must search for the var. This leads to errors and bugs.

So loud in here.

Noise is anything that adds to the source but serves not purpose. Good code has zero noise (with the exception of style dictated noise, though a note should always provide details on uncommon style and reason for use)

You have:

if (base <= 1) throw "Base must be greater than 1";
else if (base > 64) throw "Base must be less than or equal to 64";

If the first statement is true then the code is terminated at the throw. That makes the else redundant and just noise, so don't use it.

if (base <= 1) { throw new Error("Base must be greater than 1") }
if (base > 64) { throw new Error( "Base must be less than or equal to 64") }

Don't use blockless blocks.

Blockless blocks are a major source of bugs. Not only are they bugs waiting to happen, they are particularly hard to spot. There is a special place in the hell of a billion bugs for the person that introduced that in to languages.

// bad, no worse than bad.
if (something) doThat();
// or even worse than worse than bad.
if (something)
    doThat();
// and an extra notch of bad
if (something)
doThat()

// Good
if (something) { doThat(); }
// or
if (something) { doThat() }
// or
if (something) {
    doThat();
}

Vet your input

The two inputs from the question are strings. You neglect to test if base is NaN, and you do not check whether number contains only valid characters.

if(isNaN(base)) throw new TypeError("Base must be a number from 2-64 inclusive.");

The number should also be tested but as that will depend on the value of base, and to do a proper test means iterating all the characters that you will do in the function logic you should add the error in the while loop when you are doing the conversion.

Be type aware

The argument number is a string and as it is variable base, attempting to coerce it to a number can fail.

You have:

const negative = number < 0;
if (negative) number = -number;

This will not work if number = "-a"

Check for the sign as the first character of the string:

const negative = number[0] === "-";
if (negative) { number = number.substr(1) } // remove the minus sign

Did you test your code?

Looking at the function I instantly see that it will not work.  Your logic is completely wrong. You should have known that because you should have tested it and seen the wrong output for the given input. Always test your code before you let it out of your sight. You don't write half sentences nor should you write broken code. Code is broken until you have tested it not before.

The function as you have it does not allow easy testing. You should separate out the conversion so that you can automatically test it without having to modify your code.

Dont blindly follow the lead.

There is a tendency for node programmers to use nondescript variable names. This is a very bad trend and should be stopped. Out of context what is rl, or fs, only those in the know will understand. If I did not know better, the persistence of these abbreviations in nodeJS code would suggest a form of deliberate elitism.

Use descriptive names for variable. Just because everyone uses a particular abbreviation does not make it a good choice of name.

// bad
const rl = ...

// good
const readLineInterface = ...

This allows everyone to understand what the variable is, not just those in the know.

The rewrite

// Style note. Single line blocks do not include a ; before the closing } this is to comply with jsLint rule
// semicolons should be followed by a new line.

const readline = require('readline');

exports.pa11 = function () {
    const readLineInterface = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    function convertNumber(number, base){
        var value, digit, charIndex;
        const BASE_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/=";

        if (isNaN(base)) { throw new TypeError("Base must be a number from 2 - 64") }
        if (base < 2 || base > 64) { throw new RangeError("Base must be a number from 2 - 64") }

        const numberOrg = number;
        const negative = number[0] === "-";
        if (negative) { number = number.substr(1) } // remove the minus sign

        charIndex = number.length;  // start from least significant digit
        digit = 0;  // the current place of digit
        value = 0;  // the base ten value

        while (charIndex--) {
            const index = BASE_CHARACTERS.indexOf(number[charIndex]);
            if (index === -1 || index >= base) {
                throw new TypeError(`Number ${numberOrg} is not a base '${base}' number.`);
            }
            value += Math.pow(base, digit++);
        }
        value *= negative ? -1 : 1; // if negative negate result

        console.log(`The number ${numberOrg}, in base ${base} has the value ${value} in base 10.`);
        return value;
    }

    readLineInterface.question("Enter number: ", number => {
        readLineInterface.question("Enter base: ", base => {
            convertNumber(number, base);
            readLineInterface.close();
            process.exit();
        });
    });
};

Note

Many markers use automatic plagiarism systems that search the web for copied content. If you copy the above code as-is it is highly likely that your code will be flagged by such systems. You will have to modify it rather than copy and past it.

I have left one missing error check. If the input number string evaluates to a value that can not be accurately expressed as a Javascript Number then the result will be incorrect. You should test the result and ensure it is in safe bounds. Hint: look up Number.MAX_SAFE_INTEGER and its negative counterpart.


Lock-range code for Google Scripts/Sheets

It's not necessary to include SpreadsheetApp.flush() as the last command of the if blocks because there aren't any command to be executed after those blocks and Google Apps Script submits all the changes to the spreadsheet when the script execution ends. If you remove them, you will be saving three code lines.
On some scenarios using one sheet.getDataRange().getValues() is faster than having several sheet.getRange(...).getValue().
Using e.range.columnStart is faster than e.range.getLastColumn();


Some pointers:

You keep adding 2 numbers here: startingIndex + i, that could probably be avoided if you went for(int i = startIndex; i < lastIndex; i++){ where lastIndex would be startIndex + count
Since ++ happens post evaluation you could simply do buffer[startingIndex + i] = source[index1++];, it does not have to be a separate statement
Short circuit logic : if index2 >= maxIndex2, then you should probably have a  System.arraycopy copy that fills the rest into index1 and get out. You could the same for when index1 > maxIndex1 but obviously you would fill into index2 then

From a naming perspective, I would rather read upperIndex and lowerIndex than index1 and index2

Totally untested, I would try something like this:

private static void merge(int[] source, int[] buffer, int startingIndex, int count) {
    int lowerIndex = startingIndex;
    int lowerBound = startingIndex + count / 2;
    int upperIndex = lowerBound;
    int upperBound = startingIndex + count;

    for(int i = startingIndex ; i < upperBound ; i++){
        if(upperIndex >= upperBound ){
          System.arraycopy(source, lowerIndex , buffer, i, i - startingIndex );
          return;
        }
        if(lowerIndex >= lowerBound ){
          System.arraycopy(source, upperIndex , buffer, i, i - startingIndex );
          return;
        }
        buffer[i] = source[lowerIndex] < source[upperIndex] ? source[lowerIndex++] : source[upperIndex++]
    }
}


SVG is structured data and should therefore not require regex to work with it.  I would suggest that you work with either an XML or SVG-specific library in PHP which would let you parse in the input SVG, remove any unwanted nodes and then render it back out.

Here is a starting point for common PHP tools for working with XML that should be able to do what you want.

This also looks like a library that could meet your needs.


Get the Key of the highest Value in JavaScript object

I don't know about elegant, but you can omit the initial _(), use + to convert to number instead of parseInt and just pull out the iterator.

var iterator = function(p){return p[1];}
var maxKey = +_.chain(b).pairs().max(iterator).value()[0];
// Removed the | 0 since the keys are integers to begin with

Here's an alternate way to do it using ES5 Array.prototype.reduce and Object.keys. You can also use underscore's _.reduce and _.keys for compatibility. Note that this runs through the entire array, so any duplicates found will use the latest value.

var max = Object.keys(b).reduce(function(max,key){
  return (max === undefined || b[key] > b[max]) ? +key : max;
});

Making it more clear what we're doing, in case you aren't familiar of reduce, is to use Array.prototype.forEach (or _.each):

var max;
Object.keys(b).forEach(function(key){
  max = (b[key] > b[max]) ? +key : max;
});


class Node(object):

    def __init__(self, item, left=None, right=None):
        self.item = item
        self.left = None
        self.right = None

The parameters left and right are not used in the constructor!  Remove them, or actually use them.

    def _add(self, value):
        new_node = Node(value)

        if not self.item:
            self.item = new_node
        ...

Given self.item is unconditional set in the constructor, this first test seems unnecessary.

        elif not self.left:
            self.left = new_node
        elif not self.right:
            self.right = new_node

Your binary tree does not seem to have any ordering imposed on the left/right nodes.  If there is no left node, you create one even if the new value is larger than the current node.  Similarly, if there is a left node, but no right node, you create a right node even if the value is smaller than the current node.

        else:
            self.left = self.left._add(value)
        return self

Finally, if both left and right exist, you unconditionally add the new node to the left sub tree, which will create a very unbalanced tree.  Moreover, the newly created new_node is discarded, to be recreated by the _add() method one level down, so is wasteful.  And the sole purpose of return self seems to be so that there is a return value to assign to self.left, which results in the the original value self.left being assigned to itself, so again useless busy work.

  A binary tree does not have any ordering imposed - nodes are added in the following preference: root -> left -> right. Ordering is imposed i[sic] a binary search tree.  – Saurabh

With your sample code, adding the values 1 to 10 to your BinaryTree, you get the following "tree":

                           1
                          / \
                         2   3
                        / \
                       4   5
                      / \
                     6   7
                    / \
                   8   9
                  /
                10

This is not really a binary tree; it is a stick with leaves.  It could be represented as a list of tuples: [(1,3), (2,5), (4,7), (6,9), (8,), (10,)].

If you wish to create a general binary tree, which does not impose an ordering, you need to include methods for building the desired tree, such as finding the "5" node, and explicitly adding to the right branch.  A generic add_node() doesn't have enough detail to control how the tree is built.


Taking change - convergent iteration through iterate

Typically, where clauses don't include full type annotations, though this is mostly a matter of personal preference.
For prepending items to a list, prefer x:xs over [x] ++ xs.
In your "base case" of the recursive go function: go elem [] = [], elem is not used. Prefer _ in this case.
Your comment exceeds 80 characters in width. Again, a matter of personal preference. The note about passing an empty list returns an empty list is probably not necessary as this is very clearly the case from the code itself.

Here is how I would write this function:

takeWhileNotDup :: Eq a => [a] -> [a]
takeWhileNotDup [] = []
takeWhileNotDup (x:xs) = x:go x xs
  where
    go _ [] = []
    go previous (x:xs)
      | previous /= x = x:go x xs
      | otherwise = []


There is no need to iterate over the range. Consider a pseudocode:

sort numbers from the input file into an array A
N = size of collection
result = 0
for i in [0..N)
    find largest j (j > i) such that A[i] + A[j] < start
    find smallest k (k > i) such that A[i] + A[k] > finish
    result += k - j

Each find is \$O(\log N)\$ at worst. Overall complexity is \$O(N \log N)\$ regardless of the target range.


It seems I found better solution. All these buttons are located on ToolBar.

I can loop through the ToolBar and utilize the Name property on the buttons to compare with. So, I've changed it to:

  var
    LSelectionType, i: Integer;
    LButtonName: string;
  begin
    LSelectionType := 1;
    LButtonName := (Sender as TAction).ActionComponent.Name;
    for i := 0 to ToolBar.ButtonCount -1 do
    begin
      ToolBar.Buttons[i].Down := (ToolBar.Buttons[i].Name = LButtonName);
      if ToolBar.Buttons[i].Down then
        LSelectionType := i + 1;
    end;
    ...
  end;

UPDATE

Finally, I set proper Tag property and set property Grouped to True for buttons and changed code:

  var
    LSelectionType: Integer;
    LActionComponent: TComponent;
  begin
    LSelectionType := 1;
    LActionComponent := (Sender as TAction).ActionComponent;

    if LActionComponent is TToolButton then
    begin
      (LActionComponent as TToolButton).Down := True;
      LSelectionType := (LActionComponent as TToolButton).Tag;
    end;
    // and using LSelectionType
    ....
  end;


Enum vs lookup table for temporary and permanent teeth

I would recommend making an enum with properties, such as:

public enum DentitionType {
    TEMPORARY(1), PERMANENT(2);

    private final int id;
    private DetentionType(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public static DententionType forId(int id) {
        for (DententionType dentention : DetentionType.values()) {
            if (dentention.getId() == id) {
                return dentention;
            }
        }
        return null;
    }
}

This is an easy way of mapping your enum to an int (you can also use a 'char' or 'String' or whatever you feel like). Then you can inside your @Entity class use some JPA events to transform to/from enum and int.

Another solution is of course to simply use the @Enumerated annotation and automatically use the ordinal of the enum. Be aware however that there has been incidents where someone accidentally switched the order of the enums, which caused DIAMONDS to become black.


The script is extremely basic but it seems to me that it is also not secure. I have seen similar code that vulnerable to header injection, so it was possible for spammers to add a BCC header, and instead spam other people through your server (and your IP address will get blacklisted as a result).
Even a seasoned class like phpmailer has suffered nasty security bugs. Another article that touches on the issue: Why mail() is dangerous in PHP
Since $mailHeaders is injectable, I can provide an E-mail address like:
someone@attacker.com@\r\nBcc: someone@victim.com
and I should be able to send spam to someone@victim.com, with your unwitting assistance.
Validation of form fields in Javascript is not sufficient, it has to be performed server-side as well. Javascript is useful for instant, client-side validation to avoid back and forth exchanges with the server but cannot be considered a security feature since you don't control the client and can't trust it.
It is only a matter of time until your form is indexed by spambots, that will start pounding your server. The bots don't care about Javascript. Your script will not stop them. So basically everything you wrote in JS has to be implemented server-side in PHP. JS validation is nice to have but optional.
Since it appears that you are using Bootstrap, you could perhaps take advantage of the validation options available. Then you can also get rid of the inline CSS styling eg: $("#userEmail").css('border', '#e66262 1px solid');.
You can also use the required attribute in your mandatory HTML controls. Then the browser will prompt the user if some fields are empty, and will not submit the form. It is a small extra and costs nothing.
To sum up, I suggest that you read up a bit on header injection and don't reinvent the wheel. There is mature, open-source third-party code available for this kind of task. It will be more secure that your homemade attempt.
I seem to remember that there is also the possibility of nullbyte injection but can't remember the details right now.


Simulating gravitational attraction between bodies

Just a note on your commenting:

Should you be breaking XML comments up across lines like that?

/// <summary>
/// Class used for calculating
/// how an object orbits another
/// object.
/// </summary>

I feel that should be three lines:

/// <summary>
/// Class used for calculating how an object orbits another object.
/// </summary>

Likewise, I feel that the following comment:

/// <summary>
/// FixedUpdate is run once per frame.
/// FixedUpdate is used so that calculations
/// don't need to be multiplied by Time.deltaTime.
/// </summary>

Could be rewritten as:

/// <summary>
/// FixedUpdate is run once per frame.
/// </summary>
/// <remarks>
/// FixedUpdate is used so that calculations don't need to be multiplied by Time.deltaTime.
/// </remarks>

Personally, I think breaking comments along multiple lines like that makes it harder to read. You're eyes have to jump to unnatural places.

Likewise, the <remarks> bit is nice because those comments aren't shown in Intellisense, but they can still be placed in the generated XML documentation files.

The only other bit I would mention, is the use of this. You should either use it consistently, or try to limit it. Sometimes (especially in larger cases) it helps to clear things up. But if you use it for some of the properties and not others, it can have a negative impact.

I'm referring to the following:

Vector3 CalculateGravitationalForce()
{
    this.parentPosition = this.parentObject.transform.position;
    Vector3 force = this.parentPosition - transform.position;
    float distance = force.magnitude;
    float strength = (this.gravityConstant * this.parentMass * this.objectMass) / (distance * distance);
    force.Normalize();
    force = force * strength;
    return force;
}

Where does transform.position come from? The fact that you use this on all the other properties/fields of the class but not that one throws confusion into the mix. It's not a local variable, that much is true. But where exactly does it come from, is a little harder to notice right out of the box.

Again, these are all suggestions. Whether or not you like/use them is up to you, but this is how I would write it out.


Actually the only improvement I think you can make is that you use the chaining sugar, looks a lot better:

var item = _.chain(items.menuItems)
  .pluck('data')
  .flatten()
  .find(function(a){
    return a.title === 'title1-2'
  })
  .value()


Python 3 - Get n greatest elements in dictionary

Using the following test case, your code takes about 1 ms on my machine:

In [1]: import itertools
In [2]: import string

In [3]: d = dict(zip(itertools.product(string.ascii_lowercase, repeat=10),
             ([0] * i for i in range(1000))))
In [4]: %timeit get_n_longest_values(d, 3))
1000 loops, best of 3: 1.06 ms per loop

First, a short style comment: In Python, range has an implicit 0 as its first argument, so range(0, n) is the same as range(n).

You are doing this very manually, while it can be a bit faster when using built-in functions. I would first sort the items of the dictionary by the length of the values. (You cannot avoid going over the dictionary once. However this wastes some cycles, because it is a full sort, instead of a partial sort). Then you can just slice the sorted list and return the length of the values:

def get_n_longest_values_g(dictionary, n):
    longest_entries = sorted(
        dictionary.items(), key=lambda t: len(t[1]), reverse=True)[:n]
    return [(key, len(value)) for key, value in longest_entries]

This is much more readable and for the given test case performs better than your code by about a factor of 2:

In [5]: %timeit get_n_longest_values_g(d, 3)
1000 loops, best of 3: 514 µs per loop

Note that for this function, the output is actually sorted (descending), whereas yours is not.

Even for larger dictionaries, my function outperforms yours:

In [12]: import random
In [13]: d = dict(zip(itertools.product(string.ascii_lowercase, repeat=10), ([0] * random.randrange(10000) for i in range(10000))))
In [14]: %timeit get_n_longest_values(d, 3)
100 loops, best of 3: 10.2 ms per loop

In [15]: %timeit get_n_longest_values_g(d, 3)
100 loops, best of 3: 6.61 ms per loop

When n grows, your code becomes ever slower, because you iterate over the whole result in the worst case, whereas my code always sorts the whole dictionary anyways (same d as in the previous case):

In [18]: %timeit get_n_longest_values(d, 100)
10 loops, best of 3: 109 ms per loop

In [19]: %timeit get_n_longest_values_g(d, 100)
100 loops, best of 3: 6.27 ms per loop

There are a few possible routes of improvements left for this code. One could already at the beginning generate pairs of len(values), key, which can then be naturally sorted by Python, which should be slightly faster, as noted by @Peilonrayz in the comments. So, something like this:

def get_n_longest_values_g2(dictionary, n):
    return sorted([(len(value), key) for key, value in dictionary.items()],
                  reverse=True)[:n]

It is slightly slower than my previous function:

In [32]: %timeit get_n_longest_values_g2(d, 100)
100 loops, best of 3: 11.7 ms per loop

It has also a changed output (len(values), key, instead of key, len(values)).

Another possibility is to use your basic code and maintain a sorted result, so we can use binary search to insert the newest value and pop the smallest pair if needed, using the bisect module:

import bisect

def get_n_longest_values_gb(dictionary, n):
    result = []

    for key, value in dictionary.items():
        bisect.insort(result, (len(value), key))
        if len(result) > n:
            result.pop(0)

    return result

This performs somewhere between the other two approaches:

In [42]: %timeit get_n_longest_values_gb(d, 100)
100 loops, best of 3: 9.42 ms per loop

Note that its output is also reversed. It is limited by list.insert (which bisect.insort calls internally) being \$\mathcal{O}(n)\$ (as is list.pop(0), which we could get around by using a collections.deque, but a deque also has \$\mathcal{O}(n)\$ insert).

Lastly, one could use the heapq module, which has a nlargest function:

import heapq

def get_n_longest_values_gh(dictionary, n):
    return heapq.nlargest(n, ((len(value), key) for key, value in dictionary.items()))

This is the fastest for this particular test case, outperforming the sorted approach:

In [32]: %timeit get_n_longest_values_gh(d, 100)
100 loops, best of 3: 3.16 ms per loop

Note that its output is also reversed.

As stated in an answer to a similar question:

  The latter two functions perform best for smaller values of n. For
  larger values, it is more efficient to use the sorted() function.
  Also, when n==1, it is more efficient to use the built-in min() and
  max() functions. If repeated usage of these functions is required,
  consider turning the iterable into an actual heap.


SICP Exercise 1.3: Sum of squares of two largest numbers out of three, Prolog Version

The problem, as stated, has a completely straight-forward solution, because the problem statement is limited to numbers:

sicp1(X, Y, Z, SumSquares) :-
        msort([X,Y,Z], [_,A,B]),
        SumSquares is A^2 + B^2.

You can use this predicate every time the three numbers are fully specified, for example:

?- sicp1(1, 2, 3, S).
S = 13.

The problem though is that this code is not as general as it could be. It does not work for example if the arguments are variables:

?- sicp1(X, Y, Z, S).
ERROR: is/2: Arguments are not sufficiently instantiated

From a truly declarative solution, we expect valid answers even if arguments are only partially known.

Enter constraints. I show you a solution with CLP(FD) constraints. This means that the arguments are elements of the set of integers. Check out other constraint libraries like CLP(Q) to get solutions over different domains.

Working solution for SICStus, SWI etc.:

:- use_module(library(clpfd)).

sicp2(X, Y, Z, SumSquares) :-
        Max #= max(max(X, Y), Z),
        Median #= max(min(X, Y), min(max(X, Y), Z)),
        SumSquares #= Max^2 + Median^2.

Now, we can use this just like before:

?- sicp2(1, 2, 3, S).
S = 13.

However, we can also use it in other ways. For example:

?- sicp2(X, 3, 5, S).
...
S in 34..sup.

From this answer, you see that the sum of squares will be at least 34, no matter the eventual value of X.

When giving further constraints, you get more precise answers:

?- sicp2(X, 3, 5, S), X #< 4.
S = 34,
... .

This means that, if it is known that X is less than 4, then the result is certainly 34 in this case.

Thus, the solution using constraints is much more general, and it is just what we would expect from a truly declarative solution that can be queried in all directions and gives useful answers in all cases.


Creating an optimized, fully functional TextureManager in SDL

You don't need a texture copy.

Texture& getTexture(unsigned int ID);
// Texture getTextureCopy(unsigned int ID);

This works:

Texture&  t1 = tm.getTexture(1);  // Gets a reference.
Texture   t2 = tm.getTexture(2);  // Gets a reference but because t2
                                  // is an object copies it from the
                                  // original into `t2`

auto_ptr is deprecated

std::auto_ptr<SDL_Renderer>

Prefer the modern version std::unique_ptr it understands move semantics.

std::unique_ptr<SDL_Renderer, TypeThatKnowsHowToDeleteSDLRendor>  renderer;

Also std::unique_ptr and std::auto_ptr just call delete on the pointer. I am betting that the SDL library has a special function to delete render objects. In which case you need to add a class that knows what function to call.

Also std::unqiue_ptr can be used in containers:

typedef std::unordered_map<int, Texture*> atlasType;//cannot use auto_ptr in STL container !

But you don't even need to be using pointers. Texture is not polymorphic. Just create the object in the container (not the pointer).

std::unordered_map<int, Texture>  AtlasType;

Naming conventions.

It is usall to give User defined types an initial capitol letter. It is usual to give methods and member variables an initial lower case letter.

std::unordered_map<int, Texture>  AtlasType;
             //                   ^  Its a user defined type.
AtlasType                         textureAtlas;
             //                   ^ its an addressable object.

Prefer the new range based for

for (atlasType::iterator it = m_textureAtlas.begin(); it != m_textureAtlas.end(); ++it){
    delete (it->second);
}

As mentioned last time. Prefer auto, prefer std::begin/std::end over method calls. and prefer range based for over all of them:

//
for (auto it = std::begin(m_textureAtlas); it != std::end(m_textureAtlas); ++it){
    delete (it->second);
}

//
for(auto item: m_textureAtlas) {
    delete item.second;
}

//
std::for_each(std::begin(m_textureAtlas), std::end(m_textureAtlas),
               [](AtlasType::value_type& v){delete v.second;});

Compilation Failure:

 m_textureManager = TextureManager(m_pRenderer);
                               //  ^^^^^^^^^^^ that is not an auto_ptr

 // You have to create the auto_ptr object.
 std::auto_ptr<SDL_Renderer>   rend(m_pRenderer)
 m_textureManager = TextureManager(rend);

Note. When you give up ownership of the object you should not be using it from the original pointer again. The only way to access the render object should not be through the TextureManager that owns it. If you have kept another pointer to the renderer that you are cheating ownership semantics.

Writting a shard render object

class CRendWrap
{
    public:
        CRendWrap(SDL_Window* w, int x, int y)
            : SDL_CreateRenderer(w, x, y)
        {}
        ~CRendWrap()
        {
            if (rend != nullptr) {
                SDL_DestroyRenderer(rend);
            }
        }
        // Disable Copy
        CRendWrap(CRendWrap const&)             = delete;
        CRendWrap& operator=(CRendWrap const&)  = delete;
        // Allow Move
        CRendWrap(CRendWrap&& move)
            : rend(nullptr)
        {
            using std::swap;
            swap(rend, move.rend);
        }
        CRendWrap& operator=(CRendWrap&& move)
        {
            using std::swap;
            swap(rend, move.rend);
        }
    prviate:
        SDL_Renderer*   rend;
};

typedef std::shared_ptr<CRendWrap>   CRender;

// Usage.
CRender  renderer = std::make_shared<CRendWrap>(win, 10, 20);


Defining a class that behaves exactly like an `int`

I would make the bool operator explicit (and const)

The explicit will prevent the object being auto converted to bool in situations where you don't want it too. This may break with int type but is usually a better work match.

explicit operator bool() const  { return !!_i;                    }

I know how the !! works but it is obscure and a lot of people will raise an eyebrow. At least write a comment about it.

These methods should be const

operator int()    const { return static_cast<int>(_i);    }
operator double() const { return static_cast<double>(_i); }
//                ^^^^^

They do not change the state of the class.

All the assignment operator methods are defined wrong.

jd_int operator+=(jd_int jdi) { return _i += jdi._i; }

// Should be:

jd_int& operator+=(jd_int const& jdi) { _i += jdi._i; return *this; }

The op= is modifying the current object. Thus you should return a reference (not an object). Consequentially the return should return *this. There is no need to pass the input parameter by value (this could cause an unrequited copy). Rather pass the parameter by const reference to avoid this.

All the simple operator could be done better

jd_int operator+ (jd_int jdi) { return _i +  jdi._i; }

// Should be:

jd_int operator+ (jd_int const& jdi) { return jd_int(*this) += idi; }

Pass the parameter by const reference. Then use the op-assignment to do the work.

You define all the operators as members of the class. Personally I would also do this. But there is an argument for making the free standing functions.

id_int + int  => works.             (int will be converted to id_int then addition done)
int + id_int  => fails to compile.

If you convert the above members into free standing functions then you will get either side to auto convert.

The freestanding friend functions.

friend bool operator< (jd_int lhs, jd_int rhs);
...
friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);
friend std::istream& operator>>(std::istream& is, jd_int jdi);

You declare them in the function and then define them later. Why? These are trivial functions define them inside the class. Splitting the declaration and definition does not provide any benefit.

Also pass the parameters by const reference when you can.

friend bool operator< (jd_int const& lhs, jd_int const& rhs)         {return (lhs._i <  rhs._i); }
...
friend std::ostream& operator<<(std::ostream& os, jd_int const& jdi) {return os << idi._i;}
friend std::istream& operator>>(std::istream& is, jd_int& jdi)       {return is >> idi._i;}

I think you are missing a couple of operations (binary and and binary or sprint to mind).

I hate it when people use underscore as the first character of an identifier.

int _i;

There are some complex rules around its usage. Not everybody knows these rules exactly so something best avoided. Also why i why not value at least that is a bit more meaningful.


Determining whether a loop iterated at least one element in generator function

Separate Your Concerns

The function at the moment does two things: finds matching customers and checks that it's nonempty. Let's instead add a default checker:

from itertools import tee

def iter_or_default(iterable, dflt):
    orig, test = tee(iter(iterable))
    try:
        next(test)
        # if we're still here, the iterable is non-empty
        yield from orig
    except StopIteration:
        # iterable was empty
        yield dflt

And now, we just use that:

@property
def source_customers(self):
    """Yields source customers, or the instance customer if none found"""

    source_customers = (c.source_customer for c in
         RealEstatesCustomization.select().where(
            RealEstatesCustomization.customer == self.cid))
    yield from iter_or_default(source_customers, self.customer)


I have been using php for over 10 years and never found a need for a session wrapper, but maybe you find it easier/better.

There are a few improvements that could be made with your code

If we are checking to see if the session has a key, a simpler test is

public static function has($Key)
{
    // return (bool)(isset($_SESSION[$Key])) ? $_SESSION[$Key] : false;
    return array_key_exists($Key, $_SESSION);
}

The get function here would probably be more useful with a default value option then just returning false.

public static function get($Key, $default=false)
{
    return (self::has($Key)) ? $_SESSION[$Key] : $default;
}

The del function, I am unsure what you are trying to achieve by returning false, but returning nothing if it isn't set?
Personally I wouldn't bother to check if it is set or not, just unset it, and return nothing. I would also call it delete, so it is painfully obvious to the use what it does

    public static function delete($Key)
    {
       if(isset($_SESSION){
            unset($_SESSION[$Key]);
       //         return false;
       }
    }

The dump function, why do you throw an exception if the session doesn't exist, but not anywhere else if the session doesn't exist? I would re-write it like a guard clause rather then having a return halfway through the function.

public static function dump()
{
    if(!isset($_SESSION))
    {
        throw new \Exception("Session is not initialized");
    }

    print_r($_SESSION);
}

Another useful function you might add is get_once. I do something similar for when I store an error message in the session, then redirect to a new page and display the error message. After that the error message is no longer relevant so I remove it from the session.

public static function get_once($Key, $default=false)
{
    $value = self::get($Key, $default);
    self::delete($Key);
    return $value;
}

Other things you could do is to manage different "namespaces" (maybe not the best word to describe it) within a session.

// keep in mind if you do this, you can't use static everywhere like you have

function __construct($namespace) {
    $this->namespace = $namespace;
}

function set($key, $value) {
   $_SESSION[$this->namespace][$this->key] = $value;
}

// Then you can use simple keys that don't overwrite each other
$user_session = new session('user');
$user_session->set('name', 'Donald Duck');

$page_session = new session('page');
$page_session->set('name', 'Home Page');


Best approach for converting list of nested dictionaries to a single dictionary with aggregate functions

Try:

from collections import defaultdict
from datetime import date, datetime
from typing import DefaultDict, Set, List, Dict

DefaultSet = DefaultDict[date, Set[str]]

def default_set() -> DefaultSet:
    return defaultdict(set)

aggregated: DefaultDict[str, DefaultSet] = defaultdict(default_set)

for entry in db_data:
    start_date: date = datetime.fromisoformat(entry['start_time']).date()
    result: Dict[str, List[str]] = entry['results']
    for k, v in result.items():
        aggregated[k][start_date].update(v)

grouped_data: Dict[str, Dict[date, int]] = {
    k: {gk: len(gv) for gk, gv in group.items()}
    for k, group in aggregated.items()
}

Notes:

I do not know if this is faster, but it's certainly simpler
If you're able, maintain the output with actual date keys
Your data are better-modeled by a defaultdict of defaultdicts of sets.
I used a bunch of type hints to make sure that I'm doing the right thing.


Use of metaclass python to override __init__ and instantiate the class later on

From the looks of it you have objects that you only want to partially create, when you create them the first time.

To do this you can use functools.partial:

quail.run(
    partial(quail.SolutionPacked, path='Allum1'),
    partial(
        quail.Installer,
        name='Allum1',
        icon='icon.jpeg',
        binary='allum1',
        console=True
    ),
    partial(
        quail.builder.Builder,
        partial(quail.builder.CmdIcon, 'icon.ico'),
        partial(quail.builder.CmdZip, solution_path, 'solution.zip')
    )
)

Yeah, this isn't really that attractive. However it is what you want.

And so you can use a metaclass to perform this action automagically.
I'd remove the _get_instance stuff from your Egg, remove InstanceEgg and use a partial call.

from functools import partial

class PartialInit(type):
    def __call__(cls, *args, **kwargs):
        return partial(super().__call__, *args, **kwargs)

@six.add_metaclass(PartialInit)
class Test:
    def __init__(self, a, b):
        print('init {} {}'.format(a, b))

t = Test('a')
print('Made t: {}'.format(t))
t('b')


Getting the unique identifier from a given login username

catch(Exception)
{
    return null;
}

You should never do this. Exception means that there is some sort of problem. And you shouldn't ignore problems, you should learn about them and do something about them as soon as possible.

What you should do is that at first, don't catch any exceptions. Then, if you find out that some exceptions actually do happen under normal conditions, then handle those, but only those.


Find the largest element in a sorted array with increasing consecutive differences, smaller than x, in O( log(logmax_value)

#include <bits/stdc++.h>

Not a good start.  This is not a standard C++ header; it's an artefact of your compiler's implementation, so non-portable, and subject to change without notice.  Use the Standard-specified headers to define the library identifiers you need (any good reference tells you which to include).

using namespace std;

Please don't bring all of the Standard Library identifiers into the global namespace.  It makes it much harder to reason about your code, and in extreme cases, can cause future versions of C++ to silently change the meaning of the program (when a new library function becomes a better match than one you define, for example).

const int n=50000001;

Where does this magic constant come from?  What does it mean? n is not very descriptive for a global constant.

int arr[n];

Another global variable with an unhelpful name.  What's it for?  Why does it need to be global?  Why are we using C-style arrays rather than std::array or std::vector?

int binarysearch_lowerbound(int begin, int end, int x){

This function isn't very reusable, as it depends on the global arr.  If we passed pointers instead of integers for begin and end, then we would be able to find a value in any array we like.  And why are we passing signed integers?  Why would a negative value ever be useful?

    int ans=end;

We don't need this variable, since at the end of the loop ans==begin==end.  So just return end when we get there.

    while(begin<end){

Nothing wrong with this line (although I would like the operators to have more "room to breathe").

      int mid=(begin+end)/2;

There's a problem here that's frequently found in binary search algorithms.  The sum could overflow (which in signed integers, is Undefined Behaviour).  A better way, given that we know begin is less than end, is
        int mid = begin + (end - begin) / 2;

This also has an advantage of being legal when we replace the indices with pointers.
That said, what we have here is plain binary search.  We haven't used the information about the distribution (namely that the curve is concave, so all values are no higher than the straight line joining begin and end).  We're only going to scale as O(log n).

int main() {
    int N;
    cin>>N;

Again, an utterly unhelpful variable name.  I had to read the rest of main() to determine that this is supposed to be the array size to read.
After reading from a stream, we must confirm that the stream is not in error before using the value we read (e.g. if (!std::cin) { return EXIT_FAILURE; }).

    for (int i=0; i<N; i++){
        cin>> arr[i];
    }

If we'd used a std::vector for this, we could replace that loop with a simple standard copy:
std::copy_n(std::istream_iterator<int>(std::cin), N, std::back_inserter(arr));

Again, we need to check the error state after reading.

    int q;
    cin>>q;

What's q?  I'm guessing a query into the array we have read.

    for (int i=0; i<q; i++){
        int x;
        cin>>x;

No, q must be the number of queries, and x is the actual query.  These unhelpful names are really making the code harder to follow!

        int k;

Why declare k here?  It's best to declare and initialise variables together, to reduce the risk of using it before it's initialised (though any decent compiler will warn if you do that).

        int begin = x/(arr[N-1]-arr[N-2]);
        int end = x/(arr[1]-arr[0]);

Here, we're using gradient to estimate the bounds for our search, but I'm not convinced the calculation is correct (shouldn't begin be subtracted from N?).  When it has been corrected, I think we should be doing this inside binarysearch_lowerbound() at every iteration, since each subarray obeys the constraint on its shape.

        if(end>N-1){
            end=N;
        }
        k=binarysearch_lowerbound(begin,end,x);
        cout<<arr[k-1]<<endl;

There's no need to flush output using std::endl.  Just output an ordinary return "\n" and let the stream do its buffering.

    }
    return 0;

In C++, we're allowed to omit return 0; from the end of main() (but only main(), not any other function).  Success is assumed if we run off the end of the main function.

Modified code
Fixing the faults (other than the algorithm to reduce the search space, which is your own responsibility), I get:
/* Constraints (TODO: express using C++20 Concepts):
 *  * Iter must be a random-access iterator
 *  * Its value type must be an arithmetic type
 */
template<typename Iter, typename T>
Iter binarysearch_lowerbound(Iter begin, Iter end, const T x)
{
    --end;                      // make an inclusive range
    while (begin < end) {
        // TODO: improve algorithm to use curve constraint
    auto mid = begin + (end - begin + 1) / 2;
        if (x <= *mid) {
            end = mid - 1;
        } else {
            begin = mid;
        }
    }
    return begin;
}

#ifdef TEST

#include <array>
#include <cassert>
#include <iterator>

int main() {
    auto check = [](auto collection, auto value)
                 { using std::begin; using std::end; // for argument-dependent lookup
                     return *binarysearch_lowerbound(begin(collection), end(collection), value) ; };
    assert(check(std::array{ 0, 1, 1, 5, 10 }, 11) == 10);
    assert(check(std::array{ 0, 1, 1, 5, 10 },  8) == 5);
    assert(check(std::array{ 0, 1, 1, 5, 10 },  5) == 1);
    assert(check(std::array{ 0, 1, 1, 5, 10 },  -1) == 0);
}

#else  // not test

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

int main()
{
    using value_type = int;     // would work for doubles, rationals, etc

    std::size_t array_size;
    if (!(std::cin >> array_size)) {
        return EXIT_FAILURE;
    }
    std::vector<value_type> values;
    values.reserve(array_size);
    std::copy_n(std::istream_iterator<int>(std::cin), array_size,
                std::back_inserter(values));
    if (!std::cin) {
        return EXIT_FAILURE;
    }

    std::size_t query_count;
    if (!(std::cin >> query_count)) {
        return EXIT_FAILURE;
    }

    while (query_count-->0) {
        value_type query;
        if (!(std::cin >> query)) {
            return EXIT_FAILURE;
        }
        std::cout << *binarysearch_lowerbound(values.begin(), values.end(), query);
    }
}

#endif


improve performance of recursive function in c# method

Vast swaths of this code have no apparent use. Cutting out the code that does not appear to have an effect, you seem to be left with:

public void SerializeInsertCache(object item)
{
        Type type = item.GetType();
        PropertyInfo[] properties = type.GetProperties();

        foreach (var property in properties)
        {
            SerializeInsertCache(property);

        }

       SaveInCache(item);
}

Ben Voigt's point about not repeating reflection might look something like this:

private Dictionary<string,PropertyInfo[]> typeProperties = new Dictionary<string,PropertyInfo[]>();

public void SerializeInsertCache(object item)
{
    Type type = item.GetType();
    string name = type.Name;
    PropertyInfo[] properties;

    if (!typeProperties.TryGetValue(name, out properties))
    {
        properties = type.GetProperties();
        typeProperties.Add(name,properties);
    }

    foreach (var property in properties)
    {
        SerializeInsertCache(property,typeProperties);
    }

   SaveInCache(item);
 }

However, that said, I also think this is overcomplicating the problem. Why are you wanting to serialize these things in the first place? If they're being kept in memory, there is almost certainly a better approach (which we can't suggest until we know more about what problem you're solving).


Some comments:

Use the built-in database promise support in mysql2 rather than promisify stuff yourself.
In Model, don't hide low level database errors.  If the database has an error, let the caller see the error.  It's up to the caller what to do with errors.
There's no reason for your Model.getStats() to be async.
Service should use promises to communicate back the results, not a callback.  That's the modern way to handle asynchronous results.  When you already have a promise, don't introduce a plain callback.
In Controller.getStats(), when you get an error and do res.send(err) and then res.json(result).  You can't call both of those.  You send one response and only one response for each request.  Then, your code doesn't send any response when there is no an error.
Log every error somewhere so you can diagnose server problems when they are occuring.
As currently shown, there's no reason for Controller.getStats() to be async.  You only need a function to be async if you need to use await or you're trying to use async to catch synchronous exceptions for you.  It appears you are throwing async in the function definition any time you have an asynchronous operation.  That's not the right reason to use async on your functions.
Performance/speed of this type of code is largely going to be determined entirely by your database configuration and performance as there's nothing in this code that really influences the performance/speed much.  You aren't doing any processing of the data here.  The extra Service layer isn't adding much value, but also probably doesn't really change much compared to the DB performance.


Cross validation of gradient boosting machines

You didn't use enumerate for your cv loop, I assume you tried this and found it didn't work:

for i, train, test in enumerate(cv):

To understand this, you need to know what enumerate is actually doing. It's wrapping each element of cv in a 2 item tuple, with index as the first item and the element from the iterable in the other. Basically it's using this structure: (i, (train, test)).

Fortunately this means you can get the result you need with just one modification:

for i, (train, test) in enumerate(cv):

Now it can extract all 3 values correctly without error. Even though you want i to start at 1, I find this to be more clear and readable than a manually incrementing value. You can just make the allowance to push the i value up by 1.

Also you're manually concatenating strings when you should use str.format. It allows you to insert values into strings, this is how you'd use it:

    print('FOLD : {}-{}'.format(i, n_folds))

format will replace any {} with the parameters passed to it. It will also automatically try to call str on any objects that can be turned into strings so you no longer need those manual calls.

Lastly, you don't need to wrap your time expression in brackets, it returns fine without it and it's more Pythonic to leave out the brackets.

return val_scores, time() - t

You should read the Python style guide, it has a lot of info about Pythonic style coding. You have it mostly correct, but some lines are a bit long and sometimes you should put more whitespace in (eg. time()-t -> time() - t).


Array splitting in sub-arrays of consecutive elements

You should preallocate the cs cell array:

[v,x] = find(diff(a)>1); %find "jumps"
xx = [0 x length(a)];
cs = cell(length(a)+1,1);
for ii = 1:length(xx)-1
   cs{ii} = a(xx(ii)+1:xx(ii+1));
end

Style comments:

Try to keep consistent formatting, either put spaces around all equal signs, or around none.
Terminate statements with a semicolon to prevent your function producing output to the command window.


"Egyptian" brackets is uncommon practice for C#. You should place an opening brace on separate line.

I suggest to use Dictionary every time you deal with mapping:

private const string ZipExtension = "zip";
private const string PdfExtension = "pdf";

private static readonly Dictionary<string, Func<IPack>> PackCreators =
    new Dictionary<string, Func<IPack>>(StringComparer.OrdinalIgnoreCase)
    {
        [ZipExtension] = () => new ZipPack(),
        [PdfExtension] = () => new PdfPack()
    };

Then you can obtain an instance of pack with this code:

if (!PackCreators.TryGetValue(extension, out var packCreator))
    throw new InvalidOperationException("Invalid file type.");

var pack = packCreator();

Once you've got a pack instance you can perform all actions with it inside using block:

using (pack)
{
    pack.Open(inputStream);
    // ...
}

which eliminates the need to define pack outside of try-finally and the need of try-finally itself with explicit pack disposing.

You calculate i % numPages multiple times in your loop. Define a variable and use it:

var remainder = i % numPages;

if (remainder == 0)
// ...
$"{groupId}/{remainder }"
// ...
if (remainder == numPages - 1)


Parallelized Sobel algorithm using OpenMP

Avoid using namespace
Especially for large namespaces such as std, bringing so many identifiers into scope is dangerous.  Prefer to import just the identifiers you need, and/or qualify at use; as it is, I get a compilation failure:
195834.cpp: In function ‘int main(int, char**)’:
195834.cpp:81:5: error: reference to ‘end’ is ambiguous
     end = omp_get_wtime();
     ^~~

Don't include <stdio.h> and <time.h>.
When writing new code, prefer <cstdio> and <ctime>, which brings the names into the std namespace.  Even better, omit these includes entirely, as we don't need them.
And do include <cmath>, so we have a declaration for std::abs().
Don't put everything in main()
There's three parts to this program.  It's easier to follow if we split the input and output from the processing.
Avoid global variables
Part of the problem with end above is that it's declared global when it has no right to be.  Keep the scope of your variables as small as reasonably possible (and give them more meaningful names!).  Similarly, the kernels can be declared within the function:
static const int x[3][3] = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 }};
static const int y[3][3] = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 }};

Use the correct output streams
Use std::cerr for reporting errors, and std::clog for other diagnostics.
Check argv[1] is valid before using it.
We have
Mat initialImage = imread(argv[1], 0); // DANGER

// ...

if(argc != 2 || !initialImage.data)

We hit undefined behaviour if we access argv[1] before discovering that argc < 2.
Use the correct image for the y-gradient
We should be using initialImage, not finalImage to compute yValOfPixel, otherwise we'll always get zero.
Use a bigger work unit
You'll get better parallelisation if you make the outer loop a parallel-for, rather than the inner loop.  Since each row is the same length, you're better off dividing the work into bigger chunks
Hard-code the Sobel coefficients
Since this isn't a general kernel convolution, we can help the compiler by using the constants in-place.  This allows the multiplication by small constants to be replaced by addition or subtraction (or omitted entirely for the six 0s).
Use standard functions to limit values
Instead of the ad-hoc test for sum exceeding 255 (and no test for below zero), we can use std::clamp() (from <algorithm>).

Modified code
#include <algorithm>
#include <cmath>

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>

cv::Mat sobel_transform(const cv::Mat& input)
{
    cv::Mat finalImage = cv::Mat::zeros(input.size(), input.type());

#pragma omp parallel for
    for (int j = 0; j < input.rows-2;  ++j) {
        for (int i = 0;  i < input.cols-2;  ++i) {
            // applay karnel in x direction
            int xValOfPixel =
                -     (int)input.at<uchar>(j, i    ) +     (int)input.at<uchar>(j + 2, i    )
                - 2 * (int)input.at<uchar>(j, i + 1) + 2 * (int)input.at<uchar>(j + 2, i + 1)
                -     (int)input.at<uchar>(j, i + 2) +     (int)input.at<uchar>(j + 2, i + 2);

            // apply karnel in y direction
            int yValOfPixel =
                - (int)input.at<uchar>(j, i    ) - 2 * (int)input.at<uchar>(j + 1, i    ) - (int)input.at<uchar>(j + 2, i    )
                + (int)input.at<uchar>(j, i + 2) + 2 * (int)input.at<uchar>(j + 1, i + 2) + (int)input.at<uchar>(j + 2, i + 2);

            int sum = std::clamp(std::abs(xValOfPixel) + std::abs(yValOfPixel), 0, 255);

            finalImage.at<uchar>(j, i) = (uchar)sum;
        }
    }

    return finalImage;
}

#include <omp.h>
#include <iostream>
int main(int argc, char** argv)
{
    if (argc != 2) {
        std::cerr << "Usage: ./sobel imagePath" << std::endl;
        return 1;
    }

    const cv::Mat initialImage = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
    if (!initialImage.data) {
        std::cerr << "Failed to read image" << std::endl;
        return 1;
    }

    double start_time = omp_get_wtime();
    const cv::Mat finalImage = sobel_transform(initialImage);
    double end_time = omp_get_wtime();

    std::clog << "Time: " << end_time - start_time << std::endl;

    // display the images
    cv::namedWindow("Initial Image", cv::WINDOW_AUTOSIZE);
    cv::namedWindow("Final Image", cv::WINDOW_AUTOSIZE);
    cv::imshow("Initial Image", initialImage);
    cv::imshow("Final Image", finalImage);

    cv::waitKey(0);
}


Why not just pass the data type you are looking for as a second argument to get_Type() then call the Defines() or similar method inside to verify it is the correct type? You can even provide a default data type should you use one more frequently.

function get_Type( $value, $DataType = VARCHAR ) {
    if( ! $this->Defines( $DataType ) ) { return FALSE; }

    //rest of method
}

Since you only want to test a given "DataType", I'd rewrite Defines() to use in_array() rather than loop through all the constants manually. Which BTW, you don't need to declare the $key=> bit in a foreach loop unless you are actually going to use the key.

function Defines( $const ) { return in_array( $const, $this->getConstants() ); }

I wrote this non-static, don't know if it needs to be static or not, but I tend to avoid static if at all possible.

I'd also like to point out that your method names conflict with PHP functions or aren't very descriptive. With the former you run the chance of your code conflicting with something else, or confusing people as to its purpose. With the latter you just confuse people. define() is a PHP function, so Defines() is close enough that it might cause issues or become confusing. get_Type() looks too much like you are fetching the data type rather than comparing it.

I hope this answer helps, if not then I'd add those last two comments to your actual question so more people might be able to help. That's what helped me to understand what you were trying to accomplish a lot better than the original explanation. If I actually understood it. Anyways, it seems much clearer now. Good Luck!


A more efficient way to make JQL (Jira Query Language)

Instead of passing parameters to this function you can pass a single object and iterate through it.

// instead of this
makeJQL("status", "project", "priority", "description", "summary");

// Try something like this
makeJQL({
    status: "status",
    project: "project",
    priority: "priority"
});

And to itinerate the object passed to the function you can use Object.keys():

makeJQL: function(jqlObject){
    var arr = new Array();
    Object.keys(jqlObject).forEach(function(key) {
          array.push(key + "="+'"'+ jqlObject[key] +'"');
    });
}

Other good practice would be implement a function for each request in your application, creating a makeSomethingJQL will increase the readability of your code.


OpenVPN Login Bash Shell script for DD-WRT router

Be paranoid about $PATH
It's a good idea to start this script with
PATH=/usr/bin:/bin

Also consider using full paths for programs.
Get the shell to check some errors
set -e -u

Use lower-case for variables
Upper-case is used for communicating well-known environment variables between programs.  Prefer lower-case for our own internal shell variables, to avoid any conflicts.
Simplify the valid-character checking
The while-do loop could be a simple grep:
if /bin/grep -q '[^-_a-zA-Z0-9]' "$1"
then exit 1
fi

With set -e, that's simply
! /bin/grep -q '[^-_a-zA-Z0-9]' "$1"

To be honest, I'm not convinced this checking is needed, provided we don't pass the username as a regular expression - see "Match exactly" below.
Options to echo are not portable
Consider printf '%s' instead (or, in Bash, <<< redirection)
Consider for instead of while for counted loop
With Bash, we could use an arithmetic for loop.  For standard shell, consider
for i in $(seq 10)
do
     hashpass=$(printf '%s%s' "$hashpass" "$hashpass" | \
                /usr/bin/md5sum | /usr/bin/cut -d' ' -f1)
done

You could instead write a filter function and just put that in the code 10 times (which might work slightly faster, as parts can work in parallel, and built-in read is better than starting a process to remove the filename part of the output):
function hashround() {
    local hash rest
    read hash rest
    printf '%s%s' "$hash" "$hash" | /usr/bin/md5sum
}

hashpass=$(printf '%s%s' "$Username" "$Password" | /usr/bin/md5sum \
           | hashround | hashround | hashround | hashround | hashround \
           | hashround | hashround | hashround | hashround | hashround \
           | /usr/bin/cut -d' ' -f1)

(We could even eliminate that final cut if we agree to use it as ${hashpass%% *} to remove the second field as a shell substitution.)
Match exactly
Instead of passing a regular expression to the final grep, use grep -F, and also match the entire line (-x):
if /bin/grep -Fxq "$Username:$hashpass" "$users"
then
    echo "User Authenticated." >&2
    exit 0
fi

I've also redirected the output to standard error stream, so it doesn't interfere with actual output.


jQuery plugin creation and declaration for usage with $(). or $

Since your function - as far as I can tell - doesn't rely on a jQuery collection, I'd stick to always using "1 true way" of calling it.
I.e. I assume that

$("some > selector").formArrayToObject(arr) === $.formArrayToObject(arr);

that is, the two ways of calling it give the same exact result.

If that's the case, just use $.yourFunction and only that. Having two invocations that should be semantically different but actually aren't is just confusing.

For instance, jQuery doesn't have both $.ajax() and $(...).ajax() simply because the latter doesn't really make sense; the $.ajax function isn't dependent on a certain context or selector, so why would you call it as if it was?

(besides, your second declaration in the code above is broken; it ignores arguments)


The problem is that angular.copy is a really slow function (discussion here: https://github.com/angular/angular.js/issues/11099), in order to copy the array without references you could also do something like this:

var newData = JSON.parse(JSON.stringify($scope.playingField.data));

This should be a big improvement in speed.


Make To and From date range picker using jQuery UI

Instead of destroying and recreating the datepickers, use the (3rd) option method (e.g. .option('maxDate', selectedDate)) to set the minDate/maxDate options when appropriate.

Also, by utilizing the onSelect option, which receives as arguments the selected date and the datepicker instance, instead of using an onChange handler, MomentJS can be eliminated.

Lastly, the two id selectors can be combined in the same jQuery call:

$('#Start, #End').datepicker(datepickerConfiguration);

See the simplified code below.

Another option might be to consider a daterange picker UI widget like this one but perhaps the current UI is desired.

//use this one handler for both Start and End Date pickers
var onDateSelect = function(selectedDate, input) {
  if (input.id === 'Start') { //Start date selected - update End Date picker
    $("#End").datepicker('option', 'minDate', selectedDate);
  } else { //End date selected - update Start Date picker
    $("#Start").datepicker('option', 'maxDate', selectedDate);
  }
};
var onDocumentReady = function() {
  var datepickerConfiguration = {
    dateFormat: "dd/mm/yy",
    onSelect: onDateSelect
  };
  ///--- Component Binding ---///
  $('#Start, #End').datepicker(datepickerConfiguration);
};
$(onDocumentReady);  // jQuery DOM ready callback registration
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

Start Date: <input type="text" id="Start">

End Date: <input type="text" id="End">


Some notes:

self: You write self.attribute to access attributes. I won't say that's bad practice, not at all, mainly because it's easier to see if you're accessing local variables or instance methods. However, in Ruby it's idiomatic not to use self in this case.
variable.nil?: this is something we often see but 99% of the time is unnecessary verbose. You want to know if a variable is not set? write !variable. The only case a explicit nil? is needed is when you want to tell false from nil, not the case here.
Layout: Don't write long lines, 80/100 is a sound limit. It usually pays off in form of clarity also: in can_deliver? for example, if you break on the || operator the boolean expression is much more clear.
Early returns: return unless self.can_deliver?. Again, I won't say that's bad, in a language that has no syntax for guards (like other languages have), it's a handy way to do early returns when pre-conditions are not met. As a rule of thumb, however, I'd recommend to write a full conditional. Yeah, I know, it's more verbose and you get an extra indentation level, but on the other hand the layout of the function/method helps understanding what the method it's doing.
The cool thing about the way you wrote can_deliver? (using an expression instead of a bunch of imperative returns) is that you can apply boolean algebra. Notice here than (!p && !q) || (!p && q && q < t) -> !p && (!q || q < t). Of course this kind of simplifications must only be done when the resulting expression is at least as declarative as the original (we are not trying to save some NAND gates here). If you read it out loud and it makes sense then it's ok.
You have two (and probably more throughout the code) almost identical begin/rescue blocks. That's a call for abstraction (it this case an abstraction using block wrappers).
Don't write rescue Exception, that's a common pitfall. Check this SO question.
Shouldn't deliver! return something? how would the caller know if it was successful? you should always return something, either a value (a boolean seems fit in this case) or, yes, return nil but raise an exception on error. Personally I like to return values and leave exceptions for really exceptional things (like, I don't know, the hard disk exploded).

Applying all these points, and with a declarative approach in mind, I'd write:

class GiftCard
  def can_deliver?
    !sent_at && (!scheduled_at || scheduled_at < Time.now)
  end

  def deliver!
    can_deliver? && send_card_code_email && send_gift_card_email
  end

private

  def comment_on_exception(msg)
    yield
  rescue => exc
    logger.error(msg)
    line_item.order.comments.create!(:content => msg)
    false
  end

  def send_card_code_email
    comment_on_exception("Could not send email gift card #{id}") do
      Notifier.gift_card_code_mail(self).deliver
      update_attribute(:sent_at, Time.now)
    end
  end

  def send_gift_card_email
    comment_on_exception("Could not send deliver confirmation email gift card") do
      Notifier.gift_card_delivered(self).deliver
    end
  end
end

If you found some of these advices useful, take a look at the RubyIdioms page I maintain (and its RubyFunctionalProgramming companion). Comments most welcome.


Compose in Javascript - Go ahead with this example?

Interesting question,

from your comments inside the code you seem to not have written the code or have heavily borrowed from somebody else's code..

From a high level I have only a  few misgivings:

Do not modify standard JS objects, so do not add compose to the prototype of Function,  I grant you that it looks cool but it will bite you at some point
myTV instanceof asSoundReproducer does not work, so figuring what kind of object you are dealing with can be painful ( this is a drawback from not using standard js OO )
You have some provision for passing parameters to functions with argFn.apply(this,arguments) but the function signatures might look ugly since you do not cut out argFn from arguments
When reading up on composing, I prefer much to be able to compose in one go like TV = compose( asSoundReproducer, asMicroSystem );
I am not sure what as stands for in your function names, I would drop anything that resembles Hungarian notation.

This counter proposal is more complicated, but handles multiple constructors in 1 go, amd  provides support for parameters and typeof.

function merge(object, boltOn) {
  //Simply merge the properties of boltOn into object, overriding existing properties
  for(var property in boltOn)
    if(boltOn.hasOwnProperty(property))
      object[property] = boltOn[property];
  return object;
}

function compose(/*Constructor1, Constructor2, ..*/) {
  //Keep a closure reference for later
  var constructorReferences = arguments;

  return function ComposedConstructor(/*parameter1, parameter2, ..*/) {

    //Clone the constructors, we will modify the clones
    var constructorClones = Array.prototype.slice.call(constructorReferences).map(function(Constructor) {
      return new Object(Constructor);
    });

    var constructor = constructorClones.pop();
    //Set up the prototype chain, without loosing the original prototypes thru `merge`
    while(constructorClones.length) {

      var nextConstructor = constructorClones.pop();
      nextConstructor.prototype = merge(new constructor(arguments), nextConstructor.prototype);
      constructor = nextConstructor;

    }
    //Call the first constructor with the arguments provided to the constructor
    constructor = constructor.bind.apply(constructor, [null].concat(Array.prototype.slice.call(arguments)));
    return new constructor();
  };
}

function A(name) {
  this.a = name;
  console.log(arguments);
}
A.prototype.sayA = function() {};

function B() {
  this.b = 2;
  console.log(arguments);
}
B.prototype.sayB = function() {};

function C() {
  this.c = 3;
  console.log(arguments);
}
C.prototype.sayC = function() {};

var O = compose(A, B, C);
var o = new O('Samsung');

// {[object Object] { a: "Samsung",b: 2,c: 3,sayA: function,sayB: function,sayC: function}
console.log(o);
console.log(o instanceof A); //true
console.log(o instanceof B); //true
console.log(o instanceof C); //true


Your implementation is missing some basic validation. A public method should always validate its passed in arguments. Assume an IEnumerable<int> will be passed containing 10 elements

with displaceCount == 10. You won't see an exception if it is a "true"  IEnumerables<int> but you will receive wrong results.

A test with

IEnumerable<int> source = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
source = source.Where(i => i > 0);
EnumerableDisplacer dispatcher = new EnumerableDisplacer();
var result = dispatcher.Displace(source, 10).ToList();

will result in a List<int> containing the 20 elements { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }

passing

IEnumerable<int> source = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
EnumerableDisplacer dispatcher = new EnumerableDisplacer();
var result = dispatcher.Displace(source, 10).ToList();

will result in an InvalidOperationException in the second while loop at yield return enumerator.Current; because the enumeration has ended already.

You have two choices to do the input validation:

checking the count of items contained in source against displacedCount which will result for a "true" IEnumerable<T> in iterating over the elements twice

or

convert the source to an collection type like e.g an array and check its Length property against displacedCount which will result in iterating over the elements twice  as well.

I would go with the second choice because it would make the whole method easier (IMO) because you wouldn't need any other datastructure like the LinkedList.

This would result in

public class EnumerableDisplacer
{

    public IEnumerable<T> Displace<T>(IEnumerable<T> source, int displaceCount)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }

        var sourceArray = source.ToArray();
        var doubledDisplacedCount = displaceCount * 2;
        if (sourceArray.Length < doubledDisplacedCount)
        {
            throw new ArgumentOutOfRangeException("source", "The source needs to contain twice as many elements than displacedCount");
        }

        return DisplaceEx<T>(sourceArray, displaceCount);
    }
    private IEnumerable<T> DisplaceEx<T>(IEnumerable<T> source, int displaceCount)
    {

        var doubledDisplacedCount = displaceCount * 2;

        for (var i = displaceCount; i < doubledDisplacedCount; i++)
        {
            yield return sourceArray[i];
        }
        for (var i = 0; i < displaceCount; i++)
        {
            yield return sourceArray[i];
        }
        for (var i = doubledDisplacedCount; i < sourceArray.Length; i++)
        {
            yield return sourceArray[i];
        }

    }
}

What advantage should this method get from beeing virtual ? I don't see any. Overriding this method in an inherited class doesn't make sense IMO.


Numbers or integers ?

First of all, I notice that your question title talks about numbers, while your code looks only for positive integers.

In other words, it's currently not intended to take in account numbers such as 12.34 or -123.
To also detect and use this kind of numbers, your function would need a much more complex process.

Let's say you really want to remain limited to integers (I think so especially because of your parseInts). Then you may simplify your code in several ways.

Utility of regexargument ?

First I don't see why you're using a regex argument: for the purpose of your function, seems that it can't be anything else than the default you gave to it.
But this is up to you, and I'll keep this argument in what follows.

Declaring regex variable.

So just regarding it, you don't need to declare a new variable to use it: the regex argument your received has its scope limited to the function, and you may modify it directly. So you can simply write:

regex || /(\d+)/g;

Choosing the more efficient regex expression

Now regarding the way you expressed the regex: with its capturing parentheses, /(\d+)/g it makes your regex.exec(text) to return only one matching block each time, forcing you to the while() where you extract it.

At the opposite, using /\d+/g, you can merely do text.match(regex) and it'll return all matching blocks at once. Then you can directly reduce() this resulting array, though having to take care of the case it's null (like with your 'LLLLL').

Casting to numbers

While reduce() works, passed blocks contain only digits but are strings, so you're right to ensure they're processed as number instead.
But rather than parseInt (really useful only to extract integer part from a string where there are also other characters), you can merely cast curr to a number with +curr.

Using reduce().

You can take advantage of this reduce() capability: if you omit its 2nd argument (initial value for prev), then the 1st step is that curr is automatically affected to prev.
Note that in this case you must alos cast +prev!

Final reduced suggestion.

Last point, you can reduce the whole code by directly using the match() result in the reduce() process, without having to use other intermediate variables, assumed you take care of the possible null result from match().

Here is the suggested version:

'use strict';

var sum = function(text, regex) {
  var match;
  return !!(match = text.match(regex || /\d+/g)) ?
    match.reduce(function(prev, curr) {
      return +prev + +curr;
    })
  : 0;
}

console.log(sum('1 12 40'));
console.log(sum('10 12 40'));
console.log(sum('1 12 510'));
console.log(sum('LLLLLLLL'));
console.log(sum('10 1'));


This example is mostly about making and using a RAII wrapper, not about calling C from C++ (which is trivial).

If you want to show how to call C-like interfaces, then use zlib directly, without wrapping it.

If you want to show the native C++ way to wrap a C interface, then the wrapper should be an iostream subclass, like gzstream.

pack should read blocks of finite size rather than reading the whole file at once. It's a compression utility, so it's likely to be used on files that won't fit in memory!

Some confusing names:

GzWrite instances aren't writes; they're streams. How about GzStream or (if it uses the iostreams interface) gzostream?
Don't call a function read; it's easy to confuse with Posix read. This is traditionally called slurp or read_file.
infn will probably be interpreted as "in-function", not "in-filename". How about infile?
laenge (Länge?): length

BLOCK_SZ and LEVEL are unused.


Some notes:

Use 2-space indentation.
f.write chunk. You use parens in other places, be consistent.

Other than these minor issues, I think your code is pretty good. I'd just refactor read_file_in_chunks to use a enumerator instead (more versatile) and a range.

def read_file_in_chunks(chunksize=10343)
  Enumerator.new do |yielder|
    (0...@file_info_object.size).step(chunksize).each do |offset|
      data = Client.read(@file_info_object.path, offset: offset, length: chunksize)
      yielder.yield(data)
    end
  end
end

Using lazy collections (Ruby >= 2.0) it can be simplified even more:

def read_file_in_chunks(chunksize=10343)
  (0...@file_info_object.size).step(chunksize).lazy.map do |offset|
    Client.read(@file_info_object.path, offset: offset, length: chunksize)
  end
end