Better way to work with clickable regions of window

I think the overall approach of having lots of
s to act as clickable areas is just fine. An alternative is to dynamically calculate the position of a click on main-proj and see if it's sufficiently in one of the directions to count as an intent to scroll, but that's more complicated and more prone to breakage than having separate divs.
Don't be afraid of WET HTML markup in the rendered output. It's perfectly normal and isn't inelegant or indicative of a problem. It's true that having huge numbers of DOM nodes on a page can slow things down, but 4 extra
s for each image isn't incredibly likely to be a tipping point for that - and if it does turn out to be one, consider changing the page so that only a reasonable number of .main-projs are rendered at a time, like 50 or 100, but not much more than that.
That said, it would be good to avoid WET HTML in your source code if possible, if feasible given your setup - you don't want to copy-paste those 7 lines of

    ...

over and over again every time you want to add an image. It'll make understanding the code at a glance harder, and can make refactoring more difficult. To only write the template for such a section once, you can either do it server-side with a template engine, or client-side with something like React, or even with vanilla DOM methods like document.createElement.
Another thing to consider - if the different clickable divs result in different functionality depending on which was clicked, that would be a great thing to indicate to the user. For example, you might want to change the color of a hovered div, perhaps with an arrow or something, to give the user a visual indicator of what will happen when clicked. This is trivial to achieve with separate
s, but annoyingly complicated without it. (If you don't give the user a visual indicator of the difference between clicks on different sections of .main-proj, it's probably not as user-friendly as it should be.)
Other suggestions regarding your code:
Use const, avoid let - see here. It's good to indicate to future readers of the code (often including yourself) that a variable will not be reassigned.
Don't re-select elements you already have a reference to - you don't need to select the .activeproj again, select the parent again instead, or save it in a variable:
const $thisProj = $(this).parent();
// do you want to remove .activeproj from other elements at this point?
// or, if activeproj isn't used in the CSS, you could remove it completely
$thisProj.addClass('.activeproj');
const $target = $thisProj.next('.main-proj');
// ...

Unless you have other kinds of children in this projimgarray (I think you shouldn't), you can also omit the parameter to .next.
No need to wrap a jQuery object in jQuery again This:
scrollTop: $($target).offset().top

can be
scrollTop: $target.offset().top

projimgarray? Arrays are a JavaScript construct. DOM elmements aren't really arrays. Perhaps call it something more precise, and use dashed-case per convention (and to make the word separations easier to understand at a glance) - maybe something like all-projects.


Namedtuple and list to populate each record of a JSON file

A small issue, that is probably no big deal for this program, but could cause problems over smaller timescales than days:

json_data = json.load(data)
for record in json_data["data"]:
    # Time in JSON file also has timezone so i have to use timezone.utc
    today = datetime.now(timezone.utc)

Having a different definition of "now" for each element in the file is unexpected.  We can ensure consistency by assigning today once, outside the loop.  (That slightly improves efficiency, too - but probably not by enough to measure!)


Forced Async operation in a (event like) method

Instead of WatchDirectories.FirstOrDefault you can make use of Any() which is more meaningful.

Also if you are checking Any() you can return early and save horizontal spacing.

public Task AddDirectoryWatcher(string directory) {
    return Task.Run(async () => {
        if (!Directory.Exists(directory)) return;

        using (var context = _contextFactory.CreateContext()) {
            if (context.WatchDirectories.Any(wd => wd.Directory == directory)) { return; };

            var childWatchers = context.WatchDirectories.Where(wd => wd.Directory.StartsWith(directory));

This AddDirectoryWatcher() is using a context to delete and insert items. Doesn't the RemoveDirectoryWatcher() method already uses a context too ? If yes, the call to context.Delete(watchDirectory); is redundant.

Instead of checking if the passed directory exists and silently returning , I would check this before calling the method and throw a DirectoryNotFoundException.


The recommended way from Oracle is Thread.interrupt().  For example:

public void stop() {
    Thread thread = runner;
    runner = null;
    thread.interrupt();
}

public void run() {
    runner = Thread.currentThread();
    while (runner != null) {
        System.out.println("Stop Thread " + Thread.currentThread().getId());
    }
    System.out.println(" Done ");
}

It is true that sleep() can be interrupted (which will raise an InterruptedException), which is what the interrupt() will do.  However, afterwards the Thread can continue doing whatever it wants after being “interrupted”, so you must also check for a stop-condition of some kind.  Above, we check runner != null.  But as you can see above, you don’t need a sleep() in the worker thread.

If you don’t want to run the Thread in a loop, or you have many different loops where the task may spin, you will have to make the stop check in each of those places.


Enabling stack overflow protection with Y/N prompt

Your ignore can produce some erratic results, depending upon the number of characters entered by the user.  Rather than:

std::cin.ignore(std::numeric_limits<char>::digits10);

You might want to go with:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Which will ignore all of the entered characters up to the end of the input line.  That way you don't start going round the loop multiple times, or with left over characters if the user enters:

  asdfasdfasdfasdfasdf

I'd also consider moving the warning to before the question.  Telling me there may be a seg fault after I've already selected that route seems like a waste of time.  I'd prefer to have that information prompted before I select Y/N (or given the question have it assume that I already know that information).


Solution to 99 lisp problems: P08 with functional javascript

I don't think you need so much complexity in javascript. It's not a fully functional language, don't try to make it so.

var arr = [
    'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'a', 'e', 'e', 'e'
];

arr = arr.filter( function( el, i ) {
    // return if the current isn't the same as the next
    return el !== arr[ i + 1 ];
});

console.log( arr ); // ["a", "b", "c", "d", "a", "e"]

This is 2 lines.


Calculate Cosine similarity between Multisets

This is pretty good, but two things come immediately to mind:

Declare variables closest to where they're being used. Declare dotProduct, magnitudeA, and magnitudeB right above your loop.
Don't reassign method arguments. That's really confusing six months down the road. In this case, use a helper method which takes the larger and smaller sets in a specific order.

Example:

import static java.lang.Math.sqrt;

/**
 * [Excluded for brevity]
 *
 * @param <T>
 * type of the token
 */
public final class CosineSimilarity<T> implements MultisetMetric<T> {

    @Override
    public float compare(final Multiset<T> a, final Multiset<T> b) {

        if (a.isEmpty() && b.isEmpty()) {
            return 1.0f;
        }

        if (a.isEmpty() || b.isEmpty()) {
            return 0.0f;
        }

        if (a.size() >= b.size()) {
            return this.determineSimilarity(a, b);
        } else {
            return this.determineSimilarity(b, a);
        }
    }

    private float determineSimilarity(final Multiset<T> largerSet, final Multiset<T> smallerSet) {
        float dotProduct = 0;
        float magnitudeA = 0;
        float magnitudeB = 0;

        for (final T entry : union(largerSet, smallerSet).elementSet()) {
            final float aCount = largerSet.count(entry);
            final float bCount = smallerSet.count(entry);

            dotProduct += aCount * bCount;
            magnitudeA += aCount * aCount;
            magnitudeB += bCount * bCount;
        }

        // a·b / (||a|| * ||b||)
        return (float) (dotProduct / (sqrt(magnitudeA) * sqrt(magnitudeB)));
    }

    @Override
    public String toString() {
        return "CosineSimilarity";
    }
}


Am I thinking functionally in these simple Haskell functions?

Overall it's pretty nice. I like that you've learned how to use $; it really improves readability in my opinion. One thing that immediately caught my attention though was the chain of prints. Haskell can do better! You can for example put those in a list, and mapM_ print over it.

let fns =
    [ skips "ABCD"
    , skips "hello!"
    , skips [1]
    , skips [True, False]
    , skips ([] :: [Int])
    , localMaxima [2,9,5,6,1]
    , localMaxima [2,3,4,1,5]
    , localMaxima [1,2,3,4,5]
    ]

mapM_ print fns

This makes it easier to refactor  later, if you want to do something else than print, write them to different files, all kinds of stuff. The lisp-ish approach of code-as-data is quite useful when enumerating cases like you did here.

isMiddleMax (x:y:z:[]) = x < y && y > z

Spooky! Use -Wall to get a proper warning for that one: incomplete patterns in function .... You might want to consider adding a meaningful error message:

isMiddleMax _ = error "Only works on 3-element lists!"

triples (x:xs)
  | length (x:xs) < 3 = []

Dunno if you know, but there exists a thing called "alternate name capture"; it's written like so:

triples (x:xs @ allXs)
  | length allXs < 3 = []

If you consider this an overkill, why not simply change the clause to length xs < 2? I don't like the same pattern repeated for some reason.

countInstances xs = map (countInstance) $ groupSort xs

maxInstances xs = maximum $ map (snd) $ countInstances xs

The parens around countInstance and snd are unnecessary (it's not terrible to leave them, just pointing that out). HLint is a useful tool that can provide such hints for you!

Oh, and also, in the second case; multiple $ are a bit less readable; consider this instead:

maxInstances xs = maximum . map (snd) . countInstances $ xs

This expresses it in a truly functional way, and makes it susceptible to eta-reduction!:

maxInstances = maximum . map (snd) . countInstances

This is called point-free (not to be confused with pointless :)) notation, and makes it extremely clear that the function is indeed a composition of other functions ((.) is Haskell's composition operator).

I'll add more if I notice any more areas for improvement.


HackerEarth Girlfriend's Demand challenge, solved two ways

Slowness caused by System.out.println
The difference between the first and second programs isn't the parsing or long/int conversion.  The difference is that in the first program, you use a StringBuffer to build your output into one big string (which is good).  In the second program, you call System.out.println() for each of your 100000 lines of output.  This takes a significant amount of time.
The current code
I don't see any problem with your first program.  It runs about as well as can be expected.  There are some strange indentations in your code and a few places where I would have added some spaces, but otherwise I don't see other problems.  I played around with it and got it to run about 8% faster by changing the parsing, but it wasn't really significant.  For your reference, here is the modified code:
public static void main(String args[] ) throws Exception {
    BufferedReader br        = new BufferedReader(
                                    new InputStreamReader(System.in));
    String         item      = br.readLine();
    int            len       = item.length();
    int            numInputs = Integer.parseInt(br.readLine());
    StringBuffer   output    = new StringBuffer(numInputs * 4);

    while (numInputs-- > 0) {
        String line  = br.readLine();
        int    space = line.indexOf(' ');
        long   a     = Long.parseLong(line.substring(0, space-1));
        long   b     = Long.parseLong(line.substring(space+1));

        a = (a-1) % len;
        b = (b-1) % len;

        if (item.charAt((int)a) == item.charAt((int)b))
            output.append("Yes\n");
        else
            output.append("No\n");
    }

    System.out.println(output);
}


DONT! String format your sql queries, but let the cursor do it for you.

As @Gareth Rees said, this is not secure!

c.execute("SELECT accounts_info_uid "
          "FROM auth_info WHERE login='{}' ".format(login))

As taken from the docs, this would be the proper way to execute statements with sql:

cursor.execute("SELECT accounts_info_uid FROM auth_info WHERE login = %s", login)

You could use a context manager over the connection

Using a context manager would improve the readability, see PEP343

There are some resource out there how to implement such a thing
Make the login a separate function
I think it can be optimized in one SQL request?

Yes, but without the database itself it is hard to test, a github repo or some more information would help.

However you could improve on your google-fu, Simply typing "mysql join 3 tables" would have given you the answer you are looking for.

https://stackoverflow.com/questions/3709560/joining-three-tables-using-mysql


The code generally looks pretty good, but I think there are some things you could fix up here.

Don't forget the stop code

You have the start code of 0000 but you've forgotten the stop code which is 100.  When you calculate, you could just tack it onto the end with bits += '100'

Use SVG <def>s

Since the purpose is to create an SVG barcode, it make sense to tighten the resulting SVG.  You may already know how to use a <def> in SVG and it definitely makes things a little easier to understand here.  The way your code is currently structures, it creates four different styles of <rect> which are all combinations of narrow/wide and black/white.  You could predefine each of those shapes and then simply intantiate them within the body of the svg code.  That would make the definition for svg and bar like this:

svg = '''<svg height="50"><defs>
<g id="b0"><rect x="0" y="0" width="2" height="50"/></g>
<g id="b1"><rect x="0" y="0" width="4" height="50"/></g>
</defs>'''
bar = '<use xlink:href="#b{0}" x="{1}" y="0" {2}/>'

Using it would then be

svg += bar.format(bit, pos, style)

An improvement would be to create both bars and spaces like this:

<g id="b0"><rect x="0" y="0" width="2" height="50" style="fill:rgb(0,0,0)"/></g>
<g id="b1"><rect x="0" y="0" width="4" height="50" style="fill:rgb(0,0,0)"/></g>
<g id="s0"><rect x="0" y="0" width="2" height="50" style="fill:rgb(255,255,255)"/></g>
<g id="s1"><rect x="0" y="0" width="4" height="50" style="fill:rgb(255,255,255)"/></g>

Then your loop could look then like this:

for i, bit in enumerate(bits):
    width = int(bit) * 2 + 2
    svg += bar.format('bs'[i%2], bit, pos)
    pos += width

Although that may look verbose, it actually is over 2k shorter for a 12 digit barcode.

Think carefully about data representation

Your code currently translates digits into a series of '1' and '0' characters and then translates again into SVG rectangles.  Why not eliminate a step? Your code could just as easily translate them in a single operation.

Use list comprehensions instead of for loops

The use of list comprehensions is almost always faster than a for loop in Python, so we use them when we can.  It also tends to make the code shorter.  So for example, we could change your loop to calculate the string of bar code bits to calculate all the black bits and then all the white bits like this:

black = "".join([bytes[i] for i in digits[0::2]])
white = "".join([bytes[i] for i in digits[1::2]])
# shuffle them together
databits = "".join("".join(i) for i in zip(black,white))
# create the full bar code string with start and stop
bits = "".join(['0000',databits,'100'])

Doing this with join also saves time.  Appending strings with += is very slow in Python.

Prefer xrange to range

When you use range, a whole list object is created, using memory.  With xrange, a generator is created instead populated which can save memory.  For any reasonably sized bar code this won't make much difference here, but it's good practice for Python 2.7.  In Python 3, xrange doesn't exist and range creates a generator, so keep that in mind if you change versions.

Don't draw more than you have to

You're drawing one <rect> for every bar or space, but it's really not necessary.  Instead, you could create one larger rectangle that's the "background" space color and then only draw the black bars.


Why do you assume this code is limited to 10 vertices? This code comes from: http://www.geeksforgeeks.org/greedy-algorithms-set-2-kruskals-minimum-spanning-tree-mst/

But you have an error in use:

 g = Graph(14)

Defines a graph with 14 vertices but then you used 0-14 which is 15 vertices. Either use:

 g = Graph(15)

Or remove all the edges with vertex 14.


Using GeoComplete with RequireJS (with shim config)

The only thing that I see looking at this code is that you didn't keep a fully consistent formatting, and I at first thought you had an extra set of brackets or parentheses.

You should do it like the }); farther above in the code.

Keep everything consistent, you probably already know this though.


Read and reformat a list of global variables output by a compiler

The docs for locals() imply that there's some overhead involved with using it:

  Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

So it might be best to avoid it from that perspective alone.  (Though it's probably fine in most cases, and avoiding it might be a case of premature optimization.)

I generally prefer verbose format strings when using them this way, using the philosophy of "If the string was separated from the code that uses it, could someone still figure out what each variable in the string is referring to?".  So I frequently end up doing somewhat of a hybrid approach -- using a dictionary for the format arguments rather than locals() and rather than having to repeat every single argument as a keyword argument:

def parse_global_variable(line, length):
    last_element = length-1
    template = ''  # This is actually redundant

    f = {
        'module': line.partition('.')[0].rpartition('\t')[2],
        'logical_address': line.partition('#')[2].partition('#')[0],
        'var_name': get_var_name(line),
        'width': line.rpartition('\t')[2]
    }
    f['physical_address'] = get_physical_address(f['logical_address'])

    if length == 0:
        template = ' Record   GLB  {logical_address} {physical_address} {module:34}{var_name}' \
                   '\n                0    {width:7}{var_type}'
    else:
        template = ' Record   GLB  {logical_address} {physical_address} {module:34}{var_name}' \
                   '(0..{last_element})\n                0    {width:7}{var_type}'
        f['width'] = str(int(f['width'])/length)
    return template.format(**f)


Not very fast
Your memcpy() implementation is not really better than a standard byte by byte copy.  Even though you attempt to copy more bytes at a time, the limiting factor isn't actually the number of bytes you copy per instruction.
If you research the various memcpy() implementations there are for x86 targets, you will find a wealth of information about how to get faster speeds.  I think the simplest thing for you to do is to just use the simple "rep movsb" implementation.
My own benchmarks
I ran your version against the following two versions.  One is a straightforward byte by byte copy, and the other is just using "rep movsb", which on modern processors is highly optimized:
void *memcpy2(void *dst, const void *src,size_t n)
{
    size_t i;

    for (i=0;i<n;i++)
        *(char *) dst++ = *(char *) src++;
    return dst;
}

void *memcpy3(void *dst, const void *src, size_t n)
{
    void *ret = dst;
    asm volatile("rep movsb" : "+D" (dst) : "c"(n), "S"(src) : "cc", "memory");
    return ret;
}

My results for copying 2GB (32-bit host):
OP's function  : 3.74 sec
memcpy2 (naive): 3.74 sec
memcpy3 (movsb): 2.96 sec


Providing const- and non-const overloads of a strstr() implementation

I don't like casting away const on a const object.
This opens you up to the possibility of maintenance errors.

const char *strstr(const char *input, const char *find)
{
    return strstr(const_cast<char *>(input), find);
}

Here you are assuming that the other version of strstr() will not attempt to mangle the input. This may be fair to assume in the original version, but what if somebody makes a mistake while updating to use a better algorithm. The compiler will not detect the problem and you are left with UB.

I would just do it the other way around:

char const* strstr(char const* input, char const* find)
{
   do {
        char const* p;
        char const* q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

char* strstr(char* input, char const* find)
{
    return const_cast<char*>(strstr(const_cast<char const*>(input), find));
}

OK. So we need to add another cast. But in this version we protect ourselves from errors. If there is an error in the algorithm (were input is modified) then the compiler will now be able to detect it.

The const_cast<> to remove const(ness) is in a safe place returning the pointer to its original state (after there is const_cast<> to add const (needed so we can differentiate the two functions).

Personally I would take it a step further (so we can remove one of the const_casts). By making the strstr() just wrapper functions around the function that does the work.

char const* strstrDo(char const* input, char const* find)
{
   do {
        char const* p;
        char const* q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

// Interface for backwards compatibility with old C code
// that does not handle const correctness well.
char* strstr(char* input, char const* find)
{
    // It is safe to cast away the const(ness) here.
    // The result of `strstrDo()` is a location inside
    // `input` (which we already know is non const) or
    // it is NULL (where the type is less relevant).

    return const_cast<char*>(strstrDo(input, find));
}

// Correct interface.
char const* strstr(char const* input, char const* find)
{
   return strstrDo(input, find);
}

Don't like Implementation B: template because it has the same problems in that errors (in modification input are not detected by the compiler (potentially)).

Same for Implementation C: template with char_traits. But that goes way over the top. I don't actually see the need for the traits on such a simple function.


I can't comment on Ruby style, but there are a couple of algorithmic points which don't need Ruby knowledge to identify.

  if @stack.length >= 2
    unless WORDS.grep(/^#{@letters.join}/).any?
      pop_stack
      return
    end
  end

Although you've preprocessed the wordlist into a sorted data structure with logarithmic time lookup, grep seems to be a method from Enumerable and I can't see any indication that there are special cases. In other words, this is (worst case) doing a linear scan of the entire wordlist. There should be a massive speed improvement either by exploiting the SortedSet interface or (more likely) by preprocessing the wordlist into a trie. The latter gives the advantage that you can pass the current node down the stack and not have to run the entire route from the root every time.

    # Check whether the new position had been visited in current stack
    visited = false
    @stack.reverse_each do |pos|
      if pos == npos
        visited = true
        break
      end
    end

Again, this is doing a linear scan for something which doesn't need to be so slow. The OO way would be to use a Set, which ought to have fast member? checks. The optimisation-over-all approach would be to use an integer as a bitmask. Either approach requires minimal maintenance on the stack.


Python 2 is end of life, many core libraries and tools are dropping Python 2 support.
Python is dumb. If you tell it to calculate (1/(new_height*new_width) each and every loop, then Python will.
Your style is not Pythonic, you should have more whitespace.
If we change one of the for loops in calculate_mean to math, we can see we can that ¶2 isn't needed inside the loop.

for p in pixel_image_y:
    color_moments[0]+=(1/(new_height*new_width))*int(p)

$$
\Sigma \frac{\lfloor p \rfloor}{hw} = \frac{\Sigma \lfloor p \rfloor}{hw}
$$
We can utilize numpy to perform the loop, in calculate_standard_deviation, in C.

color_moments[3] = (
    np.sum((pixel_image_y - color_moments[0]) ** 2)
    * math.sqrt((1/(new_height*new_width))
)

You should change calculate_mean and calculate_standard_deviation to either work in one dimension or all dimensions.
You should remove color_moments from your code. You should return if you need to return.
You can determine new_height*new_width by the values you enter in your function. No need to pass them.

def mean(values):
    return sum(int(v) for v in values) / len(values)

def std_deviation(values):
    return np.sum((values - mean(values)) ** 2) / math.sqrt(len(values))


Filtering a list by comparing enums against a user choice

When SelectedOppType == 5, all values in OpportunitiesList will be added to FilterdOppsList, but only after evaluating many conditions unnecessarily. It would be better to handle this as a special case,
and add all values of OpportunitiesList in FilterdOppsList before ever entering the foreach loop.

Next, in the foreach loop, since selectedOppType doesn't change throughout the loop, regardless of the value of opp, it would make more sense to use conditionals on the value of opp.OpportunityStatusID instead of selectedOppType. You can rearrange the conditions to switch statement.

Putting it all together:

if(selectedOppType == 5)
{
    FilterdOppsList.AddRange(OpportunitiesList);
}
else
{
    foreach (Opportunities opp in OpportunitiesList)
    {
        bool shouldAdd = false;
        switch (opp.OpportunityStatusID)
        {
            case OpportunityStatus.Active:
                 shouldAdd = selectedOppType == 1 || selectedOppType == 4;
                 break;
            case OpportunityStatus.Draft:
                 shouldAdd = selectedOppType == 2 || selectedOppType == 4;
                 break;
            case OpportunityStatus.Closed:
                 shouldAdd = selectedOppType == 3;
                 break;
        }
        if (shouldAdd)
        {
            FilterdOppsList.Add(opp);
        }
    }
}


Replace all occurrence of REP [block] with value of the block

Does it have some security issues?

Well, you're doing an evaluation of code.  If that code comes from a foreign source somehow, that could be a problem.  If it's your code, it's no more dangerous than anything else.

But as you wrote it, it does have the property that it can infinite loop within itself.  Because after your substitution you start at the beginning again:

arr: [REP [quote REP]]

That's a stable state, but you could keep growing without bound too.

My answers will assume you didn't want this.

  Does this code follow common best practices?

It's C-like.  Rebol is a great language for writing bad C code.  :-)

Using COMPOSE is the obvious answer here:

>> compose [
    ("code1")
    | 'something
    "f"
    | [ f | 3 ]
    (40 + 2)
]
== ["code1" | 'something "f" | [ f | 3 ] 42]

And if you're worried your content contains parens that you want to leave in place, you can quote them:

>> compose [1 (quote (2 3)) 4]
== [1 (2 3) 4]

But if you want to work with the input as written, there's a lot of approaches.

The most "sensible" way--that the wiki regarding features in R3-Alpha suggests would work (but doesn't seem to)--would be:

>> parse arr [
    any [
        change ['REP blk: block!] (do blk/1)
        |
        skip
    ]
]

Which would more or less capture the essence of the task.  Any number of times, try and match a pattern of REP followed by a BLOCK!, marking the position prior to the block.  Then substitute the execution of do blk/1 for that code".  Otherwise skip and keep looking.

It gets almost there but misses the execution.  So it splices in do blk/1 literally:

== [do blk/1 | 'something "f" | [f | 3] do blk/1]

Try reporting a bug to...whoever works on that.  Or maybe to Red.  :-)

I've seen you mention you don't like UNTIL, so here's a FORALL-based solution...

forall arr [
    if arr/1 = 'REP [
        remove arr
        arr: back change arr do arr/1
    ]
]

(Note: I think forall should be called FOR-NEXT, because all it does is advance the argument until the end via NEXT.  You can modify it during the loop, and then it will run NEXT again.  It will be reset at the end.)

As a talking point on your code: Note that there are two FALSE? values (NONE! and LOGIC! false), and everything else is TRUE? (except unset which is neither).  So it's not that common to work with literal true and false.  NONE is almost always better as a contrast to some value you are interested in.

Just to show what kinds of tricks are available in an "imperative-series-assembly-language" with a WHILE approach: if we are walking along the array replacing, we might use the position back from FIND not being NONE! to cue continuation:

head while [arr: find arr 'REP] [
    arr: change/part arr do arr/2 2
]

It's able to work because change is designed for chaining, so it returns the point after the replacement.  Also because WHILE returns the last evaluation of the body.  So even though the condition wipes out the value of arr when the find comes back with NONE!, it can be recovered because the last time the body evaluated it was the end position of the CHANGE...and you can seek back to the head from that.

So there are a few possibilities.


Parking Charges exercise from Deitel's C book

I see a number of things that may help you improve your code.

Eliminate global variables where practical

The code declares and uses a global variable charge.  Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult.  It also makes the code harder to reuse.  For all of these reasons, it's generally far preferable to eliminate global variables by either making them local and/or passing them into and out of functions. That way the linkage is explicit and may be altered more easily if needed.  For example, to eliminate charge global, simply make it local to calculateCharges.

Consider improving names

I think hours is not a bad variable name, but one is, since hours gives the reader some idea of why the variable exists, but one could be anything.

Check return values for errors

The call to scanf can fail.  You can check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources.  Rigorous error handling is the difference between mostly working versus bug-free software.  You should strive for the latter.

Understand variable passing

When you write this:

float calculateCharges( float hours )

It means that the function takes a float named hours as the argument.  Because it doesn't say float &hours, which would take a reference to the passed variable (a pointer, in essence), it's passed by by value.  This means that it's really not necessary to create a local copy named h; just use hours directly.

Decompose the program into smaller parts

Right now, much of the code is in main which isn't necessarily wrong, but it means that it's not only hard to reuse but also hard to troubleshoot.  Better is to separate the code into small chunks.  It makes it both easier to understand and easier to fix or improve.  For example, one might have a function for getting input and another for printing output in addition to the existing function that converts hours to a charge.

Make sure all paths return a value

The calculateCharges routine returns the dollar amount if the passed number of hours is greater than zero, but what if it's not?  Right now the code doesn't return any value which is a problem.  Rather than printing a message, better would be to return some special marker value, such as -1 that the calling code can check for and then have it decide the appropriate action.

Use an array

Instead of naming things one, two, three, create an array: float hours[3]; and loop through that.


Your model should not know anything about how it gets created, that is what a repository is for. What if at some point in the future you changed from a database to a REST API? Now all of your models are invalid. If you use a repository, you could just add a new repository for the new API and the models are none-the-wiser.

So your model should just be this (notice I changed the name of the class, you should use descriptive names):

class PersonModel{

    private $first;
    private $last;
    private $gender;
    private $birthYear;
    private $agency;
    private $picture;

    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
        return $this;
    }
}

And then you have a repository:

class PersonRepository {

    private $_db;

    public function __construct($db){
        $this->_db = $db;
    }

    public function create($person){
        $statement = $this->_db->prepare("insert into models (first_name, last_name, gender, birth_year, agency, picture) values (:first, :last, :gender, :birth_year, :agency, :picture)ON DUPLICATE KEY UPDATE gender = VALUES(gender), birth_year=VALUES(birth_year), agency=VALUES(agency), picture=VALUES(picture)");

        $statement->bindParam(':first', $person->first);
        $statement->bindParam(':last', $person->last);
        $statement->bindParam(':gender', $person->gender);
        $statement->bindParam(':birth_year', $person->birthYear);
        $statement->bindParam(':agency', $person->agency);
        $statement->bindParam(':picture', $person->picture);

        $result = $statement->execute();
        if ($result){
            return true;
        } else {
            return false;
        }
    }

    public function read($id) {
        //...
    }

    public function list() {
        //...
    }

    public function update($person) {
        //...
    }

    public function delete($person) {
        //...
    }
}

This keeps your database layer separate from your data layer and separate from your presentation layer. The more separation you can do here, the better off you are going to be when it comes to updating and maintaining this code.

I would recommend a good read through SOLID principles to get an idea.


Security

You are escaping user input, which prevents SQL injection. It's good enough, but really not the recommended way to do this as it's too error-prone (whenever a project does this, it's basically guaranteed that you can find injections). Use prepared statements instead. It's not only more secure, but also leads to nicer code.

Guard Clauses

You have a lot of nested ifs, which makes it difficult to see what happens when (for example, I have to scroll all the way down to see what happens if it's a GET request).

If you use guard clauses / return early instead, your code will be much more readable. It might look like this:

if (!isset($_POST['submit'])) {
    header("Location: ../index.php?login=error");
    exit();
}

if (empty($username) || empty($password)) {
    header("Location: ../index.php?login=empty");
    exit();
}

// select the user

if (!$userExists) {
    header("Location: ../index.php?login=error");
    exit();
}

// verify the password

if ($validPassword) {
    header("Location: ../index.php?login=error");
    exit();
}

// set the session, redirect

Now it's very clear what happens when.

Duplication and functions

Following a  header redirect with exit is very good practice. You can make sure that you always do this, simplify the code, and make it easier to modify later by extracting that to it's own function (eg redirectError(Error error)).

True or false

Something is either true or false. There is no reason to do an else check on true if you already did one on false.

Note though that some equals checks can be unexpected, so you should always use strong comparison (===) if you don't have a reason not to.


Pythonic

I rewrote a few of the loops to prevent looping over the index. I also changed used_comps to a set which has O(1) containment checks. For smaller arrays this will not matter a lot, for larger ones this can make a difference.

I also moved the permutation_dict and used_comps definitions closer to the place they are used.

def find_permutation2(true, permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """

    corr_matrix = np.zeros((true.shape[1], permuted.shape[0]))

    # Find correlations
    for i, column in enumerate(true.T):
        for j, row in enumerate(permuted):
            corr_matrix[i, j] = np.corrcoef(column, row)[0, 1]

    # Find best order
    per_matrix = np.argsort(-np.abs(corr_matrix), axis=1)

    permutation_dict = {}
    used_comps = set()
    for i, row in enumerate(per_matrix):
        for j in row:
            if j in used_comps:
                continue
            permutation_dict[i] = j
            used_comps.add(j)
            break

    return permutation_dict

numba

You can use numba, which compiles the python to llvm. I'm no expert, but I got it to work with these settings.

m_jith = numba.jit(find_permutation2, looplift=False, forceobj=True)
m_jith(true, permuted)

np.setdiff1d

You can use np.setdiff1d. This will be slower for smaller arrays, but might be faster for larger arrays.

def find_permutation3(true, permuted):
    """
    Finds the most probable permutation of true time series in between permuted time series
    :param true: true ordered time series of shape T times X
    :param permuted: Permuted time series of shape P times T. P > K
    :return: A dict containing {true idx: permuted idx}
    """

    corr_matrix = np.zeros((true.shape[1], permuted.shape[0]))

    # Find correlations
    for i, column in enumerate(true.T):
        for j, row in enumerate(permuted):
            corr_matrix[i, j] = np.corrcoef(column, row)[0, 1]

    # Find best order
    per_matrix = np.argsort(-np.abs(corr_matrix))

    permutation_dict = {}
    used_comps = set()
    for i, row in enumerate(per_matrix):
        j = np.setdiff1d(row, used_comps, assume_unique=True)[0]
        permutation_dict[i] = j
        used_comps.add(j)

    return permutation_dict

timings

All these things have very little effect on the speed of the algorithm

%timeit find_permutation(true, permuted)

950 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation2(true, permuted)

978 µs ± 55.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation3(true, permuted)

1.05 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation_jit(true, permuted)

1.08 ms ± 139 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit find_permutation_cython(true, permuted)

1.06 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

But this can change with a larger dataset.

This close timing is probably because the python is not the bottleneck, but the numpy operations, most likely the corrcoef, but you'll need to do some profiling to see whether this is true.


Calculate the square root of the sum of the squares of the prime factors of an input number

You can use the sieve approach to create an array of square sums. For any new prime that you sieve, you have:

sqsum[m * p] = sqsum[m] + p*p;

You can build that array as you go. The primes need a square sum value, too.

uint8_t sieve[RANGE] = {0};
uint64_t sqsum[RANGE] = {0};

void CalcAuxiliaryData()
{
    uint32_t i, j, k;

    for (i = 2; i <= RANGE; i++) {
        if (sieve[i] == 0) {
            uint64_t ii = (uint64_t) i * i;

            sqsum[i] = ii;

            j = 2;
            k = i + i;
            while (k < RANGE) {
                sieve[k] = 1;
                sqsum[k] = sqsum[j++] + ii;
                k += i;
            }
        }
    }
}

uint32_t CalcDiagonalLen(uint32_t n)
{
    uint64_t square;
    uint32_t length;

    if (sieve[n] == 0) return n;

    square = sqsum[n];
    length = sqrt(square);
    if ((uint64_t) length * length == square) return length;

    return 0;
}

This approach adds more time to the initialisation, because you can't cut sieving short at sqrt(RANGE), but the sum lookup is fast.

You could also create a lookup array that tells you whether a number is a perfect square or not, but the sqrt function isn't the bottleneck here. And you could make the array itself a direct lookup table for the diagonal length.


mapping & loops - counting up or counting down

You can accomplish your task using only core Javascript, with no reference to JQuery code, in about that many lines. JQuery is overkill for this task.

I applied the following changes to make your code more readable:

Reduced knowledge required to understand it (removed JQuery).
Reduced the complex portions (see iCurrentOvertime).
Added Hungarian notation; i.e. prepending integers with "i", arrays with "a", etc.
Encased added values together within parentheses (e.g. iCurrentHours+iTotalHours becomes (iCurrentHours+iTotalHours)).

The new code is below:

function calculateOvertime(days) {
  var aHours = [];
  var iTotalHours = 0;
  for(var i=0;i<days.length;i++){
    var iCurrentHours = days[i];
    var iNewHours = (iCurrentHours+iTotalHours);
    var iCurrentOvertime = Math.max(0,(iNewHours - Math.max(iTotalHours,40)));
    iTotalHours = iNewHours;
    aHours.push({
      reg: (iCurrentHours - iCurrentOvertime),
      ot: iCurrentOvertime
    });
  }
  return aHours;
}
calculateOvertime([16,16,16,16]);


Upload image using php 7 best practices to make it secure

For some reason you aren't following suggestions have been given to you in the other post. So again:

One of insecurities is revealing the internal error message to a site user. Remove that try and catch stuff from the database interaction and configure your server to report errors appropriately like you've been told.

Same goes for adding directory to the file name. Please remember, you already added it in the step before:

$realname = "uploads/" . basename($filename);

therefore, the following code makes no sense:

$this->uploadfile = $this->directory . basename($filename);

Do you realize that?
Besides, a function responsible for storing a filename in the database should be dong only that - storing a filename. Assigning the filename or error reporting should be done elsewhere.

It means your upload image method should be exactly like this:

public function store($filename, $image_name)
{
    $sql = "INSERT INTO images (img, image_name) VALUES (?, ?)";
    $this->connect->prepare($sql)->execute([$filename, $image_name]);
}

making it to do the only stuff it is intended for.

Regarding security, the main point is to verify the file's extension. Your web-server will judge the file type by its extension so should you.

$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$extension = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
if (in_array($extension, $allowed)) {
    // process your file
} else {
    // tell a user the extension is not allowed
}

regarding general purpose best practices. Looks like your namespaces are inconsistent. It seems you want something like that

use Eli\Db as DB;
use Eli\Controller\UploadController as Image;

and also you are supposed to implement PSR-4 autoload so you won't have to include class definitions manually


Enum with associated value as stored property in Swift extension

First note that your var connectionState is  computed property,
not a stored property. It is computed using the get and set
methods. Extensions cannot add stored properties to a type.

Your current implementation crashes if the connection state is retrieved
without having been set before:

let provider = ServiceProvider()
print(provider.connectionState)

because at

let dict = NSDictionary()
dict.setValue(nil, forKey: "none")

dict is an immutable dictionary. Making it mutable does not solve the
problem

let dict = NSMutableDictionary()
dict.setValue(nil, forKey: "none")

because the second statement has no effect and therefore the assertion

assert(!dict.isEmpty, "dict must contain one key")

fails.

You want to create a NSDictionary which – when bridged to [String: Error?] – becomes ["none": nil]. The difficulty here is that the
value type of the Swift dictionary is an optional. But it is possible,
using NSNull():

    get {
        if let connectionStateDict = objc_getAssociatedObject(self, &ConnectionStateHolderKey) as? NSDictionary {
            return connectionStateDict
        }
        return ["none": NSNull()]
    }

(compare SE-0140 Warn when Optional converts to Any, and bridge Optional As Its Payload Or NSNull).

But: All these conversions between enum, Swift dictionary and NSDictionary
are actually not needed, you can achieve the same much simpler.

As stated in Swift Blog: Objective-C id as Swift Any,

  The Objective-C bridge in Swift 3 can in turn present any Swift value as an id-compatible object to Objective-C.

This means that you can pass an enum ConnectionState directly to objc_setAssociatedObject()
and conditionally cast the return value from objc_getAssociatedObject() back to the enum.
The Swift runtime automatically wraps the value into a class.
(AnyObject not working in Xcode8 beta6?
on Stack Overflow contains further information and links.)

So this is everything you need:

enum ConnectionState {
    case none, connecting, failed(Error), connected, disconnected(Error), blocked
}

private var ConnectionStateHolderKey: UInt8 = 7
extension ServiceProvider {

    var connectionState: ConnectionState {
        get {
            if let connectionState = objc_getAssociatedObject(self, &ConnectionStateHolderKey) as? ConnectionState {
                return connectionState
            }
            return .none
        }
        set {
            objc_setAssociatedObject(self, &ConnectionStateHolderKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

More suggestions:

Use the nil-coalescing operator ?? to provide a default value in the getter method.
Restrict the scope of the associated objects key by making it a static property inside extension ServiceProvider.

Then the code would look like this:

extension ServiceProvider {

    private struct Keys {
        static var connectionState : UInt8 = 7
    }

    var connectionState: ConnectionState {
        get {
            return (objc_getAssociatedObject(self, &ServiceProvider.Keys.connectionState) as? ConnectionState) ?? .none
        }
        set {
            objc_setAssociatedObject(self, &ServiceProvider.Keys.connectionState, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

Finally: Your enum has a case none for "no state". But the Swift way
of representing "no value" is to use an optional:

enum ConnectionState {
    case connecting, failed(Error), connected, disconnected(Error), blocked
}

extension ServiceProvider {

    private struct Keys {
        static var connectionState : Int = 0
    }

    var connectionState: ConnectionState? {
        get {
            return objc_getAssociatedObject(self, &ServiceProvider.Keys.connectionState) as? ConnectionState
        }
        set {
            objc_setAssociatedObject(self, &ServiceProvider.Keys.connectionState, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}


Text-based adventure survival horror game

I see you've ignored the advice from your previous question. To avoid duplication, I'm going to quote them:

From this answer:

  Goto

  At a first approximation, never use goto. It makes it more or less
  impossible to follow code. Without goto, you also don't need labels.
  Instead, just call different functions. Or keep an internal state
  machine. Or really any possible other solution. Code with goto like
  this is incredibly brittle - what if you want to add more states
  somewhere in between? Good luck keeping track of everything.

From this answer:

  There many things here that can be improved. First off, let's tackle
  some best practices. Generally, doing stuff like this with system
  isn't very good:

system("pause");
system("cls");

  To start off, system("pause"); is a bad way of "pausing" for user
  input. First off, there's a decently sized overhead just to execute a
  shell command, and doing this is rather insecure. If you really need
  to pause on user input, and ignore it, then just do something like
  this:

std::cin.get();

  Secondly, putting anything like this at the top of your file is a bad
  idea:

using namespace std;

  This pollutes your local namespace with everything in std, and it
  can lead to some name conflicts, especially if you're using a library
  like boost. There's a good reason it's named std and not
  standard. It's easier to prefix everything with std:: rather than
  standard::.

Now for some advice specific to this question:

First, all the newlines and tabs are quite noisy. You can consider putting it in a variable:

std::string tab(6, '\t');
std::cout << tab << "...";

Secondly, instead of your goto approach, it's more likely that you want a while loop instead. Some users insist that the while loop is a glorified goto, but without the negatives.

std::string answer;
while (std::cin >> answer)
{
    // ...
}


Finding overlaps between two lists of axis-aligned rectangles

Dec. 10, 2018

The simple answer is to use a 2-d segment tree.

Given that we have low value for dimension (i.e. two), an appropriate approach would be to use a 2-d segment tree. We use what is known as stabbing query or intersection query. Let list one be the list that is smaller. Store all rectangles from list one in such a tree. Query using rectangles from list two. Time to construct and query are \$O(n_1 \cdot \log^2(n_1))\$ and \$O(\log^2(n_1) \cdot k)\$, respectively, s.t. \$k\$ is number of matches to report. If we use fractional cascading and interval tree, times become \$O(n_1 \cdot \log(n_1))\$ and \$O(\log(n_1) \cdot k)\$, respectively. Assuming these better times, time for all queries is \$O(\textrm{max}(n_2, k_\textrm{overall}) \cdot \log(n_1))\$. Overall time becomes \$O((\textrm{max}(n_2, k_\textrm{overall}) + n_1) \cdot \log(n_1))\$. Given that \$k_\textrm{overall}\$ is in \$O(n_1 \cdot n_2)\$, time could be loosely \$O((n_1 \cdot n_2) \cdot \log(n_1))\$.

If rectangles are not axis-aligned, one might wish to have bounding boxes and then use a tree. In principle we then could use a segment tree again, but a natural alternative (though we usually do not have good guaranteed theoretical running time for it unless we use "look-ahead") could be an R-tree.


Since cx is not used other than a loop counter, you may consider making a countdown loop. That would spare 2 instructions:

    move cx, 16
.loopstart:
    pop dx
    ....
    dec cx
    jnz .loopstart

The MSB operations can also be shortened:

    xor al,al    # Clear al
    sal dx,1     # MSB lands in CF
    adc al,30h   # Add with carry. al becomes 30h + MSB

Yet another jump could be spared by jne printMemoryValue.


Building an ACL based on permission level

I found the solution somewhere from the documentation.  I don't know why I had not seen that before.

Symfony2 provides an easier way of doing what I was looking for:

$builder = new MaskBuilder();
$mask = $builder->add($participant->getRight())->get();


Minimum path sum in a triangle (Project Euler 18 and 67) with Python

General

Since the problem gives the triangle as a text file, your program should probably be able to read that file. It would be quite a lot of work to input them manually, and when using the file like in python triangle.py < triangle.txt a first row with the number of lines needs to be added. This reading function can be quite simple:

def read_triangle(file_name):
    with open(file_name) as f:
        return [list(map(int, line.split())) for line in f]

Algorithm

As for the actual algorithm, I'm not quite sure what yours does. Which means that it is not very readable :). Not having any documentation, like a docstring does not help either.

The easiest algorithm for this is a bottom up approach that reduces each line into the maximum sum reachable from the line above it.

def reduce_rows(row, row_below):
    """Reduces two consecutive rows to the maximum reachable sum from the top row."""
    return [max(row_below[i], row_below[i+1]) + row[i] for i in range(len(row))]

def max_sum(triangle):
    """Find the maximum sum reachable in the triangle."""
    row_below = triangle.pop()
    for row in reversed(triangle):
        row_below = reduce_rows(row, row_below)
        # print(row_below)
    return row_below[0]

if __name__ == "__main__":
    triangle = read_triangle("triangle.txt")
    print(max_sum(triangle))

Style

It's a good thing that you are already using a if __name__ == "__main__": guard. You also seem to be mostly following Python's official style-guide, PEP8. The only thing you could improve on that part is to reduce the number of blank lines. While some help the readability, parts that are logically connected should be in one block:

height = None
while True:
    try:
        height = int(input('Please enter height of the triangle: '))
        if height <= 0:
            raise Exception('Height cannot be negative or 0')
        break
    except Exception as e:
        print(f'Error occurred: {e}\n')

triangle = []
for row_index in range(1, height + 1):
    while True:
        try:
            row = list(map(int, input(f'Please enter {row_index} space seperated integer(s): ').split()))
            if len(row) != row_index:
                raise Exception(f'Exactly {row_index} numbers required')
            elif any(number < 0 for number in row):
                raise Exception(f'Numbers cannot be negative')
            else:
                triangle.append(row)
                break
        except Exception as e:
            print(f'Error occurred: {e}\n')

I also put the separate exceptions and the happy path into an if..elif..else structure. This is not really needed (the other cases are never reachable if an exception is raised), but IMO it helps with readability. It also make it easier if at some point you decide that those should just print a message directly, instead of raising an exception that is immediately caught only to be printed. You could make those print statements directly, which would allow you to be more specific about the exception you expect. This makes it so that all other exceptions stop the program (as they should):

while True:
    try:
        height = int(input('Please enter height of the triangle: '))
    except ValueError as e:
        print(f'Error occurred: {e}\n')
    if height > 0:
        break
    else:
        print('Error occurred:  Height cannot be negative or 0')

triangle = []
for row_index in range(1, height + 1):
    while True:
        try:
            row = list(map(int, input(f'Please enter {row_index} space separated integer(s): ').split()))
        except ValueError as e:
            print(f'Error occurred: {e}\n')
        if len(row) != row_index:
            print(f'Error occurred:  Exactly {row_index} numbers required')
        elif any(number < 0 for number in row):
            print(f'Error occurred:  Numbers cannot be negative')
        else:
            triangle.append(row)
            break

Better user input

This is actually a good place to implement a function asking for user input and validating it. We need type validation and input validation here, so this should suffice:

def ask_user(message, type_=str, validate=None, non_valid_msg=""):
    while True:
        try:
            user_input = type_(input(message))
        except ValueError as e:
            print(f"Expected {type_}")
            continue
        if validate is not None:
            if validate(user_input):
                return user_input
            else:
                print(non_valid_msg)
        else:
            return user_input

Which makes your code a lot easier:

def list_of_int(s):
    return list(map(int, s.split()))

if __name__ == "__main__":
    height = ask_user("Please enter height of the triangle: ", int,
                      lambda h: h > 0, "Height must be positive")
    triangle = [ask_user(f"Please enter {n} space separated integer(s): ", list_of_int,
                         lambda l: len(l) == n, f"Exactly {n} numbers required")
                for n in range(1, height + 1)]
    ...


Much of this is nitpicking, but since you keep posting revisions, you seem to want a really thorough review.

The parameter name pCrap to UseCraps.declareResult() isn't explanatory. Try renaming it to something like game instead.
I suggest doing the same for crapObj in main().
getGameResult() should probably be named getState() or something similar, since result implies that it has finished, and there is an UNDEFINED state.
Speaking of which, the state isn't really undefined, it's just unfinished. It should be renamed to something that doesn't imply an error condition.
To be super finicky, you could be declaring your local variables randN, currentNumber, crapObj, point, and inputScan as final.
In Craps.rollDice() you could just return the value instead of storing it in a variable and then immediately returning. The method should also be private.
UseCraps.declareResult() should be private.
In UseCraps.waitUser() you don't need to store the line in input since you don't use it.
Your switch in UseCraps.declareResult() doesn't have a default.
The Craps class should only expose one roll method. It may make sense to keep the two as separate private ones, but you should simplify what your callers need to do to use your class. Consider what happens if someone calls firstRoll and never calls moreRolls, or if they call moreRolls first, or if they go back and forth.
Consider adding a reset method to Craps so you can start a new game without having to create a new instance.
You should check if you are already in a win state when someone calls roll.


Workaround for overloaded constructor in PHP

Given that php allows optional parameters and doesn't require type checking of parameters that are passed in, you can sort of "fake" an overloaded constructor.

something like this:

class CommentPanel extends Panel {
    public function __construct($text_or_comment, $username=null, $timestamp=null) {
        if (is_string($text_or_comment) {
            $this->textConstructor($text_or_comment, $username, $timestamp);
        }
        else { // assume that it's a comment since it's not a string ... there are better ways to handle this though
            $this->commentConstructor($text_or_comment);
        }
    }

    private function textConstructor($text, username, $timestampe) { /* . . . */ }
    private function commentConstructor(Comment $comment) { /* . . . */ }
}

This method will allow for a more consistent API and one that is perhaps more familiar to Java and C++ developers.

Also, I'm not positive which version of PHP you're targeting, but I believe in the current version, uses __construct instead of the class name as the constructor. I'm not sure if this is preferred but the documentation does say that it checks for __construct first and then the class name style constructor, so I would guess that using __construct() instead of CommentPanel() would reduce runtime ever so slightly. I'm not 100% sure on that though, that's just my understanding. Please correct me if I'm wrong :)


Read coordinates from many files and calculate polygon areas

I couldn't run your code, so I can't say how much faster the following will be.

My suggestion is to use NumPy's loadtxt function to get the array of the necessary coordinates. With this function, you can specify skiprows and max_rows parameters to get the necessary rows, 36-45. This should be more efficient than reading all the file in memory.

Here:

areaAr.append(PolyArea(x[36:41],y[36:41]))
distance = max(np.abs(x[36]-x[39]),np.abs(x[42]-x[45]))
modifiedarea.append((PolyArea(x[36:41],y[36:41]))/distance)

you calculate PolyArea two times, but it is enough to calculate it only once and then reuse the result.

The final code could lool like this:

for filepath in df['filepath'].iloc[:10708]:
    values = np.loadtxt(filepath,
                        skiprows=35,
                        max_rows=10)
    x = values[:, 0]
    y = values[:, 1]
    area = PolyArea(x[:5], y[:5])
    areaAr.append(area)
    distance = max(np.abs(x[0] - x[3]), np.abs(x[6] - x[9]))
    modifiedarea.append(area / distance)


General

Task

In my opinion you lost the focus of your task description:

   [...]storing items into an inventory. The container is based on a grid as well as the items going into that container.

The word container can easily be replaced by inventory:

   [...] storing items into an inventory. The inventory is based on a grid as well as the items going into that inventory.

The goal is to store items in an Inventory/Container but currently it stores Shapes instead of Items:

  public class RectangleContainer implements GridContainer {

  /* ... */
  private final Map<GeoPoint, GridShape> content;

  /* ... */

  @Override
  public boolean fitsInside(GridShape shape, GeoPoint location) { /* ... */ }

  /* ... */

  @Override
  public void add(GridShape shape, GeoPoint location) { /* ... */ }

}

What is an Item

 What an Item currently is

  public class RectangleItem<I> implements GridShape, ItemHolder<I> { /* ... */}

To make it simpler to discuss:

  public class Item<I> implements Shape, ItemHolder<I> { /* ... */}

Is Item an Item? When I see only the class name I would say yes, but after looking on the signature I would say: "It could be".
From the signature it is an item that is a shape that holds an item.
Is it an item that holds an other item?

What an Item should be

A Item is something that has a Shape.

  public class Item<I> {

    private I value;
    private Shape shape;

    public Item(I value, Shape shape) { /* ... */ }

}

and an ìtem should be packed into an inventory/container:

public class RectangleContainer implements GridContainer {
    /* ... */
    @Override    public void add(Item item, GeoPoint location) {/* ... */}
}

Code Smell

Feature Envy

Inside RectangleContainer#fitsInside(GridShape shape, GeoPoint location) is the following line:

Collection<GeoPoint> relativeShape = shape.getRelativeShape(location);

The relativeShape gets passed into hasIntersection and isInBounds of RectangleContainer:

  @Override
public boolean fitsInside(GridShape shape, GeoPoint location) {
  Collection<GeoPoint> relativeShape = shape.getRelativeShape(location);
  boolean hasIntersections = hasIntersection(relativeShape);
  boolean isInBounds = isInBounds(relativeShape);
  return !hasIntersections && isInBounds;
}

Because RectangleContainer works with the internals of shape (relativeShape) it is a feature envy.

You could return a custom object PositionedItem that has the methods intersectsNotInside(inventory) and isInBoundOf(inventory):

@Override
public boolean fitsInside(Item item, GeoPoint location) {
   PositionedItem positionedItem = shape.at(location);
   return !positionedItem.intersectsNotInside(this) && positionedItem.isInBoundOf(this);
}

The benefit will be that you will not have duplicate logic for hasIntersections and isInBounds in the different subtypes of GridContainer.

Redundant Public

In both interfaces GridContainer and GridShape you have used the key word public. Per default are fields in an interface are public.

Also valid java:

public interface GridShape {
    boolean fitsInside(GridContainer container, GeoPoint pointer);
    Collection<GeoPoint> getShape();
    GeoPoint getPointer();
    Collection<GeoPoint> getRelativeShape(GeoPoint point);
}

Everything is addable

  @Override
public void add(GridShape shape, GeoPoint location) {
   content.put(location, shape);
}

I could add a shape, that is 1000 times bigger as a RectangleContainer..

The adding of a shape should be checked so that it is not possible to at wrong shapes


double wagesForEmployee(employee e);
bool askUser(std::string s);
std::string employeesToString(std::vector<employee> e);
void displayEmployees(std::vector<employee> e);
void saveEmployeesToFile(std::vector<employee> e);

When you're only reading from a variable and not modifying it, you should take it by const reference. Taking it by value like this means that you copy it.

This is particularly bad in displayEmployees since it makes a copy of the entire employee vector then passing that copy to employeesToString which then makes another copy.

e.id = -1;
e.payrate = -1;
e.hours = -1;

do {
    std::cout << "Enter the employee ID: ";
    std::cin >> e.id;
} while(e.id < 0);

Rather interestingly, you've manged to stumble across a backwards-compatibility breaking change in C++11. As per cppreference:

Before C++11:

  If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.

Since C++11:

  If extraction fails, zero is written to value and failbit is set.

This means that compiled under C++11 or newer, this code is wrong. A better approach is to simply check the result of the extraction directly:

do {
    std::cout << "Enter the employee ID: ";
} while(!(std::cin >> e.id));

Note that this has the behavior of checking whitespace delimited words. In other words, if you want to skip the rest of the line on erroneous input, you'll need to do something likely involving std::getline to eat the rest of the line. As it is, entering something like a b c 5 would output the prompt text 4 times but only actually allow the user to provide input once. (And it would exit the loop with e.id == 5.)

int main(int argc, const char * argv[]) {
    payroll();
    return 0;
}

I'd probably just pull payroll up into main since main doesn't do anything else.
Omitting return 0 silently inserts return 0. In other words, when a program only exits with a success status, you can omit the return statement so that people reading the code can see that at a glance.
If you don't use argc and argv, I wouldn't bother to take them. int main() is just as valid.

double wagesForEmployee(employee e) {
    // #1
    if (e.hours < 0 || e.payrate < 0) {
        return 0;
    }
    double wages = 0;
    // #2
    if (e.hours > WORK_WEEK_HOURS) {
        wages += (e.hours - WORK_WEEK_HOURS) * OVERTIME_RATE * e.payrate;
    }
    // #2
    wages += std::min(e.hours, WORK_WEEK_HOURS) * e.payrate;
    // #3
    return wages > 0 ? wages : 0;
}

If you're going to start applying business rules to employee, I'd put them in the employee class. This would unfortunately complicate complicate the code to prompt for employee information on the command line though.
Super minor and completely opinion: I would calculate normal wages and then add overtime on top. It threw me for a second to realize that overtime was being done first.
When wages >= 0, this is a (logical) no-op. That means that you're verifying that wages are positive. But, earlier in the function, you've verified that e.hours is nonnegative and payrate is nonnegative. OVERTIME_RATE is also presuambly nonnegative. In other words, why is this check here?

As a general note: don't hide error conditions. 0 is presumably a valid return from this function, so using it as an error sentinel is throwing away information. Instead, you need to either assert or throw an exception when you get unexpected inputs. Which you do depends on if you consider invalid inputs programmer error or user error. Personally, I would use assert here since I would expect the consuming programmer to provide a sane employee. (Actually I wouldn't check it at all, but some might say I err too far on the side of anti-precondition-verification.)

Another general note: this is a function that is oriented around an employee instance. It's also deeply aware of the internals of an employee object, and it's coupled to it. You see where I'm going with this, but just in case: this should be a method on the employee class. Stop seeing employee as a data bag, and start seeing it as a class. The e.hours >= 0 and e.payrate >= 0 conditions can be handled on the class, and this method would fit naturally onto it. You could even implement operator<<(ostream&) on it to simply printing it (though personally I have mixed feelings on human aimed operator<<(ostream&) implementations).

With regards to your employee outputting, you should have a function to output a single employee and then loop over that.

Also, Converting employees to a string and then outputting that string is incredibly inefficient. A better approach in C++ than building strings and outputting them is to output to streams and then build a string from that if you so desire. For example:

std::ostream& outputEmployee(ostream& os, const employee& e) {

    // You would of course want to do proper formatting -- just a lazy example.
    // Note that a new line is not included. That is because the newline implies some form of looping is happening, but this function operates on a single employee.
    os << e.id << ' ' << e.payrate << ' ' << e.hours;

    return os; // So the caller can easily check success ala if (outputEmployee(os, emp)) { ... }

    // In a real function, I would be tempted to put the return in the same line as the stream writing.
    // That has the same effect, but it saves a useless `return os;` line.
    // Example: return os << e.id << ... ;

}

std::string employeeToString(const employee& e) {
    std::ostringstream oss;
    // If you wanted to be really paranoid, you could check oss after this call.
    // Nothing should (reasonably) fail though, so meh.
    outputEmployee(oss);
    return oss.str();
}

This is pretty much the exact same process you wrote, but the overhead of buffering into a string only to dump out to a stream is avoided.

As mentioned earlier, you could override operator<<(ostream&). That would have the advantage of being a tiny bit cleaner to call (std::cout << emp << '\n'), and interestingly enough, it would also allow you to use some standard library tricks. For example, if you wanted to loop over outputting a collection of employees:

std::copy(std::begin(employees), std::end(employees),
          std::ostream_iterator<employee>(std::cout, "\n"));

Reading employees in can be done in a similar way if operator>> is overloaded:

std::vector<employee> employees;
std::copy(std::istream_iterator<employee>(std::cout),
          std::istream_iterator<employee>(),
          employees);

As mentioned in passing earlier though, human aimed >> and << make me a little uncomfortable (at least when the operators are defined directly on the class and not some kind of formatting decorator). I more of see them as debugging methods or methods for automatic reading (like parsing in a file or something instead of prompting a user).

I don't like how much saveEmployeesToFile does. I would pull the prompting for file name and opening of the file into at least 1 function and have saveEmployeesToFile take an ostream&. Happy side effect: you can then easily support outputting to std::cout if you want to pass that instead of a file stream.

With regards to saveEmployeesToFile:

Provided that functions stay small and focused, std::ofstream::close() is mostly noise. The file will be closed on destruction anyway.
If you prompt for the file name before you define the std::ofstream instance, you can avoid the open call.
You should verify that the file was successfully opened.

#includes should be alphabetized (though grouped by source first -- local includes first then 3rd party libraries and the standard library).


For Python object names, a single leading underscore denotes private status, like you said.
Unlike other languages, this is not enforced however.
It is only a (strong) suggestion for users of your code not to use these objects.

This could be internal variables, like your self._discount_coefficient.
For example, maybe you implement a @property that secrectly stores something in self._discount_coefficient, but for the calling code, you need to enforce an invariant (in this case, maybe 0 <= self._discount_coefficient <= 1).
This way, users can only set the discount_coefficient instance attribute (notice no underscore) to be within 0 and 1, otherwise an error is thrown.
Nothing keeps people from directly mingling with self._discount_coefficient, however.
Therefore, the convention of underscores; basically a contract where all guarantees you make about your code are void if private objects are modified directly.

Having said all that (which you probably heard of already), it becomes clear that users of your House class can never directly access the variables inside your method anyway.
They either access get_total_charges as a whole, or nothing.
The decision is therefore to either hide get_total_charges as a whole, if it is private, or leave it like in your case.

water_price, electricity_price and total_charges are only temporary variables and tossed the moment the function returns.
They are never relevant to the entire private/public debate because they are never seen from calling code.
If you assigned any of them as instance attributes via self, you would have to decide for or against a leading underscore.

As it is, Version 2 looks fine.
As for remaining style, House() can just be House and the equal signs before json_from_communal_company should not be aligned (looks fine now but is a maintenance nightmare).


How to transform true and false to 1 and 0?

sendMessage(this.name, +!event.target.checked, +event.target.checked)

Not your sending sendMessage(text, !bool, bool) which is silly just send one bool.

Also $(thing).is(":checked") is stupid (jQuery ಠ_ಠ)


First stage of a complex calculator implementation in C++

Never write using namespace ... in a header. You're forcing users of your library to do something they almost certainly don't want to do.

Don't pass strings by value. Pass them by const reference (to avoid making copies) or pass them as std::(C++17) (or boost::) string_view. This also doesn't force the caller to use an actual std::string, a string_view being easily constructed even from a char buffer.

Don't mix responsibilities, separate user input from the rest of the code. Using std::cout in your class quickly becomes wrong when you change the user interface to a graphical one, or if the code ends up in a server application that only responds to network requests.


You can compose query predicates by applying several where clauses in a row.
The predicates must be passed as Expression<Func<T, bool>> for composition.
See LINQ to Entities: Combining Predicates on Microsoft Docs.
Create a general schedules query like this
private IEnumerable<EventSchedule> GetSchedules(
    string tab,
    Expression<Func<EventSchedule, bool>> dateCondition)
{
    var result = Database.EventSchedules
        .Where(s => s.BaseEvent.IsApproved.Value &&
            !s.IsRemoved.Value &&
            s.BaseEvent.EventsCategories.Any(c => c.EventCategory.Name == tab))
        .Where(dateCondition)
        .ToList();
    return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
}

And then pass it the appropriate individual date predicate like this
private IEnumerable<EventSchedule> GetTodaySchedules(string tab) {
    var today = DateTime.Now.Date;
    return GetSchedules(
        tab,
        s => s.RecurrenceStart.Value.Date <= today &&
             s.RecurrenceEnd.Value.Date >= today);
}

private IEnumerable<EventSchedule> GetTomorrowSchedules(string tab) {
    var tomorrow = DateTime.Now.AddDays(1).Date;
    return GetSchedules(
        tab,
        s => s.RecurrenceStart.Value.Date <= tomorrow &&
             s.RecurrenceEnd.Value.Date >= tomorrow);
}


rowscols is not a very good name.
Although on one hand it's "accurate",
on another it's kind of awkward.
How about dimension or dim instead?

res is also not a very good name.
Since its value is dim * dim,
it's the number of cells in the matrix, so cellCount would be better.

It would be better to move the counter variable inside the loop,
by declaring it in the outer loop together with i,
and incrementing it in the innermost loop together with k.

It's a common practice to name loop variables i, j, k.
You skipped j and went directly for k.
It's not a "problem",
but j would be more natural,
especially because at school (I think) they teach matrices typically with \$m_{ij}\$ notation rather than \$m_{ik}\$

Lastly,
since the result of the function is a matrix,
it will be more meaningful to call the variable matrix instead of result.

Suggested implementation

Putting the above suggestions together:

static int[,] CreateMatrix(int dimension)
{
    var matrix = new int[dimension, dimension];

    var cellCount = dimension * dimension;

    for (int i = 0, counter = 0; i < dimension; ++i)
    {
        for (int j = 0; j < dimension; ++j, ++counter)
        {
            matrix[i, j] = cellCount - counter;
        }
    }

    return matrix;
}

Special thanks to @Abbas for pointing out to use the var keyword instead of explicitly declaring the matrix and cellCount variables.


The use of magic numbers isn't great.  Your xTest functions should really have Boolean return values, which would allow you to remove the local storage of the result and simplify further (relying on operator short-circuiting):

void testNumber(int number) {
    if (sameDigitsTest(number) || decreasingTest(number) || increasingTest(number)) {
        nonBouncyCounter++;
    }
    else if (bouncyTest(number)) {
        bouncyCounter++;
    }
}

(Note that the latter does actually work with the current int return values, but it appears that you've only coded them that way to fit your original implementation; it's unnecessary complexity.)


Instead of having Node use getters and setters, just make it a struct declared within the private section of LinkedList.  It won't need its own files, either.
All but one of your functions are in PascalCase.  Whether you choose that or camelCase, choose just one and maintain that.  This should be kept consistent.
When creating a new linked list, the head should first point to NULL (or nullptr in C++11) to indicate an empty list.  You're instead having the head point to a new node, so the list isn't really considered empty at the start.
You have an empty destructor, even though you allocate memory with new.  In order to prevent memory leaks, the destructor should use delete on each allocated Node.  This is typically done with a loop through the list.
Member functions that don't modify data members should be const.  This also prevents any accidental modifications to data members within these functions.

An example with your get_count() function:

int LinkedList::get_count() const {
    return count;
}


Create individual files via Bash with MD5 hashes of all files in a directory recursively

A gotcha, sort of...

Although the one-liner works, the use of $0 is inappropriate. From man bash:

   -c        If the -c option is present, then commands are read from  the
             first non-option argument command_string.  If there are argu-
             ments  after  the  command_string,  the  first  argument   is
             assigned  to  $0  and any remaining arguments are assigned to
             the positional parameters.  The assignment  to  $0  sets  the
             name  of  the  shell, which is used in warning and error mes-
             sages.

That is, the file names to compute MD5 for are not appropriate values as the "shell". Positional arguments are in $1, $2, and so on, that would be appropriate for this purpose. You can fix that using the -- special argument, that signals the end of options and disables further option processing:

find ... -exec bash -c 'printf $(md5 -q "$1") > "${1%.*}.md5"' -- {} \;

Simplify

Is it really important to strip the .jpg at the end of filenames?
Would it be terrible if the files looked like this?

./2016/05/17/photo-312.jpg
./2016/05/17/photo-312.jpg.md5
./2016/05/19/photo-1234.jpg
./2016/05/19/photo-1234.jpg.md5
./2016/05/19/photo-5678.jpg
./2016/05/19/photo-5678.jpg.md5

Because that would simplify the script a bit.

Is it really important to print only the MD5 digest without trailing newline?
That would simplify the script a bit more.
And that would get rid of the -q flag which is only supported by BSD's  md5 tool, and not by GNU's md5sum.
With this change, the script would be usable in Linux by defining md5 as an alias to md5sum.

Actually, it would be great to install GNU's md5sum (md5sha1sum package in Brew and MacPorts), because it has a -c flag to verify the file easily. For example, you would be able to verify the checksum of all files with:

find . -name '*.md5' -execdir md5sum -c {} \;

To create the files:

find . -type f -name "*.jpg" -execdir sh -c 'md5sum "{}" > "{}".md5' \;

Note that -execdir is necessary instead of -exec, so that the filenames don't have the directory part. Otherwise the .md5 files would contain the full path of files, and the md5sum -c verification would only work if invoked from the same relative path from where the digest file was created.

Use sh if good enough

The Bash script in -exec doesn't do anything Bash specific, so you could replace bash with sh.

Redundant "%s" in printf

Instead of printf "%s" something you could simply write printf something.


Prefer std::size_t for the word count and count_words()'s return type.  Also prefer std::string::size_type for the loop counter (when using indices is needed).
count_words()'s parameter should be passed by const& since it's not being modified:

std::size_t count_words(std::string const& input_text) {}

count_words() has a problem.  If I press ENTER without typing anything, it gives me 1.  To fix this, return 0 if the string is empty:

if (input_text.empty()) return 0;

In the for-loop, prefer std::isspace for detecting whitespace.
Prefer iterators over indices for std::string:

for (auto iter = input_text.cbegin(); iter != input_text.cend(); ++iter)
{
    if (*iter == isspace)
    {
        number_of_words++;
    }
}

If you have C++11, use this range-based for-loop instead:

for (auto& iter : input_text)
{
    if (iter == isspace)
    {
        number_of_words++;
    }
}

As @r-s mentions, this just counts whitespace.  Here's another solution from this answer:

unsigned int countWordsInString(std::string const& str)
{
    std::stringstream stream(str);
    return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());
}

I realize this may be difficult to understand.  I'd still recommend holding onto the answer for future reference.  If you want to try it out, include <sstream> and <iterator>.


Top level docstring

It is good practice to start a file with a string delimited by triple quotes that explains the general purpose of your file.

Python treats it specially and displays it when queried for help(your_module) and saves it in the __doc__ special variable.

Other people will get to know the general purpose of the code without reading it all.

A very basic start would be:

"""
This script adds time-stamps to images,
with particular regards to Mondays.
"""

Confusing parameter name

You write def get_date_string(optionalArg): where optionalArg is not actually optional... I am forced to provide it, an optional argument is one like def foo(a=1):

When names contrast the code I become very confused, also I do not think that kind of returning if not None is so useful, but I am not sure...

Actually you only call the function from:

image_date = get_date_string(args.d)

So you can remove the argument and the None check and call it like:

image_date = args.d or get_date_string()

Or, the equivalent:

image_date = args.d if args.d is not None else get_date_string()

Reduce nesting

else:
    today = datetime.datetime.today()
    if today.weekday() == 0:
        t = today
    else:
        t = today - timedelta(days=today.weekday())
    return t.strftime("%m/%d/%Y")

Becomes:

today = datetime.datetime.today()
if today.weekday() == 0:
    t = today
else:
    t = today - timedelta(days=today.weekday())
return t.strftime("%m/%d/%Y")

Because you already returned, and when you return the function ends, so you can reduce nesting and make it clearer that the None check is just a precondition.

Inline ternary

I like ternaries because they are less powerful than conditionals, being less powerful means that they are easier to read and understand too:

if today.weekday() == 0:
    t = today
else:
    t = today - timedelta(days=today.weekday())

Becomes:

t = today if today.weekday() == 0 else today - timedelta(days=today.weekday())

Monday is equal to zero, but you should not care

You write today.weekday() == 0 to check if  weekday is Monday, but it is much more intuitive to read: today.weekday() == MONDAY

To allow this just add:

MONDAY = 0

at the top of your code, and you gained a lot of readability with a small effort.

Avoid single letter names

t tells me nothing about the purpose of this variable, try and think about a more descriptive name.

200 it was said...

def significant_difference(v, previous_v):
    return abs(sum(v) - sum(previous_v)) > 200

Why 200? This is very confusing, make a constant containing that value and give an explanatory name to it, because a random magic number 200 in the code just leaves me wondering...

Similar ...

The function find_v_border and find_left_border are similar, but sadly I cannot think of a way to abstract the similarity out... I just wanted to point this out as a possible further modularization possibility.

Not needed global

global is needed only when modifying global variables, so you may delete it from draw_on_image.

Re-use

Re-using singular functions is impossible now, as all the script will get executed if I import it, just putting the top-level code under a if __name__ == "__main__": will allow the re-use of single functions.

Function for deciding name and content

This block of code:

if "server" in str.lower(file_name):
    text = " Server Systems"
    new_file_name =  "labelled_server.png"
elif "desktop" in str.lower(file_name):
    text = " Desktop Desktop"
    new_file_name = "labelled_Desktop.png"
else:
    text = " All Systems"
    new_file_name = "labelled_all.png"

Only does one thing, so extracting it to a function looks like a good idea:

def find_text_and_new_name(file_name):
    if "server" in str.lower(file_name):
        return " Server Systems", "labelled_server.png"
    elif "desktop" in str.lower(file_name):
        return " Desktop Desktop", "labelled_Desktop.png"
    else:
        return " All Systems", "labelled_all.png"

Calling this from the top-level makes it more abstract, and you always want your top-level code to be as abstract as possible.

Increase generality

The draw_on_image function may easily be customized by the use of optional arguments, for example why should font always be 16? Making it an optional argument increases generality thus utility of your function.

(minor) Avoid unnecessary assignment

os.path.sep is never going to change, so you do not need to store it in another variable.


Reorder objects based on provided enumerable order

If the list on input is going to be short, or if performance doesn't matter to you, you can simplify the code by using IndexOf() instead of the dictionary:

public void ReorderElements(IEnumerable<int> elementSks)
{
    var elementsToReorder = GetSession().QueryOver<DocumentElement>()
        .WhereRestrictionOn(de => de.DocumentElementSk).IsIn(elementSks.ToArray()).List();

    var elementOrder = elementSks.ToList();

    foreach(var element in elementsToReorder)
         element.DisplayOrder = elementOrder.IndexOf(element.DocumentElementSk);

    this.Save(elementsToReorder);
}


class apples{

Naming your class something like apples is always wrong. Java class names start with a Capital letter and are written in CamelCase. Thus, regardless of whether the name itself is good, it should be spelled Apples, not apples.

Also, you need to add a javadoc comment to the class that explains exactly what it does, when to or not use it, and all that.

About the name itself, now. Is Apples really a good summary of what this class is? Looking at your dialogue, probably not; maybe BasicInteractiveCommandlineCalculator would be a better fit? In any case, change the name to something that actually has to do with the class's purpose.

public static void main(String args[]){

Again, no javadoc. Javadoc for a main method should include information about what arguments it takes or how to invoke it. Pretend you were calling it from the command line, exactly what arguments are you passing it? If it doesn't take any arguments, say no args, but at least say something.

Scanner checker = new Scanner(System.in);

Here, checker isn't exactly a great name for this. Call it something shorter, like in.

While your initialization of the scanner is fine, it really ought to be created in a try-with-resources, so you can easily change to use a different input stream as needed, like a file. Instead write:

try(Scanner in = new Scanner(System.in)){

System.out.println("Calculator Program Initialized");
System.out.println("Please select your math operator");
System.out.println("Enter 1 for Addition");
System.out.println("Enter 2 for Subraction");

Doesn't this seem a little wordy for a simple calculator app? You should try talking less, and just say what you mean.

Also, you shouldn't use System.out for permanent output statements. Instead, add another declaration to your try statement. That way, you can easily change the desired stream later, with only minimal modification:

try(Scanner in = new Scanner(System.in); PrintStream out = System.out){

Now, replace the dialog with a much shorter one:

out.println("Enter operation (+ or -):");

Match the input then with in.next(String regex), so it will just wait until there is a valid input.

Handling the input should be way easier, too. Using java 7, we can switch on a string value:

String op = in.next("[+-]");

// ...

switch(op){
case "+": // ...
case "-": // ...
}

If you don't have java 7, then you should still allow the user to input this way, you just need to use if statements instead.

Now, the main problem, though, is in the way it handles the following dialog. Not only is some of the dialog itself duplicated, confusing data with logic, but in the way it computes the answer.

Refactoring the dialog out, and simplifying it, we get much, much neater code:

out.println("x=");
fnum = in.nextDouble();
out.println("y=");
snum = in.nextDouble();

switch(op){
case "+": answer = fnum + snum; break;
case "-": answer = fnum - snum; break;
default: answer = Double.NaN;
}

out.println("x" + op + "y=" + result);

This here is only the most basic level of revisions that ought to be made to the code. An application or command that attempts to do this would be expected to support all standard mathematical operations, and to be able to parse a complete expression passed to it as a string.

I once wrote a program like that, that supported all java operators and every function from java.util.Math. My approach was to use a runtime compiler janino to compile as java source code an expression given to it. (It probably would have been simpler to just use syntax trees though; configuring everything was a nightmare.)


Simple random falling object animation in Java

Here is my list of possible improvements:

Constants should be made final and if possible also private

private static final int WINDOW_WIDTH = 1300;
private static final int WINDOW_HEIGHT = 800;
private static final int SQUARE_WIDTH = 25;
private static final int SQUARE_HEIGHT = 25;

Class members should remain private, if accessible from other classes use setters/getters

private int randNumb = 0;
private int squareYLocation = -SQUARE_HEIGHT;
private boolean numberCreated;
private boolean gameRunning;

'

Limit class methods visibility, if no other class uses them

private void generateRandomNumber() {
    Random rand = new Random();
    randNumb = rand.nextInt(windowWidth - squareWidth);
    numberCreated = true;
}

private void paint(Graphics g) {
    g.setColor(Color.black);
    g.fillRect(0, 0, windowWidth, windowHeight);
    g.setColor(Color.BLUE);
    g.fillRect(randNumb, squareYLocation, squareWidth, squareHeight);
}

Don't use one letter names for object instances, use the full name or give an appropriate name that is easy to understand or reflects something relevant.

private void paint(Graphics graphics) {
    graphics.setColor(Color.black);
    graphics.fillRect(0, 0, windowWidth, windowHeight);
    graphics.setColor(Color.BLUE);
    graphics.fillRect(randNumb, squareYLocation, squareWidth, squareHeight);
}

Consistent use of Whitespace, it ok to add extras white lines but be consistent about it. Eg. update/main have a whiteline, other methods don't.
The naming of numberCreated was a bit confusing, I first thought it was only generated once but after looking through the code I saw that the flag could be set to false again. I would suggest changing to a different name eg invalidateNumber or something else that makes it more clear.
App extends JFrame is not a good name for the class, GameFrame extends JFrame would be better. And even better would be the use of the composition pattern to have an App class. (You can separate your game logic from its View (MVC)).
Commenting style is not really conform the guidelines. Your style for inline comments is ok. But normally method comments are something like this:

 /**
  * Your comment goes here, also use
  * @param for your params
  */
 public void paint(Graphics g) {
     g.setColor(Color.black);
     g.fillRect(0, 0, windowWidth, windowHeight);
     g.setColor(Color.BLUE);
     g.fillRect(randNumb, squareYLocation, squareWidth, squareHeight);
 }


Pythonic way for double iteration (list all files with extensions)

If you only need to iterate over them (once) and not an actual list, you could use itertools.chain and glob.iglob:

files = chain(*(iglob(path.join(DOC_PATH, ext)) for ext in EXTENSIONS))

If you do need an actual list, you can further call list(files), of course.