Mapping elements of nested list over values in a Python dict

You can use the dict.get(key, default) method to provide a default value instead of catching an Exception. This makes your computation a single expression, which is good for further inlining:

for elem in window:
    index = model.vocab.get(elem, unk).index
    window2index.append(index)

Which can be rewritten as:

window2index = [model.vocab.get(elem, unk).index for elem in window]

Which is faster in Cpython, and fairly straightforward.

Now, of course, you have a similar pattern for sent, and a similar pattern for input:

input2index = [EXPR-USING-sent for sent in input]

sent2index = [EXPR-USING-window for window in sent]

window2index = ... see above ...

So you can stack them all together as:

unk = model.vocab['unk']
input2index = [EXPR-USING-sent for sent in input]
return input2index

which becomes:

unk = model.vocab['unk']
input2index = [[EXPR-USING-window for window in sent] for sent in input]
return input2index

which becomes:

unk = model.vocab['unk']
input2index = [[[model.vocab.get(elem, unk).index
                for elem in window]
                for window in sent]
                for sent in input]
return input2index


Given an array of integers, return the smallest positive integer not in it

That's a nice simple solution, with two problems:

It will give incorrect result when A contains all the values in the ranges [1..1000000] or [1..999999], returning undefined instead of 1000001 and 1000000, respectively.
It doesn't meet the time complexity requirement, being \$O(n^2)\$ instead of \$O(n)\$.

The first problem is easy to fix by adjusting the end condition of the loop.

The second problem is trickier, and the interesting part of the exercise.
Consider this algorithm, that's \$O(n)\$ in time and \$O(1)\$ in space:

Loop over the elements of A from the start, and for each value A[i], if A[i] - 1 is a valid index in the array, then repeatedly swap A[i] and A[A[i] - 1] until A[i] is in its correct place (value equal to i + 1), or A[i] and A[A[i] - 1] are equal.

This should order the values to their right places such that A[i] == i + 1, when possible

Loop over the elements again to find an index where A[i] != i + 1, if exists then the missing value is i + 1
If the end of the loop is reached without returning a value, then the missing value is A.length + 1.

Here's one way to implement this in JavaScript:

var firstMissingPositive = function(nums) {
    var swap = function(i, j) {
        var tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    };

    for (let i = 0; i < nums.length; i++) {
        while (0 < nums[i] && nums[i] - 1 < nums.length
                && nums[i] != i + 1
                && nums[i] != nums[nums[i] - 1]) {
            swap(i, nums[i] - 1);
        }
    }

    for (let i = 0; i < nums.length; i++) {
        if (nums[i] != i + 1) {
            return i + 1;
        }
    }
    return nums.length + 1;
};

Note: to verify this, or alternative implementations work,
you could submit on leetcode.


Class for typecasting an Activity to an interface

It seems to me like what you have done here is to create an entire class to avoid duplicating one line. (Or OK, 5 lines if counting the try-catch statement)
I don't agree with the need to create a class for this. Especially not a generic one, since this line of code:
return (OtherType) whatNeedToCast;

Does the same thing as:
return OtherType.class.cast(whatNeedToCast);

So all you are doing additionally is to wrap it in another exception which is explained just slightly better. But personally, I think this message...

com.yourpackage.YourActivity@1df59a42 must implement com.yourpackage.SomeListener

...actually says just as much as the default one, if you would not catch the exception in the first place:

java.lang.ClassCastException: Cannot cast com.yourpackage.YourActivity to com.yourpackage.SomeListener

Actually, Cannot cast (class) to (class) would say even more if you would override the toString method in YourActivity.
If you are writing these classes to be used as a library by many other people, then it could be good practice to explain that the activity must implement some interface. Otherwise, I don't see the point of it. But either way, there's no need to create an entire class for this.
Summary:
Get rid of your additional class, just cast your activity to SomeListener and don't catch the exception to throw your own.
So in the end, all that remains is this one line:
listener = (SomeListener) activity;

And it's perfectly OK to duplicate that.


Because this is an attempt to answer an interview question, let's assume a hypothetical interviewer then asked you,

what would happen if I called your function using the following code:
...
char mylongstr[] = "This is my long string with lots of character.";
inPlaceReverseString(mylongstr, 7); // should reverse "This is"
cout << '"' << mylongstr << '"';
cout << " has " << strlen(mylongstr) << " characters\n";
...

It would print,
"i sihT" has 6 characters

That doesn't seem to make sense. Not only that, your function potentially clobbered the rest of my string, by writing \0 over the s in the word is.
Don't break expectations/convention with strings
@koblas mentioned to use the standard library function strlen().
strlen() returns the number of characters, not including the terminating \0 character, in the string passed to it. C and C++ string handling functions that take a count parameter generally expect that count refers to the number of characters to work on.
But the size parameter to inPlaceReverseString() breaks that expectation. I think you're overthinking the C-style string's terminating \0 character.
For interview questions (as well as coding in general), start with the simplest thing that can work and meets the specifications
Note that the interview question you quoted said, "write code to reverse a C-Style String", not "write code to reverse a specified number of characters in a C-Style String". For an interview-type question like this, rather than pass the length of the string as a parameter, just discover the length of the string within your function:
void inPlaceReverseString(char str[])
{
    for (int i = 0, int j = strlen(str) - 1; i < j; ++i, --j) {
        std::swap(str[i], str[j]);
    }
}

Note also that I slightly changed the loop-terminating logic, by checking i < j. This makes the logic a bit easier to read, making it obvious that when the indexes i and j pass each other, there's no more replacement to be done.

Now, if you still want to have a length parameter (or are asked to extend the simple answer I wrote above), a couple suggestions:

Use a parameter name such as num, len, or even n, as opposed to size. This is really pedantic on my part, but size tends to suggest memory sizes, as opposed to length of strings or number of characters.

Use size_t as the type of the length parameter. This is an unsigned type, and conforms with the rest of C-style string functions that have a length/number parameter.

Don't write a terminating \0 after the in place reversal.

Even if a length is specified, you should still check for a terminating \0 character within the string.

So, a possible implementation of the answer would look something like:
void inPlaceReverseString(char str[], size_t num)
{
    int len = strlen(str);
    if (len < num) {
        // length of 'str' is less than 'num'. How to handle? ...
    }
    for (int i = 0, int j = strlen(str) - 1; i < j; ++i, --j) {
        std::swap(str[i], str[j]);
    }
}

Now, the original hypothetical question asked by the hypothetical interviewer at the start of this answer would work:
...
char mylongstr[] = "This is my long string with lots of character.";
inPlaceReverseString(mylongstr, 7); // should reverse "This is"
cout << '"' << mylongstr << '"';
cout << " has " << strlen(mylongstr) << " characters\n";
...

would print:
"si sihT my long string with lots of character." has 47 characters


Project Euler # 20 factorial digit sum in Python

The standardlibrary module math already contains a factorial function. On my machine it is about 20 times faster than your function using n = 100. It also does not suffer from stack size limitations as yours does (try computing fact(3000)).

Alternatively you could learn about memoizing, which will help you in many Project Euler problems. Here it would be useful if you had to evaluate the factorial of many numbers (and even better if the numbers are increasing).

from functools import wraps

def memoize(func):
    cache = func.__cache = {}

    @wraps(func)
    def wrapper(*args, **kwargs):
        key = args, frozenset(kwargs.items())
        if key in cache:
            ret = cache[key]
        else:
            ret = cache[key] = func(*args, **kwargs)
        return ret
    return wrapper

@memoize
def fact(n):
    ...

Note that this decorator only works if your arguments are hashable (so no lists for example).

Since getting the sum of the digits of a number is something you will regularly need for Project Euler problems, you should make it a function on its own, which you put in a utils module, to be reused later:

def digit_sum(n):
    """Return the sum of the digits of `n`"""
    return sum(map(int, str(n)))

This will also be faster than your manual for loop or a list comprehension. Not by much, but it is measurable for very large numbers:

def digit_sum_list_comprehension(n):
    return sum(int(x) for x in str(n))

def digit_sum_for(n):
    total = 0
    for digit in str(n):
        total += int(digit)
    return total


I would do

supply_kpi = self.browse(cr, uid, ids, context=None)[0]
group_by = [col_map[key] for key in col_map if getattr(supply_kpi, key)]

Iterating with list comprehension is much more efficient.
You don't build iteritems list of tuples.


Copy an Entity With Navigation Property in C#

It appears that _equipments.AsNoTracking().FirstOrDefault gets some objects that have a unique ID

When you _uow.MarkAsAdded(newAsset, _userManager.GetCurrentUserId()); that collection requires unique ID. You go through round about way to to create a new ID so that you don't get a conflict.

Same thing for both Asset ID and Schedule ID.

All this is doing is assign a new unique ID.

Schedule newSchedule = new Schedule();
Guid scheduleId = newSchedule.Id;
newSchedule = row;
newSchedule.Id = scheduleId;

newSchedule is a reference to row so  newSchedule.Id = scheduleId; is just assigning a new ID to row

It someone is reading that different please comment.

It appears you changing code to get rid of error messages without fully understanding the code and objectives.


Refactor specs for service class methods

Use let (or let!) to set up your fixtures instead of the instance variables.

let!(:app)        { create :app, name: "Marketing", id: 76 }
let!(:question1)  { create :question, content: "Some super question?" }
let!(:question2)  { create :question, content: "Some extra question?" }
let!(:with_app1)  { create :question, content: "Some super question?", app: app }
let!(:with_app2)  { create :question, content: "Some extra question?", app: app }

Use subject (in combination with let). Here are some examples:

describe "#results" do
  subject { Search.new(keyword, [app_id]).results.map(&:content) }

  context "existing app_id" do
    let(:app_id) { 76 }

    context "multiple matches" do
      let(:keyword) { "Some" }

      its(:size) { should == 2 }
      it { should include(with_app1.content) }
      it { should include(with_app2.content) }
    end

    context "single matches" do
      let(:keyword) { "extra" }

      its(:size) { should == 1 }
      it { should include(with_app2.content) }
    end

    context "no matches" do
      let(:keyword) { "hiper" }

      it { should be_empty }
    end
  end

  context "non-exisiting app_id" do
    let(:keyword) { "some" }
    let(:app_id)  { 123 }

    it { should be_empty }
  end
end

You will end up with more code if you follow this through, but also with more and finer grained examples (each it or its block is a single example).


Reduce Complexity, Follow SRP
In both this question and the Binary Search Tree in C++ struct definitions have been embedded within the class definitions. This goes against good object oriented programming principles, specifically the Single Responsibility Principle. One of the basics of object oriented programing is to be able to reuse objects in multiple programs. Each object should be defined separately so that one builds up a library of objects/files that can be reused. In C++ a struct is a class where all members are public, since they are classes they should be defined on their own.

In this program it would be better if there be three header files and possibly two source files, one for Graph and one for Vertex. Vertex may not need a C++ source file since it is fairly simple. The color class also deserves it's own header file. In the Binary Search Tree question Node should be defined separately from BinaryTree.

You might also want to look into SOLID programming principles (the S is the Single Responsibility Principle).

The Single Responsibility Principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

  Robert C. Martin expresses the principle as follows:
          A class should have only one reason to change.

While this is primarily targeted at classes in object oriented languages it applies to functions and subroutines well.

Inconsistent Indentation
The contents of the struct Vertex are not indented and they should be.

Inconsistent Naming Conventions
The naming of variables and functions is inconsistent, there are well named functions and variables such as adjMatrix, addEdge(), id and color, and then there are names such as V and DFS(). It might be better to name V as verticyCount or maxVirtecies and DFS() as depthFirstSearch().

Inconsistent Initialization in Constructors
The constructor for Vertex uses C++ initialization for it's variables, but the Graph constructor does. It might be better if Graph was written as :

Graph::Graph(int v)
: V{v}
{
    adjMatrix.resize(V, std::vector<int>(V));
    for(int i = 0; i < V; i++)
    {
        vertices.push_back( Vertex('A'+i, Color::WHITE));
        for(int j = 0; j < V; j++)
        {
            adjMatrix[i][j] = 0;
        }
    }
}

Please note that the call to std::vector.resize() is not necessary in this constructor. C++ implementations generally include a base allocation of memory for constructors and as the vector grows or shrinks, resize will be called implicitly. Also note that operators such as + should be separated by spaces to make the code more readable.

        vertices.push_back(Vertex('A' + i, Color::WHITE));

In the initialization of Vertex, braces should be preferred to parens:

    Vertex(char c, Color clr) : id{c}, color{clr} {}

The use of parens is supported for backwards compatibility on some C++ compilers, however, it is obsolete.

The two other answers concerns about the DFS() function are valid, you can find a fast working Breath First Search recursive implementation in the KnightMovesImplementation.cpp file, function bool KnightMovesImplementation::CalculatePath(KMMove CurrentMove) in this question.


Prof's transcribed code has weaknesses

#include<stdio.h>

int main(){
    int n;
    while(scanf("%d",&n)==0 || n <2 || n >20){
        while ( getchar () != ’\n’);
        printf( "Wrong. Try again\n");
    }
    printf ( "%n\n",n);
    return 0;
}

Infinity loop

When input is closed after a scanf("%d",&n) == 0, getchar() can eventual return EOF before '\n' and thus while ( getchar () != ’\n’); never ends.

Smart quotes

’\n’ vs. '\n'.  Transcription problem or is that in the original?  In any case, the posted code was certainly not compiled.

Invalid specifier

"%n" does not print the int value.  It is undefined behavior as "%n" matches an int *.

    //printf ( "%n\n",n);
    printf ( "%d\n",n);

Requirement weakness

"Ask the user a number between 2 and 20" is a classic ambiguity.  Depending on perspective are 2 and 20 acceptable or not?  Better to provide more detail

"Ask the user a number, inclusively, between 2 and 20" or the like.

OP code has issues too.

#include <stdio.h>

int main()
{
    int number = -1;
    printf("Enter a number in range [2,20]\n");
    scanf("%d", &number);
    while (number < 2 || 20 < number)
    {
        while (getchar() != '\n')
        {
        }
        printf("Try again\n");
        scanf("%d", &number);
    }
    printf("Your number was: %d", number);
    return 0;
}

Failure to check input return value

scanf("%d", &number); may have failed due to non-numeric text input.  Check the result.

// scanf("%d", &number);
if (scanf("%d", &number) == 1) Success();
else Fail();

Infinite loop

OP's code suffers same potential infinite loop on end-of-file

// while (getchar() != '\n') { }
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) { }

Also check scanf() return value.

Functional difference

With non-numeric input, Prof's code tries again.  OP's code, which does not evaluate the return value of scanf(), technically leads to trouble on rare input error.  On input error, the value of number is indeterminate. See comment

The 2 locations to take user input is simply twice the amount of code that needs checking.  Better to take input from 1 call.  Production code would have a get_int() to handle this.  Something like getint()

  but is there a benefit to his method?

OP's' code does have an informative prompt.

Else not much, both need work.  Perhaps

// untested code
#include<stdio.h>
#define MIN_N 2
#define MAX_N 20

int main(void) {
  int cnt;
  int n;
  printf("Enter a number in range [%d,%d]\n", MIN_N, MAX_N);
  while((cnt = scanf("%d",&n)) == 0 || ((cnt == 1) && (n < MIN_N || n > MAX_N))) {
    int ch;
    while ((ch = getchar ()) != '\n' && ch != EOF) {
      ;
    }
    printf( "Wrong input. Try again\n");
  }
  if (cnt == 1) printf ( "%d\n",n);
  return 0;
}

Better code would read a line into a string and process the input with strtol().


I think what you want to do is:

Get the product URL
Find the Ads with that product URL
Use each Ad URL to find the relevant AdStatus object
Update each AdStatus object

This can be done by chaining the operations with the $resource.$promise

.factory('StatusSetter', ["AdStatus", "Product", "Ad", "$q"
                          function(AdStatus, Product, Ad, $q)
{
    var changeStatus = function(id, newStatus, newValue){
        var filteredAdsList = [];
        var product = Product.get({product_id: id});
        product.$promise.then(function(productObj) {
            //chain product status change
            return productObj.changeStatus(newStatus).$promise;
        }) .then (function (productObj) {
            //wait for product status to finish change
            //chain Ad query
            return  Ad.query().$promise;
        }) .then (function (adsObj) (
            //push filtered list
            angular.forEach(adsObj, function (iAd)) {
                 if (iAd.product == product.url){
                     filteredAdsList.push(iAd);
                 }
             };
            //chain adStatus query
            return AdStatus.query().$promise;
        }) .then (function (adStatusObj) {})
            //start with empty promise
            var qPromise = $q.when();
            angular.forEach(adStatusObj, function (iAdStatus) {
                angular.forEach(filteredAdsList, function(jAd) {
                     if (iAdStatus.ad == jAd.url){
                         //add to promise chain
                         qPromise = qPromise.then (function() {
                             var nextPromise =
                                iAdStatus.changeStatus(newValue).$promise;
                             return nextPromise;
                         });
                     };
                });
            });
            //return promise chain
            return qPromise;
        }) .then (function () {
            console.log("all status updated")
        })
        return product;
    };
    return {
        change: function(id){
            return changeStatus(id, "new_status", 30);
        }
    }
}])

By returning data and promises and chaining those promises, you can create code that uses asynchronous APIs in a way that looks familiar.

For more information on the AngularJS $q service and chaining promises see  AngularJS $q Service API Reference - chaining promises

Also notice that I used angular.forEach for iteration. For more information on using angular.forEach see the AngularJS angular.forEach API Reference.


Display a number as a product of its prime factors

Don't include <bits/stdc++.h> - it's not standard, and on platforms that provide it, it drags in far too much.

Don't using namespace std - this namespace is not designed for wholesale inclusion, and can produce subtle bugs when its names overload your own.

Don't use a floating-point number such as 1e7 when you want a simple integer 10'000'000.

Don't compute std::sqrt(x) every time around the loop - save the value as an integer for faster comparisons.

Use unsigned types for unsigned arithmetic.  Given that inputs (and therefore factors) are no greater than 10⁷, we can get away with std::uint_fast32_t rather than long long.

Although the code claims to use a sieve, every input number is inefficiently tested for primality without reference to the sieve (multiple times, even).

Why use a std::vector rather than std::array for something whose size is constant and known at compile time?  Also, why write the size in two places (which need to be consistent) instead of simply using Primes.size()?  (Also, fix the off-by-one error where we overstep the end of the vector).

I recommend using C++ streams, rather than mixing C buffered I/O and forcing the two libraries to repeatedly flush each other.

Avoid global variables - Primes can be a local static member (perhaps with an immediately-executed lambda expression as initializer).

Why not always include 1 as the first result, rather than have to add that in the printing code?

To dive in to one function in particular, let's pick on least_prime_factor().  Apart from the misleading name, we're doing a lot more work than we need to here.  Every time around the loop, we're multiplying i by j (a good compiler will hoist the three i*j into a single computation, and reuse that), but we could simply be adding i each time.

A standard improvement to naive sieves is to observe that every multiple of a prime p that's less than p² also has smaller factor than p, so once we've marked p, we can jump straight to p² before striding by p thereafter.

Apart from the first pass (which marks even numbers), we can stride by 2 p each time (knowing that we've already marked even numbers).  We can take that further with a wheel of factors, but even this is reducing the work by a factor of two.

Let's see what we have now:

// Create an array populated with the smallest prime factor of each
// number, or 0 for primes (and unity).
void least_prime_factor()
{
    Primes[1]=1;
    // First, mark all the even numbers; this allows us to halve the
    // work for all other primes.
    for (std::size_t i = 2;  i < Primes.size();  i += 2) {
        Primes[i] = 2;
    }

    for (std::size_t i = 3;  i < Primes.size();  ++i) {
        if (Primes[i]) { continue; }

        Primes[i] = i;
        for (std::size_t j = i * i;  j < Primes.size();  j += 2 * i) {
            if (!Primes[j]) {
                Primes[j] = i;
            }
        }
    }
}

That's noticeably less work, and if we also replace prime() with a simple lookup in Primes[], then we'll have a much more efficient program.


First off, when posting a question, try to give it some natural IDE formatting if you can. this improves readability and you're more likely to get more/better answers!
Code
Technically, you can call
$_SERVER["REQUEST_METHOD"] == "POST"

however, my personal preference is just
isset($_POST)

I find that's it's easier to understand and is more intuitive.
This first two conditions encompass basically the entire function. Why not just reduce them to be negative and return false?
Such as
if (!isset($_POST['action']) or $_POST['action'] != 'login') {
    return FALSE;
}

It's reduces unnecessary nesting. Apply the same for if ($_SERVER["REQUEST_METHOD"] == "POST").

if (!isset($_POST['user']) or $_POST['user'] == '' or !isset($_POST['password']) or $_POST['password'] == '')

could be simplified to
if (!isset($_POST['user'], $_POST['password']) or empty($_POST['user']) or empty($_POST['password']))

It's just easier to read.

In your minimum time check between form submissions, you've added an else, but because the initial condition would return false, an else is completely unnecessary. It also nests your code one more layer, which isn't too great if it can be avoided.

$user = test_input($_POST['user']);

The variable here is very ambiguous. I suggest calling something more appropriate such as $username or something that describes what the value is.

hash('sha512', $passtemp . $user);

This not as secure as it could be! First off, if your PHP version supports it, I suggest you use bcrypt instead of hash. It take scares of the salting for you, so that you don't use bad salts such as you have. The salt should typically be a long string composed of random characters. Not just a username.

if ((isset($_SESSION['session_id'])) and (checkSessionID($user)))

Why so many parentheses! It just makes things unclear!

$_SESSION['password'] = $password;

It's generally bad practice to store a password in any place but the database.
This condition returns true, again the else after this is not needed. Remove it to reduce nesting.

Overall, you're on your way, but there's a lot that could be improved.

Your code is strictly procedural which is becoming less and less
neccessary.

Your code is reinventing something that doesn't need to be made
again.

Your code is hard to read and understand. Partly because of all the nesting you have (which is easy to avoid with an OO design). Here's an article about arrow code written by StackExchange's very own Jeff Atwood.

There're hundreds of frameworks and community run scripts that do the logging in/out for you. Don't think that using one of these is limiting you or making your coding skills worse.
If you insist on using this code, it will suffice, but it will be hard to maintain and expand...


I think even the simplest solutions can and should be made modular and SOLID. Let's try to refactor your game to give you an idea how to begin...

We start with a city. A city can have different squares where a square is just a simple character/symbol.

class City : IEnumerable<Square>
{
    private readonly List<Square> _squares = new List<Square>();
    public void Add(Square square)
    {
        _squares.Add(square);
    }
    public IEnumerator<Square> GetEnumerator() => _squares.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

Each square has a position and a symbol. It's abstract so we can derive more concrete types from it.

abstract class Square
{
    protected Square(string symbol, int x, int y)
    {
        Symbol = symbol;
        X = x;
        Y = y;
    }
    public string Symbol { get; }
    public int X { get; }
    public int Y { get; }
    public override string ToString() => Symbol;
}

You seem to have two types currently. A building and a street so here they are:

abstract class Square
{
    protected Square(string symbol, int x, int y)
    {
        Symbol = symbol;
        X = x;
        Y = y;
    }
    public string Symbol { get; }
    public int X { get; }
    public int Y { get; }
    public override string ToString() => Symbol;
}

interface IUpgradable
{
    void Upgrade();
}

abstract class Building : Square, IUpgradable
{
    protected Building(string symbol, int x, int y, int level)
    : base(symbol, x, y)
    {
        Level = level;
    }
    public int Level { get; private set; }
    public void Upgrade()
    {
        Level++;
    }
    public override string ToString() => "O";
}

class School : Building
{
    public School(int x, int y, int level) : base("H", x, y, level) {}
}

class Hospital : Building
{
    public Hospital(int x, int y, int level) : base("S", x, y, level) {}
}

class Street : Square
{
    public Street(int x, int y) : base("#", x, y) { }
    public override string ToString() => "#";
}

Buildings can be upgraded thus the Upgrade method which increases its level. Each upgradable type implements the IUpgradable interface then so you can even filer on that.

I don't know how you generate your map but for the sake of this example I did it by hand:

Here's a simple city:

// ###
// #H#
// ###
var city = new City
{
    new Street(0, 0), new Street(1, 0),new Street(2, 0),
    new Street(0, 1), new Hospital(1, 1),new Street(2, 1),
    new Street(0, 2), new Street(1, 2),new Street(2, 2),
}

Next we want to upgrade some buildings (I might have the condition for upgrading wrong but it should just demostrate the general idea)

Random r = new Random(seed);

// helper encapsulating the can-upgrade logic
var canUpgradeBuilding = new Func<Building, bool>(b => b.Level <= r.Next(0, 100));

// upgrading buildings
foreach (var b in city.OfType<Building>().Where(canUpgradeBuilding))
{
    b.Upgrade();
}


A simple dictionary will do once you get the idea ;)

def get_neighbor(r, c, i, neighbors):
    if (r, c, i) in neighbors:
        return neighbors[(r, c, i)]

    if i == 'N':
        return (r - 1, c)
    elif i == 'S':
        return (r + 1, c)
    elif i == 'E':
        return (r, c + 1)
    else:  # 'W'
        return (r, c - 1)

def link_neighbors(r, c, neighbors):
    north = get_neighbor(r, c, 'N', neighbors)
    south = get_neighbor(r, c, 'S', neighbors)
    east = get_neighbor(r, c, 'E', neighbors)
    west = get_neighbor(r, c, 'W', neighbors)

    neighbors[(*north, 'S')] = south
    neighbors[(*south, 'N')] = north
    neighbors[(*east, 'W')] = west
    neighbors[(*west, 'E')] = east

def main():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        N, R, C, r, c = map(int, input().split())
        instructions = input()  # string of N, S, E or W
        neighbors = {}

        for i in instructions:
            link_neighbors(r, c, neighbors)
            r, c = get_neighbor(r, c, i, neighbors)  # new position

        print('Case #{}: {} {}'.format(case, r, c))

main()


Generate Random String and Writing to File

It's the repeated calls to file.length() that is slowing you down.

Let's try this

while (file.length() <= 1e+7) {
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
}

On my machine that took ~51s.

Now let's try this:

for (int length = 0; length <= 1e+7; length += 39) {
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
  writer.write("abcdefghijkl");
  writer.write("\n");
}

Approximately 0.3s. And a quick sanity check:

$ du -h Hello.txt
9.6M    Hello.txt

There's a problem with the original method, which is the interaction of file.length() and using a buffered writer. Let's try to write up to 400 bytes:

while (file.length() <= 400) {
  writer.write("abcdefghijkl");
  writer.write("\n");
}

We actually end up with a lot more because of the buffered writer:

$ du -b Hello.txt
8203    Hello.txt

A similar problem is also present in the method presented here: we end up writing 403 bytes, not because of buffering but because of how we're counting. If you want to be precise about the total file size, you will need to modify it.


Python sprinting game using strings, loops and statements

Your code is very straightforward, which is good.

Use a conditional for printing values that don't exist yet

At the very top of your code, you are setting these two variables to default values:

high_score = 50
name = "no-one"

To me, it seems that your reason for this is so that, a few lines later when you are printing these values, you have some data to print.

However, since this is not actual data that means nothing for the user and you are using it as a placeholder, you can use a conditional when printing these messages:

if name == "":
    ... print high score ...

Then, you can set the default values to:

high_score = 0
name = ""

However, this would require later that you ensure that the user does not enter their username as "".

Store high score

Along with that above tip, what you could also try doing is storing the high score data. You don't need some file format. In fact, you could handle your own special type.

Here could be an example high score save/data file:

50
D.C.

where the first line has the completed time, and the second line has the user who achieved that time.

Then, in your script, you can simply read from the high score file.

Remove nesting

In your while distance < 100 loop, you have quite a few levels of nesting. While the code in there isn't too complicated, it still is a bit harder on the eye.

To improve readability, try to keep everything on the same level (without breaking indentation rules):

while distance < 100:
    k = msvcrt.getch().decode('ASCII')
    if k != 'a':
        continue

    k = msvcrt.getch().decode('ASCII')
    if k != 'd':
        continue

    distance += 1
    if distance == 50:
        print("* You're halfway there!")
    elif distance % 10 == 0:
        print('*')

Note: I merged the two k1 and k2 variables into one since the k1 one is no longer needed when k2 is being checked.


Stack implementation in C++ including min(), max() functions in O(1)

I'm going to answer your direct questions first.

  Are there any potential memory management issues?

No. You don't do any manual memory management (using new and delete) so there are no issues.

  Any additional methods that would be useful (also, from educational
  point of view) to implement?

Here is the reference page for std::stack. This is the standard library documentation. You may not be able to do them all right now but those are all possible functions and members you could implement for a stack. (I recommend only trying a little bit at a time.

I'd like to point out that your code is very clean and easy to read. I also appreciate good use of const correctness.

Use unique include guards

#ifndef STACK_H
#define STACK_H

This is a very basic name. It would be easy for others to use a very similar name. Make your includes unique. Add a namespace name, a project name, a library name and possibly a GUID or all of the above to eliminate the risk of clashes.

Use the right headers

#include <iostream>
#include <memory>
#include <vector>
#include <stdexcept>

You don't use <memory> or <iostream> in your class. You don't use <stdexcept> until the cpp file. declare the header there.

You are missing <limits> for :std::numeric_limits<>

List public members first

Anyone using your stack is only going to be able to use the public member functions. It is common practice therefor to list these first.

Avoid the use of this->

It is almost always wrong to have this-> in your code in C++. For example this:

if (this->empty())

can simply be written:

if (empty())

The exception to this rule is with variable shadowing (which you don't have) which is also typically solved with a name change.

Always ask: What does this feature serve?

So you implemented a min() and max(). You did it with an O(1) lookup by having every single element keep track of the current min and max value of the entire stack. This is a problem on two levels:

Your nodes should not contain information on other nodes. That breaks encapsulation. This is the job of the Container.
And its also useless information. There is one accessible node. What value do you gain by knowing what the min and max values beneath that one are? how can you even act on that even if you knew?

If you have your heart content on keeping the min() max() then at least store the value in the container. In addition to being good practice it will also take significantly less memory.

Lastly When you are ready you should look into Template Metaprogramming. A Container / Data Structure like this needs to be usable with any type, including user defined types, in order to be truly useful/robust.

Edit: to answer point brought up in comments

The problem as I see it is the fact that you need to store state, which a stack is great for. If I needed to maintain current, min, and max values like you are, I would put them all into a struct like so:

struct State
{
     int current_value;
     int min_value;
     int max_value;
}

Then I would use a stack that supports user-defined types. std::stack<State> state_machine.

Furthermore by maintaining min() and max(), in the node or in the container, if you do decide to extend your container to support user-defined types you will force your users to overload the comparison operators for their type even if there is no logical way to do so and it isn't otherwise needed.


A for statement can have an else clause which suits your needs perfectly and allows you to eliminate the variable hidden. I would also prefer a simple if instead of the if pass elif construct:

for num in cell.getAvailNum():              # For each available number for the cell we are looking at
    for tempCell in colCells:               # For each cell in the list of cells
        if tempCell != cell and num in tempCell.getAvailNum(): # If one of the available num is the same
            break
    else:
        cell.setAvailNum(num)               # If hidden is still true, set available num to num
        break


This looks pretty good IMO. If you are considering taking these values to the database, make sure you create a separate table for each category. Do not use enum type columns.

However there are few minor things I noticed that you can refactor.

Initialize $constCacheArray as an array so you can avoid the first 3 lines in getConstants()
isKeyExist method can be a single line

public static function isKeyExist($key) {
    return (isset(self::getConstants()['_' . $key]);
}

getValue method has similar logic too but for readability's sake you can keep it as it is.
Avoid method calls inside loops. Take $user->getCountry() out of the foreach and assign it to variable which you will use for comparison.
Also to remove the _s from the keys you can use a regex. If you plan to use string keys for enums (eg: const disabled = 'Disabled';), this will come in handy.

json_decode(preg_replace('/"_([0-9]*)":/i', '"$1":', json_encode($arr)), true)


Here are some suggestions and remarks, in no particular order:

i is not a great name for a variable in most cases, and especially not when it's not short for "index", as is the case in your draw_sequence function. I would suggest naming it direction.
The official Python PEP8 style guide states that class names should be CamelCased, so your class should be named DragonCurve, without the underscore.
There's no point in making self.seq an instance/member variable, since it's only used by the create_seq function and its value is reset on each call. It can safely be turned into a local variable.
Stick to using the LEFT/RIGHT constants instead of 'l'/'r'.
One small improvement that you could make is replacing your empty strings "" with a constant named EMPTY_SEQUENCE. This would completely hide the fact that sequences are represented as strings from the reader, and would make it easy for you to change the representation if you would ever want to.
Function names should be verbs, so opposite is not a good name for a function. Perhaps something like "flip" or "invert" would be more suitable.
The parameter named str will shadow the built-in function str. This is generally not a good idea, so maybe it should be named seq or sequence, since that is actually the abstraction that the function operates on.


Iter 1: Reusable, robust c++ std::hash for GMP's big integer type

Answers to your questions

In MurmurHash3_size_t(), I check SIZE_MAX to tell whether I'm on a 32 bit system or a 64 bit system. Does this check make sense, are there alternatives which are better?

I think it's not worth it to write a generic version of this that avoids checking SIZE_MAX, even though that is possible. Machines with a different size_t size than 32 or 64 bits are uncommon, unless you're talking about 8 and 16 bit machines, but I'm assuming you are not interested in using bigints on those.
But don't forget to #include <cstdint>, otherwise SIZE_MAX might not be defined! Alternatively, use sizeof(size_t) == 4 and == 8, in combination with if constexpr (...) instead of #if ....

Near the end of the file hash_mpz.cpp, I have the statement return hash<mpz_srcptr> { }(x.get_mpz_t());. Does this create an object of type hash<mpz_srcptr> for every calculated hash value?

Technically, yet. But those objects don't have any member variables, just a member function operator(), which is resolved at compile-time, so there is no need to worry about inefficiencies here.

I'm not sure whether I'm using the references const mpz_class &x and const mpz_t &x in the most efficient way. This is partly due to GMP being a C library, mpz_t is a 1 element array with element type __mpz_struct and mpz_class being something rather obscure to me.

Using const references to the objects is perfectly fine.

Last but not least, do you see anything else which can be improved?

Yes, see below.
Your functions don't handle negative bigints correctly
As it mentions in the excerpt from gmp.h you posted, _mp_size will be negative for negative bigints. You need to handle this. One way would just be to write:
return MurmurHash3_size_t(..., abs(x->_mp_size) * sizeof(mp_limb_t), ...);

However, this means that for a given positive number, that number and its negative will get the same hash value. It may or may not be an issue for your application. One possible solution is to use a different seed value for negative numbers.
Consider using std::hash to calculate the hash
Yes, you can use std::hash instead of implementing your own. Of course, you need to pick an appropriate existing specialization std::hash. You could iterate over the limbs in the bignum, which are either 32 or 64 bit integers, so you could std::hash those individually, but then the questions is how to combine them. Just adding or XORing them might not result in a good final hash value if there are any patterns in the input. But in C++17, there is a specialization of std::hash for std::string_view. So you can create a view for the limb array, and hash that:
size_t hash<mpz_srcptr>::operator()(const mpz_srcptr x) const {
    std::string_view view{reinterpret_cast<char *>(x->_mp_d), abs(x->_mp_size) * sizeof(mp_limb_t)};
    return std::hash<std::string_view>{}(view);
}

There is a good chance that the standard library's hash function for strings is a variant of MurmurHash, see for example this question.
Use the appropriate cast operator instead of C-style casts
You should use static_cast<>() if possible to cast similar types, so the compiler will be able to generate an error if you are doing incorrect casts. For example:
size_t hash<mpz_t>::operator()(const mpz_t x) const {
    return hash<mpz_srcptr>{}(static_cast<mpz_srcptr>(x));
}


Max function with variable number of arguments

I think this function is unnecessary.

We can deal with defective classes (that don't properly implement the standard LessThanComparable concept) by either fixing them (preferable) or by providing a comparator argument to std::max:

auto const b_lessthan = [](const B& a, const B& b){ return !(a>=b); };

std::max({B{}, B{}, B{}, B{}, B{}}, b_lessthan);

Sure, you could make a generic adapter using the same if constexpr chain as in this code, but are the defective types really that common?

We can arrange for std::max() to return an lvalue by passing it an initialiser list of std::reference_wrapper for its arguments:

template<typename... T>
constexpr auto& ref_max(T... args)
{
    return std::max({std::ref(args)...,}).get();
}

We now have

#include <algorithm>
#include <functional>
#include <cassert>

int main()
{
    static_assert(std::max(1, 2) == 2);

    int a = 1;
    int b = 5;
    int c = 3;
    int d = 2;

    assert(std::max({a, b, c, d}) == b);

    ref_max(b, c, d) = 4;

    assert(b == 4);

    // This gives a compilation error because the static assertion failed
    // (void)std1::max(A{}, A{});

    // This works
    auto const b_lessthan = [](const B& a, const B& b){ return !(a>=b); };

    std::max({B{}, B{}, B{}, B{}, B{}}, b_lessthan);
}

Which isn't so very different than the main() in the question.


Using standard library to simplify pairwise iteration of container values

It would be possible to write as for_each call to a functor writing for_each again, but I don't think it would actually be shorter.

I don't think pair_wise is a good name. There are two many things that it could mean. I'd suggest something with combinations as it calls the function for all 2-combinations.


You have a surprise bug: what happens when I do page.php?Name=EBrown? Well $_GET is not empty but your page_number sure isn't set.

That said, you should be doing something like the following:

$page_number = 1;

if (isset($_GET["page_number"})) {
    $page_number = $_GET["page_number"];
}

or

$page_number = $_GET["page_number"];

if (!isset($page_number)) {
    $page_number = 1;
}

The first defaults and then checks for the parameter, the second checks if it's set then defaults. Take your pick.

But those still don't handle invalid (non-numeric) input, so we can do that as well:

$page_number = $_GET["page_number"];

if (isset($page_number) === FALSE || is_numeric($page_number) === FALSE) {
    $page_number = 1;
}

Now we safely default to 1 when page_number is not set, or when it's not numeric.

Of course, we still have another bug: what happens if page_number is 1.12? That's probably unintended. So, we'll check for that as well:

$page_number = $_GET["page_number"];

if (isset($page_number) === FALSE || strpos($page_number, '.') !== FALSE || is_numeric($page_number) === FALSE) {
    $page_number = 1;
}

And finally we'd extract that to a method:

function defaultInt($intValue, $default) {
    if (isset($intValue) === FALSE
        || strpos($intValue, '.') !== FALSE
        || is_numeric($intValue) === FALSE) {
        return $default;
    }

    return $intValue;
}

$page_number = defaultInt($_GET["page_number"], 1);

Easy to use in the future as well.


Getting a hash string for a very large file

Well, MD5 is considered to be mostly cracked, and should be avoided.  But anyway…

The comma in except IOError, e is considered deprecated.  except IOError as e is preferred since Python 2.6, and required in Python 3.x.

I don't think that your code is inefficient.  It certainly doesn't read the entire file into memory at once.  A larger chunk size wouldn't hurt.  I think that 8192 bytes would be reasonable: it's approximately a memory page on some machines and approximately the size of a jumbo frame.

I think it would be stylistically beneficial to separate the file-reading code from the hash-calculating code using a generator.  Alternatively, using mmap wouldn't be a bad idea.

def read_chunks(file_handle, chunk_size=8192):
    while True:
        data = file_handle.read(chunk_size)
        if not data:
            break
        yield data

def md5(file_handle):
    hasher = hashlib.md5()
    for chunk in read_chunks(file_handle):
        hasher.update(chunk)
    return hasher.hexdigest()

try:
    with open(sys.argv[1], 'rb') as f:
        hash_string = md5(f)
except IOError as e:
    log.error(…)


No, rule of thumbs for this case:

Never guess optimizations, use a profiler
You're not smarter then the JIT compiler

Loop unrolling only makes sense if you profiled the code and found the unrolled version to be faster then the normal version.

I guess you're coming from a C background, so please don't try to bring C-habits to Java. Java is different, always go for readability first.

public void HanningFilter(float[] array) {

The Java naming conventions dictate that function names are lowerCamelCase.

Also the name array is a bad name, more appropriate would be a name like data or input.

int len = array.length;
int i;
for (i = 2; i < len-3; i+=3) {

What you're doing here is absolutely unnecessary. Java allows declarations of variables inside the for and there's no need to define a variable for the condition.

for (int idx = 2; idx < data.length; idx++) {

Naming loop variables idx or counter is not very famous, I prefer it to i.


A couple of remarks:

You should check the return value of scanf. It returns the number of items successfully converted. You initialize n with 0 so any invalid input will yield in a single 0 output but it might be good to indicate failure anyway.
Using EXIT_SUCCESS and EXIT_FAILURE are more portable ways to indicate success/failure upon return to the OS.
256 is is not representable by an 8-bit type. The binary representation is 1 0000 0000 - so the 9th bit is set. An 8 bit unsigned type can only hold 0 - 255.
Multiplying an integer by a power of 2 can be done by a left-shift. So 2^5 for example is 1 << 5 - this eliminates any need for multiplication or even invoking pow.
You print out the order of bytes in big endian notation (the highest ordered byte is printed out with the smallest index) while for example x86 is a little endian architecture where the lowest ordered byte has the smallest index. Actually scratch that. The data in memory is laid out little endian so your code will print it in little endian order.
Your size detection works on the assumption that a char is 8 bit. This is not guaranteed by the C standard which requires CHAR_BIT to be at least 8. For example there DSPs where CHAR_BIT is 16 and in the past there were architectures with 9 and 12 bit bytes.
Your size detection only goes up to 4 bytes however unsigned long long is 8 bytes on many platforms. So if someone puts a large number in the it will simply omit the upper 4 bytes.

In the end the size detection can be generalized by finding which byte is the most significant byte - which boils down to finding the most significant bit (the highest bits which is 1). There are a bunch of clever operations to make this really fast but the simplest is to shift right until all set bits are shifted out:

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

int main(void)
{
    unsigned long long n = 0;
    unsigned long long temp;
    int most_significant_bit = 0;
    int most_significant_byte = 0;
    int i;

    printf("Enter a number: ");
    if (scanf("%lld", &n) != 1)
    {
        printf("Invalid number entered.");
        return EXIT_FAILURE;
    }

    temp = n;
    while (temp >>= 1)
    {
        ++most_significant_bit;
    }
    most_significant_byte = (most_significant_bit / CHAR_BIT) + 1;

    for(i = 0; i < most_significant_byte; i++)
    {
        unsigned char* p = (((unsigned char*)&n) + i);
        printf("byte(%i) : %i\n", i, *p);
    }

    return EXIT_SUCCESS;
}


Check before proceeding if the task in BackgroundWorker has completed

You can use ManualResetEvent to wait until background work is done. So, you can define in LoginForm as:

private static ManualResetEvent mre = new ManualResetEvent(false);

When background work is completed, you should change the state of mre from the thread method bw_DoWork and update appStatus:

mre.Set();

btn_login_Click should wait for mre instead of while loop:

mre.WaitOne();

The complete code:

public partial class LoginForm : Form
{
    private static BackgroundWorker bw = new BackgroundWorker();
    private static ManualResetEvent mre = new ManualResetEvent(false);

    enum status
    {
        Blank,
        Success,
        Error
    };

    public LoginForm()
    {
        InterimProceedings();
        InitializeComponent();
    }

    private void InterimProceedings()
    {
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

        if (!bw.IsBusy)
        {
            bw.RunWorkerAsync();
        }
        else
        {
            throw new InvalidOperationException("BackgroundWorker is busy");
        }
    }

    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
      //  Time taking task
      //  Update appStatus
      appStatus = status.Success;
      mre.Set();
    }

    private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (!(e.Error == null))
        {
            this.lbl_status.Text = "Cannot proceed, Error occured";
            appStatus = status.Error;
        }
        else
        {
            this.lbl_status.Text = "Good to go...";
            appStatus = status.Success;
        }
    }

    private void btn_login_Click(object sender, EventArgs e)
    {
        mre.WaitOne();

        if(appStatus == status.Success)
        {
            // Proceed with intended work
        }

        else
        {
            // Pop-up error occurred
        }
    }
}

The check against e.Error on bw_RunWorkerCompleted should change for clarity:

if (e.Error == null)
{
    this.lbl_status.Text = "Good to go...";
}
else
{
    this.lbl_status.Text = "Cannot proceed, Error occured";
}

I can't probe this code right now... I hope it's ok.


Sorting an integer array using heap sort

Why do you need to pass the length of an array to buildMaxHeap?

private static void buildMaxHeap(int[] arr, int len) {

The functions itself can just use find the length property itself because it is getting the actual array from function parameters.

However, I still believe that it was smart idea to check that i was less than len, which was the length of the array rather than just checking if i was less than the length the array because it is unnecessarily efficient to constantly access the length property of an array.

Here is what I mean:

private static void buildMaxHeap(int[] arr) {
    // any nodes after n/2 are leaves node and could be without children
    int len = arr.length;
    for (int i = (len) / 2; i >= 0; i--) {
        // bubble up to build max heap
        bubbleUp(arr, i, len - 1);
    }
}

All of your functions (except main) are very cluttered up with comments. I recommend that you add JavaDoc to all these functions and include as much explanation as you need up there.

That way, if there any confusions about something in a function, the answer can be found above the function, rather than in the function.

This line of heapSort

System.out.println("Sorted Array : " + Arrays.toString(arr));

is confusing in two ways:

You are printing the same message in main so I don't see why you are doing it again here.
This method is for "heap-sorting" an array, not for sending output to the user. If possible, all input and output should be done inside main.

Note: This may not apply, but you didn't include the class definition so I do not know.

I recommend calling this class HeapSort, and then having a single static public method called sort that takes a single array and "heap-sorts" it.

That way, if you are writing other code that needs to "heap-sort" an array, you can use the HeapSort class and call it's sort method to sort it. This will make your code more organized.

Here is what I mean:

public class HeapSort {
    public static void sort(int[] arr) {
        [heapSort code]
    }

    ... your other private methods...
}

Now your code is more organized and is ready to be used by another class.

Here is how you would use the HeapSort class and it's sort method:

HeapSort.sort(myIntArray);


I see three major problems with your code:

You dont use PHP 7 type hinting / return types
You dont have any scopes on your methods
If you wont modify your classes in the future and/or you wont extend from these classes you should use final for your class declarations
you should always set declare(strict_types=1); at the beginning of every php script as long as there are no veeeery good reasons to avoid it. It will force you to write your code more typesafe or you will get fatal errors

I will give you an example for each point i mentioned

1. "You dont use PHP 7 type hinting / return types"

Before:

function push($item) {

After:

function push(int $item): void

2. You dont have any scopes on your methods

Before:

function getItem() {

After:

public function getItem(): void

3. class declaration as final

Before:

class QueueNode

After:

final class QueueNode

Sidenote:

Also you should use properties like private $item = null; instead of your constructor setting. Your IDE and also any other maintainer will have trouble finding bugs and/or understanding this code.


Looking at register(), the format is as following:

def register():
    if request.method == "POST":
        if request.form['register'] == 'Register':
            stuff()
    return render_template("register.html",pageType=['register'])

This can easily be condensed using and:

def register():
    if request.method == "POST" and request.form['register'] == 'Register':
            stuff()
    return render_template("register.html", pageType=['register'])

Also, you are not inserting whitespaces between arguments.

stuff(3,3)  # <--Unconventional
stuff(3, 3) # <--More conventional

Another stylistic issue is some of your lines are too long. For all lines, line.length <= 79. You can read about the specific python conventions on the Python website.
For making it look less messy and repetitive, look at this answer to a Stack Overflow question. It is about implementing switch and case statements into Python, which seems perfect for your situation.


Why (if it is correct) when I use Netbeans PHP that it doesn't pick up the functions? See images below.

As you don't declare types in PHP, Netbeans has no way of knowing that $db is a PDO object. But you can tell Netbeans this:

/* @var $db PDO  */
private $db = null;

For further ways to Type-hint for PHP in Netbeans check out this post I wrote a while ago.

  Is this the correct way of using OOP and classes (mainly the DB connection)?

I would pass the PDO object to the user class in the constructor instead of using global.

It looks cleaner, and it would make writing unit tests a lot easier as well (you could pass a connection to a test database without changing the code or mock the PDO class). It also has the neat side-effect that you are able to define the type and thus enable auto complete.

Misc

classes should start with an upper-case letter (User).
is_int($ID) == TRUE can be written as is_int($ID).
I find it a bit odd that you return false for wrong parameters, but not for an unsuccessful delete in deleteUser.
checking empty has the effect of not deleting the user with id 0. Is this on purpose? If yes, I would make this explicit ($id != 0), if no, just remove it, it doesn't do anything else that is_int wouldn't cover.

So I would probably rewrite it like this:

class User { // upper-case U
    private $db = null;

    public function __construct(PDO $db) { // defining a type allows for auto-complete and makes testing easier
        $this->db = $db;
    }

    public function deleteUser($ID) {
        if(!isset($ID) || !is_int($ID)) { // no need to check empty. if needed, add $ID != 0
            return FALSE; // wrong parameters, return early
        }
        $deleteUser = $this->db->prepare("DELETE FROM `users` WHERE userid=?");
        $deleteUser->bindParam(1, $ID, PDO::PARAM_INT);
        return $deleteUser->execute(); // returns true on success, otherwise false

    }
}


Recursive program for generating and printing all permutations of the numbers 1, 2, ..., n for given integer number n

Single responsibility principle
Think about the possible reuse of your code. More specifically, the permute method. Do you think that the caller will always want to print out the result? Right now storing the permutations in a variable is impossible, so I cannot use this as a building block for bigger programs. What about printResult it does not only print the result, it also takes care of duplicates.
In general each method does many things, even asking for global variables around the class (printResult accesses n)
I would write follow this stub:
public class Permutation extending Array {
    public static Sequence[Sequence[Any]] permutations(Sequence[Any] array) {
        // implementation
    }
}

public class PermutationUptoApplication {
    public static void main(String[] args) {
        int upperLimit = (new Scanner(System.in)).nextInt()
        System.out.println(Range(1, upperLimit).toArray().permutations().join("\n"));
}

You see that I wrote this in pseudo-code, but the main concept is that now you can import the Permutation class from anywhere and call it and reuse the result.
The application class just handles input and output and generates the range of numbers.


Call multiple services from angular2 component

Specify types explicitly whenever it's possible (including void for methods and FindIpZoneDataService for datafetchservice instead of any).
Use const instead of let -- it will help detecting unintended assignments.
Try not to move things around when it's not necessary. E.g. the following section is pushing one array's items into another.

let res: Array<any> = [];
let extattrs: Array<any> = [];
res = response.json();
res.forEach((detail) => {
  extattrs.push(detail.extattrs);
});
return extattrs;

Why do that if simple cast would work? Like this: <T[]>response.json() where <T> is whatever the specific type of the entity returned by the API.

Stylistically, it's better to declare getIPNetwork() before getNetworkDetail() since the code is normally being read top-to-bottom.
When one map() is immediately followed by another map(), they can always be merged into a single one. There is possibility of using flatMap() in addition to that, which would simplify some things but I need better understanding of your context...

getIPNetwork(): void {
    this.datafetchservice
        .getNetwork(this.query)
        .map(response => response.json())
        .subscribe(
            result => this.getNetworkDetail(result[0].network),
            err => this.handleIpServiceError(err) // InValid IP
        );
}

getNetworkDetail(ip: string): void {
    this.networkDetail = [];
    this.dataservice
        .getNetworkDetail(ip)
        .map((response) => {
            return response
                .json()
                .map(detail => new Network(
                    detail['SITE Name'].value,
                    detail['InfoSec Security Zone'].value,
                    detail['Network Security Zone'].value,
                    detail['Data Classification'].value
                ));
        })
        .subscribe(
            details => {
                this.networkDetail = details;
                this.rowCount = true;
                this.searching = false;
            },
            err => this.handleNwServiceError(err) // Valid Network not found
        );
}

extattrs, nwerror, and similar names are meaningless/hard to decipher.
TypeScript just like JavaScript follows camelCase naming convention. Stick to it. I.e. userinputerror should be userInputError, datafetchservice -- dataFetchService, and so on...


$querySQL = "SELECT ";
$parameters = [$datum];
switch ($table) {
    case "quote":
        $querySQL .= "content, author FROM quote WHERE datum = ?";
        break;
    case "birthday":
        $querySQL .= "date, name FROM birthday WHERE datum = ?";
        break;
    case "facts":
        $querySQL .= "content FROM facts WHERE datum = ? AND category = ?";
        $parameters[] = $_POST['categorie'];
        break;
    case "lifehacks":
        $querySQL .= "content FROM lifehacks WHERE datum = ?";
        break;
}
$querySQL .= " LIMIT 10";
$stmt = $connection->prepare($querySQL);
$stmt->execute($parameter);

Perhaps you're looking for something such as this. You had lots of repetition in your code, and so I basically applied the DRY rules to your code. It could still use a lot of work and I'm sure there's other approaches, but this might help you kickstart the process!

Another way to possibly help improve your code would be to separate the logic, database access, and your echos. You've probably heard of frameworks and such, and you might want to start looking into your options. It will keep your code separated, and while maybe not shorter, it will be much neater!


Finding the prime factors of a number in Python 2

(Obligatory) Python 2 is end of life it is advised to upgrade to Python 3.
You should always indent with 4 spaces in Python. This makes it easier for me to read what is inside prime_factors and what is outside of it.
It's common to surround top level functions (prime_factors) with 2 empty lines, and other functions (is_prime, make_p_lst) with one empty line.

Otherwise your whitespace is good. Here is what it'd look like with these fixed.
import math

def prime_factors(y):
    def is_prime(x):
        count = 0
        if x > 1:
            for i in range(2, x):
                if x % i != 0:
                    count += 1
                else:
                    return False
                    break
        else:
            return True
        if count != 0:
            return True
        if x == 2:
            return True

    def make_p_lst(x):
        z = []
        for i in range(2, x):
            if is_prime(i) == True:
                z.append(i)
        return z

    n = y
    c = 0
    c = int(math.sqrt(y) + 1)
    prime_lst = []
    prime_lst = make_p_lst(c)
    p = is_prime(y)
    if p == True and y != 1:
        print '%s is prime.' % (y)
        return 'Thus, its\' only factors are 1 and itself.'
    elif y != 1:
        print '%s is composite, here are its\' prime factors: ' % (y)
        factors_lst = []
        while is_prime(y) != True:
            for i in prime_lst:
                if y % i == 0:
                    y = y / i
                    factors_lst.append(i)
        factors_lst.append(y)
        factors_lst.sort()
        if factors_lst[0] == 1:
            factors_lst.remove(1)
        n = factors_lst
        return n
    else:
        return '1 is neither prime nor composite.'

print prime_factors(871)

You don't need is_prime or make_p_lst to be inside prime_factors. This is making your code harder to read as it's not immediately apparent that you are not using them as closures.

All code after a return will not run. This means the break in is_prime will not run.

Your is_prime function doesn't handle 0 and 1 correctly.
>>> [(i, is_prime(i)) for i in range(6)]
[(0, True), (1, True), (2, True), (3, True), (4, False), (5, True)]

Since it's not already we can change your code to be simpler by removing all the count parts.
Then we can just special case 0 and 1.
def is_prime(x):
    if x <= 1:
        return False

    for i in range(2, x):
        if x % i == 0:
            return False
    return True

In make_p_lst you shouldn't do if is_prime(i) == True instead you should just use if is_prime(i).

In prime_factors you shouldn't do while is_prime(y) != True instead you should just use while not is_prime(y).

We can simplify the code by using a list comprehension. This is just syntactic sugar for building the list as your are now.

You don't need to initialize a value and then assign it.

c = 0
c = int(math.sqrt(y) + 1)
prime_lst = []
prime_lst = make_p_lst(c)

You can just remove the first of each.
c = int(math.sqrt(y) + 1)
prime_lst = make_p_lst(c)

By fixing is_prime we don't need the and y != 1 check.

Getting the prime factors should be put into a function.

Many of your variable names are hard to understand or follow.
You should really use better names than x, i, c, y, etc.
Additionally I prefer using plurals to denote a list of items.
For example the following is much easier to read.
for prime in primes:
    # do something with prime

Because I changed is_prime to make 1 no longer return True, the code to get the prime factors no longer works for 1. However we can fix that by moving the while loop into the for loop.
Then we can merge it with the if.
This has the benefit that we don't have to loop through prime_lst multiple times and we won't call is_prime.

def is_prime(number):
    if number <= 1:
        return False
    for divisor in range(2, number):
        if number % divisor == 0:
            return False
    return True

def primes_below(limit):
    return [number for number in range(2, limit) if is_prime(number)]

def get_prime_factors(number):
    if number == 0:
        return []
    primes = primes_below(int(number ** 0.5 + 1))
    factors = []
    for prime in primes:
        while number % prime == 0:
            number /= prime
            factors.append(prime)
    if number != 1:
        factors.append(number)
    return factors

def prime_factors(number):
    prime = is_prime(number)
    if prime:
        print '%s is prime.' % (number)
        return 'Thus, its\' only factors are 1 and itself.'
    elif number != 1:
        print '%s is composite, here are its\' prime factors: ' % (number)
        return get_prime_factors(number)
    else:
        return '1 is neither prime nor composite.'

print prime_factors(871)

At this point it'd be good to rethink how your code works.
prime_factors sometimes returns the prime factors. However other times it returns a string.
It also prints to the screen which is not helpful if I only want the prime factors.
Your function prime_factors should do no string manipulation.
This means it should return a list of prime factors and only a list of prime factors.

0 would return an empty list.
1 would return an empty list.
2 would return 2.
4 would return 2 and 2.

And so we can see get_prime_factors is what should actually be prime_factors.
And so we can change main to use only get_prime_factors and only print.
Returning from main is not a good idea.
def is_prime(number):
    if number <= 1:
        return False
    for divisor in range(2, number):
        if number % divisor == 0:
            return False
    return True

def primes_below(limit):
    return [number for number in range(2, limit) if is_prime(number)]

def prime_factors(number):
    if number == 0:
        return []
    primes = primes_below(int(number ** 0.5 + 1))
    factors = []
    for prime in primes:
        while number % prime == 0:
            number /= prime
            factors.append(prime)
    if number != 1:
        factors.append(number)
    return factors

def main(number):
    factors = prime_factors(number)
    if not factors:
        print '1 is neither prime nor composite.'
    elif len(factors) == 1:
        print '%s is prime.' % (number)
        print 'Thus, its only factors are 1 and itself.'
    else:
        print '%s is composite, here are its prime factors: ' % (number)
        print factors

if __name__ == '__main__':
    main(871)


I think it is cleaner to handle special cases early; your code winds up less indented.

// converting dom into array to use later
$fields = $dom->getElementsByTagName($field);
$arr['field'] = array();

foreach ($fields as $field) {
  $attributes = isset($field->attributes) ? $field->attributes : NULL;

  if (empty($attributes)) {
    continue;
  }

  $name = !empty($attributes->getNamedItem('name')) ? $attributes->getNamedItem('name')->nodeValue : NULL;
  $id = !empty($attributes->getNamedItem('id')) ? $attributes->getNamedItem('id')->nodeValue : NULL;
  $field_name = !empty($attributes->getNamedItem('field_name')) ? $attributes->getNamedItem('field_name')->nodeValue : NULL;

  if (empty($name) || empty($id) || empty($field_name)) {
    continue;
  }

  $arr['field'][$name][$id][$field_name] = $field->nodeValue;
}

This looks less complicated, at least to me, but it does exactly the same work.

You could also introduce a method to get the nodeValue or NULL, given $attributes and a name.

// converting dom into array to use later
$fields = $dom->getElementsByTagName($field);
$arr['field'] = array();

foreach ($fields as $field) {
  $attributes = isset($field->attributes) ? $field->attributes : NULL;

  if (empty($attributes)) {
    continue;
  }

  $name       = nodeIfPresent($attributes, 'name');
  $id         = nodeIfPresent($attributes, 'id');
  $field_name = nodeIfPresent($attributes, 'field_name');

  if (empty($name) || empty($id) || empty($field_name)) {
    continue;
  }

  $arr['field'][$name][$id][$field_name] = $field->nodeValue;
}


LINQ for extracting N bottom items (async streams)

where TValue : IComparable<TValue>

Don't do this. OrderBy doesn't require its type parameters to implement this interface like this either. Instead it uses the IComparer<T> interface. What's the difference? With IComparable<T>, the implementation of the comparison logic is sitting on the class T itself. This means that there is one and only one way of ordering elements of T. If I wanted to sort them using some customized logic, I would be out of luck.

Instead, IComparer<T> is a separate class that compares Ts. Providing an instance of that interface to the method allows me to use whatever logic I want to order T.

But what if I don't want to implement an entire class, but instead want to use IComparable<T>? This is where Comparer<T>.Default comes to play. This static property provides a default implementation for IComparer<T> for T, which, if T implements IComparable<T>, will default to call that logic.

So how would your interface look? We have an overload with the IComparer<TValue> argument, and an overload without:

public static async IAsyncEnumerable<T> Bottom<T, TValue>(
        this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector, IComparer<TValue> comparer)
{
    return Bottom(source, number, selector, Comparer<TValue>.Default);
}

public static async IAsyncEnumerable<T> Bottom<T, TValue>(
        this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector, IComparer<TValue> comparer)
{
    // Actual implementation.
}

Binary tree

I think this problem would call for a binary tree, instead of a list that's sorted/ranked continuously. This would you can quickly check whether the item you are iterating would even be in the top-number of items in the collection, without having to add and subsequently having to remove it again. The downside is that C# doesn't have a built-in Binary Tree that isn't hidden within the SortedX collection set. These classes sadly require unique values in their collections, which isn't guaranteed here.

Alternatively, if you can handle adding another few lines to your solution, you can check if the index returned by BestIndex is equal to number, and skip adding and removing it from the list if this is the case.

Code style

This needs to be said. Your code is really compact. It took me multiple reads to figure out what on earth BestIndex was actually doing. Docstrings, comments and/or intermediate variables with clear names please. Something as simple as "Returns the rank of value in the list by performing a merge-sort style algorithm." is enough to understand its role in Bottom.


If by simplification you mean optimization, then only one thing came to my mind:

Whenever you find a leaf node, remember its depth in minmalFound variable.
When again you hit the next leaf node you compare its depth with previously remembered node. And save the minimum of both into minmalFound.

And the main logic to add is whenever you are searching a certain path and find out that the depth becomes as great as the existing minmalFound, then you stop searching that path.

Here is code to demonstrate this technique:

public class Solution {
    public static int minDepth(TreeNode root) {
        reccallscount = 0;
        minmalFound = -1;
        if (root == null)
            return 0;
        return recur(root, 1);
    }

    public static boolean doFaster = false;
    private static int minmalFound = -1;
    private static int reccallscount = 0;

    private static int recur(TreeNode root, int depth) {
        reccallscount++;
        if (root == null) return 0;
        if (root.left == null && root.right == null) {
            if (minmalFound == -1) {
                minmalFound = depth;
            } else {
                minmalFound = Math.min(minmalFound, depth);
            }
            return depth;
        }

        if (doFaster) {
            if (minmalFound != -1 && depth + 1 >= minmalFound) {
                return minmalFound * 2;
            }
        }

        int ldepth = recur(root.left, depth + 1);
        int rdepth = recur(root.right, depth + 1);

        // either left or right subtree was not a leaf node
        // ignore non leaf node.
        if (ldepth == 0 || rdepth == 0) {
            if (ldepth != 0) {
                minmalFound = Math.min(minmalFound, ldepth);
            } else if (rdepth != 0) {
                minmalFound = Math.min(minmalFound, rdepth);
            }
            return Math.max(ldepth, rdepth);
        }
        else {
            int value = Math.min(ldepth, rdepth);
            minmalFound = Math.min(minmalFound, value);
            return value;
        }
    }

    public static void main(String args[]) {
        TreeNode root = new TreeNode();
        root.left = new TreeNode();
        root.left.right = new TreeNode();
        root.right = new TreeNode();
        root.right.left = new TreeNode();
        root.right.left.right = new TreeNode();
        root.right.left.right.left = new TreeNode();

        Solution.doFaster = false;
        int min = minDepth(root);
        System.out.println("Minimum " + min + " found with " + reccallscount + " recursive calls");

        Solution.doFaster = true;
        min = minDepth(root);
        System.out.println("Minimum " + min + " found with " + reccallscount + " recursive calls with faster approach");
    }
}

class TreeNode {
    TreeNode left = null;
    TreeNode right = null;
}

In the code above, I created a tree with left side depth = 3 and right side depth = 5.  I ran minDepth() twice; first using your algorithm, and again with my addition. The result is then printed:

Minimum 3 found with 11 recursive calls

Minimum 3 found with 5 recursive calls with faster approach


Concept

I don't believe that there is a cross-platform way to read the ARP cache.  From the use of /proc filesystem, I deduce that you are targeting Linux.  In Linux, you could read /proc/net/arp as you have done, or run the command ip neigh, which does something similar to your program.  (On OS X, you could run arp -a -n instead.)

A comment worth a thousand words

You should include a comment like this in your program:

/**
 * /proc/net/arp looks like this:
 *
 * IP address       HW type     Flags       HW address            Mask     Device
 * 192.168.12.31    0x1         0x2         00:09:6b:00:02:03     *        eth0
 * 192.168.12.70    0x1         0x2         00:01:02:38:4c:85     *        eth0
 */

That picture tells me everything I need to know about what you are trying to accomplish — you need hardly explain further.  Conversely, not having that picture makes me work a lot harder to reverse-engineer your code.

Minutiae

&Buffer[0] is usually written as Buffer.
You repeat the readLine() call — once before entering the loop, once at the end of the loop.  This is a good opportunity to make use of C's support for side-effects.

while (0 == (Ret = readLine(Fd, Buffer))) {
    …
}

Since ARP_CACHE is a compile-time constant string, you can just write

fprintf(stdout, "Arp Cache: Failed to open file \"" ARP_CACHE "\"\n");

instead of doing a %s substitution at runtime.
Reading one byte at a time is wasteful.
Print errors to standard error; don't contaminate standard output.
I suggest naming your variables to be consistent with the /proc/net/arp header fields.  For example, device instead of IfaceStr.  Also, be consistent with capitalization: count starts with lowercase, which is more common.

Big-picture issues

The function int readLine(int Fd, char *Buffer) is kind of susceptible to buffer overflow.  I can deduce that fact from the function signature: you pass a pointer to a buffer without also passing the size, so it seems unlikely that readLine would know how to stop when the buffer fills up.  You could hard-code it to use ARP_BUFFER_LEN as a limit, but it would be unfortunate to cripple an otherwise generic function like that.  It would be better to pass in the buffer size explicitly.  That's a general pattern you'll see in C APIs: a pointer to a buffer is frequently accompanied by the buffer's size.

In practice, /proc/net/arp should never contain a line long enough to overflow a 1024-byte buffer, so you're safe.  Still, you should follow idiomatic C conventions.
Once you modify readLine() to take a size parameter, you'll find that you've just reinvented fgets().
In C, passing strings from a function to its caller is usually avoided, since it involves malloc(), which introduces the potential for memory leaks.  Rather, have the caller pass a buffer and size, like how fgets() and scanf() work.

The only good reason to return a string that was allocated using malloc() would be to support arbitrary-length results.  At first glance, your getField() accomplishes that, as it allocates a buffer as large as strlen(Line_Arg).  (You forgot to add a byte to accommodate the terminating NUL character, by the way.)  But, that turns out not to be the case, since Line_Arg itself is not a string of arbitrary length.  It's either less than ARP_BUFFER_LEN bytes long (if you got "lucky") or a buffer overflow (as discussed in (1) above).
You seem to be working very hard at I/O and string processing.  Why not just use fscanf()?

The whole program, then, can be simplified to

#include <stdio.h>

/**
 * Macros to turn a numeric macro into a string literal.  See
 * https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
 */
#define xstr(s) str(s)
#define str(s) #s

#define ARP_CACHE       "/proc/net/arp"
#define ARP_STRING_LEN  1023
#define ARP_BUFFER_LEN  (ARP_STRING_LEN + 1)

/* Format for fscanf() to read the 1st, 4th, and 6th space-delimited fields */
#define ARP_LINE_FORMAT "%" xstr(ARP_STRING_LEN) "s %*s %*s " \
                        "%" xstr(ARP_STRING_LEN) "s %*s " \
                        "%" xstr(ARP_STRING_LEN) "s"

int main()
{
    FILE *arpCache = fopen(ARP_CACHE, "r");
    if (!arpCache)
    {
        perror("Arp Cache: Failed to open file \"" ARP_CACHE "\"");
        return 1;
    }

    /* Ignore the first line, which contains the header */
    char header[ARP_BUFFER_LEN];
    if (!fgets(header, sizeof(header), arpCache))
    {
        return 1;
    }

    char ipAddr[ARP_BUFFER_LEN], hwAddr[ARP_BUFFER_LEN], device[ARP_BUFFER_LEN];
    int count = 0;
    while (3 == fscanf(arpCache, ARP_LINE_FORMAT, ipAddr, hwAddr, device))
    {
        printf("%03d: Mac Address of [%s] on [%s] is \"%s\"\n",
                ++count, ipAddr, device, hwAddr);
    }
    fclose(arpCache);
    return 0;
}


Maybe it is intentionally(?):

I would expect CurrencyToInt(234.567m, "USD") to return 23457, but it returns 23456?

Instead of the rather unclear if-statements it is more readable with a switch:

public static int CurrencyToInt(decimal amount, string currencyCode)
{
  var precision = 0;

  currencyCode = currencyCode?.ToUpperInvariant();

  switch (currencyCode)
  {
    case "BHD": case "IQD": case "JOD": case "KWD": case "LYD": case "OMR": case "TND":
      precision = 3;
      break;
    case "AED": case "AFN": case "ALL": case "AMD": case "ANG": case "AOA": case "ARS": case "AUD": case "AWG": case "AZN": case "BAM": case "BBD": case "BDT": case "BGN": case "BMD":
    case "BND": case "BOB": case "BRL": case "BSD": case "BTN": case "BWP": case "BZD": case "CAD": case "CDF": case "CHF": case "CNY": case "COP": case "CRC": case "CUC": case "CUP":
    case "CZK": case "DKK": case "DOP": case "DZD": case "EGP": case "ERN": case "ETB": case "EUR": case "FJD": case "FKP": case "GBP": case "GEL": case "GGP": case "GHS": case "GIP":
....

As stated in the comments the whole thing can be boiled down to 3 lines of code, if you use the framework:

public static int CurrencyToIntByCulture(decimal amount, string currencyCode)
{
  CultureInfo culture = new CultureInfo(currencyCode);
  int precision = culture.NumberFormat.CurrencyDecimalDigits;
  return (int)(amount * (decimal)Math.Pow(10, precision));

  // Or?: return (int)Math.Round((amount * (decimal)Math.Pow(10, precision)));
}

But culture.NumberFormat.CurrencyDecimalDigits returns different numbers of decimals for certain cultures, so maybe you have special needs?


Finding top most N common character grams in English

Building up on Caleth's answer:

Beware that:

def ngrams(N, word):
    for i in xrange(len(word) - N):
        yield word[i:i+N]

will not account for the last character:

for g in ngrams(3, "small"):
    print(g)

will output

sma
mal

If it was the purpose of the strict parameter to allow to include/skip the last character (and be able to print the missing all), you can use it that way:

def ngrams(N, words, strict=True):
    last = int(strict)
    for i in xrange(len(word) - N + last):
        yield word[i:i+N]

If, however, you wanted to allow to generate n_grams whose length is lower than N:

def ngrams(N, words, strict=True):
    last = N - 1 if strict else 0
    for i in xrange(len(word) - last):
        yield word[i:i+N]

As per the documentation, FreqDist accepts generators in its constructor. It is thus more memory efficient to turn the n_grams list into a generator:

n_grams = (ngram for ngram in ngrams(N, word) for word in get_words())

Your top comment would be most suited as a docstring for the m_most_common_ngram_chars function. In fact, each function might need its own docstring.
Since almost all your code is functions, you may want to put your last two lines into the module check if __name__ == "__main__":. It will allow you to run your code from the command line as usual and it will do exactly the same thing; but also to import it and call the function with other parameters without running anything at import time.

from nltk import FreqDist
from nltk.corpus import gutenberg

def get_words():
    """generate english words from the whole gutemberg corpus"""
    for fileid in gutenberg.fileids():
        for word in gutenberg.words(fileid):
            yield word

def ngrams(N, word, strict=True):
    """generate a sequence of N-sized substrings of word.
    if strict is False, also account for P-sized substrings
    at the end of the word where P < N"""

    last = N - 1 if strict else 0
    for i in xrange(len(word) - last):
        yield word[i:i+N]

def m_most_common_ngram_chars(M=5, N=3):
    """gets the top M most common substrings of N characters in English words"""
    f = FreqDist(ngram for ngram in ngrams(N, word) for word in get_words())
    return f.most_common(M)

if __name__ == "__main__":
    # Uses the default values M=5, N=3
    print m_most_common_ngram_chars()


public boolean inCircle(int mouseX, int mouseY) {
    if (distanceFromCenterOfCircle(mouseX, mouseY) <= CIRCLE_RADIUS) {
        return true;
    }

    return false;
}

Can be

public boolean inCircle(int mouseX, int mouseY) {
    return distanceFromCenterOfCircle(mouseX, mouseY) <= CIRCLE_RADIUS;
}

(int)(Math.random() * (getWidth() - CIRCLE_RADIUS * 2));

g.setColor(new Color((int)(Math.random() * 256), (int)(Math.random() * 256), (int)(Math.random() * 256)));

Looks like you could benefit from a function that takes an integer as maximum value... and then returns an integer between 0 and max minus 1.

Which does exist - you'd simply create a new instance of Random and then call randomInstance.nextInt(maxValue).

Lastly, I think you would be better off by renaming the currentCircle variable to amountOfCirclesDisplayed because that's what it really is. currentCircle seems to point to the idea that somewhere, you have a list of circles, and right now, you're working on 1 specific circle. But that's not true, because you HAVE no list of circles and all that really matters is how many you've displayed so far.


Suggestions for optimising this front end code

Style and code

There are several places where you should use const rather than let. Mainly inside the for loops.
The second movingScreens = {} is redundant.
Avoid nesting loops too deeply. Use a function to avoid this.
Don't use for...in as you need to be sure you are not getting properties higher up the prototype chain. Use Object.keys to get the keys and iterate them with a for...of
Avoid long lines by using alias to reference object paths or long names.
The naming is confusing, you have shapes, screens, scrollScreens that seam to be interchangeable
Is this a typo or a really bad name and reference this.animations.screen1IfContainer.current.container.current

Avoid iterating again

You build the object movingScreens then you iterate it again. Would be better to process the items instead of building the object movingScreens.

You use Array.map to create an array of elements, then you iterate that array again. Process the elements as you iterate the first time.

Rewrite

Removed the object movingScreens processing the shapes in the first loop.
Added function scrollScreen to process a (screen, shape, or scroll I can not be sure).
Used aliases to reference long names and paths. currentCont, and screens
All variables are now const
Used Object.keys for safer key iteration.

As there is no way for me to test this code, nor do I have a context (what is what), it may contain typos or logic errors.

animate() {
    const currentCont = this.animations.screen1IfContainer.current.container.current;
    const scrollScreen = shape => {
        for (const scroll of shape.scrolls) {
            const from = scroll.from * this.scrollMax;
            const to = scroll.to * this.scrollMax;
            if (from <= this.scrollTop && to >= this.scrollTop) {
                const styles = scroll.styles((this.scrollTop - from) / (to - from));
                for (const style of Object.keys(styles)) {
                    for(const ref of shape.els) {
                        const el = ref === 'screen1IfContainer' ?
                            currentCont : this.animations[ref].current;
                        if (el) { el.style[style] = styles[style] }
                    }
                }
            }
        }
    }
    if (!this.animationsDisabled()) {
        const screens = scrollAnimationDefs.movingScreens;
        for (const key of Object.keys(screens)) {
            if (key !== 'appsTop' && key !== 'appsBottom' && screens[key].scrolls) {
                scrollScreen(screens[key]);
            }
        }
    }
}

Questions

  \$O(n^4)\$ (I hope that's right, if not please do correct me)

You have not defined n thus its is meaningless to define the complexity.

  Would using functional operators like map and filter improve performance?
  I'd be really interested to see some suggestions to this, and maybe the ideal optimisation for it?

As this is animation these points can not be answered. The slow point is the moving of pixels, this is highly dependent on the device it is running on. The JS code is but a fraction of the workload, you can optimize it till the cows come home and it may not make a spec of difference on the performance of the animation.

Any optimization would require the full animation to see when and where the many GPU  state changes, compositing, and what not can be optimized.

Update

I forgot this line in your question.

  I'd assume const uses a bit less memory than let due to not needing to support re-allocation

If const uses less memory that would be up to the JS engine. I would not use it as a criteria as when to use const or not.

We use const to protect against accidental mutation.
We use let and const to avoid accidentally redefining a variable.
We use const (as with let) to scope the variable to a block. A block is code between { and } The exception is when a variable is defined in a for, do,  or while loop as a const or let it is scoped to the loop block, not to the current block. eg { /*current block a is not in scope */ for(const a of b) { /* a is in scope  loop block*/ } }
We use const to give meaning to constants that are otherwise just numbers or strings in your source code. eg const unit = 1;
Currently chrome, FF, edge give const, let, and var have a slight performance benefit over literals.  eg 1 + 1 is a little slower than one + one with one defined as const one = 1;

Do not rely on this to remain true as engines are constantly changing. The benefit is very small and only an advantage under very specific conditions.


class Graph {
    public int vertices;
    LinkedList<Node> nodes = new LinkedList<Node>();
}

Graph

Graph, as other data structures in general, should be declared
public. Because you want them to be able to be used outside of the
package they are declared in.

nodes, vertices should be private so that you can know that they
are not changed outside the Graph class.

nodes should not be a LinkedList. You must depend on abstractions as
much as possible. You should prefer interfaces such as List over
specific implementations LinkedList.

Nodes of a graph is not a List, it is a Set. A standard graph cannot
have multiple copies of a node. You should prefer a Set to represent a
set unless you have a good reason.

Node

All of the above points also apply to Node. Apart from those:

AdjacenctNode should be named adjacentNode by Java naming
convention.

Feel free to remove parameterless call to super();, although Eclipse
adds it by default, it's just noise.

TopologicalSortGraph

Remove unused code :

TopologicalSortGraph Graph = new TopologicalSortGraph();

Always remove commented code. If you need to see previous versions of a
code use a version control system. :

//public LinkedList<Node> nodes  = new LinkedList<Node>();

Do not put more than one space between tokens, use autoformat of your
IDE to fix formatting after changing a piece of code:

public static void  topologicalSort(Graph graph) {

The snippets :

if(child.inDegree==0){
    q.add(child);
    ++vertexProcessesCtr;
    System.out.println(child.data);
}

and

if(m.inDegree==0){
    ++vertexProcessesCtr;
    q.add(m);
    System.out.println(m.data);
}

are duplicates. They should be extracted to a private method. You are
missing some kind of abstraction there.

You are changing the internals of an object passed in as a parameter:
--child.inDegree; I do not expect my graph to change after I ask to
see its nodes printed in topological order. What if I want to print
them again?

You are mixing the calculation and the printing out of the calculation result,
I do not expect to see printlns in a method implementing an algorithm:

System.out.println( .... );

What if I want the result to be printed somewhere other than System.out?
What if I do not want the result to be printed at all and want it to be
used as an intermediate step in a bigger calculation instead?

You probably want to return a List<Node> from a topological sort
algorithm. List is the standard return type when you are sorting some
collection, that is when the result is a collection whose order is
important. You can then print that list as many times as you want or
pass it as a parameter to wherever you like.

public static void main(String[] args) {

You should separate test code from your main code. If your actual class
is named TopologicalSortGraph put your test code in
TopologicalSortGraphTest.

Use de facto standard JUnit so that instead of one big main you can
have many small tests. You can run any one of them or all of them easily
from within your IDE or from the command line.

You should try to separate the test code into separate source
directories or even into separate projects. Your implementation code
should not need or know about your test code to compile.

Another spacing (indentation) problem :

Node TEN = new Node("10");

Your code should align well. So that it reads neatly top to bottom and
scopes in it are easily identified.

TEN should be ten by Java naming convention.

Instead of these two you should use your addAdjNode method instead:

SEVEN.AdjacenctNode.add(ELEVEN);
ELEVEN.inDegree++;

Also access chains like node.AdjacenctNode.add(otherNode) or x.y.z
are usually a sign that your encapsulation is not good enough. In this
case you are modifying a collection of one class from another class.
It's a problem waiting to happen. Same encapsulation problem is present
in ELEVEN.inDegree++, too.

The root problem here is adjacency is a property of the graph -Remember
G = (V, E) from school?- and not of the nodes themselves. Instead of
node.addAdjNode(otherNode), you should use a method like
graph.addEdge(node, otherNode).

Same problem also exists here: g.nodes.add(TWO); You should have a
Graph.addNode(node) method instead.

Coming back to G = (V, E); it says, if you listen carefully, you need
a set of vertices and a set of edges to have a graph and should not add
nodes one by one. Ideally, Graph would have a constructor like this
public Graph(Set<Node> vertices, Set<Edge> edges).


Remove first occurrence of element from list

That looks mostly right to me. I'll suggest two things.

First, there is nice syntatic sugar for defining functions:

(define (remove-elem xs elem)
    (cond ...)
)

Save yourself the lambda.

Second, you are using eq?. That is the wrong checker for this problem. That function returns true if the two objects are the exact same object in memory. It could be true for primitives like ints, but it's not necessarily true. What you want to use is eqv? which will guaranteed work for numbers.