Include the required headers

You use std::string extensively, but you don't include <string>. This is allowed to work (any standard header is allowed to act as if it includes any or all others), but it's not required to work (and didn't, for me).

Use the proper defaults

Right now, your code defaults to https on port 440, but the normal default for https is port 443. I'd tend to include the port in the result if and only if it's explicitly specified. Otherwise, it's probably better to let the browser sort out the port, since most know quite a few more than your code does.

Fluent Interface

I'm not particularly excited about fluent interfaces in general, but if you're going to use one, I'd prefer to get rid of the set on the beginnings of most of the setters. If you have something like:

auto uri = builder().scheme(HTTPS).domain("www.google.com").build();

...you don't really need a set on the beginning of each to make it apparent what you intend.

Consider unique types for the parts of a URL/URI

I tend to wonder whether we wouldn't be better served by a set of tiny classes, one for each type of element in a URL, with each able to (for example) insert itself to a stream, with the url class basically just a set of those. At least for some of the obvious cases, I'd also at least consider using overloaded operators instead of named functions. For example, a fairly minimalist version might look something like this:

struct protocol {
    enum prot { http, https } p_;

    protocol(prot p) : p_(p) {}

    friend std::ostream &operator<<(std::ostream &os, protocol const &p) {
        switch (p.p_) {
        case http: return os << "http://";
        case https: return os << "https://";
        }
    }
};

struct query {
    std::string k;
    std::string v;
};

class queries {
    std::vector<query> queries_;
public:
    void add(query const &q) { queries_.push_back(q); }

    friend std::ostream &operator<<(std::ostream &os, queries const &q) {
        std::string sep = "?";
        for (auto const & f : q.queries_) {
            os << sep << f.k << "=" << f.v;
            sep = "&";
        }
        return os;
    }
};

class path {
    std::vector<std::string> components;
public:
    void add(std::string const &path) {
        components.push_back(path);
    }

    friend std::ostream &operator << (std::ostream &os, path const &p) {
        for (auto const & s : p.components)
            os << s << "/";
        return os;
    }
};

class url {
    protocol prot_;
    path path_;
    queries q_;
public:
    url(protocol::prot p) : prot_(p) {}

    url &operator/(std::string const &p) { path_.add(p); return *this; }
    url &operator&(query const &q) { q_.add(q); return *this; }

    friend std::ostream &operator<<(std::ostream &os, url const &u) {
        return os << u.prot_ << u.path_ << u.q_;
    }
};

int main() {
    url u = url(protocol::http) / "www.youtube.com" / "watch" & query{"v", "tpnrd0xGRsw"};
    std::cout << u;
}

Note how url's operator<< (roughly equivalent to your build) is now almost trivially simple--and if we add in types for a fragment, port, user name, and so on, it'll remain almost equally trivial, because most of the complexity will be delegated to each of those classes instead of being crammed together into the one giant "build" that knows everything about a URL and how all the pieces need to be delimited and such. Instead, it needs to know the order of the components in a URL, but that's about it. All the details of how to write each piece are delegated to the type for that piece (most of which are individually pretty trivial too).

More syntactic sugar

After some further thought, I've decided that a little more syntactic sugar probably won't rot our teeth too badly. It might be worth adding a couple of tiny functions like this:

url http() { return url(protocol::http); }
url https() { return url(protocol::https); }

This way we can generate a url something like this:

url u = https() / "www.youtube.com" / "watch" & query{"v", "tpnrd0xGRsw"};

Seems a tad cleaner to me, anyway.


Bug
        if (intersects) {
            isSingle = false;
            break;
        }

This looks like a bug. The variable isSingle is already false. Setting it to false here does nothing.
Code Review:
You use std::vector but don't include its header.
    std::vector <Rect> overlaps;

You should fix that.

References and Const correctness.
This is a big part of C++.

If you are not modifying an object, prefer to use reference than making a copy of an object.

Prefer const references over normal references to prevent accidental modification.
for (auto rect_1: detected) {

Here you are making a copy of the object from the array detected into the object rect_1. Personally I would use a const reference to prevent the overhead of a copy:
for (auto const& rect_1: detected) {

The code looks mostly fine:
I think the only bug is here:
            if (rect_1 == rect_2) {
                continue;
            }

This tells you if two rectangles are equivalent not if they are the same rectangle. If you have two distinct but otherwise identical rectangle then by my logic they would overlap and thus not be in the single's list.
So you need a way to determine if these are the same object. Personally I would do that by changing your for loops to use references and then comparing the objects' addresses.
    for (auto const& rect_1: detected) {
              ^^^^^^
        ...
        for (auto const& rect_2: detected) {
                  ^^^^^^
            if ( & rect_1 ==  & rect_2) {
                ^^^          ^^^
                continue;
            }

            test(rect_1, rect_2);

Your other alternative is to make sure you never compare an object with itself. This also brings into mind that you do twice as many comparisons as you need to. You compare every rectangle against every other rectangle. But if A & B overlap then we already know that B & A will overlap.
for(std::size_t loop = 0l; loop <  detected.size(); ++loop) {
    for(auto check = loop + 1; check < detected.size(); ++check) {
        test(detected[loop], detected[check]);

in the code below "...object addresses" -- aren't rect_1 and rect_2 references already? If so, why can't we just do if (rect_1 == rect_2)

No. Because the == is supposed to compare the equality (is the state the same) of two objects. It is not supposed to be a test of equivalence (is it the same object).
Note: You can declare operator== to test if the objects are the same but that would be terrible practice and would cause a lot of issues with people expecting the normal operation. So don't do that. The above statement is said assuming you are following the normal idioms of the language.
I assume you are coming from a Java like background. The term reference in C++ has a different meaning than in Java. A reference means another name for an object (they are not like Java references (which in C++ we would call pointers). So a reference is another name for an object but the test operator== will compare if the two objects' state are the same (not if they are the same object).

Also, if I use auto const&, I would have to change my return type to vector<Rect&>...is that idiomatic? I think the OpenCV API expects vector<Rect>

No. You can pass a reference to the vector and it will copy the object into the vector. You don't want to hold references in a vector.


Algorithm to find the Array Balance Point

First, a suggestion on the interface: use null to represent no match rather than -1, since that makes it easier to force the caller to check for a no-solution case (i.e. if they try to use the unchecked return of this function as an index, a -1 will only fail at runtime, whereas null will fail at transpile time).

function arrayBalance(input: number[]): number | null {

In reading over the code I got confused by the variable names -- mid isn't actually a midpoint, it's the expected sum of each half.  Between all of the variables being declared with let rather than const and the uninformative names (why is there sum and sum2?), it's hard to even tell at a glance which values are being recalculated and which are constants.

Instead of taking six lines of code to find the "half-sum" that we want each side of the "split" to have, let's just do it in one (brevity is the soul of wit, and this kind of thing is exactly what the reduce function is for), and declare it as const since it's not going to change for the rest of the function once we've computed it:

const halfSum = input.reduce((a, b) => a + b) / 2;

From here, all we need to do is find out how many array elements we need to total up to equal halfSum.

Here's how I might write the rest, signifying the running total of the "left" side of the array as leftSum and doing a simple for loop over the array indices:

let leftSum = 0;
for (let i = 0; i < input.length; i++)
{
    leftSum += input[i];
    if (leftSum == halfSum)
        return i;
}
return null;

As we iterate through i we build a sum of everything to the left of i (leftSum).  Our goal is to make leftSum equal halfSum.  If no solution is found within the loop we return null.

It's tempting to use inequality comparisons to try to optimize the no-solution case, but consider cases where the input array has lots of negative numbers distributed randomly!  halfSum could be negative or zero, and leftSum could go up and then down and then up and then down again as you increment i, so unless you've gone through the entire array you can't ever be certain that a solution does not exist.

Note also that it's possible for there to be multiple valid solutions; this implementation will always return the lowest one in that instance, but you could write a version of this function that always goes through the entire array and returns another array of all the solutions it found.


The moment you start copy-pasting code and only changing one small thing, it's time to move that code to a method.

private void CreateAndAddNode(WhateverTypeImagesIndexIs imagesIndex, int x)
{
    var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, imagesIndex, imagesIndex);
    inTreeNode.Nodes.Add(tNode2);
    tNode2 = inTreeNode.Nodes[x];
    AddNode(xNode, tNode2);
}

I'm assuming AnalogImagesIndex etc. all inherit from some base type; that's the one to use as the method's parameter.

Moreover, all of those ifs can be changed to a switch.


You really shouldn't rethrow caught exceptions like that.

catch (Exception ex) //Could I just omit this block?
    {
        throw ex;
    }

Erases the call stack of the exception, instead use

catch (Exception) //Could I just omit this block?
    {
        throw;
    }

However the point is moot, because the try-finally block is syntactically legal, but you should bear in mind a very major caveat (emphasis my own):

  Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up.

As such, it would be a good idea to make sure you catch any exceptions you can reasonably expect, but then that's just standard good practice.

As an aside, I really don't like your use of caps. Type names should be PascalCase, and you should avoid underscores in type names or variable names.

Lastly, you really should throw a subclass of Exception, and never the parent class.


The primary issue I see is that your code is focused on the wrong sort of state. What you have written would be used something like—

iterate (getNextStr (Sequence "abc" 'a' 'c')) "a"

But this is very slow, you can see from the repeated usage of last, (++), and reverse that the actual state that matters (which character is next in the sequence) is getting parsed out of the previous state anew with every iteration. You are relying on repeating many \$O(n)\$ operations, which ends up causing your code to have a terrible constant factor performance hit.

The key insight or trick is to take advantage of lazy evaluation to produce an infinite stream of values which can hide all of the messy state machinery you need away in some thunks.

stringSequence :: [Char] -> [String]

We start with a clean slate and a new type signature. In this case we have a function that takes a sequence of Char values, and returns a list (which we know will be infinite) of String values made by applying the sequence generating procedure to the Chars. The magic obviously happens in the sequence generating procedure, so let's concentrate on that.

stringSequence chars = map (:"") chars

Starting is easy, we simply make a String out of each Char in our given sequence. Next step is to generate the two character Strings.

stringSequence chars =
  let
    strings = map (:"") chars
    front   = strings
    next    = concatMap (\f -> map (f ++) strings) front
  in
    front ++ next

This is the biggest jump I'll make, so make sure you understand it. The two character strings are made by taking each string we've already generated and appending a Char from the sequence to it (for convenience, strings makes it easy to combine previous values generated by the sequence generating function and the next element of the given Chars).

stringSequence chars =
  let
    strings = map (:"") chars
    front   = strings
    next    = concatMap (\f -> map (f ++) strings) front
    after   = concatMap (\s -> map (s ++) strings) next
  in
    front ++ next ++ after

Now we add the three character strings, and notice a pattern. Strings of length \$n+1\$ are made by appending the sequence characters to the strings of length \$n\$. Leveraging this insight and a trick called Tying the Knot, we can write the final version of stringSequence that produces an infinite lazy list of sequenced values.

stringSequence chars =
  let
    strings = map (:"") chars
    sequence = strings ++ concatMap (\s -> map (s ++) strings) sequence
  in
    sequence

Compare this version to your original. The Sequence type you had is now replaced with a simple list. Instead of getNextChar we use the whole sequence in one go so we don't have to perform additional bookkeeping to maintain correct ordering. Rather than parsing the previous result value with getNextStr, we maintain our state hidden away from the user by providing them an infinite list, instead of out in the open where the user has to keep track of it and we have to keep parsing it.


private long _currentMoney = 0;
private long currentMoney
{
    get { return _currentMoney; }
    set
    {
        _currentMoney = value;
        lbCurrentMoney.Text = $@"{currentMoney} $";
    }
}

Looks like the only reason the private properties in this class exist is to update the text of some labels. While this isn't "wrong", it feels awkward, like you're only using the property construct for a convenient side effect. Personally I would rather create a method that updates the private field and sets the label's text, I feel that would be a more appropriate tool for this scenario.

  $@"{currentMoney} $"

You're using the @ symbol for every string. It just adds one more character for my brain to parse and wonder what it's escaping. Don't use it unless it actually makes a difference.

  private Thread countThread = null;

There's no reason (shown in the code, at least) for this to be a member field rather than a local in the single method that actually uses it.

private bool stop = false;
...
while (!stop && currentMoney >= item.RequiredMoney) // executed in another thread

stop should be marked volatile, otherwise the read of the stop variable in the loop could be hoisted out of the loop and only read once, rather than on each iteration.

public MainGame()
{
    InitializeComponent();
    Initialize();
}

Second method could use a better name; the first one is initializing the "component", the other is initializing... what? (It would be fine if only an Initializing method was being called, but with both I think it's confusing.)

OnShopItemMouseUp(...)
OnShopItemClickableMouseDown(...)

Those two methods could use better names too. Normally I'm fine with "OnXEvent" names, but these aren't actually being subscribed to the events... the Item class shows an anonymous function is subscribed to each event, which in turn calls these functions. Therefore I think these should be named for what they do, rather than for when they're called.

private void OnShopItemMouseUp(object s, EventArgs e, Item item)
private void OnShopItemClickableMouseDown(object s, EventArgs e, Item item)

You're not actually using the s or e parameters anywhere in these functions, and they don't need to fit any existing delegate signature (apart from your own which you can change) since they're not subscribed directly to the events, so it's pointless to have them. Remove both and leave just the Item.

private void OnShopItemClickableMouseDown(object s, EventArgs e, Item item)
{
    stop = false;
    countThread = new Thread(() =>
    {
        while (!stop && currentMoney >= item.RequiredMoney)
        {
            if (lbCurrentMoney.InvokeRequired && bGetMoney.InvokeRequired)
            {
                Invoke(new MethodInvoker(() =>
                {
                    currentMoney -= item.RequiredMoney;
                    moneyPerClick += item.DollarsPerClick;
                }));
            }
            Thread.Sleep(100);
        }
    });
    countThread.Start();
}

This is called every time some button is clicked, right? So you create a thread, then another, then another... each spends nearly 100% of its life sleeping. Use Tasks instead. And don't sleep on the thread - it means you'll have potentially hundreds of threads using memory but doing absolutely nothing. Use Timers instead, have them fire a Task on the thread pool every 100 ms, and probably a single thread pool thread can service all the requests.

  if (lbCurrentMoney.InvokeRequired && bGetMoney.InvokeRequired)

Never used that before but as far as I can tell, it tells you whether you can update the control on the current thread. Given that this code ALWAYS executes on a thread which cannot update the controls directly, that check is redundant. Also, if it turned out that you don't have to invoke on the UI thread, you're doing nothing - presumably you should be updating the controls from the current thread, right?

  public delegate void ShopItemEvent(object sender, EventArgs e, Item item);

As stated earlier, you may as well remove the object/EventArgs parameters since you don't use them. I know people tend to like having a sender and event args on events but rarely see them used outside actual UI-generated events, so don't see the point.

  public Item(long dollarsPerClick, long requiredMoney, ...

Is money in dollars? Then be consistent in naming: requiredDollars (or possibly costInDollars or dollarCost since it appears to relate to the cost?).

    buttonActivator.MouseDown += (sender, EventArgs) => onMouseDown(sender, EventArgs, this);
    buttonActivator.MouseUp += (sender, EventArgs) => onMouseUp(sender, EventArgs, this);

EventArgs should be camelCase since it's the name of a parameter.

Here is an example of using Timers (from System.Threading, not any other namespace where timers may exist) rather than Threads (not the best but I don't really know how everything is called and used, so a very basic example):

private List<Timer> timers = new List<Timer>();
private readonly object syncLock = new object();
...
private void OnX(Item item)
{
    Timer timer = null;
    timer = new Timer(x =>
    {
        if (!stop && currentMoney >= item.RequiredMoney)
        {
            Invoke(new MethodInvoker(() =>
            {
                currentMoney -= item.RequiredMoney;
                moneyPerClick += item.DollarsPerClick;
            }));
        }
        else
        {
            timer.Dispose();
            lock (syncLock)
                timers.Remove(timer);
        }
    });

    lock (syncLock)
        timers.Add(timer);

    timer.Change(0, 100);
}

Basically this creates a Timer, gives it a delegate to run, and starts it (Change(0 /*Start immediately*/, 100 /*recur every 100 ms*/)). The timer executes the delegate on a thread pool thread, i.e. one of the threads that are always running in the background, waiting for jobs to do. The timer is added to a list, because the timer would otherwise get garbage collected, which would stop it. Adding it to the list keeps it rooted. When the timer should no longer run the delegate, the code that the Timer started turns around and disposes the Timer, and removes it from the list so it can get GC'd. Both the add and remove are locked for the sake of thread safety.


I've implemented this idiom and discovered a major caveat after a few weeks: it doesn't play nicely with boost::iterator_range or other collection views.  An example:

std::vector<std::string> dest;
std::list<std::string> src{"foo", "bar"};
// Moves elements out of src, expected
assign(dest, std::move(src));

src = {"foo", "bar"};
// Also moves elements out of src!!!
assign(dest, boost::make_iterator_range(src));

This happens because boost::make_iterator_range(src) is an xvalue.  I don't see a good way to distinguish between "container" (meaning safe to move from xvalues) and "container view" (meaning not safe to move from).


Looking for Interstitial Array Join that works like String Join

Maybe this is the simplest code to insert an element between each consecutive elements of an input array using System.Linq query:

string[] input = { "red", "white", "blue" };
string[] result = input.SelectMany(x => new [] { "or", x }).Skip(1).ToArray();
// { "red", "or", "white", "or", "blue" }

Steps:

.SelectMany(...): "Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence." - see Documentation
.Skip(1): We have to remove first "or" delimiter, because we added it before each element and we do not want it before a first element.
.ToArray(): Convert IEnumerable to string[]. If you want, you can call .ToList() method instead to receive List<string>

I do not know about any built-in method or a more straightforward way to achieve it.

See working example on dotnetfiddle.net

I hope it will help you.


Handling all error conditions on success or failure response

The response from the server is not best practice. If you have any influence over the service, it should generate an http error (4XX range) on an exceptional condition and include the exception details in that response.

Assuming you have no control over the service, I would recommend wrapping the service  call in a method returning a promise which can be resolved or rejected upon checking the response.

If you only have one piece of code making the call then I would leave it as is -- wrapping for a single call would add unnecessary complexity.


I see a couple of problems:

If you ever shrink the array, the loop for copying the elements will overrun the bounds of newdata because the index runs from 0 to mSizeOld.
You don't store the size of the array in the class, so code like this will lose data:

ResizeableArray<Thing> a;
a.resize(0, 10);
// Populate the array
a.resize(0, 11);
// Now a is empty again because resize() uses the first argument.

This might be intentional — to allow you to start over with a fresh set of data &mdash but if so, resize() should be commented to say that.


Counting occurrences of "hi" in a string, except where followed by "x"

It doesn't get much shorter than that. But some other improvements are possible.

The current algorithm uses startswith method to check for x and hi, and as such it advances by 1 or 2 characters at a time. This is inefficient.

Another performance issue is creating many temporary strings in the process (because of substring).

It would be better to use indexOf instead of startswith, which will allow you to jump multiple characters at a time. Another big improvement would be to avoid temporary string generation, by creating a helper function that tracks the position to check. Something like this:

public int countHi2(String str) {
    return countHi2(str, 0);
}

public int countHi2(String str, int start) {
    start = str.indexOf("hi", start);
    if (start == -1) {
        return 0;
    }

    int count = 0;
    if (start == 0 || str.charAt(start - 1) != 'x') {
        count++;
    }
    return count + countHi2(str, start + 2);
}


Get specific lines from a huge text file

I know this might be a one time task, however, if you want to create a reusable code, I would always put the line counting code in a "continue" block. It is more readable and safer for future enhancements. Somehow the line increment code "finds itself" pushed after a next statement...

while (my $line = <$i_fh>) {
    chomp $line;
    if (defined $indices{$lines_parsed}) {
        print $o_fh $line, "\r\n";
        $lines_found++;
    }
} continue {
    $lines_parsed++;
}


Get 5 to 10 characters and flip their case

A flexible approach to getting user input is to use a while-true loop, breaking
when conditions are met. The structure is easy to remember and allows you to
handle user mistakes without awkward setup or code repetition:
while True:
    x = input('...')
    if x is OK:
        break

I realize the variable names are coming from your teacher's instructions, but
both of you should strive for better variable names. Better does not always
mean longer (brevity and clarity are both worthy goals and they are at odds
sometimes); but it does mean using variable names that are meaningful
in context. For example, letters is a better name for a string of letters
than n, which is a purely abstract name (even worse, it adds confusion
because n is often/conventionally used for numeric values).
There is no need to build T character by character. Python strings are
iterable and therefore directly convertible to lists.
Python strings, lists, and tuples are directly iterable: just iterate over the
values and don't bother with the soul-crushing tedium imposed by many less-cool
programming languages where you must iterate over indexes. And for cases when
you need both values and indexes, use enumerate().
Use simple comments as sign-posts and organizational devices to make
your code more readable. This habit will serve you well as you try
to write bigger, more complex programs.
# Get user input.
while True:
    prompt = 'Enter 5 to 10 letters, without spaces or punctuation: '
    letters = input(prompt)
    if len(letters) in range(5, 11) and letters.isalpha():
        break

# List of the original letters.
T = list(letters)

# List of letters with case flipped.
V = []
for c in letters:
    c2 = c.lower() if c.isupper() else c.upper()
    V.append(c2)

# Same thing, in one shot.
V = [
    c.lower() if c.isupper() else c.upper()
    for c in letters
]

# Check.
print(T)
print(V)


Interface for obtaining the bounding box for a collection of elements

Another alternative.

Nutshell

Don't put type into name (PageAreaInterface etc.)
Lose the Hungarian; appropriately-short methods remove its utility.
Create an enum and method to get specific coordinates.
Create getMinimum and getMaximum methods in a PageAreaCollection taking an enum.

Justifications (working backwards)

PageAreaCollection

Static utility methods strike me as un-OO, particularly when there are other options.

Create a type, with type-appropriate methods: code shrinks, and reads better:

min = PageAreaUtils.findMinimum(pageAreas, TOP); // Contrast with...
min = pageAreas.findMinimum(TOP);

Shorter is good, but which reads nicer? Which is more communicative?

With static imports, you're still left with:

min = findMinimum(pageAreas, TOP);    // Minimum pageAreas?! No...
min = findMinimumTop(pageAreas);      // Doesn't read right.
min = findMinimumTopIn(pageAreas);    // Better?
min = findMinimum(TOP).in(pageAreas); // Better?

IMO the amount of extra work/code to remove the method from its rightful place (a method of a pageArea collection) isn't worth the effort.

Enum in bounding box

The enum and utility method could live in the collection, too, if the bounding box class isn't yours to finagle.

// In bounding box, collection, or standalone.
public enum POSITION { TOP, LEFT, BOTTOM, RIGHT }

// In bounding box or collection.
public double getPosition(POSITION pos) {
    switch (pos) {
    case TOP:    return getTop();
    case LEFT:   return getLeft();
    case BOTTOM: return getBottom();
    case RIGHT:  return getRight();
    }
    throw new RuntimeException("Bad position provided: " + pos);
}

Min/max position locators in PageAreaCollection class

This is essentially the same as the previous suggestion to use Collections.min/max, but I'd still wrap it all up so the mainline code doesn't have to see how it's implemented. This way or that, it's significantly cleaner, with an appropriately-named Comparator.

Collection<PageArea> pageAreas;

public double getMinimumPosition(MyRect.POSITION pos) {
    double min = Double.MAX_VALUE;
    for (PageArea area : pageAreas) {
        min = Math.min(min, area.getBoundingBox().getPosition(pos));
    }
    return min;
}

public double getMaximumPosition(MyRect.POSITION pos) {
    double max = Double.MIN_VALUE;
    for (PageArea area : pageAreas) {
        max = Math.min(max, area.getBoundingBox().getPosition(pos));
    }
    return max;
}

Essentially the same if getPosition() needs to be in the collection. My quibble with having the method in the bounding box is that it makes getting the position a bit bulky; I'd actually prefer this:

area.getBoundingBox(pos) // or area.getBoundingBoxPosition(pos)?

Hungarian

Ew. A method that's a dozen lines long doesn't need differentiation between parameters and locals; it's obvious. At most I could see naming member variables, but even that... Meh.

Interface naming

A PageAreaInterface is just a PageArea. An implementation may deserve a special name, but it'd be a "special" PageArea in that it implements specific functionality likely worth naming. It's the same reason we don't name things IWhatever anymore. The interface is the Whatever, implementations provide specificity and deserve naming.


Grab data from one sheet and insert/format it into another sheet

Nice job, you dceclared all your variables and your variable names are pretty descriptive. One thing is

Dim i, j, k as Integer

This only has k as Integer, they other two are Variants. You need to type them all:
Dim i as Long, Dim j as Long, Dim k as Long

I went with Long type because integers are obsolete. According to msdn VBA silently converts all integers to long.
One nitpick is Dim LastRow As Long - Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names. So lastRow.
You also have rngMerge and UrngMerge - maybe be more descriptive in those names.
Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.
Worksheets have a CodeName property - View Properties window (F4) and the (Name) field (the one at the top) can be used as the worksheet name. This way you can avoid Sheets("Trend Data") and instead just use TrendData.
I don't know what happened to your formatting, but your indenting isn't showing up as expected. It's good practice to indent all of your code that way Labels will stick out as obvious. You actually have 2 labels that are pretty well hidden.

Speaking of your labels

MergeAgain:
    For Each cell In rngMerge
        If cell.Value = cell.Offset(1, 0).Value And IsEmpty(cell) = False Then
            Range(cell, cell.Offset(1, 0)).Merge
            GoTo MergeAgain
        End If
    Next

MergeAgain2:
    For Each cell In URngMerge
        If cell.Value = cell.Offset(1, 0).Value And IsEmpty(cell) = False Then
            Range(cell, cell.Offset(1, 0)).Merge
            GoTo MergeAgain2
        End If
    Next

That's a strange way to do this looping.
For j = LastRow To startrow Step -1
    If (.Cells(j, col) = .Cells(j + 1, col)) And Not IsEmpty(.Cells(j, col)) Then .Range(.Cells(j, col), .Cells(j + 1, col)).Merge
Next

No reason to use labels if there's a better way to do it.
You see when you use a boolean function like IsEmpty, you don't need to test its value specifically because the If is looking for True or False already.
Speed
The only way to really gain speed here is to pull your data into arrays and do your operations on those, then spit out entire arrays to the sheet.
I'm not entirely sure of your goal with .Merge but they are your natural enemy. Trust me. It would be better to group the cells and .HorizontalAlignment = xlHAlignCenterAcrossSelection


Scala Codility GenomicRangeQuery performance

The basic task here is to search for the minimum value in the current subset, but there is a known floor value so it would be nice if we could terminate the search early if the floor value is encountered. Unfortunately the Standard Library doesn't have such an animal so we'll have to roll our own.

def solution(s: String, p: Array[Int], q: Array[Int]): Array[Int] = {

  val arr = s.toArray.map {   // String to Array of weighted values
    case 'A' => 1
    case 'C' => 2
    case 'G' => 3
    case 'T' => 4
  }

  def subMin(start: Int, end: Int, min: Int = 4): Int =
    if (start > end) min                                          // search done
    else if (arr(start) == 1 || arr(end) == 1) 1                  // early end
    else subMin(start+1, end-1, arr(start) min arr(end) min min)  // tail recurse

  p.indices.map(x => subMin(p(x), q(x))).toArray
}

With this I got 100% correctness and 66% performance.

So a different, and perhaps larger, performance issue is that once a subset has been evaluated it would be really nice if we never have to revisit it again, just recall the previous evaluation when needed.

That's the basic idea behind a segment tree. Essentially, your data becomes the leaves of a binary tree and each node contains the result of the associative operation on all the leaf values underneath it.

I won't paste the 40 lines of segment tree code here (worthy of independent study), but with that in place...

def solution(s: String, p: Array[Int], q: Array[Int]): Array[Int] = {

  val arr = s.toArray.map {   // String to Array of weighted values
    case 'A' => 1
    case 'C' => 2
    case 'G' => 3
    case 'T' => 4
  }

  val st = SegmentTree(arr, Math.min)  // build the segment tree

  p.indices.map(x => st(p(x), q(x))).toArray
}

... this got 100% correctness and 100% performance.


Reading integers from a file and counting the length of a descending subsequence

int main() returns an int so instead of exit(0); write return 0; at the end of main, it is more natural. exit is more something you would use to panically exit a program.

When you write the file xxx.out, you don't check if opening the file succeeded, it always good to check return values of all runtime functions like you do when you read the other file.

Initialize all variables when you declare them to avoid any surprises. You have in some cases declared the variables where you use them, that is good. You should do that with all variable declarations instead of at top of main.

Check return value of fscanf() to see if it correctly got a number. I personally prefer fgets/sscanf when reading from file/stdin but that is me.

Maybe you could separate the functionality into some smaller functions e.g. readFile, writeFile and calculateTotal. It is a good habit to learn because programs have a tendency to grow with time, although for this particular case it may be overkill.

Another good habit is to write "why" comments, but I guess in this particular case it is quite self-evident what it does, although maybe a mention of the file format expected in the header of the program would be helpful for another programmer. :)

You could add some error messages to stderr when something is wrong instead of silently quitting, it makes troubleshooting easier e.g.

fprintf(stderr, "invalid size %d", size);


Split string by substring without using String.Split()

private static string StringFromCursor(string toSplit, int cursorPosition, int matchStart)
{
    string result = string.Empty;

    for (int i = cursorPosition; i < matchStart; i++)
    {
        result += toSplit[i].ToString();
    }

    return result;
}

This is a bad idea. Since C# string is immutable, the only way to support an append or += operation is to throw the old string away and build a new one.  Doing this repeatedly leads to an \$O(n^2)\$ running time. What you really need is a StringBuilder which does support building up strings piece by piece.


Some notes:

Be consistent with the use of parens.
Use ternary expressions (?) to reduce short conditionals.
If you are using Ruby >= 2.0, check named keywords.
The resulting expression of an assignment is its value, so you can remove the last @result
What looks gross to me are those in-place updates of @result, but this goes beyond the scope of the question.

With Ruby >= 2.0, I'd write:

def apply_limit_and_offset(limit: nil, offset: nil)
  @result = offset ? @result.drop(offset) : @result
  @result = limit ? @result.first(limit) : @result
end


Well, this program can be reduced a lot in pythonic way in terms of number for lines for sure!!

def calculator(number1,number2):
    try:
        print("The first number is {}\nThe second number is {}".format(number1, number2))
        print("The sum is {}".format(number1 + number2))
        print("Knew it!" if str(input("Am I right? \nANSWER : ")).lower() == "yes" else "Oh, well. Blame my programmer!")
    except Exception as e:
        print(e)

You have not taken care of handling input types, what if 2 different data types are passed?


If your user and features model can have a many-to-many relationship, then you can use the following example:

  A has_and_belongs_to_many association creates a direct many-to-many
  connection with another model, with no intervening model

class CreateUsersAndStatusFeatures < ActiveRecord::Migration
  def change
    create_table :status_features do |t|
      t.string :name
      t.timestamps null: false
    end
    # Do not create users table if you already have.
    create_table :users do |t|
      t.string :name
      t.timestamps null: false
    end
    create_table :users_status_features, id: false do |t|
      t.belongs_to :user, index: true
      t.belongs_to :status_feature, index: true
    end
  end
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :status_features
end
class StatusFeature < ActiveRecord::Base
  has_and_belongs_to_many :users
end

If you want to know in detail, go to this link.


This seems like a waste of time:

std::vector<std::string> tokenize(const std::string & str){
    std::stringstream ss(str);
    std::istream_iterator<std::string> begin(ss);
    std::istream_iterator<std::string> end;
    std::vector<std::string> words(begin, end);
    return words;
}

The result is used here:

std::vector<std::string> tokenizedPattern = tokenize(pattern);
std::transform(tokenizedPattern.begin(), tokenizedPattern.end(),
               std::back_inserter(intTokenizedPattern),
               [](const std::string & str){ return stuff;});

You use an iterator to copy it into a vector so you can get the iterator to use in a standard algorithm. Why not just use the algorithm with the original iterator.

std::stringstream streamPattern(pattern);
std::transform(std::istream_iterator<std::string>{streamPattern},
               std::istream_iterator<std::string>{},
               std::back_inserter(intTokenizedPattern),
               [](const std::string & str){ return stuff;});


I would move all positions and other configuration to a simpleObject which contains a condition which is checked to determine if the configuration should be used for the current screen dimensions:

Remove unneeded variables
Added functions to remove duplication
Moved positions to animationConfig so logic and configuration is separated

I made a assumption in the code which is that the path is always a square, so up, down, left
and right duration are replaced with a horizontal and vertical duration

jsfiddle: http://jsfiddle.net/EJF9q/1/

'use strict';

function animate_node(down, down_dur, left, left_dur, up, up_dur, right, right_dur) {

    function animate_cfg(duration) {
        return { duration: duration, easing : 'linear', queue: true };
    }

    down    += 'px';
    left    += 'px';
    up      += 'px';
    right   += 'px';

    $('.node')
        .animate({top: down},           animate_cfg(down_dur))
        .animate({marginLeft: left},    animate_cfg(left_dur))
        .animate({top: up},             animate_cfg(up_dur))
        .animate({marginLeft: right},   animate_cfg(right_dur));
}

function animate_config(config) {
    animate_node(
        config.down,
        config.vertical_dur,
        config.left,
        config.horizontal_dur,
        config.up,
        config.vertical_dur,
        config.right,
        config.horizontal_dur);
}

// OnReady
$(function () {

    var animationConfigs = [
        {
            startTop: 157,
            delay: 1500,
            down: 425,
            left: -284,
            up: 157,
            right: 264,
            vertical_dur: 2000,
            horizontal_dur: 2000,
            conditions: function() {
                return $(window).width() > 840;
            }
        },
        {
            delay: 1500,
            down: 490,
            left: -199,
            up: 165,
            right: 179,
            vertical_dur: 2000,
            horizontal_dur: 2000,
            conditions: function() {
                return $(window).width() < 840 && $(window).width() > 600;
            }
        },
        // Etc...
    ];

    for (var i in animationConfigs) {
        var animationCfg = animationConfigs[i];
        if (animationCfg.conditions()) {
            $('.node').each(function(i) {
                $(this).delay(1500 * (i + 1))
                    .animate({ top: animationCfg.up + 'px' },
                        { duration: 1000, easing : 'linear', queue: true })
                    .animate({marginLeft: animationCfg.right + 'px'},
                        { duration: 1000, easing : 'linear', queue: true });
            });
            animate_config(animationCfg);
            setInterval(function() {
                animate_config(animationCfg);
            }, 2000);
            break;
        }
    }
});


This seems pretty optimal to me given how simple it is, only a question, why the foreach? Do you expect Get-MailContact to return multiple contacts ?
I don't have an AD I can test it against, but I'd be curious to know if "reversing" the operation by removing the member from the groups instead of removing the membership from the user could make it faster:
$ADContact = Get-MailContact <name> | Get-ADObject -Properties memberof
# Loop through all the groups and remove the user from them.
foreach ($group in $ADContact.MemberOf) {Remove-ADGroupMember -Identity $group -Member $ADContact}


Your BST can become unbalanced. In the worst case when the input is sorted, the tree degenerates to a linked list, and you traverse through it all to insert each element. Various algorithms exist for self-balancing search trees, but you might also want to look into the SortedContainers library. Even if you want to create your solution from scratch, you can find good ideas there.

Using sortedcontainers.SortedList the solution becomes very simple:

def countSmaller(self, nums):
    result = []
    seen = sortedcontainers.SortedList()
    for num in reversed(nums):
        result.append(seen.bisect_left(num))
        seen.add(num)
    result.reverse()
    return result

This is twice as fast as yours for 300 random numbers, and the gap increases as the size grows. For list(range(100)) this is ten times as fast.


SASS mixin for a font-awesome before/after usage

The $type can be passed in directly to the pseudo-class selector after you check its validity.

@if $type == 'after' or $type == 'before' {
  &:#{$type} {
    content:$unicode;
    font-family:"FontAwesome";
    font-size:$size;
    color:$color;
    font-weight:$weight;
    margin:$margin;
    @content;
  }
}


Iterative solution for generating all permutations of a string

Time complexity analysis

Let's think about what this does.

        for (char c : cArray) {

This says that for each character in the string (since cArray is the character array view of the string), we iterate once.  As you note, this is \$O(n)\$ where \$n\$ is the number of characters in the string.

        Set<String> currResults = new HashSet<String>(results);

This is \$O(m)\$ where \$m\$ is the number of entries in the Set.  Note that that will change as you go.

        String charToAdd = String.valueOf(c);
        results.add(charToAdd);

This takes constant time.

        for (String s : currResults) {

This takes \$O(m)\$ time again.

            for (int i = 0; i < s.length() + 1; i++) {

This takes \$O(l)\$ time, where \$l\$ is the length of this string.  Again, this will change over time.

                String newWord = s.substring(0, i) + charToAdd + s.substring(i);

This takes \$O(l)\$ time, as it involves copying s to a new string.

                if (newWord.length() == str.length()) {
                    realRes.add(newWord);
                }
                else {
                    results.add(newWord);
                }

This takes constant time.

We do \$n\$ iterations of the outer loop.

First iteration

\$n\$ is the number of characters in str and will be throughout.

\$m\$ is 0.  We haven't put any entries in the set yet.

\$l\$ doesn't exist.  We never get to that section of code.

We end with one entry in results and no entries in realRes.

Second iteration

\$m\$ is 1.

\$l\$ is 1.

We end with three entries in results and no entries in realRes.

Third iteration

\$m\$ is 3.  This is 2 + 1.

\$l\$ ranges from 2 to 1.

We end with nine entries in results and no entries in realRes.

Fourth iteration

\$m\$ is 9.  This is 3 * 2 + 2 + 1.

\$l\$ ranges from 3 to 1.

We end with forty entries in results and no entries in realRes.

nth iteration

We end with \$n!\$ entries in realRes.  We add increasing numbers of strings to results, equal to \$\sum\limits_{i=1}^{n-1} i!\$.  Note that that is less than \$n!\$.

Note that this assumes that all the characters in the string are different.  If some characters repeat, this will exaggerate the number of entries.  Of course, for Big-O notation, that's fine.  So we can say that overall this is still \$O(n!)\$.

Alternately styled code

    public static Set<String> getPermutations(String str) {
        Set<String> results = new HashSet<>();
        Set<String> partials = new HashSet<>();
        for (char c : str.toCharArray()) {
            List<String> current = new ArrayList<>();
            String charToAdd = String.valueOf(c);
            for (String s : partials) {
                for (int i = 0; i <= s.length(); i++) {
                    String newWord = s.substring(0, i) + charToAdd + s.substring(i);
                    if (newWord.length() == str.length()) {
                        results.add(newWord);
                    } else {
                        current.add(newWord);
                    }
                }
            }

            partials.add(charToAdd);
            partials.addAll(current);
        }

        return results;
    }

I don't like the name results for what you had.  It's not results.  It's partial permuations.  So I changed it to partials.

With the name results available, I'd prefer that to realRes.

I find it easier to read if we do the toCharArray in the for loop itself.  That way I don't have to look around to find what cArray is.

Rather than copy the entire set to another set on every iteration, I'd rather just copy the things that I'm adding.  So I made a List for that purpose.  That (and moving the charToAdd add) allows us to loop directly over partials rather than the new collection.

We can save a math operation if we say i <= s.length() rather than i < s.length() + 1.  I also find it a bit clearer about what it is doing.

The Java standard is to do the fully cuddled else.  It's not a big deal if you do it the other way, but I changed that on my way through.


Wrapping an IntPtr in a Struct for safer Interop

I think, I would experiment with a safe or smart pointer approach in a way like this:

public sealed class LuaHandle : IDisposable
{
  private static extern IntPtr lua_newstate();
  private static extern void lua_close(IntPtr state);

  private IntPtr m_handle = IntPtr.Zero;

  public LuaHandle()
  {
    m_handle = lua_newstate();
  }

  public IntPtr Handle => m_handle;

  public void Dispose()
  {
    if (m_handle != IntPtr.Zero)
    {
      lua_close(m_handle);
    }

    m_handle = IntPtr.Zero;
  }
}

Usage:

  using (LuaHandle luaHandle = new LuaHandle())
  {
    // do something with luaHandle.Handle
  }

In this way you - as a client of LuaHandle - don't have to deal with the extern api's at all and no invalid IntPtr can be past as argument to lua_close()


Relying on .hashCode() may or may not be faster and may or may not produce the same results as relying on .equals().

Do you already see where this is going? The problem begins when you stop obeying the contract of the interface you implement. I'll quote the javadoc for contains here:

  Returns true if this collection contains the specified element. More
  formally, returns true if and only if this collection contains at
  least one element e such that (o==null ? e==null : o.equals(e)).

This is the formal definition for contains that also applies to containsAll.

Now considering that a programmer seeing a Collection expects the contains method to work based on equals and countering with the fact that yours doesn't you're violating the "Principle Of Least Surprise".

This also leads to code handling collections behaving differently depending on what implementation you pass in, which is never desirable.

In general I think that relying solely on hashCode for contains is a bad idea, even when it's best practice to override hashCode so the resulting hashes of equal objects are equal and those of nonequal objects aren't.


Finite state machine written in OCaml to test for the sequence 0,1

I notice that you represent states as functions. This does give some expressive power, as seen in the composition example given in your linked answer.

If that power isn't needed we can write things directly and simply:

type element = Z | O

let rec start list = look_for_zero list

and look_for_zero = function
  | [] -> "nothing"
  | Z::rest -> have_zero rest
  | O::rest -> look_for_zero rest

and have_zero = function
  | [] -> "nothing"
  | O::_ -> "yes!"
  | Z::rest -> look_for_zero rest

If you want to stick with the given framework, then you can simplify a bit and transform into a functional style:

type ('state, 'number) state_machine = {
  initial: 'state;
  final: 'state -> string;
  transition: 'state -> 'number -> 'state; (* I changed the order! *)
};;

type state = Init | HaveZero | FoundZeroOne
type element = Zero | One

let final = function
  | Init | HaveZero -> "no"
  | FoundZeroOne -> "yes"

let transition state n =
  match n, state with
  | _, FoundZeroOne -> FoundZeroOne
  | Zero, _ -> HaveZero
  | One, Init -> Init
  | One, HaveZero -> FoundZeroOne

let machine = {
  initial = Init;
  final;
  transition;
}

let run_machine machine list =
  machine.final
    (List.fold_left machine.transition machine.initial list)


A simple program that animates the Y position of multiple elements based on the window scroll position

Faster does not mean smoother.

Some very quick notes.

Queries to the DOM are very slow compared too what they do. You should only query the DOM for the elements once and then just use the references you have.

When page is ready

// query the DOM a stash the elements in an array of objects so you can add
// And more DOM related info as you find it.
const articles = [...document.querySelectorAll('article')].map(element=> ({element}));

Then in the code

const calcVisibilityForAllArticles = () => {
  // Now you can loop through the element without needing to traverse the DOM each time.
  for(const item of articles){ // item holds the element as element
    const top = calcVisibilityForElem(item.element);

    // for the first pass
    if (top !== 0) {
       // for the first pass  of visible do the query and save the element
       if(!item.span) { item.span = item.querySelector('span') }
       // now you can use it directly
      item.span.style.transform = `translateY(${Math.floor(top * 1.5)}px)`;
    }
    // do the same for all the other elements you search the DOM for each animation cycle.

Timing

As you have not supplied a working example there is no way to know if you are overloading the page or not.

The important thing to remember is that all browsers have a fixed display rate of 60FPS. Making changes to the DOM at a rate higher than this will only result in shearing and flickering. It can also have a pull down effect on the browser as you block it from doing what it needs to do.

You must particularly be careful with events that are driven by the mouse. Some mice can trigger 500+ events a second. You should never update the DOM from move events that can come from the mouse.

RequestAnimationFrame

When ever you make any regular changes to the DOM use the timer callback via the function requestAnimationFrame. It is designed to present the smoothest possible animations. It is synced to the browsers frame rate, and will not present changes until the display device is not scanning out the pixels.

To use

var scrollPos;  // this holds the current scroll position

// In the scroll event only get the scroll position and make no changes to the
// DOM
function yourScrollEvent() {  ... scrollPos = foo ...}

You make the DOM updates via the frame request

 var lastScrollPos; // used to check if there is a need to animate

 function scrollLoop(){
      if(lastScrollPos !== scrollPos){ // only render if needed
          lastScrollPos = scrollPos;

          // do your DOM stuff here

       }

      requestAnimationFrame(scrollLoop); // request next frame

  }

   // start it off via the frame request.
   requestAnimationFrame(scrollLoop);

This will produce the smoothest possible animation. If it can not keep up and drops frames then you need to reduce the complexity of the animation.


In your case CoursesViewModel includes the logic of retrieving entities from db. It should be moved to a service/a repository. ViewModel should include only properties to be shown in the view and some displaying logic in order not to put a lot of server code to the view.

public class HomeController : Controller
{
    // should CRUD products from db
    private readonly IProductService _productService;

    public HomeController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public ActionResult Index()
    {
        var products = _productService.GetProducts(123);
        var model = new ProductViewModel(products);
        return View(model);
    }
}

public class ProductViewModel
{
    public ProductViewModel(IEnumerable<Product> products)
    {
        // init viewmodel here or use some mapper
        this.products = products;
    }

    // only those properties which are going to be displayed in your view

    public int ProductsCount { get; set; }
    public decimal Total { get; set; }
    public string VatCodeApplied { get; set; }

    // ...

    private IEnumerable<Product> products;
}

public interface IProductService
{
    IEnumerable<Product> GetProducts(int userAccountId);

    // ...
}

public class Product
{
    // ...
}


TypeScript fetch wrapper class with localStorage cache

The review will be focused on readability and testability.
Naming
I read (I think it was in Clean Code) that variables should not have a postfix like Data and Information and instead we should give things a name that they represent.
PortfolioData is actually a Portfolio while your current Portfolio is more a PortfolioRepository or PortfolioCollection.
Additionally I couldn't figure out, what Basic could mean and I looked up the json-representation of the gitconnected api:

"basics": {
   "name": "...",
   "picture": "https://avatars2.githubusercontent.com/u/2121481?v=4",
   "label": "...",
   "headline": "...",
   "summary": "...",
   "website": "...",
   "blog": "...",
   "yearsOfExperience": 2,
   "id": "...",
   "username": "...",
   "karma": 22,
   "email": "...",
   "region": "...",
   "location": {},
   "phone": "...",
   "followers": 63,
   "following": 94,
   "profiles": []
}

For me a more descriptive name would be User or Owner. A Portfolio has an Owner and a PortfolioRepository stores Portfolio-Objects:
export interface Portfolio {
  owner: Owner;
  projects?: Project[];
}

interface Cache {
  portfolio: Portfolio;
  expiration: number;
}

class PortfolioRepository { /* ... */ }

Concerns
The class Portfolio handles multiple concerns. There are two principles which can be named to emphasize the importance for separation:

Separation of Concerns (SoC)
Single Responsibility Principle (SRP)

The concerns are

fetching (await fetch(this.url))
caching (this.setCache(...))
querying (async getPortfolio(): Promise<PortfolioData>)

When we separate the concerns we could accomplish something like
interface PortfolioRepository {
    get(): Promise<Portfolio>;
}

class ApiPortfolioRepository implements PortfolioRepository {
    constructor(private cache: Cache,
                private api: API) {}

    async get(): Promise<Portfolio> {
        if (this.cache.containsPortfolio()) {
            return this.cache.get();
        }

        const portfolio = await this.api.fetch();
        this.cache.update(portfolio);

        return portfolio;
    }
}

This has multiple advantages. Beside the descriptive and shorter method body we can accomplish through the dependency injection via the constructor a better way to test the class.
Now the PortfolioRepository does not need to know about how caching works like the cacheDurationInMilliseconds and it does not need to know the http endpoint any more.
If we want to test the class we could simply mock the api (for exampe with mocha and chai):
import { assert } from "chai";

suite('API Portfolio Repository', () => {

    const cache = ...;
    const fakeAPI = new FakeAPI();

    test('when API returns no portfolio -> return undefined', () => {
        const repository = new ApiPortfolioRepository(cache, fakeAPI.withoutResponse);

        const portfolio = repository.get();

        assert.isUndefined(portfolio);
    });

    test('when API returns a portfolio -> return portfolio', () => {
        const repository = new ApiPortfolioRepository(cache, fakeAPI.withResponse);

        const portfolio = repository.get();

        assert.deepEqual(portfolio, fakeAPI.portfolio);
    });

})


Let's start with some general remarks:

Swift does not require semicolons after statements (but they are allowed). From what I have seen since Swift was introduced last year,
most people do not write semicolons in Swift.
Classes are reference types, and the properties of an instance of a class
can be modified even if the instance is declares as a constant with let.
Therefore you can replace var by let at many places in your code,
e.g.

let nodeToPushInStack: IDNode<IDType>! = IDNode<IDType>()

Often an explicit type annotation is not necessary because the compiler
can infer the type of an expression automatically. E.g. the above statement can be shortened to

let nodeToPushInStack = IDNode<IDType>()

Now the "major" points. To simplify things, I'll consider the
implementation without protocols first, so in the first part
of this answer I'll ignore your protocol definitions and assume that
the classes are defined as

class IDNode<IDType> { ... }
class IDStack<IDType> { ... }

First the IDNode class: You have defined element as a variable
and optional, but actually node elements are cannot be nil and
are never mutated once a node has been been pushed on the stack.

You probably did that because you create "empty" nodes first and then
call the insertNode() method to set the element and next pointer.
Another reason is that you use nodes "without an element", but I'll come
back to that later.

I would suggest to make element a constant and non-optional
and replace the insertNode() method by an init method:

class IDNode<IDType>
{
    let element: IDType
    let nextNode: IDNode?

    init(element : IDType, before: IDNode?) {
        self.element = element
        self.nextNode = before
    }
}

Which leads us to the IDStack class: The push and pop methods are
a bit too complicated. The reason is that you use a single node
with element == nil for an empty stack, a single node with
element != nil for a stack with a single element, and then
a linked list of nodes for two or more elements.

It becomes much simpler if you use a linked list with one node for each element in each case, and stackHead points to the front node,
or is nil for an empty stack. Then you don't need an init() method
because the optional property

private var stackHead: IDNode<IDType>?

is automatically initialized to nil, and pushing an element
simplifies to

func push(element: IDType) {
    let newNode = IDNode(element: element, before: stackHead)
    stackHead = newNode
}

Popping an element becomes simpler as well. Note that the preferred
way to check an optional (here: stackHead) for nil is optional
binding:

func popElement() -> IDType? {
    if let firstNode = stackHead {
        let element = firstNode.element
        stackHead = firstNode.nextNode
        return element
    } else {
        return nil
    }
}

Remark: Your comment

        /* Stack is empty / not initialized */

is misleading: Variables cannot be uninitialized in Swift. This is
ensured by the compiler and one of the major design goals in Swift.

Finally your getLength() method: Using Double as return type seems
quite strange to me, Int would be appropriate. And I would use
a computed property count instead, similar to the count property
of Swift's sequence types.

Modifying self.stackHead inside the method temporarily is a bad idea
and I can see no reason to do so. Use a local variable instead which
traverses through the linked list, and again use optional binding
to check if you have hit the end of the list:

var count : Int {
    var numItems = 0
    var currentNode = self.stackHead
    while let node = currentNode {
        numItems++
        currentNode = node.nextNode
    }
    return numItems;
}

Back to the protocols: Defining a protocol for "Stack" makes only sense
if it contains all required methods:

protocol StackProtocol {

    typealias IDType
    func push(element : IDType)
    func popElement() -> IDType?
    var count : Int { get }
}

Then you can create an instance of IDStack and pass it to a function
that expects a StackProtocol. Simple example:

func test<S : StackProtocol where S.IDType == String>(stack : S) {
    stack.push("foo")
    stack.push("bar")
    stack.push("baz")
    print(stack.count)

    while let element = stack.popElement() {
        print(element)
    }
}

test(IDStack<String>())

Of course you can also define protocols for both the node and the
stack type. Now the node protocol should contain all required
properties and methods:

protocol NodeProtocol {
    typealias IDType
    var element : IDType { get }
    var nextNode : Self? { get }
    init(element : IDType, before: Self?)
}

and a concrete implementation would be

final class IDNode<IDType> : NodeProtocol
{
    let element: IDType
    let nextNode: IDNode?

    init(element : IDType, before: IDNode?) {
        self.element = element
        self.nextNode = before
    }
}

(Please don't ask me why the final is necessary here :)

To make the stack independent of the used node class, the stack protocol
uses  node protocol as generic placeholder (and  not IDType  as you did):

protocol StackProtocol {

    typealias NodeType : NodeProtocol
    func push(element : NodeType.IDType)
    func popElement() -> NodeType.IDType?
    var count : Int { get }
}

and a concrete implementation (in terms of a generic node type)
is

class IDStack<Node : NodeProtocol> : StackProtocol
{
    typealias NodeType = Node
    private var stackHead: Node?

    func push(element: Node.IDType) {
        let newNode = Node(element: element, before: stackHead)
        stackHead = newNode
    }

    func popElement() -> Node.IDType? {
        if let firstNode = stackHead {
            let element = firstNode.element
            stackHead = firstNode.nextNode
            return element
        } else {
            return nil
        }
    }

    var count : Int {
        var numItems = 0
        var currentNode = self.stackHead
        while let node = currentNode {
            numItems++
            currentNode = node.nextNode
        }
        return numItems;
    }
}

As an example, a stack of strings could now be created with

let stack = IDStack<IDNode<String>>()


Compute interval for a node in a binary tree

Not sure if it is much smarter, but

p = s / k;

could be replaced by

p = s >> d;

, which removes a division, and might produce faster code.

Instead of using the Log2 function, you may get better performance with such a function for computing k directly:

uint32_t msb32(uint32_t x)
{
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);

    return x & ~(x >> 1);
}

source: http://aggregate.org/MAGIC/#Most%20Significant%201%20Bit

See also: https://stackoverflow.com/questions/671815/what-is-the-fastest-most-efficient-way-to-find-the-highest-set-bit-msb-in-an-i


Looks alright to me. A small personal nuisance for me,  but a possible improvement would be to pass the credentials in an object

var credentials = {
    username: "xxx",
    password: "yyy"
};

That would make the signature of your function smaller, and after all, the 2 variables are tightly coupled, semantically speaking.

But as I say, peccata minuta. Looks good to me.


Quick Things
First, it's good practice to indent all of your code that way Labels will stick out as obvious.
Second, Worksheets have a CodeName property - View Properties window (F4) and the (Name) field (the one at the top) can be used as the worksheet name. This way you can avoid Dim inws as Worksheet, set inws = Sheets"Items" and instead just use Items.
Comments - "code tell you how, comments tell you why". The code should speak for itself, if it needs a comment, it might need to be made more clear. If not, the comment should describe why you're doing something rather than how you're doing it. Here are a few reasons to avoid comments all together.
Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Naming
Your variable names leave a lot to be desired. It's pretty easy to use descriptive names and characters are mostly free, so things like
ctr = columnCounter or rowCounter or even just counter.
Also, Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names. So inws should be inWS or inWorksheet or sourceWorksheet.
Right now things like zell and distVals don't really tell me anything at all about what I should be expecting them to do.

Function
Function GetLast - it's your prerogative, but I think it's unneeded. If you did want you keep it, it would be better as
Private Function GetLast(ByVal choice as Long, ByVal rng as Range) as Long

Right now you're passing ByRef, which isn't best practice and you don't have a return type defined. You can return a row number, column number or address (string?). That can lead to errors down the line if you change what you're looking for and expect the wrong type back. Personally,
Dim lastRow As Long
lastRow = Sheet.Cells(Rows.Count, 1).End(xlUp).Row
Dim lastColumn As Long
lastColumn = Sheet.Cells(1, Columns.Count).End(xlToLeft).Column

Would work fine for me. And you could eliminate all of
Set fndRange = Range(GetLast(3, inws.Cells))
LastCol = fndRange.Column
lastRow = fndRange.Row
Set fndRange = Nothing

Arrays
Dim distVals() As String
Dim newRows() As String
ReDim distVals(1)
    distVals(1) = inws.Cells(2, 1)
    For ctr = 2 To lastRow
        If inws.Cells(ctr, 1).Value <> distVals(UBound(distVals)) Then
            ReDim Preserve distVals(UBound(distVals) + 1)
            distVals(UBound(distVals)) = inws.Cells(ctr, 1).Value
        End If
    Next ctr

    'Get upper bound of search array and use it to set max row value of newrows array
    arrBound = UBound(distVals)
    ReDim newRows(1 To arrBound, 1 To LastCol)

I think what's happening here is that you initialize the array, then populate it one cell at a time, assuming that your data is in some sort of order because you're checking only the last element for duplicates, right? That is a lot of redimming and isn't needed. A dictionary could help with that by eliminating duplicates for you
Dim valueDictionary As Object
Set valueDictionary = CreateObject("Scripting.Dictionary")
For counter = 2 To lastRow
    valueDictionary(Cells(counter, 2).Value) = 1
Next

Now arrBound = UBound(distVals) is just valueDictionary.Count
Now, your newRows array is a little confusing to me. Why not just build an array, maybe like this -
    Dim mySummedArray As Variant
    ReDim mySummedArray(1 To valueDictionary.Count, 1 To 2)
    ReDim arr(1 To valueDictionary.Count, 1 To 2)
    counter = 1
    Dim key As Variant
    For Each key In valueDictionary.keys
        mySummedArray(i, 1) = key
        i = i + 1
    Next
    For counter = 1 To valueDictionary.Count
        mySummedArray(counter, 1) = valueDictionary.keys(counter)
    Next
    Dim indexValue As String
    Dim arrayIndex As Long
    For counter = 1 To lastRow
        indexValue = Cells(counter, 1)
        arrayIndex = FindInArray(indexValue, mySummedArray)
        mySummedArray(arrayIndex, 2) = mySummedArray(arrayIndex, 2) + Cells(counter, 2)
    Next

Using
Private Function FindInArray(ByVal indexValue As String, ByVal arrayToSearch As Variant) As Long
    Dim i As Long
    For i = LBound(arrayToSearch) To UBound(arrayToSearch)
        If StrComp(indexValue, arrayToSearch(i, 1), vbTextCompare) = 0 Then
            FindInArray = i
            Exit For
        End If
    Next
End Function

Essentially you end up with a 2D array of unique values paired with their sum. But maybe that's not what you're doing? If not, sorry, but maybe the approach is still useful.


Making a minishell in C. How to improve error control with feoh and ferror?

I think I haven't really understood the point of your program but I'll try to give you a few hints :

The indentation is not really good. I am not sure if this is because of SE but I'd rather point it out just in case.
You'll hear everything and its opposite about goto. It surely has drawbacks but it can be quite useful to handle errors and free the ressources that are not required anymore. However, in your case, there's no need for goto so it's probably better to Keep It Simple and just use return.
I am not a big fan of a go_on variable if break can do the trick. Also, it makes stdbool pointless.
Things will be easier to understand if you declare local variables in the smallest possible scope. Depending on the version of C you are using, you can even declare j in your for statement :  for (int j=0; j < i; j++).
Because of return/break, you can now remove levels of indentation (again, this is purely personal preference).
You shouldn't repeat "quit" in multiple places. It will make it hard to change if it has to change in the future.
There is a risk that arr[i] = token; goes to far if you ever change a constant without changing the other. Let's make sure it does not go too far.

At the end, here what the code would be like :

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

#define LINE_LEN  50
#define MAX_PARTS  50

static const char quit[] = "quit";

int main ()
{
    char str[LINE_LEN];
    char* arr[MAX_PARTS];

    for (;;) {
        printf("Write a line:('%s' to end) \n $:", quit);
        fgets(str, LINE_LEN, stdin);

        if (str==NULL) {
            printf("fgets didn't work correctly");
            return -1;
        }
        size_t l = strlen(str);
        if (l && str[l-1]=='\n')
            str[l-1]=0;

        /* split string into words*/
        int i;
        char* token = strtok(str, " \t\r\n");
        for (i=0; i<MAX_PARTS && token != NULL; i++)
        {
            arr[i] = token;
            token = strtok(NULL," \t\r\n");
        }

        fflush(stdin);

        /* check if the first word is quit*/
        if (strcmp(arr[0], quit)==0)
        {
            printf("Goodbye\n");
            break;
        }
        for (int j=0; j < i; j++){
            printf("pajaritos por aqui '%s'\n", arr[j]);
        }
    }

    return 0;
}


Checking dates against a .properties file

Security concerns

Judging by the eval, it seems the properties file contains assignment statements that bash understands. Or so you think. Using eval this way is most often a serious security risk. What if somebody fobs a way to tamper with the file and append a line like this:

bash /tmp/evilscript.sh

Not only the evil script will get executed by whoever is the effective user (hopefully not root), you will not even realize it happened.

Even if you're not particularly concerned by security issues (dangerous mindset though), it's just not worth the risk. One way to make this safer is to match the live against the expected format using the [[...]] built-in, or similar.

Performance

It seems there are just two lines to parse. At this scale, I doubt performance is a serious concern, or that alternative approaches would make a noticeable difference.

Simplify

I find the way you compare the previous and current values of the two variables overly tedious. I would take a much simpler, lazier approach. For example, keep a copy of the previous version of the file at a place not editable by its current users, and replace the tedious checks for each variable with a simple diff.


Doubly circular linked list implementation

Heads and tails
I got confused reading this code because in my mind, a circular list doesn't have a tail.  Or at least, the tail is the same as the head.
The code appears to be correct, but you could have only kept a head pointer.  Anywhere where you use tail, you could essentially replace that with head->prev and get the same functionality.


Index less

Also, you're indexing a lot. Perhaps it's better to seperate the two dicts:

old, new = results_dict["Current model"], results_dict["New model"]

(And what's up with having an underscore in Current_model and a space in New model? That's asking for typos. You're not even consistent with it - in your first code they're both spaces, but in the assignment you use 3 underscores and a space for Current...)

Also, with how you make the checks, one of your conditions always implies the other. You should remove the redundant comparisons. Change:

if recall_new > recall_current or recall_new > (recall_current-(0.1)):
# Into:
if recall_new > recall_current - 0.1:

The additional braces don't do anything, and if recall_new is bigger than current-0.1, then it is also bigger than current.

Loop

If you look closely, you'll see you're doing the same thing multiple times. So just make it a loop.

Arguably you should make an outside variable for the keys to iterate over, or iterate over the keys of either new or old dict. But if hard-coding is appropriate, it could look a lot like:

new_better = 0  # i is a bad variable name. Names should have meaning.
for key in ("Recall", "Precision", "F1_score"):
    if new[key] > old[key]-0.1:
        new_better += 1
if new["Frauds"] > old["Frauds"]*1.2:
    new_better += 1

Note that I removed your rounding. Python has no issues transforming a float to the closest integer by means of int(), but neither does it have a problem with comparing ints to floats. I did notice that your adjustments make it easier to score an increment for the first three variables, but harder for the fourth. Is this intentional?


Minor things:

Don't use using namespace std. Read
this.
When you are naming variables, keep it consistent. Either stick with
camelCase or underscore.
For the inline functions, keep it on one line. It's easier to read.

void setName(string n){ name = n; }
string getName() { return name; }

I would suggest, anything over two lines, define outside of class.
Particularly the AcetoAcmeAdapter constructor.


Group by and sum query on multiple columns

First and most obvious issue is usage of ToList(), it's not required and you force creation of multiple (and possibly big) lists moreover you're repeating almost same code again and again. Step by step:

var fpslist = db.FPSinformations.Where(x => x.Godown_Code == godownid);

Unless comparison operator for Godown_Code is broken then you shouldn't need to check for null (in case you may opt for ?. to avoid it). Also you don't need .ToList(), drop it. If you will execute such code inside a loop you may consider to move this outside the loop (to be sure more context is needed).

Now let's make a reusable function (and also avoid to create multiple anonymous types, it's a micro optimization but it also simplifies our code):

static IEnumerable<Tuple<TName, TCount>> CountByType<T, TName, TCount>(
    IEnumerable<T> list,
    Func<T, TName> nameSelector,
    Func<IEnumerable<T>, TCount> aggregator)
{
    return list.Where(x => Object.Equals(nameSelector(x), null) == false)
        .GroupBy(x => nameSelector(x))
        .Select(x => Tuple.Create(x.Key, aggregator(x)));
}

Now your code can be greatly simplified (I assumed you cannot change database columns otherwise everything can be even simpler, see last section of this answer). I also used generics because type of your columns is unknown.

    var data1 = CountByType(fpslist,
        x => x.Ration_Card_Type1,
        x => x.Sum(y => y.Ration_Card_Count1));

    var data2 = CountByType(fpslist,
        x => x.Ration_Card_Type2,
        x => x.Sum(y => y.Ration_Card_Count2));

   // Repeat for each set

   var result = data1
       .Concatenate(data2)
       .Concatenate(data3)
       .Concatenate(data4)
       .Concatenate(data5);

Note that from your code it seems you can have multiple rows with a value for Ration_Card_CountX. If you have just one row then all code will be greatly reduced. Here I used a Tuple<T1, T2> because I do not know exact types of your objects, you'd better use a proper class instead.

Note that you can consume result as-is (an enumeration) or materialize a list (don't forget this if data comes from DB and connection will be disposed, LINQ execution is deferred).

About DB

I do not know if you can change your database schema and I do not know exact layout of your data then this section may not apply in your case.

If your data is in the form:

Ration_Card_Type1   Ration_Card_Count1   Ration_Card_Type2   Ration_Card_Count2
Type1                                5   NULL                                 0
NULL                                 0   Type2                               11
Type1                               12   Type2                                3

Then you have to keep your actual code but I would suggest to do not map 1:1 column names with C# property names (conventions are pretty different) then Ration_Card_Type1 should be RationCardType1 (assuming you can't simply have Type1, Type2 and so on).

If, for example, you have data with this simplified layout:

Ration_Card_Type1   Ration_Card_Count1   Ration_Card_Type2   Ration_Card_Count2
Type1                                5   NULL                                 0
NULL                                 0   Type2                               11
Type1                               12   NULL                                 0

Then you may both optimize and simplify your DB (it will also impact code):

Type   Count
1          5
2         11
1         12

In that case all you need (assuming your C# entities maps 1:1 with DB columns):

var result = db.GroupBy(x => x.Type)
    .Select(x => new { Type = x.Key, Count = x.Sum(y => y.Count) });


Memory Leak

Your code leaks. I see calls to new but I see no smart pointers or calls to delete to reclaim the memory. You need a destructor on your linked list.

class LinkedList {
public:
    LinkedList()  {}
    ~LinkedList() {/* Reclaim dynamically allocated memory here */}
};

Rule of three

Once you correct for memory management you also realize that you are violating the rule of three. By default the compiler will automatically add copy constructor and assignment opertors for you.

LinkedList   a;
a.add('x');
LinkedList   b(a);   // Makes a copy of a
                     // But only a shallow copy.
a.add('y');
// This changes 'a' to be {'x', 'y}
// Problem is that b is now also {'x', 'y}
// **BUT** in b last points at the wrong node.

// Now things get interesting:
b.add('z');
// Now a and b are {'x', 'z'} (if you follow from root)
// a.last still points {'y'} even though this is no longer
// in the chain pointed to from a.root

The default implementation of the copy constructor (and assignment operator) is to make a shallow copy of the members. This fine as long as your members are not owned pointers. But your pointers are owned (even though you missed the deletion). So you either need to implement the copy semantics of the class or explicitly remove these methods.

class LinkedList {
public:
    LinkedList()  {}
    ~LinkedList() {/* Reclaim dynamically allocated memory here */}
    LinkedList(LinkedList const&)            = delete;
    LinkedList& operator=(LinkedList const&) = delete;
};

Prefer nullptr

In C++11 we introduced nullptr to replace NULL. This is because NULL is the integer zero and can accidentally be converted to an integer type without any warning. nullptr on the other hand has a type of std::nullptr_t and can only be converted to pointer types (not integers).

Design.

When building linked lists I prefer to use a Sentinel object. This removes the need for checking for null in your list and thus makes the code easier to write and understand. There are a lot of C++ code reviews on linked lists where I explain the principle.

Node should be private

You declare Node publicly. There is no reason for people to know the implementation details of your linked list. Make this a private member of LinkedList so show that this is an implementation detail.

Prefer to use initializer list:

    Node(char data_) {
        data = data_;
    }

    // Prefer to write like this:

    Node(char data_)
        :data(data_)
    {}

For non pod types this is because the object are constructed before the body of the constructor is entered then the constructor code is applied. If data was a non pod object that means you would first be constructing it and then applying the assignment operator (ie initializing it twice).

For pod data it makes no difference, BUT does no harm either. So it is a good habit to get into. Because that way of the code is later modified to be a non pod type (i.e. CharUTF) then doing it the prefered way keeps the code optimal.

Not a fan

    Node *root = NULL;
    Node *last = NULL;

Personally I like to see all the members initialized in the initializer list. But I can see some advantages for objects with lots of constructors in avoiding writing the same thing repeatedly.

Style Check.

Most style guides for C++ (though this is not ubiquitous so just take as advice and not a rule). User defined types have an initial capital letter, while objects (which includes functions/methods) have an initial lowercase letter.

This is because the most important thing in C++ is the types. So it is useful to be able to quickly identify types from objects.

    void Add(char data) {
    // I would prefer
    void add(char data) {

Self Documenting code

Personally I don't like add() as the name of the function. It does not tell me exactly what the function does. I think a better name would be append().

Dont' use _ in identifers.

The rules on using underscore are non trivial. Even if you know them. Other people don't know them as well as they think they do. So best to avoid to prevent accidental mistakes.

    Node* _Get(int index) { // Note this is a reserved identifier.
                            // And being a common word is very likely
                            // to be used somewhere. including the
                            // wrong header file before this is likely
                            // to generate some confusing error messages
                            // on some systems.

    // Why Note
    Node* getNode(int index)

Bug

 LinkedList  a;
 a.Add('a');
 a.Get(1); // Undefined behavior.
           // I believe _Get() is going to return a `nullptr`
           // which is then dereferenced by Get()

Declaring variables

    LinkedList list = LinkedList();
                   // ^^^^^^^^^^^^  Creates a temporary object.

Technically this is creating a LinkedList temporary object then calling the copy constructor of list to copy the temporary object then destroying the temporary object.

Fortunately most compilers will spot this and optimize out the copy and destruction and just create your object.

But this is simpler to declare as:

    LinkedList list;

Prefer \n to std::endl;

The only difference is that std::endl performs an extra flush. Forcing a manual flush is usually never the correct solution as the libraries will do this for you when required.

Main and return

The main() function is special. If the compiler detects there is no return it will plant one for you.

    return 0;

So there is no need to add it yourself. It is become standard that when main can return no other value than 0 that the return 0 is omitted to indicate that the application can never fail. So when I see a return 0 at then end I generally look around for the other situations where it can fail. So if there are potentially failure situations and you exit early with an return 1; then add a return 0; and then end otherwise don't bother.


Hangman game, written after taking a Python course

Your code structure is one of infinite recursion.  Main() calls placeholder(), which calls is_letter() which calls is_over() which calls is_letter() (recursive), or play_again() which calls Main() (recursive)!  Eventually, you will end up with a Stack Overflow if you play long enough!

What you want is a loop.  Two loops, actually.  Your program should be structured to operate something like:

play_again = True
while play_again:
    # initialize game state
    while not solved and guesses_left:
        # get guess
        # update game state
    play_again = ask_play_again()

No recursive calls are necessary.

You read all lines of the file to choose a random puzzle.  When you play again, you again read all lines in the file.  Perhaps you could read and store all the puzzles, and each time a game is played, you just select one randomly from the list.

Your placeholders are complicated, 3 character entities.  They could just be single characters, and spaces could be added during printing.

self.placeholder = [ "_" if ch != " " else " "  for ch in self.word ]

To print:

print("".join(f" {ch} " for ch in self.placeholder))

Or simply:

print("", "  ".join(self.placeholder))

You should allow for punctuation in the puzzles.  Like spaces, these should be directly shown, not converted to underscores.

 _  _  _  _  _  ’  _     _  _  _  _


String encryption function in admin section

It looks great, however, you can improve it as follows:

Break out the function into two - encrypt and decrypt. Your functions should do the least amount of things.
return on trim - no need to set $encryptedString.
In the encrypt, no need to have the second $string when you concat $iv. Just concat on the initial mcrypt call.

In the end, we're left with three functions. One setupCipher which creates the key, iv_size and iv. One encrypt and one decrypt to encrypt and decrypt, as follows:

private function setupCipher(){
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

    return array(
        pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3"),
        $iv_size,
        mcrypt_create_iv($iv_size, MCRYPT_RAND)
    );
}

public function decrypt($string){
    list($key, $iv_size) = $this->setupCipher();

    $string = base64_decode($string);
    $iv_dec = substr($string, 0, $iv_size);
    $ciphertext_dec = substr($string, $iv_size);
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec), "\0");
}

public function encrypt($string) {
    list($key, $iv_size, $iv) = $this->setupCipher();

    $string = $iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv);
    return trim(base64_encode($string), "\0");
}

You would use them nearly identically to how you used them before, except no need to pass in the $method:

# Encrypt
$_SESSION['username'] = $backend->encrypt($username);

# Decrypt
echo $backend->decrypt($_SESSION['username']);


Let's start with your naming.  flower is supposed to be a list, right?  Let's make it plural, then.

def moving(flowers):
    for i in range(len(flowers)):
        while flowers[i].y() < risar.maxY:
            for p in flowers: #p is position
                p.setPos(p.x(), p.y()+5)

Next, notice that you don't actually care about i; you just want to operate on every single flower.

def moving(flowers):
    for f in flowers:
        while f.y() < risar.maxY:
            for p in flowers: #p is position
                p.setPos(p.x(), p.y()+5)

Hmm… not only are there nested loops, but two of them iterate over all flowers.  What's going on?  I think you're trying to move all flowers "simultaneously" until all of them have their y-coordinate ≥ risar.maxY.  Then just say this, which I think is a bit more expressive:

def moving(flowers):
    while any([f.y() < risar.maxY for f in flowers]):
        for flower in flowers:
            flower.setPos(flower.x(), flower.y() + 5)


How can we optimizing Java BigInteger operations?

Division of the big integers is a very expensive operation. Even a division by 2 is linear in terms of its length: all bits must be shifted. The overall complexity is \$O(n \log{n})\$.
A natural desire is to not do arithmetics at all, but simulate it. Convert the bigint to byte array, and inspect bits, pretending that you perform arithmetics. In broad strokes, run the loop (starting with cursor = 0) until the number is exhausted:
if bit(cursor) == 0
    // simulate division
    increment counter
    advance cursor
else
    peek next_bit
    if next_bit == 0
        // simulate subtraction
        increment counter by 2
        advance cursor by 2
    else
        // simulate addition
        while next_bit == 1
            increment counter
            advance cursor
            peek next_bit
        advance cursor
        set bit at cursor to 1

This touches each bit just once, driving the complexity down to \$O(n)\$. Care must be taken to correctly terminate the loop.


Order of arguments

As a convention, arguments in functions are always ordered from most likely to change to less likely to change.

Because this allows...

Simplification (Currying)

Haskell is like Math.

Look at

2x + x = 1 + x

You would like the simplify the x, so:

2x = 1

The same applies to your code:

percentize inList = map (/ sum inList) inList

You can omit inList as it is just repeated on both sides:

count x inList =  length $ filter (x==) inList

Becomes:

count x = length . filter (x==)

Now the focus is not on the transformation of the argument, but on the definition of a function as the successive application of two (or more) known ones.

Another example is:

getDistribution inList = percentize $ map fromIntegral (getNoteCount inList)

That becomes:

getDistribution = percentize . map fromIntegral . getNoteCount

This is, left to right, a description of what the function does.

Conventional names

I see that inList goes inside the function, and I can see that it is a List from the type signature, such long names are not needed.

Just use the conventional xs for general lists:

percentize xs = map (/ sum xs) xs

Use where not let

It is more natural to read from general to specific than the opposite:

recommendNote notes targetDist = let y = zip (subtractLists targetDist (getDistribution notes)) noteTypes
                                in snd (maximumBy (comparing fst) y)

Becomes:

recommendNote notes targetDist = snd (maximumBy (comparing fst) y)
  where
    y = zip (subtractLists targetDist (getDistribution notes)) noteTypes

Where you also avoid overly long lines.

Generality

Be optimistic and general with your types:

count :: String -> [String] -> Int

Becomes:

count :: a -> [a] -> Int

Where a stands for anything.

Not everything is get

get is a specific OO technical term, prefixing it before the function names is confusing, just drop it.

Make tiny functions local

Things like:

subtractLists = zipWith (-)

May be local and without a type declaration, like:

recommendNote notes targetDist = snd (maximumBy (comparing fst) y)
  where
    y = zip (subtractLists targetDist (getDistribution notes)) noteTypes
    subtractLists = zipWith (-)


Algorithm for describing chess positions

The slowness when having fewer pieces

Having fewer pieces on the board will make this slower:

piece_letters = "KkQqRrNnBbPp"
for x in range(64):
    sq = str(node.board().piece_at(x))
    if sq in piece_letters:
        d[sq].append(chess.SQUARE_NAMES[x])

Consider these two (invalid) extremes:

When the board is full of K, the evaluation of sq in piece_letters will terminate with True after checking the first letter
When the board is empty, the evaluation of sq in piece_letters will have to check each letter in piece_letters until it can terminate with False

In the rest of the code,
there are more evaluations performed in the full case compared to the empty case,
but not enough to outweigh the effects of the sq in piece_letters check,
due to the length of piece_letters.

Changing piece_letters to this would help:

piece_letters = frozenset("KkQqRrNnBbPp")

This way the evaluation of sq in piece_letters won't have to step through all letters.

But actually, since you already have a dictionary with the possible pieces in d,
you don't need piece_letters at all,
you can use simply this:

for x in range(64):
    sq = str(node.board().piece_at(x))
    if sq in d:
        d[sq].append(chess.SQUARE_NAMES[x])

This is also better for another reason:
if d doesn't have a predefined [] value for the sq key,
then the original code wouldn't work anyway.
When you write it this way,
it's clear that d[sq] exists, and will not raise a KeyError,
so it's more coherent and readable.

Actually the piece_letters string can be useful to initialize d itself:

piece_letters = "KkQqRrNnBbPp"
d = dict((c, []) for c in piece_letters)

And d is a very poor name. pieces would be better.

Other optimizations

Avoid using global variables if possible.
It would be better to pass node.board() to the method if possible.
Actually it seems the method should belong to the board itself,
and I would rename it to print_board.

The printing of the pieces is very repetitive.
It would be better to extract their logic to a helper function, for example:

def format_piece(marker, single_name, plural_name):
    num = len(pieces[marker])
    if num:
        label = plural_name if num >= 2 else single_name
        return "%s: %s\n" % (label, ", ".join(pieces[marker]))
    return ''

pos = "White pieces:\nKing: %s\n" % d["K"][0]
pos += format_piece('Q', 'Queen', 'Queens')
pos += format_piece('R', 'Rook', 'Rooks')
# ...

This achieves 2 additional optimizations:

Count the length of each pieces[marker] only once
Avoid duplication in the formatting, by setting label