This looks pretty good!  A few notes (some stuff you may still have to learn about since you are a beginner, such as pointers)

Your method isn't what I would consider "normal".  To see what I
mean, take a look at the function prototype of the standard library
function strcat():

char * strcat ( char * destination, const char * source );

As you can see, the standard library only takes in two parameters,
not 5.  This makes sense too: as the caller I want to throw in two strings and only get one returned back to me.  For a string concatenation function, I shouldn't have to manually enter in the length of the strings I want to concatenate, the function should be able to handle that.
So how do we find the length of a string exactly?  Well, we can iterate through a string until we find the \0 character (termination character).

while(*dest != '\0') /* find the end of the string */
{
     dest++;
}

All this loop does it start at the beginning of the dest string and find the end of it, very simple.  The next loop is a bit more complicated:

while((*dest++ = *source++) != '\0'); /* copy source */

This code iterates through the source string, and while it iterates through it, it appends the contents to dest (which we are doing by iterating dest at the same time as source).  We do this until we reach the \0 character.
We should be returning a value from the function.  This is more for a convenience to the caller.  This allows me to do stuff such as

puts(concat(strdup("test"), "this out"));

Rather than this longer piece:

char* str = strdup("test");
concat(str, "test");
puts(str);

strcat can be dangerous because if the string to be appended is too long to fit in the destination buffer, it will overwrite adjacent memory, invoking undefined behavior. Usually the program will simply cause a segmentation fault when this occurs, but a skilled attacker can use such a buffer overflow to break into a system.

To prevent buffer overflows, several alternatives for strcat() have been used. All of them take an extra argument which encodes the length of the destination buffer and will not write past that buffer end. All of them can still result in buffer overflows if an incorrect length is provided.

char* strncat(char *dst, const char *src, size_t n);

This will require a bit of modification to the copying for checking n, but not much.

Final Implementation (assuming no standard library functions can be used):

char* concat_s(char *dest, const char *src, size_t n)
{
    if (n != 0) // if n == 0 then we aren't concatenating anything...
    {
        while (*dest != 0)
        {
            dest++;
        }
        do
        {
            if (0 == (*dest = *src++)) break;
            dest++;
        } while (--n != 0);
        *dest = 0;
    }
    return dest;
}

Final Implementation (assuming all functions can be used except strncat()):

char* concat_s(char *dest, const char *src, size_t n)
{
    return memcpy(dest + strlen(dest), src, n);
}


Extract numbers from an AlphaNumeric string

If you want to extract both at the same time (I don't know if it is a requirement, it isn't clear in the question) you should iterate once through each character to place them in different lists.

  Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
  Dim characters As List(Of Char) = New List(Of Char)()
  Dim numbers As List(Of Char) = New List(Of Char)()
  For Each c As Char In input
     If (Char.IsNumber(c)) Then
        numbers.Add(c)
     ElseIf (Char.IsLetter(c)) Then
        characters.Add(c)
     End If
  Next

'Do whatever you have to do here

Edit

As pointed out @mjolka, since the goal of the user is to show the splitted numbers and letters, a StringBuilder would be more appropriate. Here is my updated answer :

  Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
  Dim characters As StringBuilder = New StringBuilder()
  Dim numbers As StringBuilder = New StringBuilder()
  For Each c As Char In input
     If (Char.IsNumber(c)) Then
        numbers.Append(c)
     ElseIf (Char.IsLetter(c)) Then
        characters.Append(c)
     End If
  Next

'Do whatever you have to do here


You can use explicit find like so

$ 'thead tr th', @dom.table

and put some indentations instead of braces

table_with_headers = $ "thead tr th", @dom.table
.map -> @.text()
.join '\t'

Also try to use list comprehesion

table_with_headers = [
  $(th).text()
  for th in
  $ "thead tr th", @dom.table
].join '\t'


Ordering a .txt file numerically by size and alphabetically

My first suggestion would be to use some extra functions. However, let's look at it in several parts.

First, the getting of the class number. You have

classcheck = False
while classcheck == False:
    classnumber = input("what class are you in")
    if classnumber == "1":
        print()
        classcheck = True
    elif classnumber == "2":
        print()
        classcheck = True
    elif classnumber == "3":
        print()
        classcheck = True
    else:
        print("that is not a valid class number")

The if statements are quite the same. By using set-membership, we can reduce the duplicate code.

classcheck = False
while classcheck == False:
    classnumber = input("what class are you in")
    if classnumber in {"1", "2", "3"}:
        classcheck = True
    else:
        print("that is not a valid class number")

Furthermore, writing while foo == False: is not really idiomatic Python. Better would be while foo:. But, in this case you're trying to emulate a do {...} while (...) loop. I'd suggest writing it as follows:

while True:
    classnumber = input("what class are you in")
    if classnumber in {"1", "2", "3"}:
        break
    print("that is not a valid class number")

The asking of the name is quite obvious, let's move to the part where the questions get asked:

for i in range(10):

The variable i does not actually get used. It's a minor nitpick, but convention has it that you should write

for _ in range(10):

instead.

    question1no1 = random.randint(1,20)
    question1no2 = random.randint(1,20)

What is question1no1 referring to? This will also be executed for question 2 to 10. Maybe operand_left and operand_right would be better names? Leaving them be for now, but it's something you can ponder about.

Next, the creation of the 'puzzle'/question.

    operators = ['+','-','*']
    op_number  = random.randint(0,2)
    op_sym = operators[op_number]
    op = op_number

    if op == 0:
        ans = question1no1 + question1no2
    elif op == 1:
        ans = question1no1 - question1no2
    elif op == 2:
        ans = question1no1 * question1no2

There are a few lines between the definition of the operators, and the calculation of the desired result. First suggestion: use random.choice(operators) instead of random.randint(0, 2)

    operators = ['+','-','*']
    op_sym = random.choice(operators)

    if op_sym == '+':
        ans = question1no1 + question1no2
    elif op_sym == '-':
        ans = question1no1 - question1no2
    elif op_sym == '*':
        ans = question1no1 * question1no2

Already a lot clearer, no? Still, I've typed the + sign 3 times here. By using the operator module, I could write:

import operator
...
...

    operators = [
        ('+', operator.add),
        ('-', operator.sub),
        ('*', operator.mul),
    ]
    op_sym, op_func = random.choice(operators)
    ans = op_func(question1no1, question1no2)

Adding a new operator would be a simple method of adding another line in the list above.

I'll assume the explicit print statements are a bit of debugging work, and ignore those. Ideally you'd remove them.

Look at how you write the question.

    question = "what is "+str(question1no1) + str(op_sym) + str(question1no2)+"?"

There are so many things going on, it is a bit worry-some. Also, you might want to add a space around the operator, causing the need for yet some more work. By using string formatting (https://docs.python.org/3.5/library/stdtypes.html#str.format), you can make it a bit simpler:

    question = "what is {} {} {}?".format(question1no1, op_sym, question1no2)

Now, we get to student1answer1. Why not just answer? (Or given_answer, and rename ans to expected_answer).

As for checking the results:

    if str(student1answer1) == str(ans):
        print("congrats you got the answer right")
        student1score = student1score + 1

    else:
        print("sorry you got the answer wrong")

You can remove the empty line between the if and the else block. But more importantly, instead of

        student1score = student1score + 1

you can write

        student1score += 1

with the same effect.

At the end, we also see duplicated code regarding to the class numbers:

if classnumber == "1":
    class1score = open("class1score.txt", "a")
    class1score.write("\n" + student1name + (" ") + str(student1score))
    class1score.close()

if classnumber == "2":
    class2score = open("class2score.txt", "a")
    class2score.write("\n" + student1name + (" ") + str(student1score))
    class2score.close()

if classnumber == "3":

    class3score = open("class3score.txt", "a")
    class3score.write("\n" + student1name + (" ") + str(student1score))
    class3score.close()

It should be quite obvious that the only difference in these statements is the filename. "Easy" fix:

if classnumber == "1":
    filename = "class1score.txt"
if classnumber == "2":
    filename = "class2score.txt"
if classnumber == "3":
    filename = "class3score.txt"

class_score = open(filename, "a")
class_score.write("\n" + student1name + " " + str(student1score))
class_score.close()

But the if is now still very suspicious. Let's replace those 3 if-statements with 1 statement:

filename = "class" + classnumber + "score.txt"

or

filename = "class{}score.txt".format(classnumber)

(my preference is the second).

Finally: please use capitalization when writing strings for the end-user. So, instead of "what class are you in", write "What class are you in? ". (The final space is to make the question look even better when entering the data, but that's merely convention.)

After making the changes, I ended up with

import operator
import random

while True:
    classnumber = input("What class are you in? ")
    if classnumber in {"1", "2", "3"}:
        break
    print("That is not a valid class number.")

student1name = input("Please enter your name: ")
student1score = 0

for _ in range(10):
    question1no1 = random.randint(1,20)
    question1no2 = random.randint(1,20)

    operators = [
        ('+', operator.add),
        ('-', operator.sub),
        ('*', operator.mul),
    ]
    op_sym, op_func = random.choice(operators)
    ans = op_func(question1no1, question1no2)

    question = "What is {} {} {}? ".format(question1no1, op_sym, question1no2)

    student1answer1 = input(question)

    if str(student1answer1) == str(ans):
        print("Congrats, you got the answer right!")
        student1score += 1
    else:
        print("Sorry, you got the answer wrong.")

print("Your score was " + str(student1score) + " out of 10.")

filename = "class{}score.txt".format(classnumber)
class_score = open(filename, "a")
class_score.write("\n" + student1name + " " + str(student1score))
class_score.close()

Also, I'd like to change the last write to have the "\n" at the end instead of at the beginning, as it's convention to end a line with a "\n" instead of starting one with it. But that's up to you, as it would change the semantics of the script.


Uncompressing a list with some run-length-encoded elements

There is a slight difference in the order of evaluation, in that the book's solution recurses before calling consp, whereas your solution recurses after calling consp. Either way, the recursion happens before concatenation, because the innermost expressions in (append (apply #'list-of elt) (uncompress (cdr lst))) and (cons elt (uncompress (cdr lst))))))) have to be evaluated first.

I think that your solution is a bit worse than the book's, in that the common expression (uncompress (cdr lst)) is written twice.


Abstract the (duplicate?) behavior between "sort" and "replace"

I think the later versions are unnecessarily complicated and verbose.

My first idea was to just concatenate the splitted list parts in replace-all – for you can do (concatenate 'string seqs ... ) – but that may not be very efficient.

You can use map or loop for replace-all. This map version works for lists too:

(defun replace-all (seq from to)
  (map (type-of seq) (lambda (char) (if (equal from char) to char)) seq))

Naming things clearly can sometimes be hard, and I think sometimes being terse helps readability more than being too-explicit-and-specific. That if statement above could need some better naming of things...

There is an utility library called split-sequence, that has many useful options, like

remove empty subsequences
only split count times
return the index position (useful for further processing)

I'm still learning Lisp, so you may want to hear see other answers also.


Dynamically Change Logging Level of a Python Process

Logger.setLevel() is the right way to dynamically change the logging level of a Logger object. Your script will work fine.

I'll nitpick:

Code is read from top to bottom. You should place the comments above the group of statements they are attached to, not below them. If the reader reads the comment first, they won't have to spend extra effort to decipher the meaning of the following lines, because they have read the annotation first.
Be wary of using asynchronous signal handlers when you are using the logging module. I know that this is a tiny example script, but always refer to the documentation when you are using the Python standard library.


You have introduced some weird an IMO unnecessary scope blocks here:

    {
        for(i=0;i<=strlen(pass);i++)
        if( isupper(pass[i]) )
        flag1=1;
        else if(isdigit(pass[i]))               //Loop to check if all element in pass has a digit, alpha & '$'
        flag2=1;
        else if(pass[i]=='$')
        flag3=1;
    }

and here:

            {
                if((flag1==1) && (flag2==1) && (flag3==1))      //All condition true
                {
                printf("\nNice Password!");
                }
                else
                    {
                    printf("\nPassword must contain a upper case letter, a number and a $ sign");  //Something missing
                    }
            }

The code should be reformatted like this probably:

        for(i=0;i<=strlen(pass);i++) {
            if( isupper(pass[i]) ) {
                flag1=1;
            }
            else if(isdigit(pass[i])) {               //Loop to check if all element in pass has a digit, alpha & '$'
                flag2=1;
            }
            else if(pass[i]=='$') {
                flag3=1;
            }
            if((flag1==1) && (flag2==1) && (flag3==1)) {     //All condition true
                printf("\nNice Password!");
            }
            else {
                printf("\nPassword must contain a upper case letter, a number and a $ sign");  //Something missing
            }
        }


Class method to insert a record into MySQL

There's nothing wrong with it, but it's a small piece of code. Some minor details are:

1: I would write $table instead of $tbl, why abbreviate it? You also write foreach ($data as $key => $value), which is very general. Why not specify it better: `foreach ($row as $column => $value)'? What I mean is that variable names should have meaning. I know an array has keys and values, but they are general names. Here you should use names that tell you what a variable really represents.

2: $this->_stmt is a class variable, where a local $statement variable would do. Local variables are always more efficient and have even better encapsulation.

3: Also watch your line length: 156 characters is too much. Instead of writing this:

$this->_stmt = $this->_dbh->prepare("INSERT INTO $tbl (" . implode(', ',
array_keys($data)) . ") VALUES (:" .  implode(', :', array_keys($data)) . ")");

(I wrapped it for clarity), you could have written something like;

$rowkeys   = array_keys($row);
$columns   = implode(',',$rowkeys);
$values    = ':'.implode(',:',$rowkeys);
$query     = "INSERT INTO $table ($columns) VALUES($values)";
$statement = $this->handle->prepare($query);

This makes it easier to read, and debug. It may seem longer, but effectively it does the same thing.

4: You could build in error checks. Is the array a valid array to insert? Start with is_array() for instance. Do the column names exist in the table? Does the insert execute properly? No errors?

5: you could return the lastInsertID(): http://php.net/manual/en/pdo.lastinsertid.php

6: You cannot insert multiple rows at once with this method. Perhaps you don't need this, but if you do you could add that functionallity.

7: You bind values, so that's quite secure. However, are you sure your column names can never be influenced by outside sources (= hackers)? Another good reason to check them, because they go straight into your SQL command.

8: Please note that wrapping PDO can be a burden later. See: Class for reducing development time If that puts you complete off, don't worry, I also use a wrapper despite all that good advice.


Converting a 32bit number in a proprietary timestamp with PHP

Not being a PHP expert, but messing with bitwise operations a lot, I have some advice for you:

First, the specification for your operations should be embedded with the code as a comment. Having to look up a specification that may or may not be the same as the one you used when programming it, is not useful... and changing between screens/pages to inspect the code vs. the specification is also not much fun. Something like:

// Input data is 4 bytes with following bit-specification:
// Byte0  (least significant)
//     0-5 : minutes
//     6   : reserved
//     7   : valid
// Byte1
//     0-4 : hours
//    ........

This makes it easier to compare/validate your code.

My next suggestion is to shift the data as you pull values off... This way you don't need to do 'brain-mushing' thinking when doing the manipulation.

// get the first 6 bits
$min = $decimal & 63; // 111111 in binary
$decimal = $decimal >> 6; // get rid of those 6 bits,
                          // now we only need to worry about low bits.

Then, the next suggestion is to set up some 'constants' for your masks:

$mask6bits = (1 << 6) - 1; // 00111111 in binary.

Now, the example above becomes:

// get the first 6 bits
$min = $decimal & mask6bits;
$decimal = $decimal >> 6; // shift off minutes

Then, I recommend you process the fields you don't need, and it helps you keep track of the specification:

// get the first 6 bits
$min = $decimal & mask6bits;
$decimal = $decimal >> 6; // shift off minutes

$decimal = $decimal >> 1; // shift off reserved

$decimal = $decimal >> 1; // shift off valid

$hours = $decimal & mask5bits;
$decimal = $decimal >> 5; // shift off the hours.

Follow the same pattern for the other bits...

This is a relatively concise way to do things, actually, and you only need to keep one 'dimension' (the length of each data value) of the problem in your head, and you can ignore the offset.

This leads to fewer bugs, and better understanding and readability.

I cannot find a definitive reference whether PHP supports a definitive >>= assignment operator. If it does, the lines $decimal = $decimal >> 5 can be replaced with $decimal >>= 5


Adding a new class to HTML tag and writing it back with Beautiful Soup

The second option is better, because the possible error is explicit. However, in lots of case in Python, you should follow EAFP and go for the try statement. However, we can do better.

get(value, default)

In BeautifulSoup, attributes behave like dictionaries. This means you can write img_tag.get('class', '') to get the class if it exists, or the empty string if it doesn't.

def add_img_class(img_tag):
    img_tag = img_tag.get('class', '') + ' img-responsive'

You don't need to return the new img_tag as it is passed by reference. Now that your function is a one-liner, you might as well use the one-liner directly.

Multi-valued attributes

Note that the above code doesn't work! class is a multi-valued attribute in HTML4 and HTML5, so at least BeautifulSoup 4 returns a list instead of a string. The correct code becomes:

img_tag['class'] = img_tag.get('class', []) + ['img-responsive']

Wich is nicer as you don't have to worry about the extra space between the two values.

Encoding

You don't need to convert to UTF-8 before writing the file back. What's wrong with &nbsp;?


The jQuery documentation offers the best advice:

  Event performance

  In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.

Obviously it would be ideal if you could move the calculations outside the event handler to reach the desired performance, but that may not be possible in this case. So to expand on the rate-limiting approach, there are 2 ways you could go about it:

Call event handler after the user has finished scrolling (hasn't scrolled for some set amount of time):

var timer = null;
$(window).scroll(function () {
  if (timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(function() {
    timer = null;

    // your event handling logic here
  }, 50);
});

Call event handler immediately after scrolling, with a minimum delay between scroll events:

var justExecuted = false;
$(window).scroll(function() {
  if(justExecuted) {
    return;
  }

  // your event handling logic here

  justExecuted = true;
  setTimeout(function() {
    justExecuted = false;
  }, 50);
});


If you are only executing this once, it should work fine as is.  If you are going to execute it more than once per century, you should use the Sieve of Eratosthenes, as suggested by Somnath Rakshit.

Using the algorithm as described on wikipedia:

static class MathExtensions
{
    static public List<int> GetPrimes(int start, int end)
    {
        List<int> res = new List<int>();

        // 1. Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
        int[] numbers = Enumerable.Range(0, end).ToArray();

        // 2. Initially, let p equal 2, the first prime number.
        int idx = 2;
        do
        {
            // If the number is in range, add it to the result
            if (numbers[idx] >= start)
            {
                res.Add(numbers[idx]);
            }

            // 3. Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked).
            for (var i = idx; i < end; i += idx)
            {
                numbers[i] = 0;
            }

            // 4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
            while (idx < end && numbers[idx] == 0)
            {
                idx++;
            }
        }
        while (idx < end);

        return res;
    }
}


Finding a sum of unique triplet that is close to a given number in an array

Algorithm - Reducing search space

I'd define kMax as num.length - 1.

Then, do a binary search for the point at which num[0] + num[1] + num[k - 1] is too low, and num[0] + num[1] + num[k] is too high. Set kMax to k.

Next, do a binary search for the point at which num[i] + num[kMax - 1] + num[kMax] is too high, and num[i - 1] + num[kMax - 1] + num[kMax] is too low. Define iMin to be i - 1.

Start your for loop loop with index at iMin. At the start of each iteration, set k to kMax.

Instead of your current moving up/moving down scheme, just start downing k. As long as [i][j][k-1] is too high, kMax = k. When [i][j][k-1] is no longer too high, resume your uppy-downy scheme.

Whenever you increment i, check if [i][k-1][k] is too low. If so, increase i until [i][k-1][k] is no longer too low. Check if [i-1][k-1][k] gives a better match and store it as temp.

AFter changing scope like this, check the opposite end of the scope. So if you just reduced k, check if [i][k-1][k] is too low. If you just increased i, check if [i][i+1][k] is too high. Do this until scope is stable.

Perhaps binary search could speed this (upping i and downing k) up too, but I'm not sure.

What this would do is potentially eliminate is a lot of your search space.

You see, if I gave you the number 42 to find in an array that contained random numbers between -500 and +200, -500, +199, +200 is simply too low. So you can kill off any number that's below -357, provided it's not the last number at or below -357.

This is a reduction of 20% of your search space with a simple binary search.

Additionally, once we get to -70, any number greater than 182 that is not the last number at or above 182 is not going to help.

Binary search is blazingly fast. 10000 elements can be searched through in 13-14 array accesses. 100000 elements - 17 array accesses.

Consider stopping binary search when your scope size is less than 128 (your code should go blazingly fast at that point anyway).

Your code

for (int index = 0; index < num.length - 1; index++)

For an array of 3 elements... index < num.length - 1 means index < 3 - 1 means index < 2.

So you've got a problem; You'll eventually check [1][2][2]. Your fix for this is while(j < k), but I think you'll be better served by changing the for loop header to be for (int index = 0; index < num.length - 2; index++) (changing index < num.length - 1 to index < num.length - 2). And then adding a comment WHY it is 2.

        int newSum = Math.abs( target - ( num[index] + num[j] + num[k] ) );
        if( newSum == 0 ) {
            return ( num[index] + num[j] + num[k] ) ;
        }
        else if ( num[index] + num[j] + num[k] < target ) {
            //code
            result = num[index] + num[j] + num[k];

You have here, in a single iteration, 2 to 3 summations of num[index] + num[j] + num[k]. Some languages will cache these values. Some languages will not. I'd get in the habit of summing them once, then doing what you must.

        else if ( num[index] + num[j] + num[k] < target ) {
            if( newSum < tempSum ) {
                tempSum = newSum;
                result = num[index] + num[j] + num[k];
            }

            j++;
        }
        else {
            if( newSum < tempSum ) {
                tempSum = newSum;
                result = num[index] + num[j] + num[k];
            }
            k--;
        }

Haaang on.

I think you can unduplicate your code here:

        else {
            if( newSum < tempSum ) {
                tempSum = newSum;
                result = num[index] + num[j] + num[k];
            }
            if(num[index] + num[j] + num[k] < target){
                k--;
            } else {
                j++;
            }
        }

Combine it with the idea of making the sum variable and you get the following:

        int sum = num[index] + num[j] + num[k];
        if( sum == 0 ) {
            return sum;
        }
        else {
            int newSum = Math.abs( target - sum );
            if( newSum < tempSum ) {
                tempSum = newSum;
                result = sum;
            }
            if(sum < target){
                k--;
            } else {
                j++;
            }
        }

Additionally, Math.abs is not yet required for your first if. So leaving that one out until it's needed speeds things up a bit.

And since a return statement exits the function, we can use an implicit else:

        int sum = num[index] + num[j] + num[k];
        if( sum == 0 ) {
            return sum;
        }
        int newSum = Math.abs( target - sum );
        if( newSum < tempSum ) {
            tempSum = newSum;
            result = sum;
        }
        if(sum < target){
            k--;
        } else {
            j++;
        }


Efficient algorithm for counting frequency of a numbers in intervals

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

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).  I don't know for sure that you've done this in your code (since it's just a fragment and not a complete program) but it's an amazingly common thing for especially new C++ programmers to do.

Fix your program bugs

If this code compiled on your machine, your compiler is broken.  The problem is that the definition of i in the first for loop goes out of scope when that loop ends.  That means that the second for loop should start for (int i=0; ... or it isn't really valid C++.  Also, with your \$X_0\$ term being a negative integer, the index for the mas array when you calculate \$X_3\$ will also be negative, which will cause a memory access error (and probably a program crash) when the value of mas is updated.  The initial value of x should be a positive integer.

Use more whitespace for readability

The second for loop line is extremely dense and hard to read.  To make it easier to read, put things on separate lines and use whitespace to make things easier to read and understand:

for (int i = 0; i < 10; i++) {
    std::cout << "[" << (float)i / 10 << ";" << (float)(i + 1) / 10 << "]"
        << " | " << mas[i] << "\n-----------------" << std::endl;
}

Think carefully about the mathematics

The code that is being used to decide which "bin" the psuedo random number goes into is faulty.  It currently uses ceil(u*10) but the problem is that this will incorrectly classify numbers into mas[10] which is out of range.  Instead, the code should use the simpler version:

int r = u * 10;
mas[r]++;

Note also the use of the more idiomatic ++ operator rather than the form that is currently in the code.

Omit the return for a void function

The return at the end of void function metod1 is not needed.  Omit it to make the code cleaner and easier to read.

Pass parameters instead of using global variables

The mas parameter is neither defined within the function nor passed as a parameter, so it must be a global variable.  It's almost always better to explicitly pass the variables instead of using global variables.  The advantage is that the coupling and dependencies of the function are explicit and easily read and understood.


Finding the average output
Let's figure out what your average output should be.  Your neural network has 3 inputs in the first layer, 2 nodes in the second layer, and one output.  Each weight is randomized to a value from 0..1, so call it 0.5 on average.
The inputs you use in the program are: 1, 0, 1.  On each layer, you also have a "bias" input of -1.  So with average weights of 0.5, the the input layer will do the following:
inputs = 1, 0, 1, -1
output = sigmoid(1*0.5 + 0*0.5 + 1*0.5 - 1*0.5) = sigmoid(0.5) = 0.62

The second layer has two nodes, each with average input 0.62.  It will do:
inputs = 0.62, 0.62, -1
output = sigmoid(0.62*0.5 + 0.62*0.5 - 1*0.5) = sigmoid(0.12) = 0.53

So your average output should be 0.53.  I modified your program to sum the outputs and found that this was close (actual was 0.528).  Now as for the percentage of time the output is above 0.5, that depends on the distribution of the output, and I don't know that it is easy to compute by hand.  But your program shows through experimentation that the answer is roughly 60% of the time.
Random weights
I think that your choice of random weights from the range 0..1 is the source of your confusion.  If you were to choose random weights in the range -1..1 like this:
weights[j][i] = Math.random()*2 - 1.0;

then your output would be 0.5 on average and the percentage of outputs greater than 0.5 would be 50% (I modified your program to verify this).  Perhaps that is what you were expecting.
As far as your neural net code goes, it appears to be correct as far as I can tell.


A few thoughts:

Why not write anonymous functions in form of function($container) { ... } to allow your container to inject itself into function scope vs. having to use function () use ($di) { ... }?  This would allow wider compatibility to other forms of callables besides anonymous functions (for example, objects implementing __invoke() and other named functions/closures).
Alternately, if you truly want to narrow the type of callable functions that can be passed to set(), you might consider type-hinting against Closure class, which is what PHP in fact uses to represent a "function" created using closure syntax.
Why are you invoking the callable on set() and not on get()? This means you are pre-instantiating every dependency even if it is not needed for a particular code path. This kind of limits your framework to only allowing singleton-like behavior.  You could not pass a factory provider in one of your methods.  Perhaps it would be useful to have flag on set() if you want to implement singleton-like behavior, either by calling immediately or by storing information in separate arrays for "services" vs. single objects.
Consider explicitly instantiating your services property to empty array protected $services = [] such that IDE's (and readers) can infer type (that is if you are not going to use Doc blocks).
You might consider better enforcing/validating the $name parameter.  Right now, I could pass it pretty much anything, making your container fragile to outside input. If using PHP 7+, you should type-hint for string.
Is DI really a good class name? DIContainer perhaps?
Should you throw an exception if get() is called and key doesn't exist? I would guess that this would not be an expected condition in a well-written application and failing loudly in such a case will hopefully make it obvious to a developer that they have a problem in their code.
Is it OK that set() can overwrite existing item in the container?  You might consider preventing this in favor of needing an explicit unset() method to remove an item from the container.  This might suggest the need for a has() method.

For example:

public function has($name) {
    return array_key_exists($name, $this->services);
}

public function set($name, callable $value) {
    if($this->has($name)) {
        throw new Exception('...');
    }
    ...
}

public function get($name) {
    if(!$this->has($name)) {
        throw new Exception('...');
    }
    ...
}

public function unset($name) {
    unset($this->services[$name]);
}


Tag helper to add class if the model is invalid

Have you considered adding style rules to class input-validation-error? It gets added to input element when its value is recognized as invalid.

See live example on .NET Fiddle.

However, if you really need to add your own custom class, take notice that your code only adds custom class to input elements on server side, so that specific class will stay on input elements forever (until next HTTP request). Earlier, I suggested making use of default input-validation-error class, because jQuery validation plugin takes care of removal that class when it discovers the input value as valid. Eventually, you would have to implement same client-side mechanism to remove/add your custom class probably by writing custom jQuery validation script.

Of course, none of above is a real problem if you simply do not care about dynamic client-side validation.


Finding the largest not-necessarily contiguous alternating binary string after inverting any sub-string from a given string

The score is equal to the number of edges, that is transitions from 0 to 1 and from 1 to 0. After flipping number of edges inside the flipped range remains unchanged. Flipping may add two extra edges on the range boundaries; for that you need to find two occurrences of 11 or 00 and make the range to flip just one digit in each.

For example,

    100101001
      ^^^^^
    101010101

Of course there are some corner cases to be considered.


Find the value nearest to k in the sorted array

Here's my solution which seems to work fine :

public static int getClosestK(int[] a, int x) {

    int low = 0;
    int high = a.length - 1;

    if (high < 0)
        throw new IllegalArgumentException("The array cannot be empty");

    while (low < high) {
        int mid = (low + high) / 2;
        assert(mid < high);
        int d1 = Math.abs(a[mid  ] - x);
        int d2 = Math.abs(a[mid+1] - x);
        if (d2 <= d1)
        {
            low = mid+1;
        }
        else
        {
            high = mid;
        }
    }
    return a[high];
}

Here's the principle : the interval [low, high] will contain the closest element to x at any time. At the beginning, this interval is the whole array ([low, high] = [0, length-1]). At each iteration, we'll make it strictly smaller. When the range is limited to a single element, this is the element we are looking for.

In order to make the range smaller, at each iteration, we'll consider mid the middle point of [low, high]. Because of the way mid is computed, mid+1 is also in the range. We'll check if the closest value is at mid or mid+1 and update high or low accordingly. One can check that the range actually gets smaller.

Edit to answer to comments:

As spotted by @Vick-Chijwani , this code doesn't handle perfectly the scenarios where an element appears multiple times in the input. One can add the following working tests to the code :

    // case similar elements
    int[] a8 = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10};
    assertEquals(10, getClosestK(a8, 9));
    assertEquals(10, getClosestK(a8, 10));
    assertEquals(10, getClosestK(a8, 11));

but this one will fail :

   int[] a9 = {1, 2, 100, 100, 101};
   assertEquals(3, getClosestK(a9, 2)); // actually returns 100


Switching from a List<Integer> to an int[] speeds things up quite a bit, for the  input examples you've provided. Note: I've slightly simplified your code to work off a fixed array of strings, merely because it made my testing easier.

public class SwapElements {

  private static final String[] lines = { "1 2 3 4 5 6 7 8 9 : 0-8",
      "1 2 3 4 5 6 7 8 9 10 : 0-1, 1-3" };

  public static void main(String[] args) throws Exception {
    for (String line : lines) {
      String[] temp = line.split(":");
      int[] numbers = toPrimitiveArray(temp[0]);
      printSwapped(swapList(numbers, temp[1]));
    }
  }

  private static int[] toPrimitiveArray(String input) {
    String[] numbers = input.split(" ");

    int[] result = new int[numbers.length];
    for (int i = 0; i < numbers.length; i++) {
      result[i] = Integer.parseInt(numbers[i]);
    }
    return result;
  }

  private static void printSwapped(int[] list) {
    StringBuilder result = new StringBuilder();

    for (int i : list) {
      result.append(' ').append(i);
    }

    System.out.println(result.substring(1));
  }

  private static int[] swapList(int[] input, String swapKey) {
    for (String s : swapKey.split(",")) {
      String[] keys = s.split("-");
      int index1 = Integer.parseInt(keys[0].substring(1));
      int index2 = Integer.parseInt(keys[1]);

      int target1 = input[index2];
      int target2 = input[index1];

      input[index1] = target1;
      input[index2] = target2;
    }

    return input;
  }
}

Some basic benchmarking showed me that this improved performance from 4,125ns to 2,536ns (almost 40% reduction), for processing both input strings.

Other comments:

I've  changed most of your public methods to private, since they don't appear to be used outside of the class.
Your original code doesn't correctly close the Scanner you use. These days, you can avoid that entire problem using NIO classes:

List<String> fileLines = Files.readAllLines(Paths.get(args[0]));

You may wish to refactor your code to introduce a int[] swapElements(String input) method, so you can unit test more easily.


Modern OpenGL wrapper abstractions (shaders)

Use glDetachShader() after linking the program.

Shaders are ref-counted on the driver side and prevented from cleanup until they have been detached from all used programs. You are hogging GPU resources for no good reason.
GLchar info_log[log_length - 1]; : eeep!

On top of being dangerous (you could possibly end up allocating megabytes of memory on the stack), it's not even legal C++. Just use a std::vector<char>.

Also, that -1 gives me the heeby-jeebies. It's just one byte, copy the null terminator.
Your way of loading an entire stream in a string is pretty awful and slow. You should figure out the length, make a single allocation, and read all the data at once like so:

input_stream.seekg(0, input_stream.end);
auto length = input_stream.tellg();
input_stream.seekg(0, input_stream.beg);
std::vector<char> source(length);
input_stream.read(source.data(), length);

Holding on to loggers as member variables is pretty bad in general. I have never seen a production system that requires that kind of granularity, and the multithreaded handling of these shared_ptr<>s could come and bite you in the future. Loggers are definitely one of those things that belong in singletons/global variables in my opinion.

Or even better: throw an exception with the error as its content. Let higher-level code handle the logging.
The create() functions should be invoked in the constructors (or just be the constructors). That's the whole point of RAII: bookending resource management in constructors and destructors. An additional benefit is that you won't need to keep the path and loggers around, just the GLuint.
On that same note, destroy() should just be the destructor, for the same reasons as above.
Speaking of destroy: in your current version, what would happen if destroy() is called and create() was not? Any sequence of invocations of the public interface of the class should be expected and handled (if only with an assert at worst).
void create(std::initializer_list<Shader *> shaders);

This is pretty constraining interface-wise. It's okay to have an initializer_list-based overload, but your primary interface should be a std::vector<Shader*>, or even better: a pair of iterators (or range if your code base has them).
I don't like the casts to GLuint as accessor for the programs. If you are going to have a wrapper, the wrapper should be handling all interactions that require the native handle if possible, and selectively give access using friend where absolutely necessary.
Finally, a heads up: this is pretty bare bones. You will find that once you start adding data-driven handling of Uniform Buffers Objects (you are talking about modern GL, after all) and vertex attribute bindings, a major refactor of all this code will almost certainly be needed.

Edit elaborating here instead of the comments:

  I've been told not to include too much work in constructors, and considering it's calling GL functions I figured that was considered a lot of work.

The primary role of a constructor is to establish the class invariant (the states the object is allowed to be in be in between public function calls), which you should always strive to keep as constrained as possible, because every public function should handle any and all valid invariant states. In your current code, the invariant for Shader is: The GLuint handle is either undefined, pointing to a valid shader, or pointing to a failed shader.

A better alternative would be: The GLuint handle points to a valid shader. Note that you cannot establish that invariant without using exceptions.

Limiting work done in the constructor is good, but not if it comes at the cost of a having to widen the invariant.

Similarly, keep in mind that unless there is a bug in the code, you can always count on the destructor being called, even in weird exception-handling scenarios. That's why releasing resources is always best done there. Doing the cleanup in there makes it so a user of the class can never forget to call destroy().

  I've also been told that initializer_lists are lightweight, thus its use. Thoughts on any of that?

They are lightweight, but fixed in size at compilation time. What if you wanted to load a list of shader to put in a program from a file? Again, they are fine as a secondary overload, but should not be the primary interface unless you can guarantee that the length will never be data-driven.


Find a prefix of a query string in the values of a Map

Trie

A trie would solve this problem perfectly.  With a trie, you could search all your prefixes in \$O(n)\$ time, where \$n\$ is the length of the input string.  You current implementation requires \$O(m*n)\$ time, where \$m\$ in the number of prefixes and \$n\$ is the length of the input string.

Of course, the trie solution will be much more complex than your existing solution, so you will need to weigh the performance benefits of using a trie versus the simplicity of using a HashMap.


Validating a model that requires database access

Best approach would be to have another Object to do the validation based on specific configuration.

Your User should NOT be responsible for validating itself, neither should the DAO.
Validation is a specific task and should be handled by a specific Class.

Example of this approach would be something like this (omitiong interfaces for brevity):

validation class

Class Validator
{
   protected $errors = [];

   public function __construct(DaoInterface $daoDependency, $otherDependency)
   {
      //...
   }

   public function validate($object, array $rules)
   {
       foreach ($rules as $rule)
       {
           $propertyName = $rule['property'];
           if (!$this->isValidateProperty($object, $propertyName, $rule['config'])) {
               $this->errors[$object->$propertyName] = 'is invalid ' . $rule['message'];
           }
       }
   }

   public function isValid()
   {
       return (bool)count($this->errors);
   }

   public function getErrors()
   {
       return $this->errors;
   }

   protected function isValidProperty($object, $propertyName, $ruleConfig)
   {
       // $ruleConfig should have information about what validation you want to use and relevant validation should be executed base on it (it can separate objects etc)
       if (!property_exists($object, $propertyName)
          throw new MissingPropertyException();

       if (isset($ruleConfig['email-unique-in-db') {
           if ($daoDependecny->emailExists($object->$propertyName) {
               return false;
           }
       }
       if (isset($ruleConfig['email-is-valid') {
           return (bool)strpos($object->$propertyName, '@');
       }
       // ... etc but better with objects for each validation type.
   }
}

usage

$userDAO = new UserDAO($dbh, $logger);
$user = new User();
$user->email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$user->password = filter_input(INPUT_POST, 'password');

// get your validation rules
// you can have them stored in other object, plain array, yml whatever you like. for instance $rules = new UserConstrains(); or
$rules['config] = [
  'email' => [
      'email-unique-in-db',
      'email-is-valid'
  ],
  'otherfield' => [
      'callback' => ['someCallbackFunction']
  ]
];

// create validator
$validator = new Validator($userDao, $otherDepenency);
$validator->validate($user, $rules);
// validate user

if (validator->isValid()) {
   // .. do stuff
} else {
   // do something with $user->errors
}

The separation of concerns is the most important thing here.
You can extend/decorate the validator class for specific use cases

Also if would recommend using some specialized validation library for this task for instance symfony2 validation component can be used stand alone: http://symfony.com/doc/current/book/validation.html


Managing several payment means in my Rails 3.2 app

First: "Means" is uncountable in English; it's always plural. So the model should be called PaymentMeans, and associations should be has_many :payment_means and has_one :payment_means. You can set that up in Rails' inflections config (or just call it "payment type" or something).

Anyway, I would definitely consider STI for this, depending on how similar the models really are. It really all depends on that. The more they have in common, the better suited an STI solution will be. As far as I can tell, there shouldn't be any major pitfalls. However, you've only said they "contain specific information" but without knowing what exactly that entails, it's hard to know if it'd overburden an STI approach.

Alternatively, if they have little in common beyond the reference string, your current solution seems fine, but it does add an extra association and thus extra complexity.

If you're adamant about avoiding STI, I'd think you can skip the PaymentMean (sic) model, and simply make the polymorphic association directly to the User model:

class User
  belongs_to :payment_means, polymorphic: true # can be CreditCard or Bic
end

You can then extract a service object to handle the things you'd currently handle with the PaymentMean model (in fact, you could consider this, regardless of how your models are otherwise set up).

Of course it seems semantically awkward to say that a "User belongs to their Payment Means" (although that's how banks probably think), so once again your current solution or STI might be better suited.

Lastly, you could reduce your payment means model to just the bare necessities, and keep everything else in a serialized attribute (i.e. a hash). Of course this would likely entail writing a custom validator or similar busywork, but it would be very flexible. It still is a "last resort" solution, though.


you're on the right track with using a LinkedList, this is one of the easiest ways to implement your own Queue - I hope this is an exercise, since you should otherwise use Java's built-in Queue.

I must confess I found your question interesting and decided to write a Queue so as to demonstrate. Note that you should create a class for your custom Queue. If you implement the whole thing in main, there'll be no way to reuse the code.

So you'd create a new file, let's call it Queue.java. It would look something like this:

import java.util.*;

public class Queue<T> implements Iterable<T> {

    private LinkedList<T> elements = new LinkedList<T>();

    public void enqueue(T element) {
        elements.add(element);
    }

    public T dequeue() {
        return elements.removeFirst();
    }

    public T peek() {
        return elements.getFirst();
    }

    public void clear() {
        elements.clear();
    }

    public int size() {
        return elements.size();
    }

    public boolean isEmpty() {
        return elements.isEmpty();
    }

    @Override
    public Iterator<T> iterator() {
        return elements.iterator();
    }
}

Notice that that the code is extremely simple - no method's implementation is longer than one line. However, I don't know your level of experience so there might be two weird things in here: the use of Generics and the implements Iterable<T>.

Generics

The <T> means you can put any Java object into the Queuekeeping Type safety.
This means, when you call Queue.Dequeue(), the result will still have the same type that it had when you Enqueued
it.

Iterable<T>

Oracle says:

  Implementing this interface allows an object to be the target of the foreach statement.

Note that you don't need to know more, because we simply delegate this responsibility to LinkedList.iterator() which does the work for us.

Below is some code to test your new Queue. Play around with it. You can add other queue tests to main, for instance:

testQueue(true, false, true, true);

or

testQueue(0.5, 3.6, -5.4, 0.0);

to test putting different types of data into your Queue.
If anything remains unclear, feel free to leave a comment, and I'll update my answer.

public class Main {

    public static void main(String[] args) {
        testQueue(1, 2, 3, 4, 5);
        testQueue("first", "second", "third");
    }

    private static <T> void testQueue(T... elements) {
        outputLine("testing a Queue<%s>", getClassOf(elements));
        Queue<T> queue = new Queue<T>();
        outputSize(queue);
        enqueueElementsInto(queue, elements);
        outputSize(queue);
        loopOverAllElementsOf(queue);
        dequeueAllFrom(queue);
        outputSize(queue);
        outputLine("---");
    }

    private static <T> void outputSize(Queue<T> queue) {
        outputLine("empty: %s, size: %s elements", queue.isEmpty(), queue.size());
    }

    private static <T> void enqueueElementsInto(Queue<T> queue, T... elements) {
        outputLine("enqueueing: ");
        for (T element : elements) {
            queue.enqueue(element);
            output(element + " ");
        }
    }

    private static <T> void loopOverAllElementsOf(Queue<T> queue) {
        outputLine("Queue contains: ");
        for (T element : queue) {
            output(element + " ");
        }
    }

    private static <T> void dequeueAllFrom(Queue<T> queue) {
        outputLine("dequeueing: ");
        while (!queue.isEmpty()) {
            T next = queue.peek();
            T dequeued = queue.dequeue();
            outputLine("expected: %s ", next);
            output("dequeued: %s ", dequeued);
        }
    }

    private static void outputLine(String format, Object... params) {
        output('\n' + format, params);
    }

    private static void output(String format, Object... params) {
        System.out.print(String.format(format, params));
    }

    private static <T> String getClassOf(T... elements) {
        String nameOfArray = elements.getClass().getSimpleName();
        return nameOfArray.substring(0, nameOfArray.length() - 2);
    }
}

output:

testing a Queue<Integer>
empty: true, size: 0 elements
enqueueing: 1 2 3 4 5
empty: false, size: 5 elements
Queue contains: 1 2 3 4 5
dequeueing:
expected: 1 dequeued: 1
expected: 2 dequeued: 2
expected: 3 dequeued: 3
expected: 4 dequeued: 4
expected: 5 dequeued: 5
empty: true, size: 0 elements
---
testing a Queue<String>
empty: true, size: 0 elements
enqueueing: first second third
empty: false, size: 3 elements
Queue contains: first second third
dequeueing:
expected: first dequeued: first
expected: second dequeued: second
expected: third dequeued: third
empty: true, size: 0 elements
---


Just a few hints that might better the code:

If you tend to access a structure for a given element multiple times with an operation on it, extract it in a local variable:

tweet.getUser().getScreenName() // If its String, toString not required.

Have try..catch for statements that can cause the exception i.e put this out

System.out.println(tweet.getUser().getScreenName() );

As your comment states, put the boolean out with the two states and have minimal print statements. If its for debugging, add comments or debug flag.
Having try..catch after break? Please check.
Check if tweets is null after

List<Status> tweets = result.getTweets();

Check if tweet is null inside the for loop.
Apply (5) and (6) for Stats as well.


Finding the number of longest contiguous increasing subsequences in a given array

I have no C/C++ compiler at the moment, but the algorithm only needs one loop, the while+flag being a tiny bit too unreadable.

There are two counters:

Finding the maximum length: maxLength

Sequences with next value >= prior value.
Counting the maximum length: maxCount.

length > maxLength reset maxCount to 1
length == maxLength increment maxCount

So (in java):

static int longestIncSeq(int[] arr) {
    int maxCount = 0;
    int maxLength = 0;
    boolean start = true;
    int prior = Integer.MAX_VALUE;
    int length = 0;
    for (int n : arr) {
        if (start || n < prior) {
            if (length > maxLength) {
                maxLength = length;
                maxCount = 1;
            } else if (length == maxLength) {
                ++maxCount;
            }
            length = 0;
            start = false;
        }
        ++length;
        prior = n;
    }
    if (length > maxLength) {
        maxLength = length;
        maxCount = 1;
    } else if (length == maxLength) {
        ++maxCount;
    }
    return maxCount;
}

Complexity O(N).


I wouldn't use #define macros. They expose the internal naming convention of your OS dependent functions to the world. Once you send out your library to others [as a shared library], you can never change your internal OS dependent names. The important thing is that public facing names be functions.

For example, if two systems used gcc and created ELF binaries that only called your library functions, could you compile on (e.g.) FreeBSD and that binary would run without rebuild on linux. There are other issues with doing this, so it [probably] isn't practical, but, it's something to think about.

A better way [what I've done when faced with a similar problem] is to put the OS dependent code in a .c and add static to the definitions.

The public functions just call the static ones. The static function names are the same, regardless of platform

The optimizer will either inline the static OS dependent function or will use tail call optimization. So, it's just as fast as macros but a lot cleaner.

Side note: Your naming convention is a bit [MS] Windows centric (i.e. camel hump case). I prefer snake case (e.g. see GTK, etc.). For an example, see the bottom.

vkwh.h:

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

VKWFWindow* VKWFCreateWindow(const char* title, int width, int height);
VKWFBool VKWFWindowShouldClose(VKWFWindow* window);
void VKWFWindowUpdate(VKWFWindow* window);
void VKWFDestroyWindow(VKWFWindow* window);

#ifdef __cplusplus
}
#endif

vkwf.c:

#include "vkwf.h"

#ifdef VKWF_PLATFORM_WINDOWS
#include "win32_window.c"
#elif VKWF_PLATFORM_MACOS
#include "macos_window.c"
#elif VKWF_PLATFORM_LINUX
#include "linux_window.c"
#endif

VKWFWindow* VKWFCreateWindow(const char* title, int width, int height)
{
    return VKWFPlatformCreateWindow(title, width, height);
}

VKWFBool VKWFWindowShouldClose(VKWFWindow* window)
{
    return VKWFPlatformWindowShouldClose(window);
}

void VKWFWindowUpdate(VKWFWindow* window)
{
    VKWFPlatformUpdate(window);
}

void VKWFDestroyWindow(VKWFWindow* window)
{
    VKWFPlatformDestroyWindow(window);
}

win32_window.c:

#include "vkwf.h"

static VKWFWindow*
VKWFPlatformCreateWindow(const char* title, int width, int height)
{
    // ...
}

static VKWFBool
VKWFPlatformWindowShouldClose(VKWFWindow* window)
{
    // ...
}

static void
VKWFPlatformWindowUpdate(VKWFWindow* window)
{
    // ...
}

static void
VKWFPlatformDestroyWindow(VKWFWindow* window)
{
    // ...
}

Here's an example of the snake case for the public functions. Note that since the platform specific functions are static, then can use shorter prefixes:

#include "vkwf.h"

#ifdef VKWF_PLATFORM_WINDOWS
#include "win32_window.c"
#elif VKWF_PLATFORM_MACOS
#include "macos_window.c"
#elif VKWF_PLATFORM_LINUX
#include "linux_window.c"
#endif

VKWFWindow* VKWF_create_window(const char* title, int width, int height)
{
    return platform_create_window(title, width, height);
}

VKWFBool VKWF_window_should_close(VKWFWindow* window)
{
    return platform_window_should_close(window);
}

void VKWF_window_update(VKWFWindow* window)
{
    platform_update(window);
}

void VKWF_destroy_window(VKWFWindow* window)
{
    platform_destroy_window(window);
}


shared_instance implementation using C++ and RAII

Non-Default Constructors:

Adding support for non-default constructible objects in a "lazy" fashion, could be done by adding a factory function of std::function<std::shared_ptr< t_type >()>.

template< typename t_type >
struct shared_instance
{
    using t_factory = std::function<std::shared_ptr< t_type >()>;

    static t_factory factory; // MUST be set before calling get_shared_instance

    static std::shared_ptr< t_type > get_shared_instance()
    {
        ...

            assert(factory); // or throw, or return empty shared_ptr

            result = factory(); // instead of make_shared

        ...
    }

};

// and define the static member...
template< typename t_type >
typename shared_instance< t_type >::t_factory shared_instance< t_type >::factory;

...

int main()
{
    context<int> c; // not ok... haven't set factory yet!

    // do this before any call to get_shared_instance
    shared_instance<int>::factory = [] () { return std::make_shared<int>(5); }; // store things in the lambda by value, not reference...

    context<int> c; // ok
}

I'm not sure this counts as elegant though, as it gives you a two-step initialization process. This could be fixed by recognising the shared_instance itself as a kind of factory, making its contents non-static, and passing it into the contexts:

template< typename t >
struct context
{
    context(instance_provider< t >& provider): // now it can't be created unless this exists...
        instance{ provider.get_shared_instance() }
    { }

private:

    std::shared_ptr< t > instance;
};

int main()
{
    auto provider = instance_provider<int>([] () { return std::make_shared<int>(5); });

    context<int> c(provider);
}

Further Considerations:

Does the C library you're using say anything about context lifetime itself? (e.g. Winsock reference counts calls to WSAStartup() and WSACleanup() internally, so as long as the calls are paired properly the C library handles cleaning up)

The main feature that this shared_instance class seems to provide is destroying The Instance promptly after the last context is destroyed. RAII itself could be achieved by just storing a unique pointer over the maximum possible lifetime of any contexts, which would be simpler. Is this prompt destruction actually important?

If not, then it's just a singleton, which we either live with, or do the work to pass a pointer or reference to the thing you need where it needs to be.


You're using non-standard names. Usual names are A for the matrix, i for the row index, and j for the column index.
List repetition and comprehension make the initialization shorter and faster.
Using deltas for the four directions can avoid quadrupling code.
You can know when to change direction by checking whether the next element in the current direction is already set.
Your check is inefficient. Instead of searching the matrix for an unset spot, just do while count <= n**2:. Or, try to loop through the range of numbers.
Your current code crashes for n = 0 because it always enters the loop, as you compute run only at the end. With while count <= n**2: you'd succeed.

def spiralNumbers(n):
    A = [[0] * n for _ in range(n)]
    i = j = di = 0
    dj = 1
    for A[i][j] in range(1, n**2 + 1):
        if A[(i+di) % n][(j+dj) % n]:
            di, dj = dj, -di
        i += di
        j += dj
    return A

The % n is just a little trick to avoid checking for index-out-of-bounds.


Check if an Array of Arrays contains a value in node js

Style

Your braces are not styled consistently, and most JavaScript developers find sameline braces more idiomatic.
I think it is better form to place your requires all the way on the top

Approach

You basically rewrote Array.indexOf , except that indexOf gives more info (where is the element), so I would rewrite this with indexOf.
Searching for value 19 makes your hasElement function very limited, it would be a more flexible function if you pass the row and the search value.

All in all, I would counter-propose something like this:

var LINQ = require('node-linq').LINQ;

var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];

var resultI=new LINQ(data).Any(function(row){
 return hasElement(row, 19);
});
console.log(resultI);

function hasElement(array, value){
  return array.indexOf( value ) != -1;
}

The next level?

The flow of LINQ gets a bit broken with the inline function, it would be even cooler if you would call a function there that returns a function seeking for the right value:

var LINQ = require('node-linq').LINQ;

var data= [[2, 2, 3, 4, 5],[2, 2, 2, 6], [9], [13, 1,1,90]];

var resultI=new LINQ(data).Any( seekValue(19) );
console.log(resultI);

function seekValue( value) {
  return function boundSeekValue( row ){
    return row.indexOf( value ) != -1;
  };
}


Code to find the sum of the product of all size-n combinations of an array

It first makes an iterator object containing all the unique combinations of the indices of A

Brute force is the first step in "Make it work; then make it fast". Since it's the bottleneck, you need to take the second step: exploit the structure of the problem. Here there's plenty of algebraic structure to exploit (as long as numerical stability isn't a major issue).

In particular, think about divide and conquer. Rather than compute all \$\binom{S}{2} = \Theta(S^2)\$ pairs separately, take a running total and multiply each element by each of the previous elements simultaneously:

result, running_total = 0, 0
for a in A:
    result += running_total * a
    running_total += a

and you have \$O(S)\$ time. This can be extended for larger values of \$n\$ to work in \$O(Sn)\$ time and \$O(n)\$ space.


Allowing developers to quickly create image hover effects

As a rule of thumb, when you use a jQuery selection more than once, you should cache its value. When you do $(".someElement"), jQuery now has to go find that element in the DOM, wrap it in the jQuery object and return it. If you save what it returns, then you only do the search once - not every time you use it.

The hard part is caching this. This is relative to where you are in the code, function, callback, etc. and changes to provide context. For example:

var Object = {
    init: function() {
        //this in here references Object
        //You could call this function elsewhere by doing: "this.init();"
    },

    bindEvents: function() {
        $(".someElement").hover(function() {
            //This is a callback function
            //In here "this" refers to the element your .hover() was called on - ".someElement"
        });

        //However, outside the callback, "this" now refers to Object again

        $(".someOtherElement").each(function(){
            //This is another callback
            //Here "this" refers to the element in question
        });
    }
}

The reason the plugin is breaking when you cache it is because you have to cache it at each point the reference changes. Watch this next example:

var Object = {
    init: function() {
        //Here "this" refers to Object
        //You don't need to cache this here because the Object is already saved in a variable
    },

    bindEvents: function() {
        $(".someElement").hover(function() {
            //In here however, the reference changed
            //In here "this" refers to the element your ".hover()" was called on. ie.: ".someElement"
            //You would cache it in here
        });

        //However, outside the callback, "this" now refers to Object again so you don't need to cache it

        $(".someOtherElement").each(function(){
            //This is another callback
            //The reference has changed again, so now we cache it again
        });
    }
}

From what I could understand from reading your plugin, I've cached your this references for you. I didn't change anything else except for .removeAttr() calls at the end. You can use a space and put in several attributes to be removed at once.

Anyways here's your code:

(function($){
$.fn.hovr = function(options) {

    // Default Options
    var defaults = {
        speed:           'normal',
        animateOver:     {'opacity': '0'},
        animateOut:      {'opacity': '1'},
        timThumb:        false,
        timThumbInverse: false,
        timThumbPath:    'images/img.php',
        timThumbParams:  'f=2'
        //http://www.binarymoon.co.uk/2012/02/complete-timthumb-parameters-guide/
    };
    var options = $.extend({}, defaults, options);

    // Create Images
    if (options.timThumb) {
        this.each(function() {
            var $this = $(this),
                strOrig = $this.prop('src'),
                strNew  = options.timThumbPath +
                '?src=' + strOrig +
                '&w=' + $this.prop('width') +
                '&h=' + $this.prop('height') +
                '&' + options.timThumbParams;

            if (options.timThumbInverse) {
                $this
                    .prop('src', strOrig)
                    .attr('data-hovr', strNew);
            }
            else {
                $this
                    .prop('src', strNew)
                    .attr('data-hovr', strOrig);
            }
        });
    }

    // Create Rollovers
    return this.each(function() {
        $(this).hover(
            function() {
                $(this).stop().animate(options.animateOver, options.speed);
            },
            function() {
                $(this).stop().animate(options.animateOut, options.speed);
            }
        ).each(function() {
            var $this = $(this),
                intWidth  = ($this.attr('width'))  ? $this.attr('width')  : $this.prop('width'),
                intHeight = ($this.attr('height')) ? $this.attr('height') : $this.prop('height'),
                strAlign  = ($this.attr('align'))  ? $this.attr('align')  : '',
                strClass  = ($this.attr('class'))  ? $this.attr('class')  : '',
                strStyle  = ($this.attr('style'))  ? $this.attr('style')  : '';

            $this.wrap('

');

            $this.before($this.clone(true))
                .attr('style', 'position:absolute; left:auto; top:auto;')
                .prop('src', $this.attr('data-hovr'))
                .removeAttr('data-hovr class');

            $this.prev('img')
                .attr('style', 'position:absolute; left:auto; top:auto; z-index:10;')
                .removeAttr('data-hovr class');
        });
    });
};
})(jQuery);


I would do some re-arranging:
Use the quick exit pattern.

This is basically if it fails the useful criteria exit (or in this case start the next loop). Basically you test for conditions that don't satisfy your working conditions. If the data does not match then you move on.

int
parse_config (FILE * conf_file, module_initializer_t init)
{
  char *line; /* Current line */
  char *type; /* Type of current module */
  char *name; /* Name of current module */
  char *envz;
  size_t envz_len;
  size_t lineno = 0;

  line = type = name = envz = NULL;
  while (getline (&line, NULL, conf_file) != EOF)
  {
      lineno++ ;
      if (is_comment(line))
      {    continue;        // Ignore comments;
      }

      if (line[0] != '[')
      {
          argz_add(&envz, &envz_len, line);
          continue;         // Processes arguments and continue
      }

      if (!update_header(line, &type, &name))
      {
          fprint("syntax error on line %d", lineno);
          return 1;         // Not an argument and not a header
                            // must be an error.
      }

      // Processes a header
      if (type)
      {
          if ((*init)(type, name, envz, envz_len))
          {
            fprintf("failed to initialize module %s with name %s", type, name);
            return 1;
          }
          clear_envz(&envz, &envz_len);
      }
  }

  if ((*init)(type, name, envz, envz_len)) {
    fprintf("failed to initialize module %s with name %s", type, name);
    return 1;
  }

  // You should also return a value here.
  return 0;
}


System.out.printf("%4.8s ", ...); is actually not necessary here: this code means that you will format your String so that it has at minimum 4 characters, at most 8. Since "Fizz", "Buzz" and "FizzBuzz" have a length between 4 and 8, this will result in just outputing the String with no change. Therefore, it is simpler to have System.out.print(... + " ");.
You have one part of your code that is repeated 4 times. Code duplication is something you want to avoid at all costs. It is better to refactor this duplicated logic into a small reusable method that you can then call elsewhere.
In the same way, you can store inside two booleans the result of whether the number of divisible by 3 and 5.

In this case, you are repeating the check to print only 25 values per line, when you could do this only a single time after all the if/else logic.

You can then write your code a lot more simply:

for (int i = 1; i <= 100; i++) {
    boolean shouldFizz = i % 3 == 0;
    boolean shouldBuzz = i % 5 == 0;
    if (shouldFizz && shouldBuzz) { // Checks for numbers that are both multiples of 5 and 3
        System.out.print(fizzBuzz);
    } else if (shouldFizz) { // Checks for numbers that are multiples of 3
        System.out.print(fizz);
    } else if (shouldBuzz) { // Checks for numbers that are multiples of 5
        System.out.print(buzz);
    } else { // Prints numbers that are not multiples of 3 or 5
        System.out.print(i);
    }
    System.out.print(" ");
    if (i % 25 == 0) { // Control flow allows 25 values printer per line
        System.out.println();
        System.out.println();
    }
}


Looks good to me! I mean, I'm not likely to convert to it because of its heavyweightness — you noted its use of std::apply, but it also pulls in all of <tuple> every time you use it, too. Also, it's arguably coincidental that your expressions a[I] and std::get<I>(t) work in this context, since what's actually happening in both cases is an implicit conversion from std::integral_constant<size_t, K> to size_t. In some contexts, the user might need to explicitly cast int(I) or whatever.

You could remove the std::apply dependency and simplify the user's job at the same time by writing a helper function apply_to_sequence<N>(lambda), as in:

// Convert array into a tuple
template <typename T, std::size_t N>
auto a2t(const std::array<T, N>& a) {
  return apply_to_sequence<N>([&](auto... Is) {
      return std::make_tuple(a[Is]...);
  });
}

(Oh yeah, I think your use of decltype(auto) in this function was bogus and could result in dangling references. Certainly auto would be fine, so I recommend it.)

// pretty-print a tuple
template <class Ch, class Tr, class... Args>
auto& operator<<(std::basic_ostream<Ch, Tr>& os,
                          const std::tuple<Args...>& t)
{
  os << "(";
  apply_to_sequence<sizeof...(Args)>([&](auto... Is) {
    ((os << (Is == 0 ? "" : ", ") << std::get<Is>(t)), ...);
  });
  return os << ")";
}

Writing apply_to_sequence from scratch is left as an exercise for the reader, but the trivial C++17 implementation is just this:

template<size_t N, class F>
decltype(auto) apply_to_sequence(const F& fn) {
    return std::apply(fn, integral_sequence<N>);
}

Having hidden the implementation details apply and integral_sequence from the reader, we are now free — if we so desire — to replace them with things that are

faster
C++14-compatible
<tuple>-free

One stylistic note: I prefer to name my parameter packs with plurals, so, singular auto I but plural auto... Is. That's the logic behind my renaming above.


Be careful with that algorithm.
It looks pretty intuitive, but it would not work for some other coin values.
For example, if we need to deal 20 cents using coins of 17, 10 and 1, this greedy approach would give (17, 1, 1, 1) - 4 coins, whereas (10, 10) is just 2 coins.
Figuring out the difference - when your algorithm works and when it does not - would be an interesting exercise in itself.
Wasteful loops
while ( cents >= quarter) {
  cents -= quarter;
  num++;
}

You can replace it with something like:
num += cents / quarter;
cents = cents % quarter;

Note that if you put coin values in array, this can be done in a loop.
Generally, your code would spend most of its time waiting for user to type the number and will give answer immediately, there's little point in optimisation.
You should adopt some code style though, your indentation is inconsistent. Indentation makes code structure more immediately apparent. I don't think it's a problem for you now, but it would be a problem for you on bigger assignments and it would be a problem for other people who would have to read (and grade) your code. Take a look at one of these if your course does not have one.


On a 64-bit CPython 2.x,

all(i for i in xrange(2**63 - 1))

works, but

all(i for i in xrange(2**63))

overflows.  See this explanation, and a workaround.  I suggest rewriting this using an old-fashioned while loop.

With Python 3.x,

all(i for i in range(2**63))

works.

You've implemented trial division.  A more efficient algorithm is the sieve-of-eratosthenes, especially if you want to test multiple numbers for primality.  However, the Sieve of Eratosthenes requires more memory, so you'll have to resort to some hacks to make it work for large numbers.

For truly large numbers, you'll have to implement more sophisticated algorithms.


Search iteratively in a ternary search tree

Iterables

Generally speaking, if you use range(len(some_iterable))and then access an index of the item, you can just iterate over the item itself:

for i in range(len(word)):  # okay
    print(word[i])

for character in word:  # better
    print(character)

In your case it'd be key[:-1]

Style

Good on you for following PEP8. The code looks beautiful. There are more blank lines than I usually see, but they work.

The ternary operator (x if y else z)

Your use of the ternary operator is quite elegant here, but be aware that this makes your code harder to test.

I often see code that use the ternary operator as a sort of cheat to get out of unit test coverage (coverage.py doesn't notice if only one of the cases in a ternary statement is executed).

The algorithm

It looks fine to me. I'm not certain about the correctness. Can you link that pseudo-code you're working from?

You can make it a bit more obvious if you like. How do I call this method? What kind of object is key? I'm sure this makes complete sense in context with the rest of the class, but you can always add argument annotations and function annotations to make your code that much more readable:

def nice_number(x: float) -> str:
    ...

or

def f(n: 'must be prime'):
    ...

What can you do to improve this?

Write a unit test. It makes it so much easier to play with the implementation, to try out different things, without having to worry about breaking some edge case. Write a complete unit test, and be aware of what the algorithm can an can't do.

Run profiling. I don't think you will learn anything shocking by profiling the code, but it's always good to get a sense of what takes the most amount of time. My guess is that the slowest part of your code, considering how straightforward it is, will be the attribute access (node.key). (Rule of thumb: dots are expensive)

Write a docstring. Run help() on your module and try to imagine what it looks like to users.

Get rid of the wrapper method. Unless there's something I'm not seeing here, there's no reason to have a static method TST._search(), not visible to help() because of that underscore, and a wrapper method TST.search() that merely calls it.

If you do get rid of the static method, start off by setting node = self.root (going back to the earlier comment about dots being expensive, you don't want to have that in the hot part of your loop if avoiding it is so easy).

I almost never use staticmethod() in real-world code. If I do, I make sure to spend a minute thinking about whether it's really necessary.


I think that it would be best if you could put those constants into a enum so that you can use Enum.values to get them all in an array. If so you can do this:

enum Play {
 TWOS, THREES, FOURS, FIVES, SIXES, SEVENS, EIGHTS, THREE_OF_A_KIND,
 FOUR_OF_A_KIND, FULL_HOUSE, SMALL_STRAIGHT, LARGE_STRAIGHT, ALL_DIFFERENT,
 CHANCE, ALL_SAME;
}

class Main {

  int playGame(Play play) {
     // you need to implement this method returning something meaningful.
     return 0;
  }

  int best() {
     return Stream.of(Play.values())
                  .mapToInt(this::playGame)
                  .max().getAsInt();
  }
}

If you want to keep those constants as independent static final (Strings?) then you will need to create a list of them explicitly:

//...
static final String TWOS = "TWOS";
static final String THREES = "THREES";
//...
static final List<String> PLAYS = Arrays.asList(TWOS, THREES, ...);
//...
int best() {
   return PLAYS.stream()
               .mapToInt(this::playGame)
               .max().getAsInt();
}


This is perfectly fine JavaScript, performant even. However...

var i, a, tally = {}, arr = [1, 3, 7, 9, 3, 1, 6, 3, 3, 2, 11, 2];

For better visibility, it's recommended you split up each variable to its own var. Also, to avoid gotchas and IDEs screaming "potentially uninitialized variable" (Intellij does this), initialize them with values.

for (i = 0; i < arr.length; i++) {
  a = arr[i];
  tally[a] = (tally[a] || 0) + 1;
}

Perfectly fine, except it can be better if you use let on i. That way, it strongly indicates that i lives only within the loop body and not anywhere else.

An alternate way to do this is to use array.reduce and carry around the tally object until done. This way, you avoid having to define temporary storage variables and counters.

const arr = [1, 3, 7, 9, 3, 1, 6, 3, 3, 2, 11, 2];
const tally = arr.reduce(function(tally, value){
  tally[value] = tally[value] ? tally[value] + 1 : 1;
  return tally;
}, {});

or more concisely, but entirely unreadable depending on who you ask

const arr = [1, 3, 7, 9, 3, 1, 6, 3, 3, 2, 11, 2];
const tally = arr.reduce((t, v) => (t[v] = (t[v] || 0) + 1, t), {});


Query to show each sites stock transfer history between all other sites

Here is an attempt at a rewrite, but you didn't provide any DDL or DML so there is no way for me to test it.  I'll list reasons for the changes below.

WITH Transfers_CTE (FromSiteNo, ToSiteNo, Value) AS
  (
    SELECT      Transfers.FromSiteNo,
                Transfers.ToSiteNo,
                SUM( Transfers.Value ) AS Value
      FROM      dbo.Transfers
      WHERE     Transfers.MoveDate BETWEEN @SessionDateFrom AND @SessionDateTo
                AND FromSiteNo <> ToSiteNo
      GROUP BY  Transfers.FromSiteNo,
                Transfers.ToSiteNo
  )
  SELECT        FromCS.No AS SiteNo,
                FromCS.Name AS SiteName,
                ToCS.No AS OtherSiteNo,
                ToCS.Name AS OtherSiteName,
                ISNULL( Transfers.Value, 0 ) AS ToFromValue
    FROM        dbo.CfgSites AS FromCS
    LEFT JOIN   Transfers_CTE AS Transfers
      ON FromCS.No = Transfers.FromSiteNo
    LEFT JOIN   dbo.CfgSites AS ToCS
      ON Transfers.ToSiteNo = ToCS.No
    WHERE       EXISTS
        ( SELECT    DescendantSites.Descendant
            FROM    dbo.DescendantSites
            WHERE   DescendantSites.Parent IN ( @SiteNo )
                    AND DescendantSites.Descendant = FromCS.No)
    ORDER BY    FromCS.No
;

Since Cs.No and JoinedSites.No should not be equal, and they are joined to the From & To values of the CTE, I added the filter in the CTE to exclude any transfers where the To and From site matched.
Your Full Outer Join was effectively a left outer join because any results from the Right side table would have been excluded by the Left side reference of your EXISTS clause.
You attempt to join transfers to sites from both directions.  However, if A = B, then B = A.  So if we get all of the FromSite joins established to CS on the first pass, there is no reason to do a second pass by joining JoinedSites to the FromSite as they will already have found a match.  This change also eliminates the near Cartesian product of joining CfgSites to itself.
If we consider the CS table our anchor, understanding it has all of the From Sites included, our problem then becomes how to get the To sites.  The relationship between From and To is contained in the Transfers_CTE.  Thus we just need to join back to the CfgSites using the ToSiteNo field to find the site information.
The Sum aggregate was at the grain of the Transfer relationship, To & From.  This is maintained in the changes, but now there is only one value column, returning the Value that was transferred between From and To.

There is no need to join CfgSites to itself directly, unless you may also need to show any ToFrom combinations that did not get any transfers.

Hopefully this will return your expected results.  If not, provide some DDL/DML and I may take another look at it.


Find smallest index that is identical to the value in an array

Review

Your solution naively walks the array of ascending integers from starting position s = 0. In some situations, this means you are walking tons of negative numbers, knowing they can never match an array index, which is always nonnegative.

Optimization

You could optimize s before walking the array. Since array indices are nonnegative integers, you should skip walking the array where the values are strict negative.

As en example, if input = [-10000, -9999, ..., 0, 1] you just want to check 0 and 1.

The way I would optimize the algorithm:

determine starting point s

if first item is positive: s = 0
if last item is strict negative: return -1
perform binary search to find s (you want s to hold the first positive integer in the array)

walk i as from s to end of array

on match: return match
on array[i] > i: return -1
on end reached without match: return -1

Optimized Time Complexity

~\$0(\lg m)\$ with m <= n and m being the number of positive integers in the array


First Python script: number-guessing game with a global variable

Some notes:

Mutable global state is a bad programming practice. Instead, pass values as arguments so functions are black boxes that take values (as arguments) and return values. If such a function does not perform any side-effect (print to console, write a file, ...), then it's a "pure function". Try to write pure functions whenever possible.
Conditionals: Don't write a fallback (return False) where some branches get and others don't. Non-overlapping conditionals are more clear.
Use name_of_variable and name_of_function.
Try to use Python 3 whenever possible.

I'd write:

from random import randint
from itertools import count

def is_guess_correct(number, guess):
    if guess == number:
        return True
    elif guess < number:
        print("The number is HIGHER.")
        return False
    else:
        print("The number is LOWER.")
        return False

def is_valid_guess(number_string):
    return number_string.isdigit()

def get_number(guess_iteration):
    while 1:
        number_string = input("({0}) Guess a number: ".format(guess_iteration))
        if is_valid_guess(number_string):
            return int(number_string)
        else:
            print("Please enter a valid integer!")

def run_game(nmin, nmax):
    number = randint(nmin, nmax)
    print("I'm thinking of a number between {0} and {1}...".format(nmin, nmax))

    for guess_iteration in count(1):
        guess = get_number(guess_iteration)
        if is_guess_correct(number, guess):
            print("YOU WON!")
            break

if __name__ == '__main__':
    run_game(1, 100)


Partitioning an array of objects into four arrays by one attribute

This can easily be done with array.reduce

let resultsByMethod = data.reduce((results, result) => {
  if(!results[result.method]) results[result.method] = [];
  results[result.method].push(result);
  return results;
}, {});

The end result is something like:

{
  GET: [...],
  POST: [...],
  PUT: [...],
  DELETE: [...]
}

One disadvantage in your approach is when it encounters a method that's note one of the 4 you're comparing.


Use path.join() instead of manually concatenating file paths

This will make sure that it will work on different OS's, windows uses \ backslashes for instance
No need to convert with strftime

A datetime has years, months and days as properties, if you want them in str format you could:

map(str, iterable) to convert them into strings

Code

import datetime
import os.path

now = datetime.datetime.now()
y, m = map(str, (now.year, now.month))

location = os.path.dirname(os.path.abspath(__file__))
ipath = os.path.join(location, 'images', y, m + '.jpeg')
video_path_mp4 = os.path.join(location, 'videos', y, m + '.mp4')
video_path_webm = os.path.join(location, 'videos', y, m + '.webm')


Brute force passwords in C (CS50 exercise)

valid_args is a well-known anti-idiom:

    if (condition) {
        return true;
    }
    return false;

is a long way to say

    return condition;

crack always return an empty string "". It is as good as returning nothing.
check terminates the program on success. This seriously limits its utility: the business logic doesn't belong to such depth of the call tree. Consider returning a boolean instead.
I do not endorse recursion when an iterative approach suffices. Try to express a power set generation iteratively (hint: think of base-52 numbers).
From what we can see, it is impossible to tell whether crypt returns a static buffer, or allocates a new one for each call. Consider documenting that.
I happen to know that <cs50.h> defines string as an alias to char *. I don't think it is a good idea to begin with; in any case you should be consistent: brute_force passes salt and hash as string, while check receives them as char *.


Simple object oriented design for an Allergy class

Two things to notice..

    def add_symptoms(symptom, severity)

Actually, you don't add many symptoms, but only one :)

Secondly, but this has nothing to do with object oriented. Why is the sympton name given to attr_accessor? Do you expect to change it at runtime (e.g: changing "Rash" to "Sneezes"?)
Same thing with time_reported, do you expect it to be updatable? :/

Secondly, but I think this is more a "taste" of matter.. I'd honestly prefer to pass something similar:

def add_symptoms(symptom)

with symptom already being the object instantiated. Why? Because if you are to then have multiple subclasses of Symptom (e.g:

class HeavySimptom
class RespiratorySimptom
class AmbiguousSymptom

) your code would be quite a pain to change


User name and password validation in a MVP application

For the GetHash() function you could go with PBKDF2. It was specifically created to address password hashing. It requires at least 8 bytes of salt, so the code below builds a SHA1 hash to "stretch" your salt to that minimum length. The better approach would be to generate a cryptographically-strong random salt and store that along with the resulting hash. (c.f. RNGCryptoServiceProvider)

public static string GetHash(string salt, string password)
{
    if (string.IsNullOrEmpty(salt))
    {
        throw new ArgumentNullException("salt");
    }

    if (string.IsNullOrEmpty(password))
    {
        throw new ArgumentNullException("password");
    }

    byte[] passwordSaltBytes = System.Text.Encoding.UTF8.GetBytes(salt);

    if (passwordSaltBytes.Length < 8)
    {
        using (var saltStretcher = System.Security.Cryptography.SHA1.Create())
        {
            passwordSaltBytes = saltStretcher.ComputeHash(passwordSaltBytes);
        }
    }

    using (var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, passwordSaltBytes, 10000))
    {
        return Convert.ToBase64String(pbkdf2.GetBytes(20));
    }
}


The good

So, you're trying to allow users to create new questions, but those questions must have a slug which is unique. You're enforcing this on the database level with unique=True, which is a good start.

You are using a form to handle the creation of new questions, which is definitely the right way to do this. It'll also be really useful when you need to build in the ability to edit a question, since you can just reuse the same form.

The bad

But you're enforcing the uniqueness of a question outside of the form. The form ultimately has the business logic that determines whether or not the input is valid, which is why Django has built-in support for validating forms. If you find issue with isolating your form validation logic inside of a form, I would recommend breaking it out as general utilities which can be easily tested.

Right now you're enforcing these constraints either on the model level (through save, which is definitely not the right place) or on the view level (through form_valid, which is not right but also not horrible).

Django designed the generic views to be easy to implement, assuming you follow the standard Django conventions. If you don't follow the conventions, you end up with cases like your form_valid where you have to do additional validation and then decide that it's actually invalid, forcing them to form_invalid. You shouldn't have made it to form_valid, since the state is not actually valid.

The fix

You should move your uniqueness logic into the form. Since you are only validating a single field, the title field, you only need to handle the logic for that field. This means that you can isolate your logic inside a custom cleaning method.

class QuestionForm(ModelForm):

    class Meta:
         model = Question
         fields = ['title', 'text']

    def clean_title(self, title):
        from django.utils.text import slugify
        from django.core.exceptions import ValidationError

        slug = slugify(title)

        if Question.objects.filter(slug=slug).exists():
            raise ValidationError('A question with this title already exists.')

        return title

class QuestionCreate(generic.CreateView):
    form_class = QuestionForm

This means that you no longer need the form_valid override and you don't need to worry about having to replicate that validation logic in other places which use this form.


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

Use the required #includes

The code uses strlen and memcpy which means that it should #include <string.h>.  It was not difficult to infer, but it helps reviewers if the code is complete. It's also an important part of the interface.  I believe these are the required includes:

#include <string.h>
#include <stdlib.h>
#include <ctype.h>

Use const where practical

In your findxy routine, the passed string is never altered, which is just as it should be.  You should indicate that fact by declaring it like this:

int findxy(const char *c)

Check for a null pointer

Things do not go well if the routine is passed a NULL pointer.  On my machine, I get a segmentation fault and a crash.  You can eliminate this hole by adding these lines near the top of the routine:

if (c == NULL) {
    return -1;
}

Use better naming

The days array is well named because it's easy to guess from the name what it contains.  Likewise i and j are commonly used as index variables as you have done in this code.  However, findxy is a rather cryptic name for what this does and c is a poor name for the passed string.  I'd recommend something like this instead:

int findWeekdayDate(const char *str)

Avoid copying if practical

It's not strictly necessary to make copies of portions of the passed string.  With a bit of careful planning, it can be done in place.  Here's one way to do it, although it's not very efficient:

int isValidWeekdayDate(const char *str) {
    static const char *days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    if (str == NULL || strlen(str) < 5) {
        return 0;
    }
    for (const char **dayname = days; *dayname; ++dayname) {
        char *pos = strstr(str, *dayname);
        if (pos && pos == str) {
            if (isdigit(pos[3]) && isdigit(pos[4])) {
                int val = (pos[3]-'0') * 10 + (pos[4]-'0');
                if (val > 0 && val <= 31) {
                    return 1;
                }
            }
        }
    }
    return 0;
}

int findWeekdayDate(const char *str) {
    for (const char *curr = str ; *curr; ++curr) {
        if (isValidWeekdayDate(curr)) {
            return curr-str;
        }
    }
    return -1;
}

Use a finite state machine

We can create a much more efficient routine by creating a finite state machine. For a particular candidate string, we note that the first character must be one of {'F', 'M', 'S', 'T', 'W'}.  If it is not one of those, then the candidate string can be immediately rejected.  Now let's say the first character is 'S'.  In that case the second character must be one of {'a', 'u'}.  We can proceed like this, one character at a time to create a finite state machine.  Here's a visualization of such a state machine:

This is how compiler tools like flex and bison and lex and yacc work.  The code is very efficient but might not be as easy to understand, so it's a tradeoff you should be aware of.

A very pedantic note

Strictly speaking, this line:

int val = (pos[3]-'0') * 10 + (pos[4]-'0');

is guaranteed to be portable.  The C standard requires that encoding of digits is contiguous, so this will work with any character encoding, including EBCDIC, Unicode and ASCII.


PHP creating username with random number

I don't write PHP, but there are several general things I would suggest.

Your 2-space indent makes your code more difficult to read, I would recommend 4.

$digits is always 4, so I would declare it as a constant, and rename it accordingly. You can move it outside the while loop also.

const $NUMBER_OF_DIGITS = 4;

$first3 and $last3 are also not going to change, so I would move them out of your while loop, and also name them accordingly.

const $NUMBER_OF_DIGITS = 4;
const $FIRST_3 = substr($firstname, 0, 3);
const $LAST_3 =  substr($lastname, 0, 3);
while($user == $dbusername) {
    // ...

Your comments point out what should be easy to deduct for anyone who writes code regularly. I would suggest to reserve comments for function/class documentation (for example using PHPDoc) and otherwise, just to document things that are not obvious, or may be unusual workarounds to a certain problem/use case.

I think, in particular, perhaps this line deserves a short explanation:

$randomNumber = rand(pow(10, $digits-1), pow(10, $digits)-1);

Comments can also cause more work for you as the maintainer, as you have to also maintain comments in addition to the code, if anything is changed.

Comments can also be misleading, take this for example:

  // if the created user happens to exist in the database, set it to $dbusername
  $dbusername = $row['username'];
  // rerun the loop if this happens

The comment should really say something like:

  // set $dbusername to either NULL, or an existing username in the case it does exist, which will cause the loop to re-run if it already exists in the database

But that's already pretty obvious from the code, so I would just delete the comment instead, along with most or all of the other ones.

Lastly, I think the while loop works fine, but a do-while loop would make a bit more sense, in that it makes it clear that the loop should run at least once, but may run more times under certain conditions.

do {
    // your logic code as it is
} while($user == $dbusername);