I don't know about standard, so I'll just say what I see.

I found that the second is cleanest of all three and easiest to read.  The logic flow is very simple, with just one simple if/else.  However, it is not DRY, with all the problems that that entails.

the first and third are both a bit more complex.
the third also has the same if block defined twice (once at the beginning and once at the end), which makes it also not DRY

regarding the first, I personally don't like the idea of creating an a tag that gets javascript:void(0). It seems that it will just add clutter to the rendered page.

The other problem (with all three) is that you have your logic mixed in to the html. I would recommend something like as follows:

<?php
    //first define all the variable items
if($modelStatic->isVerifiedEmail) :
    $startTag = '
';
    $endTag = '
';
else:
    $startTag = '<a href="<?php echo Yii::app()->createUrl('/user/reActivate'); class="item">'
    $endTag = '';
endif; ?>

     <?=$startTag?>

            <?php echo Yii::t('app', 'Verify Email'); ?>

     <?=$endTag?>


Persistent login ("remember me" cookie) using PHP

Security

  I am not sure if I have done the same thing as explained there

  Is my code a good way to secure remember me cookie ?

No and no.

Non-Random Token: Login as anyone

The only data you store in your cookie is the username*. But usernames are generally not considered secret, and are relatively easy to obtain.

Because of this, an attacker can just calculate cookie=$username. "," .md5($username). "," . hash('sha512','sometext') themselves and log in as anyone.

You definitely always want at least partly random data in your cookie.

* and sometext. It's not entirely clear what this means, but because of the line $newhash = 'sometext';, I'm assuming that it is some hardcoded value, which is not good enough. Having (correctly generated) random data is essential here.

Non-Random Identifier: Invalidating Remember-Me Cookie of any user

Your identifier only consists of the (hashed) username.

An attacker can invalidate the remember-me cookie of any user by simply submitting a remember-me cookie like this: username,md5(username),invalid_token.

This is why the post suggests that the identifier should be random (otherwise, it wouldn't be needed, as the username could be used instead; the hashing itself doesn't add any security).

Plaintext Cookies: Login as anyone after database compromise

You also do not want to store the cookie as plaintext in the database, because it means that if an attacker gained access to your database, they can log in as anyone.

The hashing you do apply (md5 and sha512) do not solve this problem, as they are used to create the cookie, but not to store the cookie, or to compare the stored cookie to a user supplied cookie.

You should use bcrypt to store the cookie (the token part) in the database (just as you would when storing passwords).

Identifier and Token: Preventing timing attacks

The reason that the linked answer suggests using an identifier and a token is to prevent timing attacks which may result from a db lookup such as "SELECT * FROM tokens WHERE cookie=:user_supplied_cookie".

The problem here is that you actually use the identifier correctly, but then use ==, re-introducing the timing attack. If you use bcrypt as suggested, you will get a timing-safe string-compare for free.

httpOnly

Cookies such as this should be httpOnly to somewhat mitigate the risk of XSS attacks.

For more information on remember-me, this and this may help.

Misc

Your formatting is rather non-standard and partly inconsistent, making your code hard to read: Your indentation is inconsistent, and one space for indentation is definitely not enough. Your spacing is also inconsistent, and you could use more spaces (especially around comparisons such as !=, >, etc).
Don't shorten variable names, it makes your code hard to understand. What's a Utoken or a Uidentifier?
be consistent in the structure of your variable names. Some of your variables start with an upper-case character, some with a lower-case one, and all your variables are all lower-case afterwards, making them harder to read.
die after a header redirect, as a client does not have to actually follow the redirect.


Speed up simple Python function that uses list comprehension

def loadData(filePath):
    reader = csv.reader( open(filePath) )
    rows = []

    for i, row in enumerate(reader):
        categories = ["id", "title", "description", "rawLocation", "normalizedLocation",
                        "contractType", "contractTime", "company", "category",
                        "salaryRaw", "salaryNormalized","sourceName"]

A list like this should really be a global variable to avoid the expense of recreating it constantly. But you'd do better not store your stuff in a dictionary. Instead do this:

   for (id, title, description, raw_location, normalized_location, contract_type,
       contractTime, company, category, salary_raw, salary_normalized, source_name) in reader:

       yield salary_normalized, ''.join((description, normalized_location, category)), title

All the stuff is then stored in python local variables (fairly efficient). Then yield produces the three elements you are actually wanting. Just use

   salaries, descriptions, titles = zip(*loadData(...))

to get your three lists again

        # Skip header row
        if i != 0:
            rows.append( dict(zip(categories, row)) )

Rather than this, call reader.next() before the loop to take out the header

    return rows


You can eliminate the .close() using a with ... as ...: statement.

Since newlines are white-space characters, re.sub('\s+', ' ', ...) will already convert any '\n' characters to a space, so the .replace('\n', ' ') is unnecessary.

And you don't need to write everything on one line, even when you
want a "one-liner".

with open(args.hql, 'r') as fdHql:
    queries = [
               re.sub('\s+', ' ', each.strip())
                   .replace('( ', '(')
                   .replace(' )', ')')
                   .replace(' ,', ',')
               for each in fdHql.read().split(';')
              ]

Of course, the clearest is to move the work to a helper function.

def _format_sql(sql):
    return re.sub('\s+', ' ', sql.strip())      \
               .replace('( ', '(')              \
               .replace(' )', ')')              \
               .replace(' ,', ',')

with open(args.hql, 'r') as fdHql:
    queries = [ _format_sql(each) for each in fdHql.read().split(';') ]


Deciding whether a list of sum types is homogeneous

homogeneous could also be defined using pattern matching, though that would not necessarily be an improvement.

However, homogeneousButOne can definitely be simplified using pattern matching, with no need for Data.Map or Data.List.

data Foo = Bar | Baz | Quux | Id | Mix deriving (Eq, Ord, Show)

homogeneous :: [Foo] -> Bool
homogeneous []           = True
homogeneous (Mix : _)    = False
homogeneous (Id  : xs)   = homogeneous xs
homogeneous (x   : [])   = True
homogeneous (a:Id:rest)  = homogeneous (a:rest)
homogeneous (a:b:rest)   = (a == b) && homogeneous (b:rest)

homogeneousButOne :: [Foo] -> (Foo, Foo, Bool)
homogeneousButOne xs
  | null nonId           = (Id, Id, True)
  | x' == Mix            = (Mix, Mix, False)
  | length nonId == 3    = majority2of3 nonId
  | homogeneous nonId    = (x', x', True)
  | homogeneous xs'      = (head xs', x', False)
  | x' == predominant    = (predominant, alt, False)
  | otherwise            = (Mix, Mix, False)
  where nonId = filter (/= Id) xs
        (x':xs') = nonId
        majority2of3 (a:b:c:[]) =
          if      a == b then (a, c, a == c)
          else if a == c then (a, b, a == b)
          else if b == c then (b, a, b == a)
          else                (Mix, Mix, False)
        (predominant, alt, _) = homogeneousButOne xs'


Konrad's answer has a big advantage: it is safe!
In your code sample, if an operator raise an exception before you leave the critical section, this one will never be released. In Konrad's answer, not matter what, the critical section will be unlocked when you exit the scope, even if you don't catch an exception.


Sending test emails to a list of email addresses

Set olMailItem = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing

is unnecessary. VBA is garbage collected, there's no need for this, or any of the other = Nothing's you have. Here's an article from one of the MS developers about this practice. It refers to VBScript, but VBA's garbage collection algorithm is similar, and probably substantially better than VBScript's.
Around
'Open record set on
        Dim dbC As DAO.Database

You start a new level of indentation. Why? I thought when I first read this that it was a part of the loop below.
Finally, you might want to think more about your error handling (although VB's error handling isn't very fun to work with). For example, if you get an exception on olMailItem.Send, you might not care -- you want the script to keep going and try to send the next email, in case that was a fluke. However, if something goes wrong on Set rcdSet = dbC.OpenRecordset(strSQL), you probably want the script to quit entirely, since nothing afterwards is going to be useful if you don' have anything to work on.


It's a good start, but I see a number of things that may help you improve your code.

Try to reduce the scope of variables

The variables o_is_set and found are essentially global variables, but don't need to be.  Instead, the code might be structured as a series of functions, reducing the linkage within the code.

Use standard option parsing

One could use getopts for parsing command line options, or plain old bash for that.  For example, consider this code for parsing a -o option with its corresponding argument:

while [[ $# > 1 ]]
    do
        opt="$1"
        case $opt in
            -o)
            OUTPUT="$2"
            shift
            ;;
            *)
                # ignore unknown option
            ;;
        esac
        shift
    done

Use make instead

The basic operation of this file is to create an executable from either a .cpp or .c file using the gcc compiler and then running the resulting executable.  One can do essentially the same thing with a single line:

#!/bin/bash
make $1 && ./$1

For example, if we have nuts.c in the current working directory and the file above is called car we can execute ./car nuts and make will run, find the nuts.c file, create an executable nuts and then run it.


If zero found in Matrix. make entire row & column zero

Implementation

You did it right that you first find the zero entries and only after that set the rows/columns to zero. However, you can come up with more cohesive and flexible code:

public static void zeroMatrix(final int[][] matrix) {
    findZeroEntries(matrix).forEach((p) -> {
        setToZero(matrix, p.x, p.y);
    });
}

private static List<Point> findZeroEntries(final int[][] matrix) {
    final int height = matrix.length;
    final int width  = matrix[0].length;
    final List<Point> zeroEntryList = new ArrayList<>();

    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            if (matrix[y][x] == 0) {
                zeroEntryList.add(new Point(x, y));
            }
        }
    }

    return zeroEntryList;
}

private static void setToZero(final int[][] matrix,
                              final int x,
                              final int y) {
    setRowToZero(matrix, y);
    setColumnToZero(matrix, x);
}

private static void setRowToZero(final int[][] matrix, final int y) {
    final int width = matrix[0].length;

    for (int x = 0; x < width; ++x) {
        matrix[y][x] = 0;
    }
}

private static void setColumnToZero(final int[][] matrix, final int x) {
    final int height = matrix.length;

    for (int y = 0; y < height; ++y) {
        matrix[y][x] = 0;
    }
}

Coding conventions

Braces

What comes to braces, the recommended way to write them is to put the opening brace ({) on the same row with the statement that belongs to it. Instead of

for (...)
{
    ...
}

you should write

for (...) {
    ...
}

Spaces

For the sake of readability, you should have a single space character after each for and if, and a single space character before and after any binary operator. So instead of

for(int i=0; ...) {
    if(i==1) {

    }
}

you should have

for (int i = 0; ...) {
    if (i == 1) {
        ...
    }
}

Program to interface

Not that it makes much difference in your method, but usually the rule goes that people should program to an interface, and not to an implementation. So instead of

ArrayList<Integer> coord = new ArrayList<>();

you should write

List<Integer> coord = new ArrayList<>();

Naming

arr1 is not the best possible name. Why not use, say, matrix?

Also

int row = arr1.length;
int column = arr1[0].length;

above I would have used the plural form:

int rows = arr1.length;
int columns = arr1[0].length;

Zero entry coordinates

As @200_success mentioned, packing the coordinates the way you do is not a good idea.

Hope that helps.


LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers I

Ensure you match the given API
Using size_t for sizes is a good thing to do, however the LeetCode problem specifies the API, and you should not change it. minimumDistance() should return int.
Use static constexpr for compile-time constants
Use static constexpr instead of const for the constants. This allows the compiler to make more optimizations, and they can then also be used in other places where a compile-time constant is required, for example:
Use a std::array
Since dp has a compile-time constant size, you can make it a std::array:
std::array<int, ALPHABET_LEN> dp;

Avoid using small types unnecessarily
Here you have a problem where you know the maximum distance between two letters is 25. I see you have decided to make coordinates() return an unsigned short. I would not do this. While it might seem more optimal, it is not: on many 32-bit and 64-bit platforms, 16-bit integers are often less efficient than 32-bit integers, since they are smaller than the natural register size, and thus the compiler might need to add instructions to ensure all but the lower 16 bits are zeroed. There might also be a penalty because it has to convert it back to a regular int when adding it the result to  total_distance.
The right time to use shorts or even chars to hold integer values is when you have large arrays of them, since then it might reduce memory usage and memory bandwidth.
Proper naming
The function coordinates(), contrary to what the name implies, does not return coordinates. Instead, it returns a distance. So name it distance().
I would also not name the arguments left and right, but just a and b. Left and right sounds confusing here since you might think it gets the character under the left and right fingers as inputs.
Also, what does dp stand for? It seems like this vector holds the maximum distance traveled given a starting position. Try to find a more descriptive name for it. If there is no good one, then at least add a comment explaining what dp is.
The names second and third are slightly misleading for index > 0. Maybe it would be better to name them from and to.
Use WIDTH consistently
You still use one literal 6 in coordinates().


Speed problems with SetValue, ToType and Reflection

Style

Based on the naming guidlines method names should use PascalCasing casing.

determineCanMessageValueFields()

Instead of calling Count() and checking if it is greater than 0 you should call Any().

So determineCanMessageValueFields() would become

private IEnumerable<PropertyInfo> determineCanMessageValueFields()
{
    return this.GetType().GetProperties()
                            .Where
                                (p => p.GetCustomAttributes(false)
                                            .Any(x => x.GetType() == typeof(IsValueField))
                                )
                            .OrderBy(x => ((IsValueField)x.GetCustomAttributes(false)[0]).ValueFieldIndex);
}

ConvertDataFrameToValueFields()

The creation of the List<byte[]> is not needed at all. If you increment the i counter by 2 you can just use this.DataBytes for the calling BitConverter.ToUInt16(this.DataBytes,i).

This leads after using Any()instead of Count() > 0 to

public void ConvertDataFrameToValueFields()
{

    int i = 0;

    foreach (var prop in DetermineCanMessageValueFields())
    {
        ushort value = BitConverter.ToUInt16(this.DataBytes, i);

        if (prop.PropertyType == typeof(MessageStatusValueField))
        {
            prop.SetValue(this, new MessageStatusValueField(value, prop.Name, this.UnitType), null);
        }
        else if (prop.PropertyType == typeof(MessageValueField))
        {
            prop.SetValue(this, new MessageValueField(value, prop.Name), null);
        }
        else if (prop.PropertyType == typeof(MessageValueFieldInt32))
        {
            prop.SetValue(this, new MessageValueFieldInt32(value, prop.Name), null);
        }
        else if (prop.PropertyType.GetCustomAttributes(false).Any(x => x.GetType() == typeof(BitmaskValueFieldClass)))
        {
            var tempField = new MessageValueField(value, prop.Name);
            prop.SetValue(this, Convert.ChangeType(tempField, prop.PropertyType), null);
        }

        i += 2;
    }
}

and applying the Any() change to the ToType() method

public object ToType(Type conversionType, IFormatProvider provider)
{

    if (!conversionType.GetCustomAttributes(false).Any(x => x.GetType() == typeof(BitmaskValueFieldClass)))
    {
        throw new NotImplementedException("The conversion is only available for conversion types with the BitmaskValueFieldClass attribute");
    }

    var instance = Activator.CreateInstance(conversionType);

    foreach (var item in instance.GetType().BaseType.GetProperties())
    {
        item.SetValue(instance, this.GetType().GetProperty(item.Name).GetValue(this, null), null);
    }

    return instance;
}

Comments

Comments should be used to explain why something is done, not what is done. The what part should be done by the code itself.


Solving for equilibrium index in an array

I'm piggy backing on @jonah's answer. The first code snippet returns what Codility is asking for: any equilibrium index. Second code snippet returns all answers like in @jonah's suggestion. I also added two accumulating arrays for side by side comparison. You can add a breakpoint at the end of the function to compare the two arrays.

var A = [-1, 3, -4, 5, 1, -6, 2, 1];

function solution(A) {
    var rightSum = A.reduce((acc, val) => acc + val, 0), leftSum = 0;

    for (var i = 0; i < A.length; i++) {

        rightSum -= A[i];

        // Codility is asking for any, so return first found
        if (rightSum === leftSum) return i;

        leftSum += A[i];
    }

    return -1;
}

solution(A);

var A = [-1,3,-4,5,1,-6,2,1];

function solution(A) {

    var rightSum = A.reduce((acc, val) => acc + val, 0), leftSum = 0, rightSums = [], leftSums = [], answers = [];

    for (var i = 0; i < A.length; i++) {

        rightSum -= A[i];

        // You can keep track of answers for comparison/debugging
        rightSums.push(rightSum);
        leftSums.push(leftSum);

        if (rightSum === leftSum) answers.push(i);

        leftSum += A[i];

    }

    return answers;
}

solution(A);


Possible improvements:

localise functions of the math library, and sometimes, self.r and self.i. It will reduce the number of table lookups, improving the performance, and will make the expressions simpler,
define __call metamethod for Complex. It will allow you to replace Complex:new(x, y) with Complex(x, y),
the 'constructor' should correctly handle cases when it is called with one parameter (Complex(5) = 5 + 0i). It can be achieved with a 'nullsafe operator' emulated as local a = user_input or value_if_null,
in can also be mage more concise, using the fact that setmetatable returns the table,
__newindex metamethod is not needed here, unless you want to set the absolute value or phase with code like c.abs = 1 or code.arg = pi. In addition, the arguments to __newindex are the table, the absent key and value set to it,
you can emulate the ternary operator in Lua with and and or, which allows to write more concise code: local a = condition and on_success or on_failure,
your arithmetic metamethods should handle the cases when the first argument (self) is a number,
you can define conjugate method and __div metamethod for division,
to square a table element, I'd rather recommend using ^ rather than multiplying by self. It will save table lookups,
you can define methods for polar coordinates and __pow metamethod for Euler's and de Moivre's formulae,
the __lt metamethod can be simplified using boolean operations,
Complex:tostring() can be simplified using 'ternary' operators, also handling of negative imaginary parts can be improved,
whether to put the i before or after the imaginary part and whether to surround a complex number with parentheses can be customisable,
the expression tests can be automated somewhat with load() function.

The improved code:
local math = require 'math'
local pi, sin, cos, atan2 = math.pi, math.sin, math.cos, math.atan2
local sqrt, exp, ln = math.sqrt, math.exp, math.log
local floor, abs = math.floor, math.abs

Complex = {
    IMAGINARY_CHAR = 'i'
}

function Complex:new(r, i)
    self.__index = self
    return setmetatable({r = r, i = i or 0}, self)
end

setmetatable(Complex, {
    __call = function (tbl, r, i)
        return Complex:new(r, i)
    end}
)

function Complex:__unm()
    return Complex(-self.r, -self.i)
end

function Complex:__add(other)
    return type(self) == 'number'   and Complex(self + other.r, other.i)
        or type(other) == 'number'  and Complex(self.r + other, self.i)
                                     or Complex(self.r + other.r, self.i + other.i)
end

function Complex:__sub(other)
    return self + (-other);
end

function Complex:__mul(other)
    return type(self) == 'number'   and Complex(self * other.r, self * other.i)
        or type(other) == 'number'  and Complex(self.r * other, self.i * other)
                                     or Complex(self.r * other.r - self.i * other.i, self.i * other.r + self.r * other.i)
end

function Complex:conjugate()
    return Complex(self.r, -self.i)
end

function Complex:__div(denominator)
    -- https://www.mesacc.edu/~scotz47781/mat120/notes/complex/dividing/dividing_complex.html
    local conjugate = type(denominator) == 'number' and Complex(denominator) or denominator:conjugate()
    local new_numerator, new_denominator = self * conjugate, denominator * conjugate
    -- new_denominator is real.
    return Complex(new_numerator.r / new_denominator.r, new_numerator.i / new_denominator.r)
end

function Complex:abs2()
    return self.r ^ 2 + self.i ^ 2
end

function Complex:abs()
    return sqrt(self:abs2())
end

function Complex:polar(abs, arg)
    return Complex(abs * cos(arg), abs * sin(arg))
end

function Complex:arg()
    return atan2(self.i, self.r)
end

function Complex:exp()
    local abs = exp(self.r)
    return Complex(abs * cos(self.i), abs * sin(self.i))
end

function Complex:__pow(power)
    -- Euler:
    local x = type(self) == 'number' and self or self.i == 0 and self.r > 0 and self.r or nil
    if x then
        return (power * ln(x)):exp()
    else
    -- de Moivre:
        local n = type(power) == 'number' and power or power.i == 0 and power.r or nil
        if n and floor(n) == n then
            local abs, arg = self:abs(), self:arg()
            return Complex:polar(abs ^ n, n * arg)
        end
    end
end

function Complex:__eq(other)
    return
        self.r == other.r and
        self.i == other.i
end

function Complex:__lt(other)
    -- incorrect but for sorting:
    return self.r < other.r or self.r == other.r and self.i < other.i
end

function Complex:tostring(i, prefix, parentheses)
    local im = type(i) == 'string' and i or 'i'
    local r, i = self.r, self.i

    local str = ((r ~= 0 or i == 0) and r or '')
             .. (r ~= 0 and i > 0 and ' + ' or '')
             .. (i < 0 and ' - ' or '')
             .. (i ~= 0 and (prefix and im .. abs(i) or abs(i) .. im) or '')
    if parentheses then
        str = '(' .. str .. ')'
    end
    return str
end

function Complex:__tostring(i)
    return self:tostring(self.IMAGINARY_CHAR, self.PREFIX, self.PARENTHESES)
end

-- ===================================================================

Complex.IMAGINARY_CHAR = 'j' -- electrical notation.
Complex.PREFIX = true
Complex.PARENTHESES = true

local context = {
    Complex = Complex,
    x = Complex(0, 10),
    y = Complex(-5, 5),
    z = Complex(5),
    pi = pi
}

local cases = {
    'x', 'y', 'z', 'x:abs()',
    'x + y', 'x - y', 'x + 12', 'x - 12', '12 + x', '12 - x',
    'x * y', 'y * 12', '2 * x',
    'y:conjugate()', 'x / y', 'y / y', 'x / 5', '5 / x', '5 / x * x',
    'y:abs()', 'y:arg() / pi * 180', 'Complex:polar(2, pi / 4)', 'y:exp()', 'x ^ 2', '2 ^ x',
    'x == y', 'x ~= y', 'x < y', 'x > y', 'x <= y', 'x >= y'
}
for _, expr in ipairs(cases) do
    print(expr, assert(load('return ' .. expr, nil, 't', context))())
end
```


Partition a linked list arround an element

I just have a point on naming of your function. You named it partition but you're just rearranging the elements and returning the head pointer! If you want to partition, you may want to return pointers to heads of partitions (the head you already return and another pointer to start of bigger than x partition), this way someone using your function doesn't need to iterate over linked-list to find start of next partition, and this pointer can be easily recorded in if statement in your while loop.


Formatting a list with commas and occasional line breaks

You have serval ways to achieve this task. You can pass the length of array as well.
About the implementation you can use forEach method like this.

 function formatNumberArray(arr) {
        let output = "";
        arr.forEach((v, i, a) => {
            output += v.number + "[" + v.amount + "]" + ((i + 1) % a.length == 0 ? "" : i % 5 == 4 ? ',
' : ', ');
        });
        return output;
    }

or you can iterate the array to the last index - 1 and then simply add the last value

function formatNumberArray(arr) {
        let output = "";
        for (let i = 0; i < arr.length - 1; ++i) {
            output += arr[i].number + "[" + arr[i].amount + "]" + ((i % 5 === 4) ? ',
' : ', ');
        }
        return output + arr[arr.length - 1].number + "[" + arr[arr.length - 1].amount + "]"
    }

I assume that the array is something like this.

  let arr = [{ number: 123, amount: 24 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }, { number: 16, amount: 10 }]


Demonstration of inheritance with some shapes

Shadowing

There is some shadowing going on between Rectangle and Square.

Rectangle implements IShape, and Square inherits from Rectangle.

As it stands, Square is hiding Rectangles Draw method. This is evident from the following compiler warning:

  Warning   1   'ConsoleApplication1.Square.Draw()' hides inherited member
  'ConsoleApplication1.Rectangle.Draw()'. Use the new keyword if hiding
  was
  intended.

This can pose a problem in the following scenario:

  Square s = new Square();
  s.Draw(); //Square method called

  Rectangle r = new Square();
  r.Draw(); //Rectangle method called!

As you see, this breaks inheritance and will only call the method on Square if the variable is a Square.

Instead, you might want to make the method virtual on Rectangle:

public class Rectangle : IShape
{
    public virtual void Draw()
    {
        Console.WriteLine("Rectangle object draw method\n");
    }
}

public class Square : Rectangle
{
    public override void Draw()
    {
        Console.WriteLine("Square object draw method\n");
    }
}

This will ensure that the correct method is always called.

Line breaks

There is no need to add \n when calling Console.WriteLine. It will add a line break automatically.

Moreover, \n is not the correct method of adding a line break in .NET. Use Environment.NewLine instead.

Misc.

The order of the final print in your example is wrong. It prints before actually assigning shape = new Rectangle().


Finding the best matching block/patch in Python

The following outlines a couple variations of a numpy solution. For the problem sizes in your post, they all clock faster than 100us, so you should get your 30,744 calls in about 3 seconds.

import numpy as np

N = 3

W = 15
x, y = 15, 15

data = np.random.randint(20, size=(30, 30))
current_patch = np.random.randint(20, size=(N, N))

# isolate the patch
x_start = x - W//2
y_start = y - W//2

patch = data[x_start:x_start+W, y_start:y_start+W]

# take a windowed view of the array
from numpy.lib.stride_tricks import as_strided
shape = tuple(np.subtract(patch.shape, N-1)) + (N, N)
windowed_patch = as_strided(patch, shape=shape, strides=patch.strides*2)

# this works, but creates a large intermediate array
cost = np.abs(windowed_patch - current_patch).sum(axis=(-1, -2))

# this is much more memory efficient, but uses squared differences,
# and the fact that (a - b)^2 = a^2 + b^2 - 2*a*b
patch2 = patch*patch
ssqd =  as_strided(patch2, shape=shape,
                   strides=patch2.strides*2).sum(axis=(-1, -2),
                                                 dtype=np.double)
ssqd += np.sum(current_patch * current_patch, dtype=np.double)
ssqd -= 2 * np.einsum('ijkl,kl->ij', windowed_patch, current_patch,
                      dtype=np.double)

# for comparison with the other method
cost2 = windowed_patch - current_patch
cost2 = np.sum(cost2*cost2, axis=(-1, -2))

# with any method, to find the location of the max in cost:
best_X, best_y = np.unravel_index(np.argmax(cost), cost.shape)


Well, what you want is just a product of the alphabet, with increasing numbers of elements. You can use itertools.product for this:

from itertools import product, count
from string import ascii_lowercase

def generate_labels():
    """Yields labels of the following form:
       a, b, ..., z, aa, ab, ..., zz, aaa, aab, ..., zzz, ...
    """
    for n in count(start=1):
        yield from map("".join, product(*[ascii_lowercase]*n))

Here is what it outputs:

from itertools import islice

print(list(islice(generate_labels(), 1000)))
# ['a', 'b', ..., 'z', 'aa', 'ab', ..., 'az', 'ba', 'bb', ..., 'bz', ..., 'za', ..., 'zz', 'aaa', 'aab', ..., 'all']

This has the slight disadvantage that the list being passed to product gets larger every iteration. But already with \$n=5\$ you can generate \$\sum_{k=1}^n 26^k = 12,356,630\$ labels, and the list is only about sys.getsizeof([ascii_lowercase]*5) + sys.getsizeof(ascii_lowercase) * 5 = 479 bytes large, so in practice this should not be a problem.

I also made the name a bit longer (and clearer IMO) and added a docstring to briefly describe what the function is doing.


Algorithms to find statistical information of an array

Glaring Deficiencies

Let me venture here that your getMedian method is slower than your getMode method. Thanks to your sort. You use a naive bubble-sort, which is \$O(n^2)\$. It can be done using \$O(n\log(n))\$ using quicksort (for practical input), mergesort, heapsort, etc. However, you can get the best of all worlds by just using the static method sort() from java.util.Arrays. It will get you an implementation of mergesort or Timsort, both very fast compared to bubble sort.
About getAverage. You recalculate the sum in a loop where you already have a getSum method. Use that.
You have really inconsistent return types in some places, especially getSum and getMedian.
In getMedian, int[] sorted = x; probably doesn't do what you want it to do, which is create a copy of the argument array which you can sort. Try using int[] sorted = Arrays.copyOf(x, x.length); instead, which will do the required deep copy instead of a reference assignment.

I disagree with @coderodde's approach. You should get what you ask for when computing statistics. You should not incur costs which you do not deserve. That is, if you want to get the average of all the elements in an array, you should not have to pay the overhead of sorting it and calculating the median.

Algorithmic improvements

In getMin and getMax, set the default value of the accumulator variable to the first element of the array, i.e., arr[0], and start the loop at 1 instead of 0. It makes more sense. Or, better, use Streams, they have these methods in-built.
Use @coderodde's idea for calculating mode, as that is \$O(n+n\log(n)) = O(n\log(n))\$, whereas yours is currently \$O(n^2)\$ in the worst case. That is, his way is faster.

Note, however, that your mode calculation algorithm is a bit problematic; for an input set {1, 1, 2, 4, 4}, your code will return 4, though for a multimodal set it would be mathematically appropriate to return the first mode, i.e., 1 here.

I have managed to fashion a faster approach to the problem, involving only partially sorting and partitioning the array, however, this works correctly only for unimodal sets (and works in a mathematically correct fashion for multimodal sets). I use the naive approach to get all the modes of a multimodal set.

In my code it appears that I need \$O(n)\$ additional space due to the Set<Mode> used for maintaining multimodal data, but for unimodal data, this is unnecessary and it can be made to work in \$O(n\log(n))\$ time and \$O(1)\$ additional space.

I make both pieces of code return a double[] (in the former case, a single-element array even for multimodal sets), for API consistency.
Use a selection algorithm, such as the Floyd-Rivest Algorithm for calculating the median in linear time, instead of the best-case \$O(n\log(n))\$ when using sorting.
Use a numerically stable one-pass algorithm like Welford's Method to get the variance / standard deviation.

Ideas

You should name getAverage to getArithmeticMean, as that is the more appropriate statistical term here.
As regards the above, you could try implementing a getGeometricMean, which would be calculated as follows:

\$GM = \sqrt[n]{\prod\limits_{i=1}^n x_i}\$

Or, the \$n\$th root of the product of \$n\$ numbers.

Suggestions

Java 8's Streams would help a lot here.
Declare your method parameters final. That way, the caller will not have to worry about you changing their data out from under their feet (it's not especially helpful with arrays, but even so).
Try using the for-each loop where you don't need explicit indexing, rather just the elements in sequence, e.g. in getMode.
Try to fail-fast: throw exceptions when you encounter exceptional conditions, like being supplied an empty array (java.util.NoSuchElementException seems to be a good fit for this use case).

New Code:

Note that this is not one of the best examples when it comes to coding in Java, but take a look at it anyway (there are comments when the going gets tough). There are usually 2 versions of each method, one utilizing your original idea, the other utilizing a faster algorithm. The naive versions have UnOpt suffixed to their names. Except in the case of getMode as noted above, both versions are semantically equivalent. In case of the Floyd-Rivest algorithm used in select, there are some magic numbers, you can look at the linked Wikipedia article for details.

import java.util.*;
import java.util.stream.*;
import static java.lang.Math.*;
public class Stats{
    private static double[] unbox(Collection<Double> collection){
        return collection.stream().mapToDouble(Double::doubleValue).toArray();
    }

    public static double[] getModesUnOpt(final double[] x) {
        Set<Double> modes = new HashSet<>(x.length);
        long count = 0, countMax = 0;
        for (final double v : x) {
            count = Arrays.stream(x).filter(y -> y == v).count();
            if (count >= countMax) {
                if(count > countMax){
                    countMax = count;
                    modes.clear();
                }
                modes.add(v);
            }
            count = 0;
        }
        return unbox(modes);
    }

    public static double getModeUnOpt(final double[] x) {
        return getModes(x)[0];
    }

    private static class Mode{
        public double Value = 0.0;
        public int Count = 0;
    }

    public static class Pair<L, R>{
        public final L left;
        public final R right;
        public Pair(L left, R right){
            this.left = left;
            this.right = right;
        }
    }

    public static double getMode(final double[] x){
        return getModes(x)[0];
    }

    public static double[] getModes(final double[] x){
        return findModePartialSortRecursive(x, 0, x.length, new Mode(), new HashSet<>()).right.stream().mapToDouble(y -> y.Value).toArray();
    }

    private static Pair<Mode, Set<Mode>> findModePartialSortRecursive(final double[] array, int begin, int end, Mode best, Set<Mode> modes){
        int pivotIndex = (int) (begin + (random() * (end - begin)));
        Mode mode = best;
        double pivot = array[pivotIndex];
        int left = begin, right = end - 1, pos = left;
        Pair<Mode, Set<Mode>> data = new Pair<>(best, modes);
        while (pos <= right){
            if (array[pos] < pivot){
                array[left++] = array[pos++];
            }
            else if (array[pos] > pivot){
                swap(array, right, pos);
                --right;
            }
            else{
                ++pos;
            }
        }
        int pivotCount = right - left + 1;
        for (int i = left; i <= right; i++){
            array[i] = pivot;
        }
        if (pivotCount >= mode.Count){
            if(pivotCount > mode.Count){
                mode.Value = pivot;
                mode.Count = pivotCount;
            }
            modes.add(mode);
            data.left = mode;
            data.right = modes;
        }
        int leftCount = left - begin;
        if (leftCount > mode.Count){
            data = findModePartialSortRecursive(array, begin, left, mode, modes);
        }
        int rightCount = end - right - 1;
        if (rightCount > mode.Count){
            data = findModePartialSortRecursive(array, right + 1, end, mode, modes);
        }
        return data;
    }

    public static void swap(double[] array, int i, int j){
        double temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    /**
     * Uses the Floyd-Rivest Algorithm for a quickselect with median-optimized pivot selection.
     * Modifies the input array such that array[k] is the (k - left + 1)th smallest element in the array.
     */
    public static double select(double[] array, int left, int right, int k){
        while(right > left){
            // use select recursively to sample a smaller set of size s
            // the arbitrary constants 600 and 0.5 are used in the original
            // version to minimize execution time
            if(right - left > 600){
                double n = right - left + 1;
                double i = k - left + 1;
                double z = log(n);
                double s = 0.5 * exp(2.0 * z/3.0);
                double sd = 0.5 * sqrt(z * s * (n - s)/n) * signum(i - n/2);
                int newLeft = (int)max(left, k - i * s/n + sd);
                int newRight = (int)min(right, k + (n - i) * s/n + sd);
                select(array, newLeft, newRight, k);
            }
            // partition the elements between left and right around t
            double t = array[k];
            int i = left;
            int j = right;
            swap(array, left, k);
            if(array[right] > t){
                swap(array, right, left);
            }
            while(i < j){
                swap(array, i, j);
                ++i;
                --j;
                while(array[i] < t){
                    ++i;
                }
                while(array[j] > t){
                    --j;
                }
            }
            if(array[left] == t){
                swap(array, left, j);
            }
            else{
                ++j;
                swap(array, j, right);
            }
            // adjust left and right towards the boundaries of the subset
            // containing the (k - left + 1)th smallest element
            if(j <= k){
                left = j + 1;
            }
            if(k <= j){
                right = j - 1;
            }
        }
        return array[k];
    }

    public static double getMedian(final double[] x){
        if(x.length == 0){
            throw new NoSuchElementException("Median of an empty array cannot be found");
        }
        int halfLength = x.length / 2, endIndex = x.length - 1;
        //calculate a generic median
        double median = select(Arrays.copyOf(x, x.length), 0, endIndex, halfLength);
        if((x.length % 2) == 1){
            //length is odd, only 1 middle element to consider
            return median;
        }
        //length is even, 2 median elemnts to consider.
        return (median + select(Arrays.copyOf(x, x.length), 0, endIndex, halfLength - 1)) / 2.0;
    }

    public static double getMedianUnOpt(final double[] x) {
        if(x.length == 0){
            throw new NoSuchElementException("Median of an empty array cannot be found");
        }
        double[] sorted = Arrays.copyOf(x, x.length);
        Arrays.sort(sorted);
        double median;
        if (sorted.length % 2 == 0) {
            //length is even, 2 median elemnts to consider.
            median = sorted[(sorted.length / 2 - 1 + sorted.length / 2) / 2] + 0.5;
        } else {
            //length is odd, only 1 middle element to consider
            median = sorted[sorted.length / 2];
        }
        return median;
    }

    public static double getArithmeticMean(final double[] x) {
        return Arrays.stream(x).average().getAsDouble();
    }

    public static double getGeometricMean(final double[] x) {
        return Arrays.stream(x).reduce((a, b) -> a * b).getAsDouble();
    }

    public static double getSum(final double[] x) {
        return Arrays.stream(x).sum();
    }

    public static double getMin(final double[] x){
        return Arrays.stream(x).min().getAsDouble();
    }

    public static double getMax(final double[] x){
        return Arrays.stream(x).max().getAsDouble();
    }

    /**
     * Uses Welford's method for calculating variance in 1 pass.
     */
    public static double getVariance(final double[] x){
        if(x.length == 0){
            throw new NoSuchElementException("Variance of an empty array cannot be found");
        }
        int n = 0;
        double mean = 0.0, M2 = 0.0;
        for(double y : x){
            ++n;
            double delta = y - mean;
            mean += delta / n;
            M2 += delta * (y - mean);
        }
        return M2 / (n - 1);
    }

    public static double getStandardDeviation(final double[] x){
        if(x.length == 0){
            throw new NoSuchElementException("Standard Deviation of an empty array cannot be found");
        }
        return sqrt(getVariance(x));
    }

    public static double getStandardDeviationUnOpt(final double[] x) {
        if(x.length == 0){
            throw new NoSuchElementException("Standard Deviation of an empty array cannot be found");
        }
        double sumDiffs = 0;
        double avg = getArithmeticMean(x);
        for (int i = 0; i < x.length; i++) {
            sumDiffs += (x[i] - avg) * (x[i] - avg);
        }
        return sqrt(sumDiffs / (x.length - 1));
    }
}


Instead of

i, ok := this.BoxItems[id]
if ok {
    i.Qty += qty
}

a more idiomatic usage is

if i, ok := this.BoxItems[id]; ok {
    i.Qty += qty
}

Calling the receiver this doesn't seem like a good practice to me. Calling it box would be clearer.

You seem to want to make your method chainable. I'm not sure this is a frequent practice in Go but it's probably more a matter of style and experience than a question of idiomatic code or not.

The rest could be condensed a little but that's not a matter of idiom. I have nothing to say regarding your use of pointers.


Short version:

You may trust your own PHP code, if you write it well.
You should not trust data received by cookies, $_GET or $_POST.
Attempting to distinguish data sent from your JavaScript application from malicious input relies on methods that are both hard and easily bypassed.

Long version:

First of all, do you really need the ? true : false?
The == operator already returns a boolean.

Forbidding direct access is a complex (impossible?) task.
The user might just watch the web traffic you send your own Ajax application, and then imitate the output your app would send.

Even if you could prevent that, it'd probably still be pointless - the user could just edit the JavaScript code in many ways (so many in fact that it's probably worthless to try to detect them) so the application would be manipulated into doing what the "attacker" wants.

If you are not concerned about the current application user but rather protecting your user against third parties, then using HTTPS might be the best option. Why re-implement what's already available and designed by people who are - let's face it - smarter than both of us combined (and with the added advantage that it's been around for some time, so its flaws have already had more time to be detected and fixed!)

At some point you are using __FILE__ to detect if the code is authorized? Does this mean the attacker can directly execute PHP code on your server?
If not, then your __FILE__ check is worthless.
If so, then your __FILE__ check is still worthless, as the attacker can just directly call the file functions bypassing your whole security system.

Remember this:

Users can manipulate all sent data. Cookies, $_GET and $_POST data can all be manipulated by the user.
All data you send your client-side application can be inspected by the user. See Firebug for a good example. If you send some_hash to the client, the user has ways to find that out.
You may, however, protect your user against third parties.
Code that is executed in the client-side can be manipulated. HTML, CSS and JavaScript can all be edited.
Fortunately, those edits are local. Meaning that an user can change the JavaScript that's executed on his computer, but fortunately not the JavaScript that's executed in someone else's computer - provided the server is well implemented.

Ajax code is typically executed client-side (I'm going to bet it's also true in your case), so all your JavaScript can be modified. Your "receive token" function can just be modified to include an alert function.

function receive_token() {
    var key = ajax_request_token();
    //Code injected by the user
    alert(key);
    //End code injected by the user
    return key;
}

The user could then proceed to use your key token to pretend he's the application.

Not sure what you mean by "the file being included within another one".


How many points are we talking about that makes performance slow?  If its a crazy amount, you could use a Range Partitioner and a Parallel.For.  But I would suggest outputting as a List<Point> rather than an array so that each parallel thread can merge the subset of points.  I'd rather not get into details about in this answer though.

One alternative is to check X or Y against the tolerance once:

private Point[] FindNearbyPoints(Point[] points, Point initialPoint, int tolerance)
{
    tolerance = Math.Abs(tolerance);
    return points.Select(p => p)
                 .Where(p => (Math.Abs(p.X - initialPoint.X) <= tolerance) &&
                             (Math.Abs(p.Y - initialPoint.Y) <= tolerance))
                 .ToArray();
}

You could try making that an extension method in a public static class, such as:

public static Point[] FindNearbyPoints(this Point[] points, Point initialPoint, int tolerance)
{
    tolerance = Math.Abs(tolerance);
    return points.Select(p => p)
                 .Where(p => (Math.Abs(p.X - initialPoint.X) <= tolerance) &&
                             (Math.Abs(p.Y - initialPoint.Y) <= tolerance))
                 .ToArray();
}

A bigger consideration is whether the return type must be Point[].  You might see some performance boost if you went with IEnumerable<Point>.  In fact the extension method could be more reachable if you changed the input signature a bit too.  Something like:

public static IEnumerable<Point> FindNearbyPoints(this IEnumerable<Point> points, Point initialPoint, int tolerance)
{
    tolerance = Math.Abs(tolerance);
    return points.Select(p => p)
                 .Where(p => (Math.Abs(p.X - initialPoint.X) <= tolerance) &&
                             (Math.Abs(p.Y - initialPoint.Y) <= tolerance));
}

Other than that, your coding style looks fine.  Give these changes a try and see if performance is still an issue.  If it is, I'll try to find time to work up an example using a range partitioner.


for key in graph.keys():
        dist[key] = 1000

Why 1000? There are two values which are easy to defend here: positive infinity (which is the value that an algorithms textbook would use), or half the maximum value of the datatype (to avoid overflow when adding two weights). Even the second one of those requires a comment to justify it.

        prev[key] = ""

Why not just leave it undefined?

        Q.append(key)

What is the purpose of Q? It just seems to duplicate dist.keys().

    #I had to have another distance data structure dst
    # to store all the distance covered

Why? It's not used anywhere that I can see.

        # Here I get the minimum distance
        u = min(dist, key = dist.get)

Hopefully you can see that this is quite inefficient, and that's the motivation for using more sophisticated data structures.

            #I also want to improvise this condition block
            #It is because of 't': {'': None}
            if graph[u][v] is None:
                continue

Why is it not just 't': {}?


Script to encrypt a file and add it to IPFS(ipfs.io)

Some things:

You'll want to wrap the call to main in if __name__ == '__main__': to be able to import from your package in other packages.
For maximum flexibility use argparse to pass the file name rather than making an interactive script.
Format strings are generally preferred over string concatenation, so fileToEncrypt + ".gpg" becomes "{}.gpg".format(fileToEncrypt).
Run the code through pycodestyle to get a bunch of tips on writing idiomatic Python. For example, Python appropriately uses snake_case for variable, function and method names.
Function in a function name is completely redundant. Use a highlighting editor or (ideally) an IDE to trivially distinguish between functions and variables.
Magic strings like encryption parameters and the IPFS address should be moved to either a configuration file, a command line parameter (possibly with a default) or a constant at the top of the file.
The shebang line should be #!/usr/bin/env python3 for maximum portability - it basically means that the first python3 executable on the PATH will be used.
You have a race condition in delEncryptedFile. Rather than checking for a file and then deleting it you should just try to delete it and then let the exception bubble up to the user if it fails. If at some point you want a nicer formatted error message that should be generated in main, not further down, so that, again, other packages can use your package easily.


Welcome to codereview. Here are my suggestions:
Functional decomposition and Naming
The trickiest part of programming is to decouple your complex problem into smaller easier (sub)problems. It is easier to tackle small and focused problems than one large and vague. So, my first suggestion would be to try to find small and independent pieces of functionalities.
In your case here is one way to decompose:

Ask for a movie and store it
Ask for continuation
Print out the already gathered movies

You can directly map these to functions:
void EnterANewMovieAndStoreIt()
bool WishToContinue()
void PrintOutMovies()

Then you can compose them like this:

Ask for a movie and store it then
Print out the already gathered movies until
the consumer Answers with yes for continuation
when (s)he Answers with no then Print out already gathered movies

With that in hand your Main function will look like this:
static void Main(string[] args)
{
    do
    {
       EnterANewMovieAndStoreIt();

       PrintOutMovies();

    } while (WishToContinue());

    PrintOutMovies();
}

Store and Retrieve functionalities
Because we have separated storage and retrieval functionalities that's why they can be really small and concise functions:
private static void EnterANewMovieAndStoreIt()
{
    Console.WriteLine();
    Console.WriteLine("Please enter a movie you want to see but have not seen it yet.");
    var movieName = Console.ReadLine();
    ToBeWatchedMovies.Add(movieName);
}

private static void PrintOutMovies()
{
    Console.WriteLine();
    Console.WriteLine("Your haven't seen but to be watched movies:");
    foreach (var movie in ToBeWatchedMovies)
        Console.WriteLine(movie);
}

As you can see they rely on a shared resource called ToBeWatchedMovies. It is defined on a class level like this: static readonly List<string> ToBeWatchedMovies = new List<string>();
Error handling
Your current implementation does not handle that case when the user enters something different then Y or N. It is a good practice to assume that a userInput can be anything and handle that accordingly. In this example we can easily ask them nicely to try to provide the answer again.
So, the WishToContinue would look like this:
private static bool WishToContinue()
{
    while(true)
    {
        Console.WriteLine();
        Console.WriteLine("Do you want to enter another movie? Y/N?");
        var userInput = Console.ReadLine();

        if (string.Equals(userInput, AnswerYes, StringComparison.OrdinalIgnoreCase))
            return true;

        if (string.Equals(userInput, AnswerNo, StringComparison.OrdinalIgnoreCase))
            return false;

        Console.WriteLine($"Please provide either '{AnswerYes}' or '{AnswerNo}' ");
    }
}

Obviously this code could be further optimized but my main point here is that you should try to handle the wrong inputs as well.

Let's put everything together:
class Program
{
    static readonly List<string> ToBeWatchedMovies = new List<string>();
    const string AnswerYes = "y", AnswerNo = "n";
    static void Main(string[] args)
    {
        do
        {
           EnterANewMovieAndStoreIt();

           PrintOutMovies();

        } while (WishToContinue());

        PrintOutMovies();
    }

    private static void EnterANewMovieAndStoreIt()
    {
        Console.WriteLine();
        Console.WriteLine("Please enter a movie you want to see but have not seen it yet.");
        var movieName = Console.ReadLine();
        ToBeWatchedMovies.Add(movieName);
    }

    private static void PrintOutMovies()
    {
        Console.WriteLine();
        Console.WriteLine("Your movies in your list are:");
        foreach (var movie in ToBeWatchedMovies)
            Console.WriteLine(movie);
    }

    private static bool WishToContinue()
    {
        while(true)
        {
            Console.WriteLine();
            Console.WriteLine("Do you want to enter another movie? Y/N?");
            var userInput = Console.ReadLine();

            if (string.Equals(userInput, AnswerYes, StringComparison.OrdinalIgnoreCase))
                return true;

            if (string.Equals(userInput, AnswerNo, StringComparison.OrdinalIgnoreCase))
                return false;

            Console.WriteLine($"Please provide either '{AnswerYes}' or '{AnswerNo}' ");
        }
    }
}

I hope this helped you a bit.


Takes function and throws exception if passed function doesn't throw an exception

It kind of boils down to coding style, but this is how I'd refactor your code.

I like my assertions to clearly state they are; rename throws() to assertThrows().
I like guard clauses rather than "unneccessary" else statements.
If a function ever throws an exception with an undefined message, your assertion would fail.
I like a specific format of assert failures: expected xxx but got yyy.

Code:

function assertThrows(testFunction, expectedMessage) {

    var actual = catchExceptionFrom(testFunction);

    if (actual === undefined)
        throw new Error("Function did not throw an exception.");

    if (actual.message !== expectedMessage)
        throw new Error("Expected exception '" + expectedMessage + "' but got '" + actual.message + "'");
};

function catchExceptionFrom(fn) {
    try {
        fn();
    }
    catch (exception) {
        return exception;
    }
};


You require pry, and you don't seem to use it.  Perhaps it is being used for troubleshooting, and the binding.pry or other code, has been removed.  In that case it may be more appropriate to simply use the -rpry option as in ruby -rpry file.rb.  Then you don't have to remember to remove that line, just the troubleshooting line.  (Or even better, set up a system that lets you leave things in but turn them off and on from an option in the system call.  Perhaps -w or -v flags.  Perhaps an environment variable.  A line in with this in mind may look like this:  binding.pry if $VERBOSE  And a require 'pry' if $VERBOSE)

Looking at your loop do tells me that you have an infinite loop.  But you have a well defined exit strategy, there is no need for an infinite loop.  Using something like until @board.winner? will run the block at least once, and will stop when your method returns true/truthy value.  You also call 'play' from inside the loop inside of play, but it is already going to start from the beginning of the loop.

If you had folders bin/, lib/, I would expect some of the code in your tic-tac-toe.rb file to be in maybe bin/tic-tac-toe. The start equivalent for sure.  This will allow you to use the lib/tic-tac-toe.rb file in a way that someone that requires that library would expect.  Right now, you are unable to require that library file without starting the game.

The interface of using words like top left seems clumsy and error prone, even if it is nice.  Creating a numbered or lettered menu or presenting the grid with numbers or letters could make play easier, less typing to do, less error prone.  Perhaps a lettered 'x, y' grid.  Presenting that grid would also document the game play, and make initial play more straight forward.

Your "choose_character" method does two things, it prompts and processes the choice.  The @player_character and @computer_character is repetitive, confusing in a way.  Simply having @player and @computer is probably clear enough.  @player.character might be better, though I think we consider that letter a 'marker', as the player mark may be 'X' and the AI mark may be 'O'.

Looking at cell.rb you could be using the new named arguments in Ruby 2.0.

In the Board file you can likely use the all? Enumerable method, if an array has all? the markers that match the current players marker, then that player is the winner.


Detecting cycles in a directed graph without using mutable sets of nodes

An easy way to detect a cycle is through the implementation of a disjoint set structure, sometimes called a Union-Find structure.

You start with a source node and attempt to add a node to that set.  If your   Find() call for the source node and the other node returns the same root node, then a cycle world result if the nodes are unioned.

UPDATE:

You could implement a topological sort, arranging the nodes with edges going from left to right. A topological sort can only be completed successfully if and only if the graph is a Directed Acyclic Graph. So, if the algorithm detects any cycles, it will stop.

The runtime is O(|V| + |E|), which is better than DFS, in the case that repetition occurs during traversal.

Topological Sorting


Some suggestions:

black can format your code to be more idiomatic.
flake8 can check your code for remaining non-idiomatic code.
mypy can enforce typing to make it more obvious what the code is meant to do.
Names like a, r, d and dfs are unhelpful. Naming is a hard skill to learn, but is enormously helpful in making code more readable and therefore maintainable.
if not '.' in x: etc looks like it might be a good candidate for a separate function - it doesnt't take too many inputs, returns only one thing (dfs), and is short.
It looks like you are doing a lot of conversions: dataFrame[tableName].values.tolist(), list(…), dict(). I'm not familiar with Pandas, but I expect you can speed things up significantly by not converting values.


Handling HTTP status messages and multiple returns

If you're going to drop in a comment block for function documentation, fill it out. Otherwise, delete it.
Generally you shouldn't import on the inside of a function. import at the top of a file.
Your constructed URL shouldn't use a series of +. You should be using the % formatting operator or str.format(). This will also avoid calling str(0).
None of your elses are necessary. You return before each of them, so you can simply continue writing the rest of the function afterward.
If I were you, I would simply return s_details['data']. Decomposing the payload into a series of lists isn't really useful, and if it is indeed useful for your application, it should be done in a separate function.
Returning an error string to indicate an error is a bad idea. You should raise an exception instead.


Can I return an object on which a function is applied?

Looks good to me, if you always want those 3 params and never want to send anything else.

Otherwise, you could improve it by receiving the non-mandatory params in an options object:

"use strict";
var initiate_shop = function(container_id, options) {
    var default_settings = {
            containerID     : container_id,
            first           : false,
            perPage         : 5,
            '...'           : '...',
            callback        : function(pages){
                current_page = pages.current;
                total_pages = pages.count;
            }
        },
        settings = $.extend(default_settings, options);
    return $(shop_navigation).jPages(settings);
};
// ...
initiate_shop('outputCell', {
    perPage:     10,
    first:       true
});

Related (hows 3 ways to assign default values to parameters):
https://stackoverflow.com/a/3672142/148412


First of all: Extract your classes into extra files and require_once them as necessary. I found the Java style of having one class per file a very good one.

Second: Learn and start to use PHPDoc to document your code.

//Blueprint

That's not a helpful comment...only write a comment if it is helpful.

// properties of human
private $gender;
private $name;
private $age;
private $talk;

Such structural comments are unnecessary if your class is correctly structured and indented.

$this->gender   = $gender;
$this->name     = $name;
$this->age      = $age;
$this->talk     = $talk;

Personally I don't like this kind of intending. It can make code easier to read, but in a pure "assign all parameters to all fields" constructors it seems kinda unnecessary.

class female extends Human{

Is it a typo that female is lower case?

private $bum;

If it holds the size of the bum, then it should be called $bumSize. The same goes for $feet.

$malePerson     = new male('male', 'John Doe', '32', 'clear', 'beard', 'adams apple in my throat');

Apart from the unnecessary intending, this is a good example stringly typed programming. You're using a string for everything even though the age should be an integer.

Let's have a look at the basic variables a Human consists of:

$gender Should an enumeration with two values, Male and Female.
$name Names are strings, so it's okay.
$age Is an integer and should therefor be an integer.
$talk Is also a string.

And let's go forth with the Male:

$facialHair Should be an enum, or an integer to indicate strength.
$adamsApple Not sure what this is.

Also forget what I just said about $gender, Human should be an abstract class and getGender() should be an abstract method that is implemented by the next class.

<html>
     <?php Some code with echo... ?>
</html>

That's not a well-formed HTML document.

<html>
    <head>
        <title>Title of your page</title>
    </head>
    <body>
        Content goes here.
    </body>
</html>

Ideally you would perform initializations before the html tag and then just use everything prepared in the body.


Format all identifiers in order to avoid a syntax error. Assuming it's mysql, use backticks for the purpose:

$key = "`".implode("`,`",array_keys($properties))."`";

You are going to repeat the second half of the code in the every crud method.  To avoid that, add a query() method to your db class

public function query($sql, $params = []) {
    $stmt = self::getConnection()->conn->prepare($sql);
    $stmt->execute($params);
    return $stmt;
}

so you'll be able to make your crud methods much more concise.

public function create(){
    $properties = $this->properties();

    $key = "`".implode("`,`",array_keys($properties))."`";
    $value = implode(",:",array_keys($properties));

    $sql = "INSERT INTO `".self::$table."` (" . $key . ") ";
    $sql.= "VALUES (:" . $value . ")";
    db::query($sql, $properties);
    $this->id = db::the_insert_id();
}

There is no point in returning true or false from such a method, the only reason for it to return false is a database error and such an error should be thrown in the form of Exception and handled elsewhere, making all this true false stuff rather useless.
Your current setup is following Active Record pattern, making a data object to contain all the database interaction related code. Consider switching to Data Mapper pattern where you have two classes - your data class and a mapper that is responsible for all the database interactions.


I'll try to keep things brief, for a change:

nameField seems reasonable enough. Although I do have some suggestions (see below).
The numberField function is another matter. If you want to check for a valid phone number, there are a couple of things to consider:

User tend to enter a phone number in a human-readable format: 213-1234-4454 or 123/1234.4567
International phone numbers can start with Either a double 0, or a plus sign. both of which are valid: (0012) 123/1234-5678 is a possible value you'd have to process, just as +12 123/1234-5678

Bottom line: First trim the non-numeric chars, then check if the input is valid, I'd say:

function sanitizeAndValidate($phoneNr)
{
    //replace all non-numeric chars, after replacing a single + char with 00
    $phone = preg_replace('/[^\d]/', '', str_replace('+', '00', $phone, 1));
    $len = strlen($phone);
    //perhaps changing these constants to argumenst might be preferable
    if (is_numeric($phone) && $len >= MIN_PHONE_LEN && $len <= MAX_PHONE_LEN)
        throw new \InvalidArgumentException(
            sprintf(
                '%s is an invalid phone number (%s after sanitation)',
                $phoneNr,
                $phone
            )
        );
    return $phone;

}

Pas the raw phone number to this function, if the phone number is valid, you'll get a santized version back. If the phone number is invalid, catch the exception and present the user with an error message.

The nameField function is OK, but it's a bit redundant. If you only use it in one place, I'd avoid the overhead of a function-call, and simply inline the check, by replacing if (nameField($_POST['name'])) with this:

if (preg_match('/([%_\$#*\'"\()]+)/', $_POST['name']))

You might have noticed that I don't escape all of the chars, simply because there's no reason to escape them all. I've also added _ to the restricted chars. Simply because everybody knows that % is a MySQL wildcard, but not everybody seems to be aware that _ is, too.

Regular expressions can impact preformance, which is, I suspect, why you're asking for ways to improve your code. An alternative to preg_match here could be to have an array of prohibited chars, and use str_replace:

$notAllowed = array('%', '_', '$', '#', ...);//and so on
if (str_replace($notAllowed, '', $_POST['name']) !== $_POST['name'])
{//values are not the same, a forbidden char was replaced
    //name contains prohibited char
}

I'm not so sure if that would be faster then a preg_match, though, and besides: premature optimization is the root of all evil.

Last comment:
Please, try to adhere to the coding standards as much as possible. You seem to have some formatting issues


1. DRY (Don't Repeat Yourself)

You should define containers for your questions and answers. This way you can avoid having to repeat the whole logic for every question.

As a first step, I would advise to put all your question texts, answer texts, choice texts and correct answer texts in lists.

Then you can write a function that iterates over these lists (at the same time) and does the actual game. For this you can use zip.

questions = ["What is 1 + 1",
             "Who is the 45th president of the United States?",
             "True or False... The Toronto Maple Leafs have won 13 Stanley   Cups?",
             "What was the last year the Toronto Maple Leafs won the Stanley   Cup?",
             "True or False... The current Prime Minister of Canada is Pierre Elliot Tredeau?"]
answer_choices = ["a)1\nb)2\nc)3\nd)4\n:",
                  "a)Barack Obama\nb)Hillary Clinton\nc)Donald Trump\nd)Tom Brady\n:",
                  ":",
                  "a)1967\nb)1955\nc)1987\nd)1994\n:",
                  ":"]
correct_choices = [{"b", "2"},
                   {"c", "donald trump"},
                   {"true", "t"},
                   {"a", "1967"},
                   {"false", "f"}]
answers = ["1 + 1 is 2",
           "The 45th president is Donald Trump",
           "",
           "The last time the Toronto Maple Leafs won the Stanley Cup was 1967",
           "The current Prime Minster of Canada is Justin Tredeau"]

def quiz():
    score = 0
    for question, choices, correct_choice, answer in zip(questions, answer_choices, correct_choices, answers):
        print(question)
        user_answer = input(choices).lower()
        if user_answer in correct_choice:
            print("Correct")
            score += 1
        else:
            print("Incorrect", answer)
    print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%")

if __name__ == "__main__":
    quiz()

2. OOP (Object-Oriented Programming)

A second step could be trying to encapsulate this whole object of a question into an actual Python object. That is, a question is an object that has a question(text), an answer, answer choices and correct answer choices.

You could define a class like this:

class Question:
    def __init__(self, question, answer, choices, correct):
        self.question = question
        self.answer = answer
        self.choices = choices
        self.correct = correct

But this class would be nothing but a data storage for these strings. Whenever you have this, you can use a collections.namedtuple.

>>> from collections import namedtuple
>>> Question = namedtuple("Question", "question answer choices correct")
>>> q = Question("What is 1 + 1", "1 + 1 is 2", "a)1\nb)2\nc)3\nd)4\n:", {"b", "2"})
>>> q.question
'What is 1 + 1'
>>> q[3]
{'b', '2'}

So a Question is just a tuple with nice names, so that afterwards q.question = q[0] = 'What is 1 + 1', and so on.

from collections import namedtuple
Question = namedtuple("Question", "question answer choices correct")

questions = [Question("What is 1 + 1", "1 + 1 is 2", "a)1\nb)2\nc)3\nd)4\n:", {"b", "2"}),
             ...]

def quiz():
    score = 0
    for question in questions:
        print(question.question)
        user_answer = input(question.choices).lower()
        if user_answer in question.correct:
            print("Correct")
            score += 1
        else:
            print("Incorrect", question.answer)
    print(score, "out of", len(questions), "that is",
          float(score / len(questions)) * 100, "%")

if __name__ == "__main__":
    quiz()

3. The last push

Last, but not least, you could make enumerating the choices automatic, using string.ascii_lowercase (which is simply the lowercase alphabet) and str.joining it with newlines and the ")" used to separate a letter from the choice associated with that letter.

You could also pass a list of Questions directly to the function, allowing making different quizzes (by choosing randomly 5 questions out of a pool of 100 question, for example).

Finally, you could use str.format to make the print of the final score a bit nicer.

import string
from collections import namedtuple
Question = namedtuple("Question", "question answer choices correct")

questions = [Question("What is 1 + 1", "1 + 1 is 2",
                      ["1", "2", "3", "4"], {"b", "2"}), ...]

def quiz(questions):
    score = 0
    for question in questions:
        print(question.question)
        for line in zip(string.ascii_lowercase, question.choices):
            print(") ".join(line))
        user_answer = input().lower()
        if user_answer in question.correct:
            print("Correct")
            score += 1
        else:
            print("Incorrect", question.answer)
    print("{} out of {} that is {} %".format(score, len(questions), score / len(questions) * 100))

if __name__ == "__main__":
    # Use all questions but the first
    quiz(questions[1:])


Chaining Internal Class Methods in Python

Class methods calling each other is perfectly acceptable in general, but this should be done toward the end of making the code easier to follow by encapsulating complexity.  Two things in your example potentially work against that goal:

All of the methods and attributes are public.  (In Python you denote a "private" member by starting its name with _.)
Data is passed between the methods via instance attributes.

This means that someone reviewing this code for possible bugs needs to assume that a caller might call any of these methods while the object is in any arbitrary state -- that's a lot of combinations to consider!

If the only intended usage of this class is the one you've given (create a single instance, call create_repository exactly once), then there isn't much benefit to making it a class with state (since that state is never meant to be reused beyond that one function call).  The other typical way of grouping related functions is to simply define them locally within a larger function:

def create_repository(project_name: str, repo_name: str) -> None:
    """Creates a new repo under the specified project"""

    with open("./repo_request_body.json", "r") as file:
        data = json.load(file)

    def get_project_id() -> str:
        """Returns the Azure DevOps project ID for a project name"""
        _request_object = make_request(
            "_apis/projects/",
            project_name,
            "?api-version=5.1-preview.1",
            request_method = "get"
        )
        return _request_object.get("id")

    def update_project_id() -> None:
        """Updates JSON dictionary with new ID"""
        new_id = get_project_id()
        data["project"]["id"] = new_id

    def update_repo_name() -> None:
        """Updates JSON dictionary with new repo name"""
        data["name"] = repo_name

    json_content_type = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic XXXXXXXXXXXXXXXX'
        }

    update_project_id()
    update_repo_name()
    make_request(
        project_name,
        "/_apis/git/repositories",
        "?api-version=5.1-preview.1",
        request_method = "post",
        data = json.dumps(data),
        headers = json_content_type
    )

create_repository("project_name", "repo_name")

But given that each of these functions is only called once, is there any value to actually giving them individual names and making the reader jump around between them?  I'd probably just write this as one function where everything is written in exactly the order it happens in:

def create_repository(project_name: str, repo_name: str) -> None:
    """Creates a new repo under the specified project"""
    # Load the repo request data from disk.
    with open("./repo_request_body.json", "r") as file:
        data = json.load(file)

    # Get the Azure DevOps project ID for a project name
    _request_object = make_request(
        "_apis/projects/",
        project_name,
        "?api-version=5.1-preview.1",
        request_method="get"
    )
    new_id = _request_object.get("id")

    # Update JSON dictionary with new ID
    data["project"]["id"] = new_id

    # Update JSON dictionary with new repo name
    data["name"] = repo_name

    # Make the server request.
    json_content_type = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic XXXXXXXXXXXXXXXX'
    }
    make_request(
        project_name,
        "/_apis/git/repositories",
        "?api-version=5.1-preview.1",
        request_method="post",
        data=json.dumps(data),
        headers=json_content_type
    )

create_repository("project_name", "repo_name")

IMO this is a lot easier to follow, in that dependencies between the different blocks of code are very obvious and I can read it from top to bottom and easily keep track of what's happening when.

Taking it one step further, I'd eliminate the named variables that only get used once, which shortens the new_id part of the code (again, less for the reader to keep track of if they can see at a glance that function calls chain together to produce a single result, rather than having to try to figure out if a given value is going to be used again later):

def create_repository(project_name: str, repo_name: str) -> None:
    """Creates a new repo under the specified project"""
    # Load the repo request data from disk.
    with open("./repo_request_body.json", "r") as file:
        data = json.load(file)

    # Update JSON dictionary with new ID from server API
    data["project"]["id"] = make_request(
        "_apis/projects/",
        project_name,
        "?api-version=5.1-preview.1",
        request_method="get"
    ).get("id")

    # Update JSON dictionary with new repo name
    data["name"] = repo_name

    # Make the server request to create the repo.
    make_request(
        project_name,
        "/_apis/git/repositories",
        "?api-version=5.1-preview.1",
        request_method="post",
        data=json.dumps(data),
        headers={
            'Content-Type': 'application/json',
            'Authorization': 'Basic XXXXXXXXXXXXXXXX',
        }
    )


You could use a bit less comments, most of the code is self-explnatory
You could also use a bit more split of the code into functions, e.g. a function to create a default file
This is a full script, so it's nice to have the if __name__ == "__main__": condition to call the main function
If you use the """ to have a multi-line string, whatever you put will be there, including newlines and tabs. You probably want to split the string by using " on separate lines (see later).
Also, if you concatenate that way, you're losing the \n, it's better to use format

Revised code:

#madlibs.py : ABS Chapter 8 Project
#Make mad libs using madlibtemplate.txt file that will prompt user for parts of speech
#Will return new file with replacements called madlib.txt

import re, os

def generate_default_template():
    with open('madlibtemplate.txt', 'w+') as template:
        template.write("The ADJECTIVE girl walked to the NOUN and then VERB. "
                        "A nearby NOUN was upset by this.")

def capitalize_sentences(text):
    sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text)
    capitalized_sentences = [sentence.capitalize() for sentence in sentences]
    return ''.join(capitalized_sentences)

def main():
    print("Let's play MadLibs!\nNote: Your current working directory is {0}".format(os.getcwd()))
    if not os.path.exists('madlibtemplate.txt'):
        print("No template file found. Using default 'madlibtemplate.txt'")
        generate_default_template()
    else:
        print("Using your 'madlibtemplate.txt' file:")

    with open('madlibtemplate.txt', 'r') as template:
        template.seek(0)
        text = (template.read()).lower()

    wordregex = re.compile(r'\w+|\s|\S')
    words = re.findall(wordregex, text)

    for i, word in enumerate(words):
        if word in {'adjective', 'noun', 'adverb', 'verb', 'interjection'}:
            print('Enter a(n) %s ' % word)
            words[i] = input()

    madlib_text_unformatted = ''.join(words)
    madlib_text = capitalize_sentences(madlib_text_unformatted)

    print('Here we go... \n')
    print(madlib_text)

    with open('madlib.txt', 'w') as madlib:
        madlib.write(madlib_text)

    print("\nThis has been saved to file 'madlib.txt'")

if __name__ == "__main__":
    main()

If you want to capitalize a word, there's the... well, capitalize function for that.
When opening files it's nice to use the with keyword, so they'll be closed automatically.
You don't need to do a loop when checking the parts of speech, just use the in operator.


Use classes
You should consider making animals a class, since you intend to make many of them that all have the same types of characteristics.  This is exactly what classes are good for.  I've taken the liberty of creating a characteristics dictionary for easy characteristic assignment using the data read from files
Don't repeat yourself
You do most things 5 times in a row (one for each characteristic).  You can avoid this in most situations.  For reading data, you can stuff each set of characteristics into one element of a dictionary.  For assigning characteristics, you can randomly select one item from each element of that dictionary.
Here's a crack at your code, revised:
import random

documents = [
    "ani_nom.txt",
    "ani_adj.txt",
    "ani_ori.txt",
    "ani_cor.txt",
    "ani_cou.txt"
    ]

data = {}

for document in documents:
    try:
        data.update({document.split(".")[0]: [line.strip() for line in open(document)]})
    finally:
        close(document)

class Animal(object):
    def __init__(self):
        self.characteristics = dict(
            ani_nom=None,
            ani_adj=None,
            ani_ori=None,
            ani_cor=None,
            ani_cou=None
        )

    def assign_all_characteristics(self):
        for characteristic in self.characteristics:
            self.characteristics[characteristic] = random.choice(data[characteristic])

    def print_random_characteristics(self):
        num_to_print = random.randint(1, 5)
        characteristics_to_print = list(self.characteristics.values())
        print "\n".join(characteristics_to_print[:num_to_print])

number_of_animals = 120
for _ in range(number_of_animals):
    animal = Animal()
    animal.assign_all_characteristics()
    animal.print_random_characteristics()


Here are a few suggestions...

You could DRY up your code in add_me by returning the string and then making the API call in one place. Also, you should call Repo.insert/1 with a changeset. This will ensure your validation is checked. You can also remove the nesting with the with special form. Its a really handy function that I recommend you learn if haven't already.

  def add_me(msg) do
    message =
      with nil <- Repo.get_by(Rewards, user: msg.author.id),
           changeset <- Rewards.changeset(%Rewards{}, %{user: msg.author.id}),
           {:ok, _} <- Repo.insert(changeset) do
        ":white_check_mark:"
      else
        {:error, _} -> ":x:"
        _ -> "You're already registered"
      end
    Api.create_message(msg.channel_id, message)
  end

You can reduce some of the one-time variables in thanks like this:

  def thanks(msg) do
    Enum.map msg.mentions, fn user ->
      repo_user = Repo.get_by(Rewards, user: user.id)

      repo_user
      |> Ecto.Changeset.change(quantity: repo_user.points + 1)
      |> Repo.update!
      Api.create_message(msg.channel_id, "#{msg.author.username} gave a :cookie: to #{user.username}")
    end
  end

Finally, it appears that you don't care about the type of error on the Repo.insert. Keep in mind that the changeset returned with {:error, changeset} contains the validation errors.

NOTE:

I see 4 common style / issues with programmers learning Elixir.

error Calling a side affect free function without using the return value. Data in Elixir is immutable, so you need need to either capture the results of a function, call it as the last statement so it returned to the caller, or create a side effect in the function (send an event, write to database, file, etc)
warning Use a variable outside the scope of the block it was set in. In other words, don't set a variable inside an if, case, or cond, then use it later
style Use lots of single use variables. This is typically a sign that the pipe |> operator may clean up the code.
style Use logs of conditional statements where multi-clause function heads with pattern matching and guards may make the code cleaner, with less nesting


Counting block combinations I: Project Euler 114

Firstly, I have to admit to not doing too much in the way of thinking up better variable names; in part because the algorithm was a little hard to follow without solving the problem myself.

The spacing is all over the place: I'm not a PEP 8 purist but you have -= with a space before on one line, with a space after on another, and neither on a third. I fixed all the things my IDE complained about, including a redundant import of itertools.

   LIST = list(partitionfunc(n,k))
   for b in LIST:
      ...

Writing LIST to not shadow the builtin list is evil but it's also unecessary: you don't need to listify the generator to iterate over it. That becomes:

   for b in partition(n, k):
      ...

I changed the partition from tuples to lists, since I thought that was more natural in Python for an homogenous sequence of arbitrary length.

There is a loop in valid_partitions:

count = 0 #Max. number of tiles that can be placed on a row.
while True:
    count += 1
    total -=3
    if total <= 3:
        break
    total-=1

I replaced this with:

max_tiles = (p + 1) // 4

I made valid_partitions a generator, and lost some temporary variables like 'data'. I also changed the range() to start from 1 as the comment suggests.

There is a little logic in the function final that I felt was doing too much, so moved it into calculate_ways()

for q in data:
    m = len(q)
    remain = w - sum(q) - m + 1
    n = 2*m -1 + remain
    total_variations+= calculate_ways(m,n)*count_permutations(q)

final() became:

def total_variations(w):
    return sum(calculate_ways(q, w) * count_permutations(q) for q in valid_partitions(w)) + 1

Mayble the one liner is a little too dense, and one should keep the for loop.

calculate_ways() is now a bit opaque and could probably use tidying but at least it's all in one place now.

I added MIN_SIZE = 3. It's probably overkill to pass 3 around as a parameter but probably worth flagging as a magic number.

from scipy import special
import time

MIN_SIZE = 3

def partition(n, k, min=MIN_SIZE):
    """n is the integer to partition, k is the
    length of partitions, min is the min partition element size"""
    if k == 1:
        if n >= min:
            yield [n]
        return 0
    for i in range(min, n+1):
        for result in partition(n - i, k - 1, i):
            yield [i] + result

def valid_partitions(p):
    """Find all the valid partitions with length [1,max_tiles] that can be placed on the row with length p"""
    max_tiles = (p + 1) // 4
    for k in range(1, max_tiles+1):
        min_part = k * MIN_SIZE
        for n in range(min_part, p+1):
            for b in partition(n, k):
                if sum(b) + (len(b)-1) <= p:
                    yield b

def count_permutations(array):
    """Counts how many possible permutations are there for the particular partition"""
    get_unique_elements = set(array)
    lengths = [array.count(x) for x in get_unique_elements]
    total_length = len(array)
    answer = 1
    for b in lengths:
        answer *= special.comb(total_length, b, exact=True)
        total_length -= b
    return answer

def calculate_ways(q, w):
    m = len(q)
    remain = w - sum(q) - m + 1
    n = 2*m - 1 + remain
    return special.comb(n - m + 1, n - 2*m + 1, exact=True)

def total_variations(w):
    return sum(calculate_ways(q, w) * count_permutations(q)

if __name__ == '__main__':
    start = time.time()
    print('Answer: {}'.format(total_variations(50)))
    print(time.time()-start)

As always with Project Euler, there may be some deep mathematical insight that can optimise the algorithm. And there still are a lot of single letter variables; it's a start, though.


Generate random characters from ranges 0–9 and a–Z

Small Bias
First a nit pick, Math.random() generates a number from 0 to < 1. It will never generate 1. Thus to get a statistical odds of 1/2 you must test either Math.random() < 0.5 or Math.random() >= 0.5. Testing Math.random() > 0.5 ? char : char.toUpperCase() will give a very (VERY) small bias in favor of upper case characters.
Dramatic Bias
Also there is a very strong bias towards numerals in your function with a 0-9 being 2 times more likely than a-z or A-Z
The following snippet counts the occurrence of each character generated by your function and plots them (normalized) on a graph.
I animated it slowly for dramatic effect.

canvas.width = innerWidth - 10;
const ctx = canvas.getContext("2d");
const w = canvas.width;
const h = canvas.height;
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var testCount = 2;
const val = new Array(chars.length)
val.fill(0);
const func = randString;
function randString() {
    return [
        ...Math.random()
            .toString(36)
            .substr(2, 5),
    ].map(element => (Math.random() > 0.5 ? element : element.toUpperCase())).join('');
}
function testRandomness() {
    var i = testCount;
    while (i--) {
        const a = func();
        for (const c of a) {  val[chars.indexOf(c)] += 1 }
    }

    const max = Math.max(...val);
    ctx.clearRect(0, 0, w, h);
    const ww = w / val.length;
    i = val.length;
    ctx.fillStyle = "blue";
    while (i--) {
        if (chars[i] === "z") { ctx.fillStyle = "green" }
        if (chars[i] === "9") { ctx.fillStyle = "red" }
        const v = val[i] / max * h;
        ctx.fillRect(i * ww, h - v, ww- 2, v)
    }
    setTimeout(testRandomness, 1000 / 30);
}
testRandomness();
canvas.addEventListener("click",()=> (testCount = 10000,d.textContent = "Sample rate ~300,000per sec") ,{once:true});
body { font-family: arial black; }
canvas {
  padding: 0px;
}
#a { color:red; }
#b { color:green; }
#c { color:blue; }
#d { font-family: arial; }
<canvas id="canvas"></canvas>
Red 0-9 Green a-z Blue A-Z Click graph to increase sample rate to 10000

Click the graph to increase the tests per sample to 10000 per 30th second (approx) and you will see that apart from the numeral bias the graph quickly becomes very flat showing no other major bias (the uppercase bias is way to small to see)
The reason for the bias is that you split the characters a-z in two when you convert half to uppercase.
Also note as pointed out in the other answer, there is a small chance that the returned string is less than 5 characters long.
Performance
In terms of performance using a lookup table is around 3 times faster ie calculate 1.5million strings in the time yours calculates 0.5million.
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function randString(size = 5) {
    var str = "";
    while (size--) { str += chars[Math.random() * chars.length | 0] }
    return str;
}

As a function it is much more flexible, and can easily be adapted to include extra characters, or reduced character sets.
If all that matters is performance you can get around 10% faster by avoiding some of the readability introduce overhead with
function randString() {
    return  chars[Math.random() * 62 | 0] +
        chars[Math.random() * 62 | 0] +
        chars[Math.random() * 62 | 0] +
        chars[Math.random() * 62 | 0] +
        chars[Math.random() * 62 | 0];
}

Or (on chrome) the following is on average 2% faster than the one above but only after it has been run many time so that the optimizer knows what it does. If run only a few time it is slower than above
function randString3() {
    return  `${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}${chars[Math.random()*62|0]}`;
}


Looks ok in its basic form, but here are some points to consider:

You may want to consider using at least Long, as factorials tend to get large quickly.
Whenever you write a function that you believe to be tail-recursive, then do add @tailrec (from scala.annotations) to it. This has two major advantages: First, it corrects your thoughts and tells you immediately, if it isn't tail-recursive although you thought so, and second, it tells everyone else and stops them from making a "fix" that causes the function to no longer be tail-recursive. May not be a big deal for such a small one, but in general tail-recursive functions can be more complex and then it's much harder to see at a glance that the function is tail-recursive if you do not annotate it as such.
Naming convention: The semantics of what you labelled offset is not really an offset as we would usually think about it. If you say offset most people have a certain meaning in mind that they associate with this term. The traditional meaning that resembles your semantics would be given by the term accumulator. Especially, when writing recursive functions we run into this intermediate-result-variable-thing very often and you will almost always see it referred to as an accumulator, so for clarity's sake you should just name the variable as such.


Creating an array of objects for dictionaries

var DrugArray:[Drug] = []
var drugs:[String] = []

for i in array {
    if contains(drugs, i["drugName"]! as String) {
        continue
    } else {
        drugs.append(i["drugName"]!)
        DrugArray.append(Drug(name: i["drugName"]!))
    }
}

for a in DrugArray {
    for i in array {
        if i["drugName"]! == a.name {
            a.dosage.append(dose: i["dose"]!, time: i["time"]!)
        }
    }
}

So, now that we've cleaned up the code and made it more readable, let's talk about some refactoring we can do.

The first thing I notice is that your nested loop at the bottom is entirely unnecessary.  We can do all of that logic in the top loop.

We're also doing a lot of forced unwrapped... which you really don't want to do.  All this is going to do is result in a crash in your app eventually.

We're also using single letter variable names which invokes no meaning to the reader.  These loops are short... for now.  If & when the contents of the loop grows (the top loop is already close to being at the point), you'll start to see the value in having meaningful variable names.  It helps you remember exactly what the variable represents.  Better variable names is just one part of making your code self-documenting.

And ultimately, as Mario Zahone's answer points out, what we clearly need is a dictionary rather than an array (and a separate array to keep track of what's already been tracked).

Finally, repeatedly appending to a collection almost always results in poor performance.  If there's not enough space in the collection's current memory location for one more item, the entire collection has to be copied into a new memory location, which is an expensive task.  In a loop with lots of iterations, this is likely to happen multiple times.  So, when we can guess at a good minimum size, we want to go ahead and make sure our collection is allocated in a large enough memory space.

So, taking all of these things into account, the final implementation of our code probably looks something like this:

var drugs = [String:Drug](minimumCapacity: array.count)

for drugDictionary in array {
    if let
        drugName = drugDictionary["drugName"],
        drugDose = drugDictionary["dose"],
        drugTime = drugDictionary["time"] {

        drugs[drugName] = drugs[drugName] ?? Drug(name: drugName)
        drugs[drugName]?.dosage.append(dose: drugDose, time: drugTime)
    }
}

If we really want an array, we can always fetch one from the dictionary:

let drugArray = drugs.values


The tought process to make your code DRY is almost always the same:

Find the commonalities between blocks of code.
Extract these into an iterable structure.
Loop.

Here we can see that everything is the same except the prefix and the value.

The code could be changed to:

Please note that you should always specify the radix argument when using the parseInt function since 10 is not default in every browser.

$('#date').on('change', function() {
    var newVal = $(this).val().split('-'), //renamed new_val to newVal, always stick to one naming convention
        dateParts = {
            year: parseInt(newVal[0], 10),
            month: parseInt(newVal[1], 10),
            day: parseInt(newVal[2], 10)
        };

    $('#anchor').append($.map(dateParts, function (index, key) {
        var name = 'date_' + key;

        return $('<input>', {
            type: 'hidden',
            name: name,
            id: name,
            value: dateParts[key]
        });
    }));
});

EDIT:

Note that with the above logic, you will end up having duplicate inputs with different values if the user changes the value multiple times. You could solve this by removing the previously added inputs before adding the new ones, but you could also simply add the inputs just prior to form submission by listening to the submit event instead.

Also, if you want to avoid sending #date's value, you can disable that input before submitting; disabled inputs aren't sent to the server.

Finally, you could choose to simply submit the form in AJAX using $.ajax (or any of it's shortcut methods such as $.post). That would have the advantage of making your site slighlty more dynamic and you would not have to append inputs to the form since you can use the data option.