Extracting time duration in the session from 30 million rows

A few basic points:
The bool datatype is basically just an int and therefore 1 == True and 0 == False. This makes your two ternaries easier to read, because instead of
purchased=1 if session in buyersession else 0
segmentchange=1 if (segment[maxtime.hour]!=segment[mintime.hour]) else 0

You can just write
purchased = session in buyersession
segmentchange = segment[maxtime.hour] != segment[mintime.hour]

noofnavigations is a bad name. You should at least call it no_of_navigations, to go along with PEP8. But why not just navigations?
While we're here, you might as well comply with PEP8 on the other things as well (mainly, put spaces around all infix operators and equal signs).

If you demote all of your temporary variables (which you only use once anyways) to keys in a dictionary you can make the printing a lot easier:
with open('/tmp/gensim/yoochooseclick_new.dat', 'w') as f1:
    for session in clickersession:
        temp = clicksdat[clicksdat.Sid == session]
        maxtime = dt.datetime.strptime(temp.Timestamp.max(), "%Y-%m-%dT%H:%M:%S.%fZ")
        mintime = dt.datetime.strptime(temp.Timestamp.min(), "%Y-%m-%dT%H:%M:%S.%fZ")
        d = {'purchased': session in buyersession,
             'day': maxtime.day,
             'month': maxtime.month,
             'navigations': len(temp.Timestamp)-1,
             'duration': int((maxtime-mintime).total_seconds()),
             'totalcats': len(temp.itemcategory.unique()),
             'totalitems': len(temp.itemid.unique()),
             'timesegment': segment[maxtime.hour],
             'segmentchange': segment[maxtime.hour] != segment[mintime.hour],
             }
        s = "{purchased}, {day}, {month}, {navigations}, {duration}, {totalcats}, {totalitems}, {timesegment}"
        f1.write(s.format(**d))

Lastly, the building of the words for the different times of day could be written slightly more concise when using a list instead of a dictionary:
segment = ['EM']*24
segment[7:10] = ['M']*3
segment[10:13] = ['A']*3
segment[13:18] = ['E']*5
segment[18:23] = ['N']*5
segment[23] = 'MN'

In the end your code is probably slow, because of all the finding of mins, maxs and lens. This just takes time. Would be good to see a run with a profiler to see at which operation, though.

With four more years of experience, here is how you could make this even faster:
def process(group):
    min_time = group.loc[group["Timestamp"].idxmin()]
    max_time = group.loc[group["Timestamp"].idxmax()]
    diff = max_time["Timestamp"] - min_time["Timestamp"]
    return pd.Series({"purchased": group["Sid"].iloc[0] in buyer_session,
                      "day": max_time["Timestamp"].day,
                      "month": max_time["Timestamp"].month,
                      "navigations": group["Timestamp"].count() - 1,
                      "duration": int(diff.total_seconds()),
                      "totalcats": group["itemcategory"].nunique(),
                      "totalitems": group["itemid"].nunique(),
                      "timesegment": max_time["segment"],
                      "segmentchange": max_time["segment"] != min_time["segment"]})

if __name__ == "__main__":
    buys_data = pd.read_csv(...)
    buyer_session = set(buys_data["Sid"].unique())
    clicks_data = pd.read_csv(...)
    clicks_data["Timestamp"] = pd.to_datetime(clicks_data["Timestamp"],
                                              format="%Y-%m-%dT%H:%M:%S.%fZ")
    clicks_data["segment"] = pd.cut(clicks_data["Timestamp"].dt.hour,
                                    [0, 7, 10, 13, 18, 23, 24],
                                    labels=["EM", "M", "A", "E", "N", "MN"])
    sessions = clicks_data.groupby("Sid", as_index=False).apply(process)
    sessions.to_csv('/tmp/gensim/yoochooseclick_new.dat', index=False)

I used the fact that you can directly get the number of unique items using nunique and that it is easier to group by the session ID than iterate over it using groupby (provided you are actually interested in all session IDs). I also converted to datetime objects right away and assigned the segements using cut. Before, there was a possible bug, because you determined the maximum and minimum date using string comparison. For the datetime format you have, this just happens to also sort correctly by date, but if that format ever changes, your code would break.


One reader / one writer no-memory-allocation lock-free ring-buffer

there is absolutely no thread safety constructs, this means that you'll see a lot of interesting race conditions and memory inconsistencies
just assuming dequeues happen fast enough does not mean they will in production
you return T by value in Obtain(), instead of by reference so you can't actually write into it
Obtain is a bad name, it sounds like it gets the next value like TryGet does
memcpy is a bad idea to use to store the values if there is ever a custom copy constructor and a destructor
that said Obtain->store->Commit can be put into a single Put(T*) member function
eventually curReadNum and curWriteNum will overflow, it's not a real problem here because your length is a power of 2 and they are unsigned


"options" binding with an enum as data source

Your solution works fine and I didn't find a better solution. I've just upgraded it little bit, by automatic fill the options, so it is usable to any Enum class.

Here I found how to enumerate Enum type

export class SelectEditorObject
{
    private options: KnockoutObservableArray<keyValuePair<number, string>>;
    private selection: KnockoutObservable<number>;

    constructor(e: any, value: number)
    {
        var options = SelectEditorObject.getNamesAndValues(e);
        this.selection = ko.observable<number>(value);
        this.options = ko.observableArray<keyValuePair<number, string>>(options);
    }

    public toString()
    {
        var selected = undefined;
        this.options().forEach((pair) =>
        {
            if (pair.key === this.selection())
            {
                selected = pair.value;
            }
        }, this);
        return selected;
    }

    public getValue()
    {
        return this.selection();
    }

    private static getNames(e: any)
    {
        return Object.keys(e).filter(v => isNaN(parseInt(v, 10)));
    }

    private static getValues(e: any)
    {
        return Object.keys(e).map(v => parseInt(v, 10)).filter(v => !isNaN(v));
    }

    public static getNamesAndValues(e: any): Array<keyValuePair<number, string>>
    {
        return SelectEditorObject.getValues(e).map(v => { return new keyValuePair(v, e[v]) });
    }
}

export class keyValuePair<key_type, value_type>
{
    public key: key_type;
    public value: value_type;
    constructor(key: key_type, value: value_type)
    {
        this.key = key;
        this.value = value;
    }
}


ConsoleColor existingColor = Console.ForegroundColor;
PrintLine(line);
Console.ForegroundColor = existingColor;

This suggests something in PrintLine changes the Console.ForegroundColor... but nothing does, so why even bother with the foreground color at all?

Seems this would have the exact same effect:

PrintLine(line);

But let's pretend for a minute, that PrintLine takes an argument that does change the foreground color:

PrintLine(line, logType);

Whose job is it to cache the original ForegroundColor, and reset it? That's right, PrintLine should be responsible for that.

By abstracting the Console.WriteLine call behind a method call, you've introduced mixed abstraction levels in your Log method: you have low-level Console.ForegroundColor reads and writes, and a higher-level PrintLine call, in the same method: if Console.WriteLine is too low-level implementation details for Log, then so is Console.ForegroundColor.

Keep abstraction levels separated.

You're still omitting braces:

if (logSettings.TypesToSave.Contains(logType))
    WriteContentToFile(logSettings.LogFile, line);

Should be:

if (logSettings.TypesToSave.Contains(logType))
{
    WriteContentToFile(logSettings.LogFile, line);
}

XML comments are great, but completely useless on private members; private members don't show up in IntelliSense, so what's the use? At best, they're redundant - if you're looking at WriteContentToFile, you are looking at the source code. If the code needs such comments, you need to work on naming things properly - but WriteContentToFile, filePath and content are pretty darn crystal-clear.

Actually the XML comments are not so great:

/// <summary>
/// Prints a line to the console using custom settings.
/// </summary>
/// <param name="line">Line you want to print.</param>
/// <param name="logType">Type of line you want to print.</param>

This is wrong. It's printing a line to the console and writing that line to a file, using hard-coded settings. This would be more accurate:

/// <summary>
/// Writes a new log entry.
/// </summary>
/// <param name="line">The text content of the log entry.</param>
/// <param name="logType">The type/level of log entry.</param>

The notion of "printing" is an implementation detail that doesn't belong in the public interface or anywhere in the documentation: one day that method will be writing log entries to a database - would "printing" still apply?

I would say the other isses have already been pointed out in the previous iteration - and they're important issues too, and you haven't addressed them here.

Log timestamps are still culture-dependent.
Settings are still hard-coded in the constructor.
Using that logger in a console app will still wreck the app's output.


Random date gen class. Returns a tuple of a start date and end date

You thought about using a generator… and why did you reject the idea?  If you have an object that does nothing other than iterating, then you might as well make it a generator — that's exactly what they are for.

The code is generally sound.  In my opinion, it could flow better if you defined the variables in a more logical order: (random year, random month, random day), followed by (random span), then packaging the results.

The meaning of the term parameter is unclear.  I would prefer a more explicit name.  The default value, 5, is unexpected to me.  Choose either:

A "sensible" default of 1 day, because that is a natural lower limit for a hotel stay (unless you run one of those sleazy hotels that rents rooms by the hour)
A default value of 0 days, because 0 is the additive identity
No default at all: make it a required parameter

In any case, it's probably a good idea to handle max_days=0 correctly without crashing.

The docstring is a bit cumbersome, and slightly self-contradictory when it comes to explaining the year parameter.

import calendar
from datetime import date, timedelta
import random

def rand_dates(max_days=1, year=None):
    '''
    Returns a date range as (start_date, end_date) tuple.

    The start date is a random date in the specified year (defaulting
    to the current year).

    The end date is a random date between 1 and max_days (inclusive) after
    the start date.

    Example usage: Picking random check-in and check-out dates for a hotel stay.
    '''
    while True:
        y = year or date.today().year
        m = random.randint(1, 12)
        d = random.randint(1, calendar.monthrange(y, m)[1])
        days = random.randint(1, max_days) if max_days > 0 else 0
        start_date = date(y, m, d)
        yield start_date, start_date + timedelta(days=days)


Instead of overloading the == and != operator you could simplify the part with the heavy casting by casting only once.
Instead of multiple if..else..else if statements you should use a switch..case.
using braces {} for single statment if's will make your code less error prone.
also this will be just a typo, but you really should fix it. RequestTypesEumn vs. RequestTypesEnum this can be easily achieved if you place the cursor on the name of the enum and hit the F2 key. And while we are at this enum, the enum in the name automatically implies that these are multiple items, so RequestTypeEnum instead of RequestTypesEnum would be better.

RequestTypeEnum currentRequestType = (RequestTypesEumn)row.RequestType.ID;

switch(currentRequestType )
{
    case RequestTypeEnum.Leave:

        // request is leave
        break;

    case RequestTypeEnum.Loan:

        // request is loan
        break;

    //......
}


if you less care about the "Dirty read" then you can use the "(nolock)" after the table name.
And you already have the indexing.


I think you can avoid inheritance here ("Favor Composition Over Inheritance") and use Attached Behavior instead.

Also, did you take a look at MaskedTextBox from Extended WPF Toolkit (http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox)?


Sorting a list of numbers, each with a character label

Names

Using the name list for a variable is legal but usually avoided because it hides the list builtin. The name lst would be a better candidate.

The function name comp could be improved as well. Maybe get_best_elements (even though I am not fully convinced).

Tests

Before going further, it may be wise to add tests so that you can easily be sure that we do not break anything.

A proper solution would involve a unit-test framework but for the time being, we can go for the simple:

TESTS = (
    ([], []),
    ([[1,'a']], [[1, 'a']]),
    ([[1,'a'], [1,'a'], [1,'a'], [1,'a']], [[1,'a'], [1,'a'], [1,'a'], [1,'a']]),
    ([[1,'a'], [1,'b'], [1,'c'], [1,'d']], [[1,'d'], [1,'c'], [1,'b'], [1,'a']]),
    ([[1,'a'],[3,'b'],[7,'c'],[6,'d'],[4,'e'],[1,'f'],[7,'g'],[4,'h'],[6,'i']], [[7, 'g'], [7, 'c']]),
    ([[1,'a'],[3,'b'],[7,'c'],[6,'d'],[4,'e'],[1,'f'],[4,'h'],[6,'i']], [[7, 'c']]),
)

for test_input, expected_output in TESTS:
    output = get_best_elements(test_input)
    assert output == expected_output
print("OK")

Style

Parenthesis are not required in the return statements.
Also, the temporary variable is not really required.

List comprehension

The new_list could be defined with a list comprehension.

def get_best_elements(lst):
    lst.sort(reverse = True)
    new_lst = [lst[y] for y in range(1, len(lst)) if lst[0][0] > lst[y][0]]
    return [x for x in lst if x not in new_lst]

Loop like a native

I highly recommend Ned Batchelder's talk "Loop like a native" about iterators. One of the most simple take away is that whenever you're doing range(len(lst)), you can probably do things in a better way: more concise, clearer and more efficient.

In our case, we'd have something like:

def get_best_elements(lst):
    lst.sort(reverse = True)
    new_lst = [e for e in lst if e[0] < lst[0][0]]
    return [x for x in lst if x not in new_lst]

Another approach

The last list comprehension can be quite expensive because for each element x, you may perform a look-up in the list. This can lead to a O(n²) behavior.

Instead of filtering out elements that do not correspond to the biggest number, we could just keep the one that do correspond to the biggest number.

def get_best_elements(lst):
    if not lst:
        return []
    lst.sort(reverse = True)
    big_n = lst[0][0]
    return [x for x in lst if x[0] == big_n]

Sort a smaller numbers of elements

You could use max to get big_n.

Also, we could perform the sorting on the filtered list so that we have fewer elements to sort:

def get_best_elements(lst):
    if not lst:
        return []
    big_n = max(lst)[0]
    return list(sorted((x for x in lst if x[0] == big_n), reverse=True))


Approximation search source reconstruction localization algorithm

Remove empty lines after if/else. Remove empty lines in general, this has too many. Use the new math.dist. Add comments about how the approximation works. Add docstrings.
If you want to make it more readable, pull out sub-loops into functions. That reduces nesting depth, which is just too high here--it's a problem you don't run into often. Also, don't use names like 'ei'.
One approach to make it more readable (but maybe slower), rewrite 'approximate' as a function taking in: a function to compute, an interval to search, and a maximum number of iterations. Also, you could use scipy or another specialized package which has this built-in.
If you want to make it more readable AND fast, don't use this solution. Use some other maximization method, for example gradient descent. These are also available as prebuilt tools, so it should be readable.
Last, in this case, I think there is probably a very direct answer specific to the problem. Look up GPS algorithms, because this is more or less how they work (although the speed is always the speed of light)


Your code is buggy due to you guarding against Exception, rather than a more specific exception.
This can lead to you saying a division by zero error is actually due to the user not passing in a number.

From this you have the following choices:

Change the errors to your own errors, whilst reducing the amount of errors you guard against in your try-excepts.

This would make filter_build look more like:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate

    if filter_type == 'bandpass':
        try:
            normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
        except TypeError:
            raise ValueError("Must provide tuple of frequency ranges for a bandpass filter")
    else:
        try:
            normal_cutoff = frequency / nyq
        except TypeError:
            raise ValueError("Must provide a single frequency value for this filter type")

    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

This keeps the entire error stack, and makes debugging the code much easier, whilst keeping your error messages.
But, you may want to change your approach, as you say you expect a tuple, rather than any indexable type.
And so you could use the LBYL approach of:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate

    if filter_type == 'bandpass':
        if not isinstance(frequency, tuple):
            raise ValueError("Must provide tuple of frequency ranges for a bandpass filter")
        normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
    else:
        if not isinstance(frequency, (float, int)):
            raise ValueError("Must provide a single frequency value for this filter type")
        normal_cutoff = frequency / nyq

    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

However, you could always remove all the try-excepts, and just leave the default Python error messages.
This can look like:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate
    if filter_type == 'bandpass':
        normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
    else:
        normal_cutoff = frequency / nyq
    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

I personally don't raise custom errors in most of my code, and so use the last option mostly.
I think Python's errors are pretty good, and I'm kinda lazy.
But all three options above are good.
You need to decide how you'll handle your errors.
You want to either do no handling, and your program just exits with the error.
Or you want to handle the error and display the actual error.
To do the latter should instead look like:

import traceback

def filter(signal, frequency, sample_rate, filter_type, filter_order=2):
    try:
        b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    except Exception:
        traceback.print_exc()
        return None
    return filtfilt(b, a, signal)

I'd highly recommend that you don't do the above.
Maybe you have a usecase where it's good.
But in almost all cases, it's better to remove the try-except, and for your program to exit.

If I were writing the above two functions I'd use the following:

def filter_build(frequency, sample_rate, filter_type, filter_order):
    nyq = 0.5 * sample_rate
    if filter_type == 'bandpass':
        normal_cutoff = (frequency[0] / nyq, frequency[1] / nyq)
    else:
        normal_cutoff = frequency / nyq
    return butter(filter_order, normal_cutoff, btype=filter_type, analog=False)

def filter(signal, frequency, sample_rate, filter_type, filter_order=2):
    b, a = filter_build(frequency, sample_rate, filter_type, filter_order)
    return filtfilt(b, a, signal)


Find and print all numbers in a comma-delimited string using sscanf

Some general comments about your current code:

You just dumped everything in the main method. This makes your code difficult to read, and more importantly, prevents it from being re-used. You should have factored the logic out into a separate method, which you would then call from main. This method would take the input string as a parameter, and then either do the printing directly, or use output parameters to return the parsed data.
Your variable names are…terrible. tmp, tmp2, tmp3 provide no semantic information whatsoever about the purpose of that variable. All that tells me is that they are "temporary", but all local variables are temporary! What temporary values do these variables hold? Choosing meaningful names for your variables goes a long way towards making your code readable—and bug free!
Your commenting style is inconsistent. You can use either C89-style comments (/* ... */) or C99-style comments (// ...), but whichever one you use, stick with it! I would prefer the C99-style comments, since these are easier to write, less error-prone when editing, and ubiquitously supported by C compilers (even Microsoft's, which has notoriously incomplete support for other C99 syntax).
Speaking of comments, it looks like you are using comments to remove your debugging code. A better way to do that would be to use conditional compilation, based on the definition of a DEBUG symbol (defined for debug builds; undefined otherwise). For example:

#ifdef DEBUG
    printf("ptr moved step: %d\n", tmp2);
#endif  // DEBUG

You could go one better by defining a TRACE or DEBUG_OUTPUT (or whatever you want to call it) macro, and then using this each time you want to print debugging output. This makes your code cleaner because you don't have to have all the preprocessor statements littered throughout.
Prefer to declare variables at the point of initialization. This allows you to limit the scope and prevents the inadvertent use of uninitialized variables.

Speaking of uninitialized variables, if you had been compiling with warnings enabled (by passing -Wall or a similar option, depending on your compiler), you would have seen a warning that tmp2 and tmp3 may be uninitialized at the point of use. Since the use of uninitialized variables is undefined behavior, this is something that you want to avoid at all costs.
There are typos, grammatical errors, and inconsistent formatting (trailing spaces, etc.) in your output strings. This makes your code—and even your finished application—look unprofessional. Even if English is not your first language, you should carefully proofread any output strings that the user is going to see. Maybe even get someone to look over them. (You know, like in a Code Review! :-p)
Combine back-to-back calls to printf into a single call. For example, this code:

printf("\n");
printf("howm any number found: %d\n", tmp);

should instead be written simply as (grammar fixed, too):

printf("\nTotal numbers found: %d\n", tmp);

printf is an extremely slow function, so for both readability and performance, you should avoid calling it multiple times when you don't actually need to!

A major improvement using strtod:

You have made this way too difficult! You don't need to write nearly as much of your own parsing code if you leverage the power of the standard library, which has powerful string-manipulation functions.

One of the comments mentions using strtod. That is an option, but the sample input you provided suggests that these are integer values, not floating point values. Therefore, strtol would be a better choice. By passing 0 as the base (third parameter), it will automatically detect the correct representation for the value, which is the most flexible.

Here is my first pass at rewriting your code:

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

void FindAndPrintNumbers(const char *psz)
{
   // The beginning of the list should be marked by an open curly brace.
   assert(*psz == '{');

   // Parse and print out each of the numbers in the list,
   // keeping track of how many were found in all.
   printf("Filtered number(s): ");
   int numbersFound = 0;
   while (*psz++ != '}')
   {
      ++numbersFound;

      char* pszNext;
      printf("%ld ", strtol(psz, &pszNext, 0));
      psz = pszNext;

      // The next character should either be a comma or closed curly brace.
      // If not, the input string is malformed.
      assert((*psz == ',') || (*psz == '}'));
   }

   printf("\nTotal numbers found: %d\n", numbersFound);
}

Note that I tend to use semantic Hungarian prefixes for my variables—in particular, psz means "pointer to a string that is zero-terminated. You can either like this style or hate this style. Rename them if desired; it won't offend me.

Also, I had to introduce a temporary pszNext variable because the strtol function is not const-correct. In particular, although the first argument is a const pointer, the second parameter is a non-const pointer-to-a-pointer. This is a defect in the C standard library, and you just have to work around it, making sure not to inadvertently invoke undefined behavior by modifying the string through that non-const pointer! This makes the code uglier than I'd like, but the only other choice would be a cast, and that's arguably even uglier!

Finally, my code just assumes that the input string will be in the format you've shown. That is, it will begin with an open curly brace ({), will contain an arbitrary sequence of integer literals separated by commas (,) with no spaces, and will end with a closed curly brace (}). There are assertions here to enforce these assumptions, but the behavior is left formally undefined if a malformed input string is passed in. If you want to be more robust in what you handle, you will need to add extra error checks. Your original code wasn't robust in the face of invalid inputs, either, so I assumed this wasn't important.


Loading configuration properties from XML

Your conversion is pretty good. I would make some suggestions but on the whole it would "pass" a code review - depending on the code that's calling this function (yes, that does make a difference). If I was to suggest changes they would be...

Interfaces over concrete classes.

Use interfaces instead of concrete types for return values and parameters. In your case, your function returns ArrayList<String>, but I would convert that to List<String>. This may not be possible without changing other code in your system, though. That would also imply changing the variable final ArrayList<String> valueArray to be final List<String> valueArray.

Error Handling

Your handling sucks.... but if you're locked in to the function signature because of other code, then you can't do much to change it, easily. Still, printing the stack trace is a very poor-man's solution.

Note that you can use a multi-exception catch now, and do:

} catch (IOException | FileNotFoundException e) {
    // ... handle e
}

Use java.nio.file.*

The newer NIO functions typically are more efficient, so use them when you can.

In your case, I would have:

Path script = Paths.get(getScriptPath(propertiesFileName));
try (InputStream input = new BufferedInputStream(Files.newInputStream(scritpt))) {
    // .....
} catch (.....) {
    // .....
}

Note that the input is an InputStream and not a FileInputStream ... use the highest form of the instance where you can.

Declare variables where they are used....

You declare the result variable valueArray outside the try-block. This is because of how you do the error handling and you may want to return it when it has an empty value. This is not the best solution though, I would have:

try (InputStream input = new BufferedInputStream(Files.newInputStream(scritpt))) {
    // .... get properties
    List<String> valueArray = new ArrayList<>();
    // .... populate it....
    return valueArray;
} catch (....) {
    // ... report the error
    e.printStackTrace();
    // ... return an empty array.
    return Collections.emptyList();
}

The finally....

You are using a finally on the file handle close... that's what the try-with-resources does for you.


The basic algorithm you use is logical, and well presented. The general style is standard, and I see no issues there. I believe the algorithm can be changed slightly to make the comparison code simpler, but the performance will still be comparable.
I looked for edge cases I would have expected, specifically relating to large differences, but you appear to have covered that well. Unfortunately, your pair-counts for diff == 0 are all off. For example, your third test case:

{new int[]{ 4, 4, 8, 8, 15, 15, 16, 16, 23, 23, 42, 42 }, 0, 18},

should have a count of 6, and not 18. There are only 6 pairs with difference 0. The pair at index 0, and 1, is the same pair as index 1 and 0, so you can't double (or, for some reason triple) count them.
This also applies to cases like: {new int[]{ 1 }, 0, 1},.... you have an input array of just a single element... but you have 1 pair with diff 0? Really???
There is one small performance improvement related to how far you need to iterate in the loop - you have: while (lowIndex < sorted.length && highIndex < sorted.length) { but that can be just while (highIndex < sorted.length) { since lowIndex is always less than or equal to highIndex. This is particularly confusing if your input difference is negative.
For some reason, and I can't explain it, I prefer left and right for those variable names too... lowIndex seems not-quite-right, but I understand it anyway. Just a niggly thing.
Additionally, there are a few places where I would do things in a more Java-8 way. Let's deal with the smaller items first...
Small things
Consider this code:

int[] sorted = Arrays.copyOf(input, input.length);
Arrays.sort(sorted);

I would (now) use the following:
int[] sorted = IntStream.of(input).sorted().toArray();

As for negative difference input values, I would just handle that as an up-front special condition. The count of pairs with a negative difference will be the same as the count with a positive difference and the same magnitude. Just convert negative difference to positive, and handle the Long.MIN_VALUE special case.
Algorithm
I would alter the algorithm a little. I would have a simple scan of the data to count value duplicates, and store that count in a separate array. With that data structure, the search for duplicates later is much easier. Consider this:
    if (input.length <= 1) {
        return 0;
    }

    int[] sorted = IntStream.of(input).sorted().toArray();

    // remove and count duplicate values
    int[] counts = new int[sorted.length];
    int size = 0;
    for (int i = 0; i < sorted.length; i++) {
        if (sorted[i] != sorted[size]) {
            sorted[++size] = sorted[i];
        }
        counts[size]++;
    }
    size++;

The above code ends up with a simpler data set to navigate. Unfortunatley, it makes the case where diff==0 a little more complicated... you need to use factorials for that, and not simple products. (Edit, I extracted that logic completely)....
Still, I put the whole method together as:
import java.util.stream.IntStream;

public class NumberPairsDiff {

    public static int pairsWithDifference(int[] input, long difference) {

        if (input.length <= 1) {
            return 0;
        }

        if (difference == Long.MIN_VALUE) {
            return 0;
        }

        if (difference < 0) {
            difference = -difference;
        }

        int[] sorted = IntStream.of(input).sorted().toArray();

        // remove and count duplicate values
        int[] counts = new int[sorted.length];
        int size = 0;
        for (int i = 0; i < sorted.length; i++) {
            if (sorted[i] != sorted[size]) {
                sorted[++size] = sorted[i];
            }
            counts[size]++;
        }
        size++;

        if (difference == 0) {
            int pairsFound = 0;
            for (int i = 0; i < size; i++) {
                pairsFound += factorial(counts[i] - 1);
            }
            return pairsFound;
        }

        int left = 0;
        int right = 0;
        int pairsFound = 0;

        while (right < size) {
            long diff = (long)sorted[right] - (long)sorted[left];
            if (diff < difference) {
                right++;
            } else if (diff > difference) {
                left++;
            } else {
                pairsFound += counts[left++] * counts[right++];
            }
        }
        return pairsFound;

    }

    private static int factorial(int n) {
        int f = n;
        while (--n > 1) {
            f *= n;
        }
        return f;
    }

}

The above function fails a bunch of your test cases because it produces the correct results ;-)


Install Ruby using rbenv in a bash script

Not a lot can be improved on a simple installer script like this.
I have a few tips but nothing really significant.

The script doesn't check if it has already been executed.
If you run it again by mistake, it will append to ~/.bashrc lines that were already there.

As a simple workaround, you could add -e flag to the shebang:

#!/bin/bash -e

This will cause the script to exit on the first error.
Which will happen on the first git clone command,
which will fail because the local clone already exists.
The script will stop there and not reach the lines that append again to .bashrc.

Speaking of shebang, you have a second #!/bin/bash in the middle of the script, which was probably a copy-paste mistake and has no purpose there, so should be removed.


Batch file to delete calling program and then itself

TASKKILL /IM "%filename%" /F

It makes sense that you might want to do this, but I expect the file would be more useful if it waited for its calling program to end on its own. That way we can be sure the calling executable is done with everything else, including releasing any resources it's holding. Because you already have looping code checking for the process, this should be as simple as removing the line.

Comments would be great.

For example, I understand that PING -n 6 127.0.0.1>NUL is a fairly common delaying tactic, but it's still downright odd if you haven't seen it before.

Likewise filename manipulations (%~nx1 and such) will always be arcane. A comment saying that it pulls out the name and extension would be appreciated.

There's an alternative here, which is a bit of a cheat but worth mentioning as potentially safer in some cases. Because the use case of this batch file is that it's created by the executable that wants cleaning up, that executable could do the text substitution and put its own filename directly into the relevant code of the batch file. Obviously this depends on the language that the executable is written in having good string manipulation capabilties, but it would help protect against deleting whole folders and other such disasters.

GOTO CONTINUE

Personally, I would not have called it 'CONTINUE' because in many C family languages continue would continue with the next iteration of a loop, rather than break out of it. Obviously it makes no difference to the script, and it's not something that a pure batch programmer would trip over. I just found it slightly jarring, and thought I'd mention it.

) ELSE (

This is not clear cut, but some people find it easier to read if the else is omitted when the if side breaks, returns, or otherwise interupts the control flow. That is

:LOOP
TASKLIST | FIND /I "%filename%" >NUL 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
)
ECHO %filename% is still running
PING -n 6 127.0.0.1>NUL
GOTO LOOP

Alternatively, you could swap the test around and avoid the goto CONTINUE altogether.

:LOOP
TASKLIST | FIND /I "%filename%" >NUL 2>&1
IF ERRORLEVEL 0 (
  ECHO %filename% is still running
  PING -n 6 127.0.0.1>NUL
  GOTO LOOP
)

I would personally find that easier to read as the batch magic equivalent of a conventional spin lock style construction.


The question

The last andWhere() method adds a LIKE condition with one percentage sign at the right. I'm wondering if there a better way to do it.

Hmm... let us look at that last addWhere() line:

$query->andWhere(['LIKE' ,'name',strtr($city_name,['%'=>'\%', '_'=>'\_', '\\'=>'\\\\']).'%', false]);

That is quite a long line - and appears to have manual character escaping, which isn't a bad thing but not something you want to handle manually if you can help it. Since you are using bound parameters for the first two parameters you likely know that they can help prevent SQL injection attacks and it would be wise to find a way to bind a parameter for that last where condition.
As this StackOverflow answer suggests, a bound parameter could still be used with the LIKE condition - then you might not need to escape as many characters:
$query->andWhere(new \yii\db\Expression('name LIKE :city_name', [':city_name' => $city_name . '%']));

But if the presence of certain characters like % in the city name still present a problem then continue to escape them
Other feedback
The code is very easy to read. Perhaps it was written to be compliant with PSR-2, which is now deprecated1, though it mostly is compliant with PSR-12. I like the fact that the short array syntax is used- I wish I had started doing that back then!
I see it contains assignment within the conditionals - e.g.

    if ($city_id = \Yii::$app->request->getQueryParam('city_id'))

While it doesn't take much to notice that the variables are later used within the statement that follows, it might be nice to help readers with a comment above the group that says something like intentional assignment.


Optimal code without using for, while and if

I am not a fan of this type of interview process... but ... you can assume that you need to differentiate yourself from the other candidates in some way.

Your solution may work, but does not show much in the way of 'clever' algorithms. You do the minimum to get the answer right, but not in the best way.

Things I think you could do better are:

Do not load the entire document in to memory. It may be large. Instead, use a mechanism for counting the words in a streaming way. It will save memory.
What about handling mixed-case words "The quick brown fox jumped over the sleeping dog" has the word 'the' twice, note the words 'The' and 'the' once each.
Consider a faster method for processing the data than a linnear scan through the words. A binary search and adding data to a sorted array would differentiate you.

EDIT: I took the liberty of copying and running the code, and it does not work. I changed the code to be:

BufferedReader br = new BufferedReader(new
    InputStreamReader(new FileInputStream(new File("src/FreqWord.java"))));

and this produced the result:

 Enter the String :

-------------

Word    freq

-------------
import  1
java.io.*;  1

------------

This is obviously not correct, so I will take a moment and write what I consider to be a 'good' solution. This will also answer the comment below about the Binary Search.

EDIT 2: Here's an answer that demonstrates the three issues I mentioned (just the main method), and as a bonus it gets the right answer.... :

public static void main(String[] args) throws IOException {
    // show you know the Java7 language changes...
    try (BufferedReader br = new BufferedReader(new InputStreamReader(
            new FileInputStream(new File("src/FreqWord.java"))))) {
        int wordcount = 0; // the number of unique words we have

        String [] wordvalues = new String[32];
        int [] counts = new int[32];

        String line = null;
        // Using regular expressions is a differentiator
        final Pattern pattern = Pattern.compile("\\w+");
        while ((line = br.readLine()) != null) {
            // Only keep one line at a time in memory.
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                // use toLowerCase() to show a grasp of the problem
                String word = matcher.group().toLowerCase();
                // use BinarySearch to order the words, which is faster than a scan.
                int ip = Arrays.binarySearch(wordvalues, 0, wordcount, word);
                if (ip < 0) {
                    // word we have not yet seen.
                    ip = -ip - 1;
                    if (wordcount == wordvalues.length) {
                        // grow the word array by about 25% each time we need to.
                        wordvalues = Arrays.copyOf(wordvalues, wordcount + 1 + (wordcount >>>2));
                        counts = Arrays.copyOf(counts, wordvalues.length);
                    }
                    // insert the word in sorted order.
                    System.arraycopy(wordvalues,  ip, wordvalues,  ip+1, wordcount-ip);
                    System.arraycopy(counts, ip, counts, ip+1, wordcount-ip);
                    wordvalues[ip] = word;
                    wordcount++;
                }
                counts[ip]++;
            }
        }
        // output the words in alphabetical order.
        System.out.println("\n-------------");
        System.out.println("\nWord" + "\t" + "freq");
        System.out.println("\n-------------");
        for (int i = 0; i < wordcount; i++) {
            System.out.println(wordvalues[i] + "\t" + counts[i]);
        }
        System.out.println("\n------------");
    }
}


Specify imports

Do you know the names of all functions in Data.List? Me neither. Specify what you import like

import Data.List (delete)

In my final version, this becomes

import Data.List (minimumBy,partition)
import Data.Ord (comparing)

Ord vs Eq

Your Ord and Eq instances do not agree! For Ord, only the frequency matters, for Eq, both frequency and payload have to be equal. This leads to oddities like this:

> let i c x = Internal (Leaf c 0) (Leaf ' ' 0) x -- helper
> i 'a' 1 >= i 'b' 1
False
> i 'b' 1 >= i 'b' 1
True

To solve the issue, I'd get rid of the Ord instance by

where mf = minimumBy (comparing freq) list

Use deriving

You implement a custom Eq instance for Tree, where deriving Eq would suffice. It takes a second to figure out what deriving Eq does, to read yours takes longer and does nothing different.

use pattern matches

length and indexing with !! 0 look like a direct translation from imperative programming. Use pattern matching instead:

treeBuilder []   = error "Empty"
treeBuilder [x]  = x
treeBuilder list = treeBuilder $ collapseLowest list

The use of length causes an unnecessary traversal of the list and can cause performance issues: In the worst case you lose list fusion.

Getting rid of Eq constraint

Just as minimumBy allowed to get rid of the Ord instance, deleteBy allows to get rid of the Eq constraint.

extractMinFreq list = (mf , deleteBy ((==) `on` freq) mf list)

Now you can compress uncomparable things like functions or IO actions after Char has been replaced by a.

Eta reduction

leafMap allows eta reduction, the lambda can be written with uncurry. (The latter is of dubious value)

 leafMap = map (uncurry Leaf)

Github

You can see all steps at https://github.com/Frank-Siebert/codereview86061


Purposeful PowerShell Help

I see that you have some comments in your script. Those for the most part would be hidden inside the script and the only way someone would see them is to open it. This may or not be what you intended but PowerShell has its own help based comment system that can contain this information as well as make it easy for running users to be informed.

About the parameters

You are using throw with the idea that you want the parameter to be mandatory with a message to show. That functionality is better handled by advanced function parameters

param (
    [parameter(Mandatory=$true,
        HelpMessage='Expecting an array of samaccountnames')]
    [string[]]$userNames
)

Mandatory is self explanatory and HelpMessage

  Windows PowerShell displays this message in the prompt that appears when a mandatory parameter value is missing from a command.

Module checker

Obviously this script is dependent on the activedirectory module being present. You have created a function that will load the module if it has not been already. The is some improvement that can be made of this function. Namely no sense in checking twice for the module presence. It is also good practice to use approve verbs properly. Get could be misleading in this case when in fact you are trying to Confirm

After looking at it a little more this can be reduced to one line that can be evaluated as a boolean which should accomplish the same thing. If you choose to keep the function keep in mind the points I made above. We only need it once so it does not really need to be in a function. Perhaps it should be in a local PowerShell profile.

if(!(Import-Module -Name $name -PassThru -ErrorAction SilentlyContinue)){
    # Script should exit will useful message as we cannot continue.
}

There are 3 possible scenarios for when this is run.

Module $name is not loaded but available: Command will execute and import the module $name. Once imported the module object will be returned because of -PassThru. The command is cast as [boolean] would return true.
Module $name is loaded:  The module object will be returned because of -PassThru. The command is cast as [boolean] would return true.
Module $name is not available: The command will silently fail and $null should be returned. The command is cast as [boolean] would return false.

Grouping Logic

The way the hashtable is built here obviously works but can be completely replaced with the use of the cmdlet Group-Object. I would suspect that, at the time, you were not aware of it. It would handle the grouping and the counts that we need for this. Also there is no test to see if the users actually exist. Need to account for that else the script will just hard fail.

You can see this in the completed solution below.

Updated solution

All the points collected above are used down here.

<#
.SYNOPSIS
Get and groups AD groups of specified users

.DESCRIPTION
This script will take a list of samaccountnames from
active directory and count the membership lists between them.
This can be used to track the group similarities between accounts.

.PARAMETER Users
Specifies the array of samaccount names to be looked up.

.EXAMPLE
C:\PS> extension -Users jsmith, bjangles
#>

param (
    [parameter(Mandatory=$true,
        HelpMessage='Expecting an array of samaccountnames')]
    [string[]]$Users
)

if(!(Import-Module -Name activedirectory -PassThru -ErrorAction SilentlyContinue)){
    # Script should exit will useful message as we cannot continue.
    throw("The module $name must be present in order to continue.")
}

$userMemberships = ForEach($user in $users){
    try{
        # Get the memberships of this user.
        #Since it is possible the user has no groups we need to separate the logic for that and failure
        (Get-Aduser -Identity $user -Properties memberOf -ErrorAction SilentlyContinue).memberof | ForEach-Object{
            [pscustomobject]@{
                User = $User
                Group = $_
            }
        }
    } catch {
        Write-Warning "Error retriving the group membership of $user"
    }
}

# Collect all the groups and display counts
$userMemberships |
    Group-Object -Property Group |
    Select @{Name="Group";Expression={(Get-ADGroup $_.Name).Name}},Count |
    Sort-Object Count -Descending

# Output the number of users check so the output has context
Write-Host "$($users.Count) users checked" -ForegroundColor Green

Minor comments

Principal Group Members

For me this is just the Domain Users group. Potentially in other orgs they use the principal group member for something else.

Accounting for bad users

You might consider adding more verbose output concerning errors. If there is a user that could not be queried then the last line could be considered faulty. I would think the warning would be indication enough.

Calculated Expression

You will see a calculated expression used in the final output. The groups returned from Get-ADUser contain the full DistinguisedName of the groups. Using a calculated expression we just get the name from the dn. While you could use string manipulation the cmdlet is more efficient and precise.


Your regex looks wrong, see my link below.

If your functional requirement is that usernames match a certain regex, then your tests should reflect that. It is wrong to test a bunch of edge cases that a generic regex catches.

See this. All you need in your test is to do:

username_regex = /^[a-z0-9][a-z0-9-]*$/i
passing_usernames = ['passing','pAsSing-PASS-'.....]
failing_usernames = ['-failing','failing#'....]
passing_usernames.each { |username| assert_match username_regex, username}
failing_usernames.each { |username| assert_no_match username_regex, username }

If you're getting your username from somewhere else then just plug that in the same way.


You could slightly simplify the code as follows:

Reduce the number of variables.
Use the LinkedList<T> (and the AddFirst method) instead of the List<T> to eliminate reversion of array.
Alternatively you can use the List<T>.Insert method to achieve the same result.

The code:

private static string ToBase26(int myNumber)
{
    var array = new LinkedList<int>();

    while (myNumber > 26)
    {
        int value = myNumber % 26;
        if (value == 0)
        {
            myNumber = myNumber / 26 - 1;
            array.AddFirst(26);
        }
        else
        {
            myNumber /= 26;
            array.AddFirst(value);
        }
    }

    if (myNumber > 0)
    {
        array.AddFirst(myNumber);
    }
    return new string(array.Select(s => (char)('A' + s - 1)).ToArray());
}


Regex, match the most informative pattern

I cannot say much about the limits of the pattern, the only one that I encountered so far was the length of the group name.

IEnumerable<Affirmation> affirmations = matches.Cast<Match>().Select(m => {
    if (yesses.Contains(m.Value.ToLower())) { return Affirmation.Yes; }
    else if (nos.Contains(m.Value.ToLower())) { return Affirmation.No; }
    else { return Affirmation.Unsure; }
});

You can however make the lookup faster by using a HashSet<T>. Its Contains method is an O(1) operation unlike the array's O(n).

Additionaly you should instantiate it with StringComparer.OrdinalIgnoreCase so that you don't have to use ToLower/ToUpper.

Another possibility would be to use named groups and catch the expressions there so that you can just use them without looking them up in the collections.


Implementation of Dijkstra's algorithm to find the shortest path in graph

This is a bad idea:
class Vertex
{
public:
    int m_id;
    >>> unsigned int m_cost;
    >>> bool m_isVisited;

You are conflating two things into a single class. The concept of a vertex and the concept of performing Dijkstra's algorithm on the node. You should separate the two issues into their own classes.
The main problem with this technique is that you need to reset the graph before use. ie. you can not run your algorithm twice in a row. You must reset the state of the whole graph before it can be re-used. Look up the visitor pattern.
You really want a constructor that does no initialization?
Vertex()
{
}

The POD members will be left in an undefined state.
Your have void findMinDistance(std::vector<Vertex>&); in the vertex? Find min distance to where?
Use the new C++ range based for:
for(std::map<int,unsigned int>::iterator iter = m_edgeList.begin();
    iter!=m_edgeList.end(); iter++)

// can be rewritten as:
for(auto& edge: m_edgeList)

Overall I don't think you are actually implement Dijkstra's algorithm.
Dijkstra algorithm
The algorithm should look like this (this is pseudo code).
The classic part is the frontier list (I called it boundryList) and the set of vertex we have found the shortest route to.
 RouteCostObject findRout(Graph& g, Vertex& start, Vectex& end)
 {
      OrderedListByDistance    boundryList;
      SetOfVertex              foundVertixes;

      boundryList.push_back([start, 0, []]);

      while(!boundryList.empty())
      {
          // Remove the top items from the list.
          (vertex, cost, route) = boundryList.top();       // Note: boundryList is sorted
          boundryList.pop();

          // If we have reached the end.
          // This is the shortest route.
          if (vertex == end)
          {    return [cost, route];
          }

          // Check if we have already found the shortest distance
          // to this vertex.
          if (foundVertixes.find(vertex) != vertex.end())
          {
              continue;
          }
          foundVertixes.insert(vertex);

          // Add all edges to the boundary list.
          for(auto& edge: vertex.edges)
          {
              boundryList.push_back([edge.dst, cost + edge.cost, route + edge]);
          }
      }
      // No route from start to end
      return [infinity, []];
 }


This seems a textbook case for using Angular.

Assuming you do not have the time to invest in Angular, you could consider the following:
If you named all your divs after your result properties ( for example '#job-agency' -> #job-company ), then you would have to do far less extraction work and far fewer text() calls.

You could do something like:

$.each(results.jobs, function(i, result){

  var key;

  //Enhance your result object with some calculated values
  result.thePosted = posted[2]+'-'+posted[1]+'-'+posted[0];
  result.theJobNo = pages*i +1,

if(result.hasOwnProperty('salary')){
  result.theSalary = result.salary.information.replace(/Â/g, '');
}

var jobContainer = $('#job-container').clone(true, true).attr('data-jobno', theJobNo);

for( key in result )
{
  jobContainer.find( '#job-' + key ).text( result[key] );
}

jobContainer.find('.apply-btn, .email-btn, .save-btn').attr('id', theID);
jobContainer.find('.save-btn').text('Save Job').removeClass('job-saved');

etc. etc.

The rest of the code is ok once you apply consistent indenting.


First and foremost:

  Anyway, should performance be always the top priority?

Definitely not.  Don't write things that are needlessly unperformant, but only be overly concerned with performance when you have a reason to be.  Most of the time JS execution time is irrelevant, because you're waiting for user interaction, or for a network request, or something else that makes the execution time of the JS pretty unimportant.

I'd be more concerned with writing code that's clear, expressive, and maintainable than performant.

Regarding your usage of this, though, you definitely shouldn't be using this as you are in the first example.  You're leaking into the global scope.  When addg is run, what is this?  If you were calling obj.addg(), this would be obj, but since you're just calling addg(), this is the global scope A.K.A. window (in the browser).

With your first version if you run this in your console you'll see:

addg();
//undefined
addToCollection;
//function!  Whoops

That's not what you want.  You don't need to assign the internal addToCollection function anywhere, so don't.

An add function is a bit pointless.  You're adding undefined to the array of numbers in the () case, then adding special logic to exclude it from the sum, later, but instead you should just not add undefined at all.  Only do numbers.push(val) if typeof val === 'number'.

But, then, do you really need to keep an array of numbers at all?


Python Tic Tac Toe Building Block Function

Flat array for display

It looks like display_field accepts a one-dimensional array. By the time you're manipulating it with business logic and presenting it back to the user, it should be a two-dimensional array. Rather than one format string, you would then call '\n'.join().

Presentation vs. business logic

In several places your presentation ("Impossible", "X") is all conflated with your business logic. Do not use strings to return status from analyze_field. What to use instead depends on a number of factors; some options are:

Use an Enum
Use a callback object where there is one function per result option

Along similar lines, do not store 'x' and 'o' strings in the cells. You can use an Enum here, perhaps with values PLAYER1/PLAYER2. Strings are unconstrained, and a matter of style/presentation/UI rather than business logic, which should be more verifiable.

Set membership

if abs(num_x - num_o) not in [0, 1]:

can be

if abs(num_x - num_o) not in {0, 1}:

since order does not matter and set lookup has O(1) time complexity. That said, I think this is equivalent to

if not(-1 <= num_x - num_o <= 1):

assuming that num_x and num_o are integral.

Zip

I question this logic:

for row, column in zip(rows, columns):
    if len(set(row)) == 1:
        num_winners += 1
    if len(set(column)) == 1:
        num_winners += 1

I think what you're looking for is a chain, not a zip:

for sequence in chain(rows, columns):
    if len(set(sequence)) == 1:
        num_winners += 1

In other words, there's no point to checking a row and its corresponding column in the same loop iteration.


Copying data to a .txt, but making it look nice?

You could do a better job describing the task; the task description should be a docstring.  I would also rename the function to select_platenumber(), since it's not really calculating anything.

If you're using plain text files as a database, watch out for race conditions.  Unless you implement some kind of locking mechanism, you could easily end up with corrupted files.

As @JamesKhoury says, you should only have to open each file once, using a with block.  Use the appropriate mode: you only need to append to the output file.  For the input file, you can truncate and overwrite it.

For efficiency, I prefer to select a random array index rather than a random array element.  Selecting a random element is more readable, but to remove that element involves a linear search through the list.

I think it would be safer to write the used_license_numbers.txt entry before overwriting license_numbers.txt, in case of an I/O error.  (You could have inconsistent data, but at least you would be less likely to lose data.)

Having similarly variables self.platenmb and self.platenumber is confusing.

def select_platenumber(self):
    """Selects and removes a random line from license_numbers.txt as the
       license plate, and appends a line to used_license_numbers.txt
       recording the license plate and customer name.
    """
    firstname = str(self.customer2_entry.get())
    lastname = str(self.customer3_entry.get())

    with open('license_numbers.txt', 'r+') as in_file, \
         open('used_license_numbers.txt', 'a') as out_file:
        plates = in_file.readlines()
        self.platenmb = plates.pop(random.randrange(len(plates))).rstrip()
        self.platenumber.set(self.platenmb)

        out_file.write('%-19s %s %s\n' % (plate, firstname, lastname))

        in_file.truncate(0)
        in_file.writelines(plates)


Formatting - if the code looks the same in your editor as it does here, you could really do with an automatic indentation tool (many editors have that built-in, or you could use GNU Indent, for instance).
I'll assume that the inconsistent indentation is due to the way you've copied your code into the site; a good way to avoid problems is to consistently use either spaces or tabs for indentation, but never to mix the two.

It's a good idea to specify that main() takes no arguments:
int main(void)

When we read input, we must check whether it was successful or not:
int physics;
if (scanf("%d", &physics) == 1) {
   // physics has been set, and we can safely use it
} else {
   // physics is still uninitialised
}

If input fails, then we might want to re-ask (but be careful about doing this if we reach end of the input stream, or we'll try and try again, indefinitely).
Output can also fail, but for this application, that's less of a concern.

There's an unused argument to printf() here:

printf(" MEAN OF :  %.2f\t",mean, round(mean) );

That suggests that you could enable more compiler warnings (e.g. gcc -Wall -Wextra - other compilers should have similar options).

If mean is between (say) 59.0 and 60.0, then it will fall in between the grade boundaries, and no grade will be printed.  The easy way to avoid this is to use else if:
if (mean >= 70) {
    puts("AND THE  GRADE IS A");
} else if (mean >= 60) {
    puts("AND THE  GRADE IS B");
} else if (mean >= 50) {
    puts("AND THE  GRADE IS C");
} else if (mean >= 40) {
    puts("AND THE  GRADE IS D");
} else {
    puts("AND THE  GRADE IS E");
}

Now, exactly one of those blocks will be executed.
I also changed the printf() to puts() there - prefer the simpler function when you just need to print a single string and a newline.

More advanced ideas
Should the grade thresholds be fixed in the code?  If they change, you need to re-compile the program.  Think about how you might read them from a configuration file.
Should the list of subjects be fixed?  How would you make the program more flexible for students of different courses?


Returning rental invoice data transfer object

Make separate methods for getting equipment from the cart, creating rentals from the equipment, getting loyalty points from the equipment, and creating the invoice from the rentals and loyalty points.


Change your fields' visibility to private as others object shouldn't know (nor care) about the inner working of your TicTacToe, this is known as Encapsulation
Turn the buttons into a 2D array and make the name clearer (b isn't really informative ^^)
Avoid magic numbers (talking about 3, 9, 500 which can be replaced by GRID_LENGTH, GRID_SIZE...) : this way, not only it's clearer for a newcomer but if you ever change one value it'll be updated everywhere
I don't think there is any point in making win a field, it's only used like a local variable
Turn the // WHO WON part into a method that'll do all the checks for you and return you a boolean : in general, calling multiple short methods makes for a clearer code as the code is more declarative this way (and it removes useless comments)
For same reasons as above, turn the victory message printing into its own method
Use a for loop to check every lines and every columns without caring for their size, that'll make for a clearer code and it'll also be easier to modify the current behaviour (if you ever want to allow for differents grid size)
You may want to not compute diagonals unless someone has checked one of the diagonal value, it'll probably slighty increase cyclomatic complexity though so it's up to you ;)
You forgot to disable the buttons if the game ends in a tie... in the same way as points 5 and 6, creating a disableTicTacToe or disableFrame method may be neat
Maybe you should consider offering the players a new game when one has ended


In this code, I find it misleading that n is first assigned zeros,
and then its content is replaced with strings.

n = [0]*3
n[0], op, n[1], x, n[2] = parse_op.search(s).groups()

I think it would be more clear this way:

num1, op, num2, _, num3 = parse_op.search(s).groups()
nums = [num1, num2, num3]

Notice that I replaced x with _. It's a common convention when a variable is unused.

Some doctests with example inputs and expected outputs would be great too,
making the code easier to digest, and play with.


What's the optimal 'pythonic' way to make dot product of two lists of numbers?

The most "pythonic" way of doing this makes use of the sum and zip built-ins:

def __mul__(self,other):
    if other.dimensions() != self.dimensions():
        raise ValueError("Number of dimensions of multiplied vectors must be equal.")
    return sum(a * b for a, b in zip(self.coordinates, other.coordinates))

I suggest making use of the REPL (interactive shell) to learn about them, here is an example REPL session that you can read explaining zip and sum:

>>> x = [1, 4, 8]
>>> sum(x)
13
>>> y = [6, 1, 0]
>>> zip(x, y)
<zip object at 0x7f51da3db5c8>
>>> list(_) # `_` means previous value
[(1, 6), (4, 1), (8, 0)]
>>> help(zip)
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  __next__(self, /)
 |      Implement next(self).
 |
 |  __reduce__(...)
 |      Return state information for pickling.

>>> help(sum)
Help on built-in function sum in module builtins:

sum(...)
    sum(iterable[, start]) -> value

    Return the sum of an iterable of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the iterable is
    empty, return start.

>>> zip( (1,2,3), "abc" )
<zip object at 0x7f51dba79648>
>>> list(_)
[(1, 'a'), (2, 'b'), (3, 'c')]

Other points

Tests should be automatic and NOT rely on you manually checking that wha is printed is right. This manual method will become too time consuming very soon.
f makes no sense (probably it is a leftover from a previous assignment). Please remove it.
get methods are discouraged in Python, accessing the items directly is very simple anyway.
Use @property to give convenient call sintax in dimensions(self) or remove this property completely as you can just call len(vector.coordinates) very easily.


Creating users with different roles using .Net Identity 2.0 within Entity Framework

Well, you say that both Student and Teacher inherit from the base class Person. Considering that, and the fact that you never actually use either the Student or Teacher specifically in this code, why bother checking the Role at all? Your UserManager<IdentityUser> is taking in a person, not a Teacher or a Student.

Now, if I would happen to be wrong about that, I would suggest looking into the Factory Pattern. You could create a factory that takes in all of the fields from your GUI as arguments, and decides which type of Person to create based on the arguments it's recieved. It won't do away with all of the if...else if logic, but it will abstract it away and hide it from your GUI and make your code more testable.


You're right, your second method is way too complicated. It also doesn't handle the case where the string starts with a space (in which case words[0] will be the empty string and letters[0] will be out of bounds). Since all your method seems to be doing is to capitalize the first letter of the string and lower case everything else, why not just do that?

public static string CapitalizeFirstWord(this string sentence)
{
    if (String.IsNullOrEmpty(sentence))
    {
        return String.Empty;
    }

    String firstLetter = sentence.Substring(0,1);
    String rest = sentence.Substring(1);
    return firstLetter.ToUpper() + rest.ToLower();
}


Viewing test scores from one of three CSV files

If you see a whole bunch of if/else statements with the only difference being some function, take advantage of the fact that functions are first class objects in python. For instance, you could create a dictionary that maps your sort options to sorting functions; while you're at it, explore the built ins (such as operator) as well:

from operator import itemgetter

sort_options = {
    # itemgetter(0) is equivalent to lambda x: x[0]
    # >>> x = [1, 2, 3]
    # >>> f = itemgetter(0)
    # >>> g = itemgetter(1)
    # >>> f(x)
    # 1
    # >>> g(x)
    # 2
    # sort_option: (key_of_sort, your_word, sort_in_reverse?, your_field)
    'alphabetical': (itemgetter(0), "- Highest Score on test:", False, 5),
    'average': (itemgetter(4), "- Average Score", True, 4),
    'highest': (itemgetter(5), "- Highest Score on test:", True, 5),
}

def custom_sort(data, sort):
    fn, word, rev, field = sort_options[sort]
    sorted_ = sorted(data, key=fn, reverse=rev)
    return word, sorted_, field

word, sorted_, field = custom_sort(data, sort)


I'm not familiar with Spark. It's obvious that this code isn't thread-safe (ArrayList isn't thread-safe, and tokens is accessed without any explicitly locking), but I don't know whether Spark provides the thread safety.

The cookie handling is missing two important parameters:

                res.cookie("token", token, 3600);

There are various overloads which take boolean secured, boolean httpOnly, and ideally you would set both of those to true. If you can't set secured because you're using a cheap web host which doesn't support HTTPS, at least set httpOnly.


Code style: passing a reference to subroutine

Here are some considerations when writing such functions:

By passing the function all of the variables it needs (test1), you don't need to rely on global variables. This makes the function easier to test, more predictable (no side effects) and easier to refactor as you can move it to another module or file easily. If it relied on global variables, it would be broken if the variable is moved or its data structures changed.
Returning the original reference is not necessary for test3, because the original $ref is changed. Returning is useful if you want to chain function calls.
Modifying the arguments passed your function directly can be surprising to the function's caller. If you do this, make it clear in the documentation. If you actually want to make a new copy of the object, modify it and return it, use something like Clone. Of course, this can be slow.
Just in case you are writing object accessors/mutators: please consider using a module such as Class::Accessor or the more heavyweight but extensive Moose which can generate such functions for you automatically.


It depends on a lot of factors, there's no universally "optimal" size. 512kB is probably good enough.

If you want, you can always benchmark it for various buffer sizes: this will let you know what the best option is for your computer and OS.


Get resources inside or outside constructor?

Are these resources always linked to the bigObject instance? Do they have something in common with certain data or functionality in bigObject? Are they somehow related mutually? It's hard to say exactly what is the better approach without knowing all this, but there are several sanity checks you can do:

Do GetResource1 to GetResource3 really all depend on the bigObject instance? Can you extract this functionality into a different class? Extract class refactoring might be an option.
Does bigObject know too much? Big kinda sounds like God, as in "god object".
If these three resources always come together (i.e. they all belong to the same interface), you might want to extract only them into a "parameter object". This means that you might end up with something in the middle, like:

public Foo(Bar bigObject, IResources resources)
{
   ...
}

Which means your bigObject will implement IResources, but you will also be able to implement them in a different way, and it will reduce the number of params.
If these resources are all of the same type, and there is a large number of them, then even a simple delegate might be enough. You might even want to make the call weakly typed for greater extensibility:

public Foo(Bar bigObject, Func<string, IRes> getResourceByName)
{
     var res1 = getResourceByName("1");
     var res2 = getResourceByName("2");
     ...
}

These suggestions popped out as I was writing, but ultimately, it's hard to give any exact guidance unless you state the actual problem you are trying to solve. Design should then follow from there.


I have an encrypted file, how to remove a specific string from that file

Some clarifications

I got a file with lots of ASCII characters. [...] I have many characters like L¿ö in the file [...]

As others have pointed out, these are not ASCII characters.

No extension, and has the Type Of file attribute 190000 File.

Configure Windows Explorer to show file extensions.

I required to remove lines from a word PYGR to another word MCG. It has several lines in between.

Your code tells us otherwise. You are not removing the lines from PYGR to MCG; your code removes the word PYGR and every character that follows up to one character before MCG. I assume that is not quite what you were trying to achieve?
If you update your question to explain if you are trying to remove everything between (excluding) PYGR and MCG, including one of them or including both of them, I'll gladly adapt my answer. For now, I will assume the latter.
Edit: All right, in accordance with your comment I have changed my answer to replace all text from PYGR (inclusive) to MCG (exclusive).
Reviewing your code
Readability

Please use the well-established C# naming conventions: local variables are camelCase
Format your code with the correct indentation to make it more readable
Start your file with using System.IO to avoid repeating yourself
Get rid of unnecessary parenthesis
Choose proper names
Join declaration and usage of variables where possible

For example:
string EditedString;
// ...
EditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1)));

should be more like
string editedContent = fileContent.Remove(startIndex, endIndex - end.Length);

Maintainability
Hard-coding the paths is something that should be avoided even during development. You can use Environment.GetFolderPath with Environment.SpecialFolder.Desktop to retrieve the path to the current user's desktop and add the file name with Path.Combine.
Regex
I really don't like the heave use of indexOf: your code seems to be all about how the replacement is done, instead of what is going on (i.e. it is imperative, not declarative).
Using a Regex, we can arrive at a more declarative style. You may need to adjust this to suit your needs (your question is ambiguous).

Refactored
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string inFilePath = Path.Combine(desktop, "SYSI091512.190000");
string outFilePath = Path.Combine(desktop, "SYSI091512.190000V1");

// you would probably pass the paths into your method as parameters

var fileContent = File.ReadAllText(inFilePath);
var result = Regex.Replace(fileContent, "PYGR.*MCG", "MCG", RegexOptions.Singleline);
File.WriteAllText(outFilePath, result);


Finding number of possible arrangements of books on a shelf with a Monte-Carlo approach

I don't really understand your question. So I'll take things to the extreme and assume there are n1 books, n2 categories, n3 super categories... etc.
This whole hierarchy can be represented as a rooted tree, and the number of valid permutations would be the number of postorder traversals of the tree (or equivalently, preorder).
(I don't expect this will answer your question, I just thought it was interesting)
Also, if you'd like to find some middle ground between your specific example and my extremely overgeneralised... whatever this is... it might be easier to come up with a reasonable answer.
(edit...)
Some more points
This is not specific to matlab, just DSA in general
I still maintain that randomness is not the way to go for this problem.
As far as data structures go using arrays is fine, but for generality/scalability I suggest encoding the categories into the lists as well.
tree = {{1,2,3},{1,2},{1,2,3,4}} <- a cell array lets you structure data
Also, it's inefficient to check each new permutation against every saved entry. The usual thing to do is to use a set (a hashmap or a hashtable). But this adds the problem of computing a hash of the array (or finding some succinct unique id)


I would merge the 2 loops (there is one in the max part), since not all parts are relevant for the maximum:

def best_subsum(array):
    running_sum = 0
    for i in range(1,len(array)):
        if array[i-1] > 0:
            array[i] = array[i] + array[i-1]
            if array[i] > running_sum: running_sum = array[i]
    return running_sum

array = [4, -2, 7, -9]
print(best_subsum(array))

Note that branch prediction shouldnt be too much of a problem, since running sum is not check until the same if statement in the next succeding iteration.


Write DRY code:

DRY - Don't repeat yourself.

std::cout << "Enter bits for first binary number \n";
for (int i = 0; i < n1; i++)
{
   std::cin >> val;
   A.push_back(val);
}

std::cout << "Enter bits for second binary number \n";
for (int i = 0; i < n2; i++)
{
  std::cin >> val;
  B.push_back(val);
}

These two bits of code are way to similar. Make a function that does this work and pass as parameters any differences.

Highest order bit is where?

  std::cin >> val;
  B.push_back(val);

With this code your most significant bit is at location 0. This gives you no room to expand the number. Put the least significant bit at 0 and the more significant bits at higher locations. This will make it easier to do the standard maths operations in the long run.

This looks like a switch:

  if (sum == 0)
  {
     carry = 0;
     C[k] = 0;
  }
  else if (sum == 1)
  {
     carry = 0;
     C[k] = 1;
  }
  else if (sum == 2)
  {
     carry = 1;
     C[k] = 0;
  }
  else if (sum == 3)
  {
     carry = 1;
     C[k] = 1;
  }

I would write as:

  switch (sum) {
      case 0: carry = 0;C[k] = 0;break;
      case 1: carry = 0;C[k] = 1;break;
      case 2: carry = 1;C[k] = 0;break;
      case 3: carry = 1;C[k] = 1;break;
      default: throw std::exception("Something very wrong happened");
  }

Another case of DRY:

  while ( i >= 0 && j >= 0 && k >= 0)
  {
      sum = A[i] + B[j] + carry;
      // STUFF
      k--;i--;j--;
  }
  //if size of first binary number is greter than first
  if (max_size == size_A)
  {
     while (i >= 0 && k >= 0)
     {
        sum = A[i] + carry;
        // STUFF
        k--;i--;
     }
  }
  //If size of second binary number is greater than first
  else if (max_size == size_B)
  {
     while (j >= 0 && k >= 0)
     {
       sum = B[j] + carry;
       // STUFF
      k--;j--;
     }
  }

Not only can all the "stuff" by factored out into its own function. But those three loops can be combined into a single loop.

  for(;k >= 0;--k)
  {
      int a = (i > 0) ? A[i--] : 0
      int b = (j > 0) ? B[j--] : 0;
      sum = a + b + carry;
      // STUFF
  }


Constraint Algorithm Optimization in C++

I don't know much about SSE and can't offer you any suggestions on performance right now, just a few suggestions to improve your code a little bit. Nevertheless, it looks well written and clean.

Since the default constructor does nothing, you can make it = default. That's the new syntax for such cases since C++11. It also conveys more meaning that you want a default no-op constructor.
The move constructor is pointless. An __m128 is a native type like an integer, so it fits in a CPU register. It will always be copied. You can remove this constructor overload.
The other constructor that takes a __m128 by const reference is probably less efficient that it could be. Again, __m128 can be passed via registers, so taking by reference will instead pass a pointer that has to be dereferenced. I bet you it is generating more code than if you'd just pass it by value.
The constructor that takes the four X,Y,Z,W floats doesn't have to be explicit. For any constructor taking more than one argument that has no default, explicit doesn't make sense. It is only meaningful when the constructor has a single required argument and you want to force writing something like func(FVector{42.0f}). If the constructor takes more than one argument, it can't be implicitly called.
const float& operator[](int index) const should instead return by value. Again you are forcing the compiler to generate indirection code when the value can be cheaply passed in a register.
I would also recommend asserting in the array subscript operators to ensure index in >= 0 && < 4.
If you decide to port this code in the future, __forceinline is going to be a problem. It is a Microsoft extension. I would #define a portable macro for it instead or just use standard inline. __forceinline is no guarantee of inlining, despite the misleading name. It just provides a slightly stronger hint to the compiler than inline.
__m128 is somewhat an ugly type to pass around, with those double underscores. In your place, I would declare some alias for it, perhaps simd_t or something. It might even be of value in the future if you decide to port FVector to some other SIMD set like AltiVec.


Selecting a table with multiple ID on MySQL using PHP PDO

When I changed from the mysqli_functions to PDO with prepared statements, I had the same question. I found the answers to this question to be very usefull: https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection.

Let's say you have messaging functionality and someone types SQL injection code in the title field when sending a message. You use a prepared statement, and the SQL injection code gets saved as the title. the SQL injection code didn't get executed, you have been saved from 1st order SQL injection.

Now let's say you have a function to reply to messages that uses the previous message title and adds "RE: " before it. If this reply function assumes the new title is safe since it's not coming from a user input field and doesn't use a prepared statement on the reply title, the SQL injection code will get executed. This is called 2nd order SQL injection.

You're 1st order safe if you use prepared statements for queries requiring user input. You're 2nd order safe if you use prepared statements for every query.


How do I improve this logging mechanism?

Why would you have serious trouble with persistance?

Just do null checks for InnerException and TargetSite, rest will be inserted as null or string empty depending on your db setup.

And why not just simplify it as:

var innerExceptionMessage = e.InnerException == null ? string.Empty : e.InnerException.Message;
var targetSiteMessage     = e.TargetSite == null ? string.Empty : e.TargetSite.Message;

exceptionLog.Add("Inner Exception", innerExceptionMessage);
exceptionLog.Add("Message", e.Message);
exceptionLog.Add("Source", e.Source);
exceptionLog.Add("StackTrace", e.StackTrace);
exceptionLog.Add("MethodName",targetSiteMessage);

Keep it simple :)


Writing a class that represents a sorted list of filenames

Empty lines as separation around code lines that are related are always a good idea. Your code has a little too much empty lines where it is not common in C# (or C/C++, Java, JavaScript):

public class RecentlyUsedList

{

This in fact decreases readability. Instead just write:

public class RecentlyUsedList
{

      private readonly List<string> items;

      public RecentlyUsedList()

      {

        items = new List<string>();

      }

Here the constructor is not necessary. Just do:

private readonly List<string> items = new List<string>();

Your Add(...) method can be simplified to this:

  public void Add(string newItem)
  {
    items.Remove(newItem);
    items.Insert(0, newItem);
  }

items.Remove(newItem) just returns false, if the item is not present, so it's safe to use in any case. There is no need to be concerned about the existing string because it is the same as the newItem.

public int Count... can be simplified to:

public int Count => items.Count;

  List<string> items

has an indexer it self, so you can use that when implementing the indexer:

  public string this[int index]
  {
    get
    {
      if (index < 0 || index >= items.Count)
      {
        throw new ArgumentOutOfRangeException();
      }
      return items[index];
    }
  }

Here I throw an exception if the index argument is out of range. You could let items handle that as well...

In fact your foreach-loop is potentially much slower than the List<T>[index] because you make a kind of search where List<T>[index] just performs a look up. So you hide an efficient behavior with a not so efficient one.


Python exception-raising generator function

In terms of raising the KeyError as soon cluster_terminals is called (rather than when its result is iterated), this general pattern is likely the best. There are a couple of other points that bear mentioning, though.

First, assert False is one of the worst ways to handle a detected error (marginally better than, say, sys.exit(0)). Make the assertion self-documenting so that if when it gets triggered sometime in the future, you have more immediate information in the stack trace about what is going on. At a minimum, include a message with the assertion:

assert False, "`return_list` contains unexpected object of type " + str(type(x))

An arguably better option is to put it up front with an explicit test, even if that means duplicating some of your logic:

assert all(isinstance(x, (ClusterTerminal, NodeTerminalMappingName)) for x in return_list)

And then adjust your conditional to either have a pass (and a short comment pointing to the assertion) in that branch, or omit that branch entirely. This makes it abundantly explicit to anyone reading your code that that is an 'impossible' situation, and means the invariants of this class have been broken (and that it isn't that client code has passed in bad data - for that, use a normal exception rather than an assertion).

A more minor quibble is that you don't need to pass return_list into the helper function as an arguments. You can use closures:

return_list = self.cluster_map[key]
def internal_cluster_terminals():
    ...
return internal_cluster_terminals()

This will behave identically - Python functions can see variables from the scope they are defined in, even if that scope no longer 'exists' when they are executed.

internal_cluster_terminals is a bit of an unwieldy name, and doesn't tell us anything we don't already know (it's.. internal to the function it's defined in. Wow, amazing). A more usual name for this type of function is something like helper. return_list isn't a great name either, especially since it's actually misleading (it isn't ever returned). Since it's a value from a mapping, call it after what those values conceptually are - cluster might be a good option.

Finally, consider adding a short comment to document why you need a helper function in the first place, like:

# Use an internal generator instead of yielding directly
# so we can bail out early if there's a KeyError


I think the first one is more understandable to a reader, while the second is more efficient and or more easily adapted to higher dimensions. Have you thought about something like:

if (dir == LEFT || dir == RIGHT){
  int x = dir == LEFT ? 1 : block_width-1;
  double *boundary = dir == LEFT ? left_edge : right_edge;
  for(int j = 1; j <= block_height; j += 2)
    left_edge[j/2] = (u[index(x,j)]   + u[index(x+1,j)] +
                      u[index(x,j+1)] + u[index(x+1,j+1)]) / 4;
}
else if (dir == UP || dir == DOWN){
  int y = dir == UP ? 1 : block_height-1
  double *boundary = dir == UP ? top_edge : bottom_edge;
  for(int i = 1; i <= block_width; i += 2)
    boundary[i/2] = (u[index(i,y)]   + u[index(i,y+1)] +
                     u[index(i+1,y)] + u[index(i+1,y+1)]) / 4;
}

Or if the second is more inclined I would recommend just clear comments to show the intention of each variables meaning.

Also in the future adapting to more c++ style arrays (vectors), utilizing a c++ Matrix library, or making your own iterator (boundary iterator) would make for a very nice solution to this problem.


Passing Row Index of TableViewCell (custom) to another view controller

There are several problems with your code.

First, you should use more descriptive names for your instance variables/properties.

 @interface firstViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

Class names in Cocoa are conventionally named with a prefix in capitals followed by the name of the class in TitleCase.

 @property NSMutableArray *MasterRecords;   //  Each element in Array is dictionary.

Names of instance variables and properties should be in camelCase.

    static NSString *columnIdfer = @"items";
StudentCell *cell = (StudentCell *)[tableView dequeueReusableCellWithIdentifier:columnIdfer];
if ( cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StudentCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

You should register the nib of your cell before using your table view. This eliminates the need for instantiating a cell yourself every time it's need, and also does away with if (cell == nil), as dequeueReusableCellWithIdentifier: will always return a valid cell, provided you set the table view up properly. Proper code with these things in mind would be:

- (void)viewDidLoad
{
    [super viewDidLoad];
    . . .
    [self.tblMasterTable registerNib:[UINib nibWithNibName:@"StudentCell" bundle:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StudentCell *cell = (StudentCell *)[tableView dequeueReusableCellWithIdentifier:@"items"];
    . . .
    return cell;
}

- (IBAction)btnSubmitPressed:(id)sender {
    NextViewController *sVC = [[NextViewController alloc]     initWithRecIndex:@"NextViewController" bundle:nil Index:self.iRecordIndex];
    // Pushing NextViewController to NavigationViewController.
}

Following the MVC pattern, your view should know nothing about your controllers. You could reimplement the above using a view controller as the cell's delegate, passing a suitable identifier in a suitable method. The delegate view controller could then manage instantiating and presenting/pushing other view controllers.

- (id)initWithRecIndex:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  Index:(NSInteger )iRecIndex;

Several problems with this. You're specifying the return type as id, but I assume it always returns a NextViewController. As suggested in the comments, current practice is to use instancetype as the return type instead of id. For more information on id vs instancetype check this answer out.

You do not attempt to make a distinction between RecIndex and Index in the method name. The argument names do not match what the method name tells us. The implementation of this method doesn't help matters.

-(void) viewWillAppear:(BOOL)animated
{
//Get FistViewController.   say  ==> fvc.

NSMutableArray *mRec = [fvc MasterRecords];
NSMutableDictionary *mDict = [mRec objectAtIndex:self.iRecordIndex];

NSLog (@" value1 is %@ ", [mDict valueForKey:@"value1"]);
NSLog (@" value2 is %@ ", [mDict valueForKey:@"value2"]);

// Using value1, and value2 to display MKMapView.
}

Inconsistent spacing. Make up your mind about how you want to space out your method implementations/declarations and use that style consistently throughout your code.

CodeReview does not appreciate pseudo-code. Please post all relevant bits of code.

Again, instance variables are badly named. Use more descriptive names.

This view controller should not know much about it's presenting view controller.

It should declare properties for the information it needs to get from its presenting view controller. The presenting view controller can then set these properties up after instantiating but before presenting this view controller.

NextViewController *vc = . . .;
vc.mRec = . . .;

[self.navigationController pushViewController:vc animated:YES];

Or in the prepareForSegue: method if using storyboards.


* {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font: bold 15px Arial, sans-serif;
    }

You should avoid the * if possible. The issue with * is that it affects all elements on the page, yours or otherwise. Consider using normalize.css to make default element styling consistent in a non-destructive manner.

.keys,
.top

For this app, this looks fine. Putting this on another page with existing markup, you can potentially clobber other styles (or get yours clobbered) because the class names are too generic. Also, very specific CSS (nested selectors) increase specificity. CSS written like this isn't easy to override. Consider using BEM naming scheme instead. It allows you to construct low-specificity selectors as well as make them meaningful.

transition: all 0.2s ease;

Assuming you can CSS3 or don't care about older browsers. The problem with all is that it applies to all. If you happen to change another property which also happens to be transitionable, this can catch you off guard. Consider specifying the specific property to transition.

window.onload = function() {

Nothing wrong here. Just wanted to point out that window.onload is probably the very last event to fire during the page load process. It also fires only after all images have loaded, which can take very long. Consider usign DOMContentLoaded event instead.

    clear.onclick = function() {
      result.innerHTML = '';
    };

One issue I see when doing handlers this way is that what if you want to add more handlers. Simply assigning a function to the event would only assign one at a time. In times where you want more handlers, this can be tricky. Use addEventListener instead.

var numbers = document.getElementsByTagName('span');
var result = document.querySelectorAll('.result')[0];
var clear = document.getElementsByClassName('clear')[0];

querySelectorAll has a single-element counterpart: querySelector. Use that for single-element returns. And while you're at it, you can forget the getElementsByTagName and getElementsByClassName, use querySelector and querySelectorAll for consistency. Performance losses are negligible in this case.

for (var i = 0; i < numbers.length; i += 1) {
  if (numbers[i].innerHTML === '=') {

= isn't a number. You should probably remove it from the numbers collection to avoid complexity in the code. Treat it like your clear.

Also, consider converting numbers to a proper array. This is possible using Array.prototype.slice.call(numbers). This way, you can easily use the forEach method to loop through the elements instead of constructing a fiddly for loop.

result.innerHTML = eval(result.innerHTML);

This can be tricky, not because eval is very powerful (that's a different issue), but because you're allowing execution of an arbitrary expression that may be interpretted very differently by JavaScript. One example is mentioned in the comments, where the numbers may be treated as octal. 011 + 2 isn't 13 but instead, 9 + 2 which is 11.

Since you are not separating the numbers explicitly anywhere for us to use parseFloat on each one to get the correct number representation, consider building a simple expression parser.


COMpatible+ Google+ Integrations+ Scoping+

In COM_GetLoginStatus,
you can get rid of the if (scopes == "") by incorporating it in case "all" in the switch:

        case "":
        case "all":
            googlePermissionScopes |= GooglePermissionScopes.All;
            break;

This is probably good to move to a constant declared at the top of the file where it's easy to see:

string endpoint = "https://accounts.google.com/o/oauth2/auth?";

If the values in GooglePermissionScopes have distinct bits,
then instead of this:

    if ((googlePermissionScopes & GooglePermissionScopes.OpenID) == GooglePermissionScopes.OpenID)

You could write simpler like this:

    if ((googlePermissionScopes & GooglePermissionScopes.OpenID) > 0)

But then again, I'm not familiar with GooglePermissionScopes so I don't know if this is correct, or acceptable.

It's not clear what magic number 6 is about here:

        if (endpoint.Length > 6)
        {
            endpoint += "%20";
        }

It would be good to make that clear somehow, at the minimum with a comment.

As @Heslacher pointed out, endpoint is initialized to a string longer (much longer) than 6 characters, so this condition is completely pointless.

This can be written simpler using +=:

    endpoint = endpoint + "&state=" + state;

This can be similarly simplified,
and "&response_type=code" + "&client_id=" can be joined:

endpoint = endpoint + "&redirect_uri=" + CallbackUrl + "&response_type=code" + "&client_id=" + ClientId + "&access_type=offline";

As for your question:

  I'm not sure if I should be using a StringBuilder here or not, since it's not a looped string concatenation.

Since it's not in a loop, I doubt the performance difference would be measurable. I think it doesn't matter. It's fine to keep it simple.

You wrote URL-encoded strings at multiple places, for example %20 and https%3A%2F%2F.
Writing this by hand is error prone, and a PITA.
It would be better to write in human-readable format,
and call a url-encoder method at the end.
Granted, the current approach is better in terms of "performance",
but again, it's probably not measurable and not worth it.


Optional argument for which None is a valid value

I would argue the best option is to make an explicit sentinel value for this task. The best option in a case like this is a simple object() - it will only compare equal to itself (aka, x == y only when x is y).

NO_DEFAULT = object()

def item_by_index(iterable, index, default=NO_DEFAULT):
    ...

This has some semantic meaning, and means there is no potential overlap between a value a user wants to give and the default (I imagine it's highly unlikely they'd want to use Ellipses, but it's better to make as few assumptions as possible about use cases when writing functions). I'd recommend documenting it as such as well, as it allows the user to give a default/not using a variable, rather than having to change the call.

try:
    default = get_some_value()
except SomeException:
    default = yourmodule.NO_DEFAULT

item_by_index(some_iterable, index, default)

As opposed to having to do:

try:
    default = get_some_value()
except SomeException:
    item_by_index(some_iterable, index)
else:
    item_by_index(some_iterable, index, default)

The only downside it's not particularly clear what it is if you are looking at the object itself. You could create a custom class with a suitable __repr__()/__str__() and use an instance of it here.

As of Python 3 enums have been added - the default type of enum only compares equal on identity, so a simple one with only the one value would also be appropriate (and is essentially just an easy way to do the above):

from enum import Enum
class Default(Enum):
    no_default = 0

Thanks to metaclass magic, Default.no_default is now an instance of a Default, which will only compare equal with itself (not 0, by default, enums are pure).