Unfinished ?
You have the variable run set to false and then use it in a ternary to set i. run is never set to true. I assume you intended to set it true after scanning a plateau.
JavaScript Style

In JavaScript we put the opening { on the same line and else on the same line as the closing }

Spaces between operators. eg arr[i+1]; becomes arr[i + 1];

Always declare variables. The variables next and previous are undeclared and are thus automatically declared in global scope. Global scoped variables are significantly slower, and highly likely to conflict with other globals if you are unaware. Use the directive "use strict" (strict mode) which will throw an error when you use undeclared variables.

Use ; consistently. JavaScript requires them and will insert them automatically if you do not add them where required. The insertion rules are complex and unless you are familiar with them it is best to always use them.

Use meaningful names. obj could be result. Better yet you can declare the arrays pos and peaks as variables and build the object on the return. eg return {pos, peaks} this saves you having to indirectly reference the arrays when you use them. (see rewrite)

Learn the difference between function scope var and block scope let, const and use appropriately.

Always declare vars at the top of the function. You declared j as a var in the middle of the function.

Always delimit code blocks with {} eg while (foo) j++; should be while (foo) { j++; } with the exception of empty blocks. eg while (arr[i++] !== 0); I know that C like languages let you skip the {} but after years of coding I can tell you it is a very hard bug to spot when you change code and forget to delimit the block.

Avoid single use variables unless doing so will make a line too long. Eg next = arr[j] < arr[i]; if (previous && next) { becomes just if (previous && arr[j] < arr[i]) {

Use the simplest logic. the line if (new Set(arr.slice(i, i + 2)).size === 1) { creates a new Array, a new Set, populates the Set by generating a hash for each array item. That is a lot of overhead (you generate a Hash twice for each inner array item) that can replaces with if (arr[i] === arr[i+1]) { with only the i + 1 being overhead

Always try to reduce indexing into arrays by assigning array items into variables. Generally do this if you use the item 2 or more times. For engines like V8 (Chrome and Node) this can provide some worthwhile performance improvements. Firefox this makes no difference however it does make the code less noisy and thus easier to read..

Rewrite
I think your solution is a little over complicated, especially indexing into the array so many times. Nor is there a need to make a special case of plateaus.
The rewrite is a simpler solution that uses the variables climbing to track positions where the current item is greater than the previous. If the item is less than the previous then record the peak to be the climbing position. The plateau is thus automatically handled, and the number of lines and variables is greatly reduced.
The rewrite runs on average 15 times faster on the same data.
However to be fair the slow point is the use of the Set in the statement  if(new Set(arr.slice(i, i+2)).size === 1) If you change that line to if (arr[i] === arr[i + 1]) { and add run = true in the plateau statement block, your function is then only about 30% slower than the rewrite (see second rewrite)
"use strict";   // not needed if this was a module
function pickPeaks(arr) {
    const pos = [], peaks = [];
    var i = 1, climbing, prevVal = arr[0];
    while (i < arr.length) {
        const val = arr[i++];
        if (val < prevVal && climbing) {
            pos.push(--climbing);
            peaks.push(arr[climbing]);
            climbing = 0;
        } else if (val > prevVal) { climbing = i }
        prevVal = val;
    }
    return {pos, peaks};
}

And rewriting you algorithm using the points in this answer we get...
function pickPeaks(arr){
    const pos = [], peaks = [];
    var j, i = 1;
    while (i < arr.length) {
        const val = arr[i], nextVal = arr[i + 1];
        let run = false, peak = false;
        if (val === nextVal) {
            j = i;
            while (arr[j] === val) { j++ }
            if (arr[i - 1] < val && arr[j] < val) { peak = true }
            run = true;
        } else if (val > arr[i - 1] && val > nextVal) { peak = true }
        if (peak) {
            pos.push(i);
            peaks.push(val);
        }
        i = run ? j : i + 1;
   }
   return {pos, peaks};
}


Hexadecimal number to decimal conversion

To take a quick first stab at some style issues:

Follow a consistent indentation style. This makes the code extremely readable, and you will thank yourself later when you come back to your code.

For example:

void foo()
{
  do
  {
    bar();
  } while(0);
}

int main()
{
  foo();
}

Try to break down your program into smaller code blocks that you can reason about them independently, and perhaps even test them independently.

For example, how about start with this template, and fill in the code:

// checks
bool isValid(const std::string &hexInput)
{

}

int64_t convertHexToDecimal(const std::string& hexString)
{

}

int main()
{
    std::string input;
    std::cin >> input;

    while(isValid(input))
    {
        // perform the conversion
        int64_t convertedDecimal = convertHexToDecimal(input);

        // output the conversion
        std::cout << "..." << convertedDecimal <<  std::endl;

        // get new input
        std::cin >> input;
    }
}

Use std::string liberally instead of a character array. I think this is a more c++11 style of going about it. This will allow you to utilize the wealth of STL. This is more recognizable, and reduces the changes of introducing bugs in your hand-rolled while/for loop.

auto found = input.find('.');
if (found != std::string::npos)
{
    std::cout << "Period found at: " << found << '\n';
}

Your way of checking if the input string is hexadecimal is very awkward and unreadable. Whenever you use constants, you should declare them as consts, so you can update them without having to change the code.

A hexadecimal string has characters from one of the following set of characters:

0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F and the ., also the . should appear exactly once, and should probably not be the last character of the string. Also, you can use the characters directly for the comparison instead of the ASCII values.

bool isValidHex = true;

// for_each will iterate between the the provided iterators
// for each position, you can pass a lambda function that checks
// the characters
std::for_each(
    str.begin(),
    str.end(),
    [&isValidHex](char c)
          {
            // std::cout << "Checking" << c << std::endl;
            if ((c >= 'a' && c <= 'f') ||
                (c >= 'A' && c <= 'F') ||
                (c >= '0' && c  <= '9'))
            {
                // this is a valid hex.
            }
            else
            {
                isValidHex = false;
            }
          });

If lambdas are not your style, you can also use the new c++11 loop style, which is much more readable.

for (char c : input)
{
    // perform checks here
}

To Be Continued..


Scaling the last column in a table (with input) to match the container

The 7px padding issue can be solved by adding box-sizing: border-box to the input. That'll make the input's 100% width include the input's border and padding.

As for using a read-only input, I'd say that's a fine solution - at least for the data. Besides scrolling without requiring a scrollbar, it also let's you use a select all command, without it selecting the entire page.

The series name and r2 stuff doesn't need to be labels and inputs, though. They can be spans if you want to style their values, but basically I'd suggest something like this:

  Series

  Manual Sizing

The trick, then, is to add the following to .details td:

width: 1%;
white-space: nowrap;

This will prevent the text wrapping on the space in "Manual Sizing", but the explicit break tag is still respected. And, because the cell is set to 1% width (or some other low, low value), it'll shrink to its smallest size, leaving more room for the data.

Again, if you use spans to separately style name and value within the two cells, you can apply the nowrap rule to the spans alone, while the 1% width can remain on the enclosing  to squish it.

In the end I get:

#dummy {
    width: 100%;
    background-color: lightgreen;
}

.details {
    width: 100%;
    border-collapse: collapse;
}

.details td {
    border: 1px black solid;
    padding: 3px;
    width: 1%;
    white-space: nowrap;
}

.details td:last-child {
    width: 100%;
    background-color: lightblue;
}

.details td:last-child input {
    box-sizing: border-box;
    width: 100%;
}

text to show where a graph would be

    Manual visualization

          Series

          Manual Sizing

          RSquared

          0.98765432

          Description

          <input id="seriesDetail" type="text" readonly
            value="[1,23],[2,20],[4,20],[8,21],[16,23],[32,22],[64,26],[128,28],[256,41],[512,55],[1024,81],[2048,136],[4096,244],[8192,474],[16384,959],[32768,1987],[65536,3613],[131072,6957],[262144,14250],[524288,28215],[1048576,55882],[2097152,116210],[3145728,175000],[4194304,229976],[5242880,291501],[6291456,347649],[7340032,399349],[8388608,485512]">

I've dropped the  tag for the data input, but that's just me.

Lastly, the readonly attribute doesn't need to have a value; it just needs to be "mentioned", so to speak. It's presence is its value. Giving it a value is fine too, of course. Just thought I'd mention it.

The downside of squishing the cells is of course that the layout will shift a little for different content. E.g. a longer series name will push things around.

Again, if you use a span, you can add something like this to limit its size:

display: inline-block; /* allows the span to respect a max-width */
max-width: 100px; /* or something */
overflow: hidden;
text-overflow: ellipsis;

That'll truncate the text to fit 100px (e.g. you'd get "Manual S…" or something).

The gotcha is that the text-overflow literally chops off some of the text, so it's no longer selectable. On my screen the snippet below shows the series name as "Manual…", while selecting it and copying only copies "Manual" (leaving out both the truncated text, and the ellipsis that replaced it).

.details {
    width: 100%;
    border-collapse: collapse;
}

.details td {
    border: 1px black solid;
    padding: 3px;
    width: 1%;
    white-space: nowrap;
}

.details td:last-child {
    width: 100%;
    background-color: lightblue;
}

.details td:last-child input {
    box-sizing: border-box;
    width: 100%;
}

.details td span {
    display: inline-block;
    max-width: 64px;
    overflow: hidden;
    text-overflow: ellipsis;
}

          Series

          Manual Sizing

          RSquared

          0.98765432

          Description

          <input id="seriesDetail" type="text" readonly
            value="[1,23],[2,20],[4,20],[8,21],[16,23],[32,22],[64,26],[128,28],[256,41],[512,55],[1024,81],[2048,136],[4096,244],[8192,474],[16384,959],[32768,1987],[65536,3613],[131072,6957],[262144,14250],[524288,28215],[1048576,55882],[2097152,116210],[3145728,175000],[4194304,229976],[5242880,291501],[6291456,347649],[7340032,399349],[8388608,485512]">

Edit: Thinking about it some more, you probably should go for having a separate table header section:

      Series
      RSquared
      Description

      Manual Sizing
      0.98765432
      data...

It's more semantically correct, and it also gives you better opportunities to apply styling without requiring extra span elements or classes or what have you.

Depending on your setup, you could even add all the series as rows, and simply hide/show them as needed.


Looks good, nice and clean. Nitpicks:

no need to introduce a method called printSimpleResult when you can simply override toString (either way, the "print" part is a lie as the method returns the string, doesn't print it)
missing @Override annotation in DeltaBiggerThanZero
naming a variable "result" in the tests is a bit ambiguous, especially since it seems that you don't know what order of params assertEquals takes in (it's "expected, actual", for the record)
why artificially limit input parameters a, b, c to integers only?
what's the purpose of throws NullPointerException in calculate's signature? I see no way in which this exception could be triggered, and you're not required to declare unchecked exceptions (and it's a matter of discussion whether you should)

You didn't include the code for NoSolution but apparently it's an implementation that returns null for most of the fields. This begs for using Java 8's Optional. Returning null and hoping the clients will know and remember how to interpret it is a bad idea.

On the other hand, creating a class hierarchy for different kinds of solutions is rather problematic for the client (arguably this is not the scenario that calls for inheritance, which should be used judiciously). Since calculate() returns an abstract Result, the client still needs to do "sniffing" on the returned object to figure out how many (if any) results there were. They could to this either by checking via instanceof or trying to see what x1 and x2 are (if x2 is null it must be the "delta-is-zero" case, if both x1 and x2 are null it must be the "delta-is-negative" case with no solutions). Neither of these options is elegant or clean. A better solution could be to return a List<Double> that has either zero, one or two elements in it. A simple implementation that would allow you to get rid of the Result type and its subclasses could be:

public List<Double> calculate() {
    Double delta = calculateDelta();
    if (delta > 0) {
        return new ArrayList<Double>(Arrays.asList(new Double[] { calculateX1(), calculateX2() }));
    } else if (delta == 0) {
        return new ArrayList<Double>(Arrays.asList(new Double[] { calculateOneRoot() }));
    } else {
        return Collections.<Double> emptyList();
    }
}

A List has a nice default implementation of toString() so the client calling the code above could just do:

QuadraticFunction qf = new QuadraticFunction(1, -4, -5);
List<Double> results = qf.calculate();
System.out.println("Rozwiązania to: " + results);

To get the output of:

  Rozwiązania to: [-1.0, 5.0]


I don't see much reason to worry about this method's length. At least not right now - if you add more event handling, yeah, it might become a little cumbersome. But for what it does now, there's no pressing need to do anything.

I would recommend more whitespace, though. There's no reason to compress,every,line,that,has,commas,in,it. Just makes it harder to read.

I'm also fairly sure that the :finished event is actually called :finish

Structurally, just for the sake of it, you could do something like:

class Uploader
  attr_reader :host, :user, :password

  def initialize(host, user, password)
    @host = host
    @user = user
    @password = password
  end

  def upload(local_file_path, remote_file_path)
    Net::SFTP.start(host, user, password: password) do |sftp|
      sftp.upload!(local_file_path, remote_file_path) do |event, uploader, *args|
        send(event, uploader, *args) if respond_to?(event, true)
      end
    end
  end

  private

  def open(uploader, *args)
    Rails.logger("Starting upload...")
  end

  def close(uploader, *args)
    Rails.logger("Upload complete")
  end

  def finish(uploader, *args)
    Rails.logger("All done")
  end
end

Basically, we're handling events with methods instead of a case block. I've added the close method/event handler as an example.


Simple DNA sequence finder w/ mismatch tolerance

This is a solved problem in bioinformatics and there are specific algorithms depending on your specific use-case:

Do you allow gaps?
How many mismatches do gaps incur?
… etc.

In the general case, this is a global pairwise alignment which is computed by the Needleman–Wunsch algorithm. If you are just interested in the score of the alignment, rather than the complete alignment, this can be simplified by not performing the backtracking.

Now, if you have a threshold and are only interested in finding matches below said threshold, then a more efficient variant employs the Ukkonen trick – unfortunately, references for this are hard to find online, and the print literature is quite expensive. But what it does is essentially break the recurrence in the above-mentioned algorithm once the score exceeds the threshold chosen before (using the insight that the error score can only increase, never decrease in a given column).

But all this is unnecessary if you don’t allow gaps. In that case, the algorithm is as straightforward as walking over both strings at once and looking whether the current positions match.

And this can be expressed in a single line:

def distance(a, b):
    return sum(map(lambda (x, y): 0 if x == y else 1, zip(a, b)))

and:

def distance_less_than(k, a, b):
    return distance(a, b) < k


Illegal void pointer arithmetic
This code is illegal in C:
void *array;
... (array + offset)

You are not allowed to do pointer arithmetic on a void * pointer.  You should use char * instead of void *.
Simplifications
I would suggest defining a generic structure like this:
typedef struct EnumName {
    int         value;
    const char *name;
} EnumName;

to avoid all of the struct length shenanigans.  You can also make it a rule that each EnumName array must be terminated with a NULL name.  This rule allows you to avoid passing in an array length argument.  Then your code would look like this:
const EnumName direction_data[] =
{
    {north, "north"},
    {south, "south"},
    {east,  "east" },
    {west,  "west" },
    {0,      NULL  },
};

const char *Get_text_from_enum(int enum_value, const EnumName *names)
{
    while (names->value != enum_value && names->name != NULL)
        names++;
    return names->name;
}

int main(void)
{
    printf("Expect south,    got %s\n",
            Get_text_from_enum(south, direction_data));
}


Insert 271 million records from text file to mongodb

First, you need to consider that adding 271 million records is going to be long, there's no changing that. You should also consider your processing power. You could have the best code in the world, if it runs on an average computer it's going to be average.

Now, what can be done better?

What you're doing is called bulk insertion. There are mechanisms with every database engine that enable doing this faster than one insert at a time. For example, you should consider using the Bulk object to insert many lines at the same time. Basically, you want most of your processing to be done by the database engine, simply because it was written by experts on how to do things fast and without problems. Looking at the Bulk object maximum size, your bulk insert cannot be bigger than 16 megabytes. Considering you have 8 digits number, you can figure out what's the biggest bulk insert you can do!

Running 261 threads probably hurts your performance. After all, the 261 threads probably don't run in parallel (because.. I doubt you have 261 threads available, but who knows). Do more research of multi-threading, maybe using a simple parallel library with way less threads would even be faster. I've got to admit I'm not an expert in threading myself, but I'm pretty confident running 261 threads will simply hurt your performance, these threads need to be managed!

Now, there are a couple things that bother me with your situation :

How many files do you have? If you have like... a million files with 271 lines each, you should consider pre-processing the whole thing to reduce the number of file access necessary. I'd even consider keeping only 1 file.
If you have \$2.71*10^8\$ 8 digit numbers and, I didn't have my morning coffee yet, there are \$9*10^7\$ possible combinations of 8 digits, you would have a lot of duplicates. Are you sure there isn't a simpler way to insert your data than reading 271000000 8 digits numbers from files?

Anyways, I think the main thing you need to consider is using bulk insertion, which brings me to my final tip : Read the documentation of whatever database engine you're using. They are big pieces of code and it's pretty sure you will find something interesting to help you.


small web scraper to read product highlight from given urls

Splitting lines
Don't call splitlines() here:
org_file = open('config/organisation.txt', 'r')
return org_file.read().splitlines()

The file object itself is an iterator over its lines. Also, use a context manager to ensure file closure:
with open('config/organisation.txt', 'r') as f:
    return {line.rstrip() for line in f}

This is a set comprehension. You want a set because you're only ever checking for membership, and this will be more efficient.
Generator simplification
You don't really need to yield here:
for url in start_urls:
    yield scrapy.Request(url=url, callback=self.parse)

Instead,
return (
    scrapy.Request(url=url, callback=self.parse)
    for url in start_urls
)

Strongly-typed results
Since you're more experienced in .NET, consider how you would traditionally represent this:
yield {
    'product_id': product_highlight.css('[data-id="ProductId"] span::text').get(),
    'title': product_highlight.css('[data-title="ProductTitle"] h1::text').get(),
    'price': response.css('[data-price="ProductPrice"] span span::text').get(),
    'organisation': organisation,
}

Hint: it's not a dictionary. You would do better to make a class (perhaps a @dataclass) with well-defined members, and set your return type hint for this method to  -> Iterable[ResultType].


You can look for only the checked checkboxes, and then check that you found two:

if ($("#agree1:checked,#agree2:checked").length == 2) { ... }


JavaScript/HTML web application - user interface logic

Readability - the code reads fine.  The modes concept is explained well just by reading the code, so I wouldn't worry about that.

Code style - Javascript programmers are used to passing functions around and probably wouldn't bat an eyelid at the idea of assigning different functions to a variable, but it makes more sense to me to always have the same function as the event handler, and call the action for the current mode from within it:

var bookmarkEventMapping = function(e) {
    bookmarkActions[bookmarkActions.currentMode].eventMapping(e);
};

A couple of other things I would do, out of personal preference more than anything:

store the list of modes separately, not in the bookmarkActions object
refer to the modes using references to the actual objects, as opposed to using the object property names.

If you did store the mode list separately, you could also make things cleaner by making that list the only place where information about the modes is stored and using it to generate the html, instead of having to maintain the html and the code in initModeMenu separately.


Reach certain Wiki page through random links

Wikipedia has an API available. You can make calls to e.g. "https://en.wikipedia.org/w/api.php?action=query&prop=links&titles={title}&pllimit=500" and get back a list of titles the Wikipedia page title links to, without all the internal links (but with non-existing pages and things like categories).

Incidentally, there is even a python package available that makes using it a lot easier, Wikipedia-API. With this your code would become:

import requests
from bs4 import BeautifulSoup
import wikipediaapi
import random
from itertools import count

WIKI = wikipediaapi.Wikipedia('en')

def random_page():
    r = requests.get("https://en.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(r.content)
    page = WIKI.page(soup.title.text[:-12])
    assert page.exists()
    return page

BLACKLISTED = ["Wikipedia:", "Category:", "Template:", "Template talk:", "User:",
               "User talk:", "Module:", "Help:", "File:", "Portal:"]
def blacklisted(title):
    return any(title.startswith(x) for x in BLACKLISTED)

def random_walk(target_title):
    page = random_page()
    for i in count():
        print(i, page)
        if page.title == target_title:
            return i
        links = list(page.links.values())
        # print(f"{len(links)} links")
        if not links:
            return None
        page = random.choice(links)
        while blacklisted(page.title) or not page.exists():
            page = random.choice(links)

if __name__ == "__main__":
    print(random_walk('Mathematics'))

This still needs to blacklist some pages (see BLACKLISTED constant, the content of which I found by trial-and-error) and I'm not quite happy about the trial and error way of getting a random page, but filtering for existing pages needs to fetch them all, which is quite slow.

In any case, this should be a bit faster than actually getting the whole page and parsing it yourself.

I also put the code into function and guarded the calling under a if __name__ == "__main__": to allow reusing of the code. In doing this I took the liberty of adding a counter and returning it in case the target page is found (12000 pages and counting...).

Another question is if this is the best/most fun way to play this game. The way I know it, the goal is to reach a target page as fast as possible. In that case you will want to do a breadth-first search of all links instead (depth-first would fail because there are loops, meaning you could get lost forever). Although I have to admit, it is fun watching the bot and seeing where it wanders...

A good compromise might be checking if any of the links on the current page is to Mathematics, and only randomly jumping to the next page if not.

Some generic comments about your code:

You don't need parenthesis around your conditions, and they are discouraged unless needed to make the condition span multiple lines.
Empty lists are falsey, so you can replace if (a == []): with if not a:.
Your code only tries twice to get a random page, which will work most of the time but will fail eventually. Instead use a while loop that continues indefinitely.


Possible bug:

The following demo will throw a NullPointerException:

public static void main(String[] args) {
    Deque<Integer> stack = new ArrayDeque<>();

    stack.addLast(2);
    stack.addLast(-1);
    stack.addLast(-3);
    stack.addLast(1);

    System.out.println("Original stack: " + stack);
    SortStackAscendingOrder sorter = new SortStackAscendingOrder();

    Deque<Integer> sortedStack = sorter.sortStack(stack);

    System.out.println("Sorted original stack: " + sortedStack);

    stack.clear();
    stack.addLast(11);
    stack.addLast(8);
    stack.addLast(9);
    stack.addLast(10);

    System.out.println("Another stack: " +
            sorter.sortStack(stack));

    System.out.println("Sorted original stack again: " + sortedStack);
}

Most likely the problem above is due to the fact that you return stackhelper1, which is an essential internal facility in your algorithm.

API design:

First of all, I would consider implementing the stack sort as a static method that does not "leak" any internals. The idea here is that you sort the input stack: just like sorting methods in java.util.Arrays, all are void and modify the input arrays instead of returning a sorted copy.

All in all, I had this in mind:

public static void sortStack(Deque<Integer> mainStack) {
    Deque<Integer> stackHelper1 = new ArrayDeque<>();
    Deque<Integer> stackHelper2 = new ArrayDeque<>();

    while (!mainStack.isEmpty()) {
        int mainItem = mainStack.pop();
        int helperItem1 = -1;

        if (!stackHelper1.isEmpty()) {
            helperItem1 = stackHelper1.peek();
        }

        if (mainItem > helperItem1) {
            while (!stackHelper1.isEmpty() && mainItem > helperItem1) {
                stackHelper2.push(stackHelper1.pop());
                helperItem1 = stackHelper1.peek();
            }

            stackHelper1.push(mainItem);

            while (!stackHelper2.isEmpty()) {
                stackHelper1.push(stackHelper2.pop());
            }
        } else {
            stackHelper1.push(mainItem);
        }
    }

    mainStack.clear();
    mainStack.addAll(stackHelper1);
}


Using method chains when rendering a scene

Is writing Java code in chain like _hud.getStage().getCamera().combined an ugly practice?

The general design guideline (Law of Demeter) is to avoid such method chains. In some cases it can be justified.

The ugliest thing on this line is the _ prefix of a field which I suppose you intended as private, but there is no such convention in Java. Use camelCase for fields and methods, regardless of visibility, that's the convention.

Another unusual thing on this line is the direct use of the public field combined instead of a getter. It's unusual because a getter would give more flexibility for future extensions, as methods can be overridden by derived classes, while fields cannot be.

In any case, the chained call and the public field are not your "fault". The GDX library designers decided to provide this usage, and I assume they knew what they were doing. If you meant your question as "should I break up the chain to local variables and call them like that?" like this:

Stage stage = _hud.getStage();
Camera camera = stage.getCamera();
Matrix4 projection = camera.combined;

No, that wouldn't change the fact of the coupling, this is still a chained call, just expanded, and this is worse than the compact writing style, with no benefits within this snippet.

  If yes, what would be the pretty way to write the code?

Going just a tad further than @rolfl:

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    Stage stage = hud.getStage();
    batch.setProjectionMatrix(stage.getCamera().combined);
    stage.draw();
}

That is:

Avoid the _ prefix for all fields
Add a space after commas in parameter lists
Extract shared code (hud.getStage()) to local variable

It's not much prettier than the original, but you asked for it.

  What are the consequences of this?

The wiki page of Law of Demeter explains this in detail, but in a nutshell, chained method calls are tight coupling, unless the chained calls return the same object, such as in a fluent Builder or in a Java 8 Stream (thanks @sylvain-boisse, good point). It's ok that your class knows that hud has a Stage, but it's not ok that it knows that Stage has a Camera and further, that it has a projection named combined. The recommendation would be to provide a getCombinedCameraProjection method on hud, which would hide the class hierarchy, giving the designer the freedom to redesign the elements used behind that method (the Camera, etc), without affecting users of the API.

However, not following the Law of Demeter to the letter doesn't imply that this in itself is bad design. Applying LoD systemically everywhere would not be practical, as it could lead to an explosion of getters for the permutation of all uses of a Camera in this example. Multiple design recommendations often conflict (here encapsulation and usability), balancing them is extremely difficult. You have to choose between tradeoffs, and the designers of GDX have made their own, probably good choices.


stack->data = (uint8_t *)realloc(stack->data, stack->capacity * stack->itemSize);

This is wrong, because if realloc() failed, then there's now no way to access the memory previously pointed to by stack->data.  The correct pattern for realloc() is:

void *newData = realloc(stack->data, stack->capacity * stack->itemSize);
if (!newData) {
    // Insert error handling - you'll want to restore the old stack->capacity here
    // or (better) wait until we're okay before updating.
    return FAILURE:
}
stack->data = newData;

I recommend against casting the result of malloc() family when assigning - these functions return void*, which is assignable to any pointer type without a cast.  The unnecessary cast just distracts the reader (because casts generally indicate danger areas in code).  The same is true for conversions from pointer types to void*, such as this one:

return (void *)item;

That can simply be

return item;

The stack_pop interface is difficult to use - callers have to deal with possible null pointer return, and must remember to free() the result.  Instead, consider having the caller provide memory to write into:

void stack_pop(Stack *stack, void *target);

The caller should already know the size required for target, and can now get  results in local (auto) storage:

int foo;
stack_pop(&stack, &foo);
// no need to check for null, or to call free()


Regular Expression to remove blank lines

What follows is a fairly harsh critique, but I'm hoping that that's what you're looking for as you seem to want to improve you ruby and programming style. Ruby is a lovely language, but getting to know it takes some time - eventually you'll realise that just about everything you write used to take twice as many lines. So, a few pointers:

Variables

Generally in ruby normal variables are underscored. So instead of aVariableName you should probably use a_variable_name. Both will work, but the latter would fit the Ruby style better.

Additionally you choice of variable names seems to go from overly verbose to the opposite. Some are great, but others leave my guessing.

For example where you write:

reader = File.read(input_filename)

I would prefer to write:

in_file = File.read(in_filename)

Functions

Like your variables, the naming of your functions could do with a touch-up. Your functions do not make use of the implicit return that Ruby offers, something that is often considered a better practice.

For example where you write:

  def  remove(stringToremove)

    regEx = /^[\s]*$\n/

    stringToReturn = stringToremove.gsub(regEx, '')
    stringToReturn.strip!

    if stringToReturn.length >= 1
      return stringToReturn
    else
      return ""
    end
  end

In this regard I might have written:

  def remove(stringToremove)

    regEx = /^[\s]*$\n/

    stringToReturn = stringToremove.gsub(regEx, '').strip
  end

Also on your initialize function you include brackets in the definitions this is not required, and is discouraged. Additionally you don't need to include a initializer if there's nothing for it to do.

Rubyness

Some things you might want to consider further as you do more programming in ruby are:

Chaining. For example you can do a_string.gsub("some", "substitution").strip.reverse and other such things all in one line and still keep readability high. Obviously there's a point where it's too much, but that's your judgement.
Your code formatting is a bit out. In a lot of places you seem to be using extra spaces. For example you class definition is class  BlankLineRemover and should really be class BlankLineRemover. You might be using soft-tabs here, and if that's the case - please don't.
You spacing is also very generous. Unless you're separating code into particular chunks then you can skip a few newlines.
This is a real nit-pick, but generally using .size is considered better than .length.

Rewrite

Here's your main class rewritten the way I would have gone about it.

class BlankLineRemover
  def run(in_filename, out_filename)
    File.open(out_filename, "w") do |out_file|
      out_file.write clean(File.read(in_filename))
    end
  end

  def clean(input)
    input.gsub(/^[\s]*$\n/, "").strip
  end
end


Callback of setTimeout function when performing synchronous actions

I'd make the counter function return a promise. If you understand promises, I think this example will be enough. If not, please ask and I'll clarify.

function counter(count) {
    var deferred = Promise.defer();

    var countDownFrom = count;
    var timer = setInterval(function() { handleTimer(countDownFrom); }, 1000);

    function handleTimer(count) {
        if (count === 0) {
            clearInterval(timer);
            deferred.resolve();
        } else {
            console.log(count);
            countDownFrom--;
        }
    }

    return deferred.promise;
}

Promise.resolve()
    .then(function() {
        console.log('start');
        return counter(3);
    })
    .then(function() {
        console.log('ready');
    });


The obvious improvement to the code you have here is that you should package it up as a jQuery plugin, to improve code reusability and reduce the number of global variables created.

You'll also want to use a class instead of id, to improve reusability (if you chose not to change this to a plugin), and to store as much information on the element themselves, instead of using global variables to store information, to create less coupled functions.

Otherwise, going down the code line by line:

Inside the fill_ratings function:

$rating.append('<img id="' + i + '"src="star_default.png" />');

You are creating elements with id attribute starting with a number. This is illegal before HTML5. Also, you can create elements in a more 'jQuery' manner with this syntax instead:

$('<img>', {
    id: 'star-' + i,
    src: 'star_default.png'
}).appendTo($rating);

The main benefit of this is that now you have a reference to element you just created. You can then push it to an array, to reuse later, instead of creating new jQuery objects by attempting to select the same elements again later in the code.

Variable declaration - mostly a style suggestion, but you can avoid multiple vars by using the comma operator:

var hovered = 0,
    has_clicked = false,
    star_clicked = 0;

Don't use $(this) to get element attributes:

$(this).attr('id');

is about 97% slower than

this.id;

the latter is less verbose and much much more efficient.

Inside each of the event handlers attached to #rating img - instead of looping through all #rating img element, like you're doing:

    for (i = 1; i <= max_stars; i++) {
        if (i <= hovered) {
            $('#rating img#' + i).attr('src', 'star.png');
        } else {
            $('#rating img#' + i).attr('src', 'star_default.png');
        }
    }

We can always use the information already given (the current element triggering the event) to do the processing. The above code, for instance, can be written as:

$(this).prevAll().attr('src', 'star.png');

thereby reducing the all those lines into one, and removing a variable. Most of the other event handlers can be similarly rewritten.

Type coercion to Number can be done without using Number - just append a + in front of the variable. In your case, it is completely unnecessary, since you're coercing it back to String again after joining it to another string in the selector passed to the jQuery selector


javascript multiple inheritance code review

First of all, I responded to the post in c.l.js, and this content in part reiterates the comments there.

My first thought is that you should look at some of the available mixin libraries.  There are many mixin techniques available.  And on top of that, there are many interesting approaches layered on top of them.  Peter Michaux published one recently on applying mixins to constructor functions.  Angus Croll published one on creating functions out of mixins, and together with Dan Webb he also presented this technique at the recent Fluent Conference.  I published a rough draft of an article on a still different approach to mixins.

I don't understand the reason for your complex syntactic structure.
You assign your ObjectExt variable to the result of an immediately
invoked function expression (IIFE).  That IIFE involves defining a
constructor function, attaching the inherit function to its
prototype`, and then constructing and returning an instance of that
constructor:

 var ObjectExt = (function () {
     var ObjectExt = function () { };
     ObjectExt.prototype.inherit = function (Parent, Child) {
         // content here
     };
     return new ObjectExt();
 })();

I don't see that any of that serves any purpose over the much simpler
version here:

 var ObjectExt = {inherit: function (Parent, Child) {
     // content here
 };

Can you give any reason for the existence of this constructor
function, the IIFE, the prototype, etc?  It seems to be plain
overhead, and serves only to obfuscate your code.

One other minor point is that you probably should declare your key
variable once in the top of the inherit function.

But the main issue is that you add properties to the parent.prototype object.  In this code:

if(Child.uber === undefined)    {
    Child.uber = Parent.prototype;               // (1)
} else {
    for(var key in Parent.prototype)    {
       Child.uber[key] = Parent.prototype[key];  // (2)
    }
}

in the line marked (1), you create the Child.uber property as reference to the Parent.prototype.  So any properties you add when you come through the if-block again and hit (2) will be added to the orignial prototype object.  This is a pretty fundamental flaw.  An example would be the following:

var Pet = function(name) {this.name = name;}
Pet.prototype.speak = function(){
    console.log(this.name + " speaks.");
};
var WalkingAnimal = function() {};
WalkingAnimal.prototype.walk = function() {
    console.log(this.name + " is walking.");
};
var SwimmingAnimal = function() {};
SwimmingAnimal.prototype.swim = function() {
    console.log(this.name + " is swimming.");
};
var Dog = function(name) {this.name = name;};
WebbaseUtility.ObjectExt.inherit(Pet, Dog);
WebbaseUtility.ObjectExt.inherit(WalkingAnimal, Dog);

var ClownFish = function(name) {this.name = name;};
WebbaseUtility.ObjectExt.inherit(Pet, ClownFish);
WebbaseUtility.ObjectExt.inherit(SwimmingAnimal, ClownFish);

var rover = new Dog("Rover");
var nemo = new ClownFish("Nemo");
rover.walk();  // "Rover is walking";
nemo.swim();   // "Nemo is swimming";
nemo.walk();   // "Nemo is walking";   // WTF?

This is a fairly fundamental design flaw.  I think you need to rethink your approach to this problem.

Cheers,

-- Scott


Storing statistics as JSON in a simulation game

Some extra points that Sam Onᴇᴌᴀ's good review skipped.

Capitalizing function names

Don't capitalize functions if they are not used to create an object. In JavaScript we only capitalize functions or objects that can be instantiated with the new token. Thus MakeStats should be makeStats.

However if you were to return the object statJSON then you could use the name MakeStats to indicate that it instantiates an object. You can then create the object in 3 ways, each of which return the same object.

    // last 2 lines of MakeStats to be
    return statJSON;
}

const s1 = new MakeStats();
const s2 = new MakeStats;  // with new objects () is not needed if there are no arguments
const s3 = MakeStats();

Quoted property names

I see this a lot, when people create an object that is to be stringified. For some reason  quoted property names are used. Doing so is just adding unneeded noise to the code.

The only time you need to use quotes to define a property is if the property is not a valid javascript variable name. e.g.  {data-one: "one"} will throw an error as data-one is not a valid name, you would thus write it {"data-one": "one"}

Shorthand property names (ES2015)

Use object property shorthand if you are adding existing named variables to an object.

You have

let tempJSON = {
    "location": {
        "home": home,
        "motel": motel,
        "relative": relative,
        "shelter": shelter,
        "apartment": apartment
    },
    "moneyLeft": money,
    "ACLeft": AC,
    "finalDestination": currentlocation,
    "hasAttorney": hasAttorney,
    "hasAC": hasAC,
    "hasMoney": hasMoney
};

can be written as

const tempJSON = {
    location: {home, motel, relative, shelter, apartment},
    moneyLeft: money,
    ACLeft: AC,
    finalDestination: currentlocation,
    hasAttorney,
    hasAC,
    hasMoney
};

the resulting object is identical to the longhand version.

localStorage

You can use simpler notation when accessing localStorage.

You have

localStorage.setItem("playerStats", JSON.stringify(statJSON));

is identical to

localStorage.playerStats = JSON.stringify(statJSON);

The same applies to reading from localStorage

stats = localStorage.playerStats; // Note If that data is not there you get undefined
                                  // Note All data from local storage is a string

Don't trust localStorage

There is no way to guarantee that localStorage content written in one session will be available next time, nor can you trust the data you read back, and many 3rd party extensions have full access to localStorage.

If the data is important, requires trust, or contains personal client data it should be saved on the server.

Warning about cyclic data

JSON.stringify will throw a TypeError: "Converting circular structure to JSON" if the data contains cyclic references.

Cyclic references are everywhere in JavaScript so if you are stringifying data from unknown or unsure sources is pays to wrap the stringify in a try catch so at least you can recover gracefully. As your function is using data from outside its control it would pay to be safe (unless you are in full control of all data).


Unit testing means that automated tests can run in isolation from any dependencies (such as other classes, but also the environment).

The DownloadFile method has a hard-coded dependency on WebClient and thus on the environment. It can't be used without using the network and (presumably) a remote service. Even if you decide to hit localhost, you'll need to set up an FTP server on your own machine, and that counts as an external dependency as well. Thus the method can't be unit tested as is.

One possible remedy is to hide WebClient behind an appropriate interface (you could call it IWebClient) and inject that into the class holding the DownloadFile method.

In general, however, such methods are better left as Humble Objects and perhaps subjected to integration tests.


would like to make next private[this], but it's then very tricky to set up

To achieve that, you can define the initial next person as a lazy val field, and then define a var locally in the act method:

case class Person(id: Int) extends Actor { Self =>
  private[this] lazy val initialNext: Person = acts((id + 1) % N)
  ...
  def act {
    var next = initialNext

The initialization then simplifies to

val acts = 1 to N map Person
acts foreach { _.start }
acts(0) ! (1, null)


Read/write a pipe-delimited file line by line with some simple text manipulation

Here is another way to organize your code. Instead of an if within the loop, use iterators more explicitly. Concretely:

with open(r"C:\Path\name.txt") as source:
    lines = iter(source)

    # first line
    first_line =  next(lines)
    with open(r"C:\PATH\2019.txt") as summary:
        # ... omitted ...

    # remaining lines
    with open(r"C:\PATH\PythonWrittenData.txt", 'a') as dest:
        for counter, line in enumerate(lines, start=1):
            # ... omitted ...

I have also used enumerate to update counter and line simultaneously.

The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.


Find the longest subarray with sum less than K

Time complexity check

The best way to see if a function is indeed running in average linear time is to actually run it and look at the graph of size (N) vs time needed.

(Ask me if you are interested in the code used to generate this graph.)

There are a few outliers when the algorithm has to iterate more rather than less, but in general the trend is clearly linear.

Actual code review

As far as the code itself, you could yield the lengths and call max afterwards, to separate the code into finding all subarrays lengths and picking the max one: (this way finding all sub-arrays is just list(length_subarrays_more_than_k(array, K)))

def length_subarrays_more_than_k(array, K):
    head, tail = 0, 0
    current_sum = 0
    while(tail<len(array)):
        if current_sum + array[tail]<=K:
            current_sum += array[tail]
            tail += 1
            yield tail - head
        else:
            current_sum -= array[head]
            head += 1

def max_subarray_more_than_k(array, k):
    return max(length_subarrays_more_than_k(array, K))


Seeing this is 'unanswered' here's my tuppence worth:

If you are reading a file I suggest you get the file size first, eg using fstat(), allocate a buffer of the correct size and read into that.

Alternatively, if the file is big and you have OS support, consider mapping the file into memory using mmap().  This maps the file into virtual memory but does not read it immediately.  As you access the memory into which the file is mapped the file is read into that address space for you (in the background) by the OS.

On your code, I have a few comments:

If you have a stderr, perhaps add a call to perror() on error.
It looks as if you always re-alloc, even if the initial buffer is big enough.
If zero bytes are read, you will realloc(buf, 0).  realloc man page says this is ok.
Add a bracket around size != nread - I always have to check operator precedence in statements like this and I guess I am not alone.  Brackets save the reader the trouble.
I would prefer *bread to be set to 0 on failure.  Should bread be size_t ?


Concatenating two IEnumerables with a limit

Before answering your questions let me note that your example code is wrong, second parameter should be Func<int, IEnumerable<T>> directly IEnumerable<T>. If your concern is to do not retrieve unneeded elements from DB you probably need to let this task to Entity Framework (or your favorite ORM), it understands Take() and generate proper TOP clause.

Let me assume, in this example, that you're using EF (and Users and Employees table have same type...):

return dbContext.Users.Concat(dbContext.Employees).Take(20);

EF may generate something like this:

SELECT TOP 20 * FROM
(
    SELECT * FROM Users
    UNION ALL
    SELECT * FROM Employees
)

Now from QP you may verify what effectively will be generated. Almost-optimal expected result (what you're trying to do with your custom method) is something like this:

SELECT TOP 20 * FROM
(
    SELECT TOP 20 * FROM Users
    UNION ALL
    SELECT TOP 20 * FROM Employees
)

As you can imagine if (2) is ORM generated code (check with your) or ORM generates (1) but you verify QP and you see (2) then simplest proposed code is preferable. ORM will generate best SQL code (for its knowledge) and you will be able to defer query to the last moment (using expressions you can't call custom functions in this way) effectively losing some optimizations it may apply. Note that generated code for, let's say, SQL Server and MySQL may be pretty different (recall rules for nested LIMIT in MySQL.)

My favorite is still this code (unless you have a measured performance issue):

return dbContext.Users.Concat(dbContext.Employees).Take(20);

Let's say that you do need your extension method and you can't use proposed code. What should be changed?

First of all if called function respects its contract (to return at most limit items) then you do not need to reinforce this constraint.
You're not validating your parameters (and if you did you will have trouble because generated IEnumerable<T> does it when enumeration effectively happens, that's why so many *Impl() method proliferated.)

In code:

public static IEnumerable<T> ConcatLimiting<T>(this IEnumerable<T> first,
    Func<int, IEnumerable<T>> getSecondWithLimit,
    int limit = int.MaxValue)
{
    if (first == null)
        throw new ArgumentNullException(nameof(first));

    if (second == null)
        throw new ArgumentNullException(nameof(second));

    if (limit <= 0)
        throw new ArgumentOutOfRangeException(nameof(limit));

    var itemsFromFirst = first.Take(limit);
    return itemsFromFirst.Concat(getSecondWithLimit(itemsFromFirst.Count() - elems);
}

Third: I don't like guard values like Int32.MaxValue even when they're literally used. In this case you do not really want to get only 2,147,483,647 items but you're using a very big limit to...don't have limits.

Not to mention that useless TOP clause may slow down your query. See, for example but it's not the only one, Why SELECT TOP clause could lead to long time cost. What I'd do is then to replace int limit = Int32.MaxValue with a nullable argument and apply Take() only when required.

public static IEnumerable<T> ConcatLimiting<T>(this IEnumerable<T> first,
    Func<int, IEnumerable<T>> getSecondWithLimit,
    int? limit = null)
{
    // Arguments validation...

    if (limit == null)
        return first.Concat(getSecondWithLimit(null));

    var itemsFromFirst = first.Take((int)limit);
    return itemsFromFirst.Concat(getSecondWithLimit((int)limit - itemsFromFirst.Count());
}

For completeness some answers to your questions.

  Are the two IEnumerables going to be handled correctly...

Yes, compiler generated code is correct and it will dispose everything as expected. Note, however, that initialization code won't be executed until you effectively enumerate returned enumeration. This caused some funny bugs in code like File.ReadLines("path_to_file").Take(0).

  Is the name ConcatLimiting() not very conform with what you usually see in C#?

It has to be clear, waiting for elevator we may discuss if ConcatWithLimit() is better or not...

  Is this Extension Method completely useless?
  Am I more or less following best practices?
  Are there any other glaring issues?

Maybe yes, maybe not. See answer...


As far as naming is concerned: Using 2 instead of to is pretty much a no-no - "to" is spelled out everywhere in the Java standard library. Further Java's naming convention is to capitalize every word, but the first in method names - except for acronyms which are all-caps no matter where they appear in the name. So the methods should be called intToRGB and RGBtoInt (to is lower case because it directly follows an acronym - compare for example Color.RGBtoHSB in the java standard library).

In regards to the code: I'd recommend representing your colors as Color objects rather than 3-element arrays. If you choose to do that, you don't have to define any of your methods, because that functionality already exists in the Color class.


Missing Error Checking

I usually use c++ so it may not be best practice for c.

In C++ when memory allocation fails in new an exception is thrown, this is not the case in the C programming language when using malloc(), calloc() or realloc(). An additional check is required after any memory allocation call. The check is to see if the memory returned is NULL or not, if the allocation fails references through the pointer are Unknown Behavior.
Vm *new_vm() {
    Vm *ret = (Vm*)malloc(sizeof(Vm));
    if (!ret)
    {
        fprintf(stderr, "Allocation of the Virtual Machine failed.\n");
        return ret;
    }

    ret->pc = 1024; /* add space for the stack */
    ret->sp = -1;
    ret->running = true;
    return ret;
}

In main():
#include <stdio.h>
#include <stdlib.h>
#include "vm.h"

int main() {
    Vm *vm = new_vm();
    if (vm == NULL)
    {
        fprintf(stderr, "Exiting Toy Virtual Machine.\n");
        return EXIT_FAILURE;
    }
    i32 buffer[] = {
            0x00000A01, /* push 0x0A(\n) */
            0x00004301, /* push 0x43(C)  */
            0x00004201, /* push 0x42(B)  */
            0x00004101, /* push 0x41(A)  */
            0x00000009, /* output */
            0x00000002, /* pop */
            0x00000009,
            0x00000002,
            0x00000009,
            0x00000002,
            0x00000009,
            0x00000000  /* halt */
    };
    for (int i = 0; i < sizeof(buffer); i++) {
        vm->mem[vm->pc+i] = buffer[i];
    }
    run_vm(vm);
    free_vm(vm);
    return EXIT_SUCCESS;
}

Include Only Necessary Headers
In the code as posted, stdlib.h is included in vm.h, stdlib.h is not necessary in main(), only in vm.c. To reduce the scope of the header files and source files only include what is needed. Amoung other things, this will reduce compile times, and may also reduce linking problems.
Missing Default Case in Switch Statement
It is generally a good programming practice to have a default : case statement in a switch statement to handle cases that haven't been specified yet:
static void execute(Vm *vm) {
    switch(vm->opc) {
        default:
            fprintf(stderr, "Unknown Opcode in execute(). 0x%x\n", vm->opc);
            return;
        case 0x00: /* halt */
            vm->running = false;
            printf("Halt\n");
            break;
        ...
    }

Then all possible paths through the function have been implemented. This is true in either C or C++ and most other programming languages that have a switch statement.
Use an ENUM for the Opcodes
The code would be much more readable if less numeric constants and more symbolic constants were used. In C there are 2 ways to do this, to create single symbolic constants use macro definition
#define SYMBOL  VALUE

or to use enums
typedef enum {
    HALT = 0x00,
    PUSH = 0x01,
    POP = 0x02,
    ...
    INPUTCHAR = 0x0A
} OPCODE;

typedef struct {
    i32 mem[0xffff]; /* approx. 64k */
    si32 sp;
    i32 pc;

    i32 raw;
    OPCODE opc;
    i32 param;

    bool running;
} Vm;

Use Unsigned Types as Indexes
The stack pointer index is currently a signed integer and is initialized to -1, this is what I consider to be a bad practice since stack[-1] will cause Unknown Behavior. It would be better to use size_t or unsigned as the stack pointer index. This will force a change in a number of areas, but here is what I would recommend:

Initialize running to false rather than true.
Initialize sp to zero
Only index the stack and increment the stack pointer if running is true
At the beginning of run_vm(Vm *vm) before the loop set running to true
Change the implementation of reset_vm(Vm *vm) to match all of the above

Type Names and Variable Names
Initially I was confused about Vm, whether it was a Virtual Memory or a Virtual Machine, this was true of other variables and types as well. Well written code is self documenting and doesn't need a lot of comments, type names and variable names play a big part in this. In my opinion Vm should be renamed VirtualMachine, sp should be renamed StackPointer, pc should be renamed ProgramCounter etc.
Use Library Functions Where Available
C++ contains std::memset(), and memset() in C predates C++. The function reset_vm() should use memset() rather than the loop it is using to reset the memory. The function memset() should be faster than the current loop.
void reset_vm(Vm *vm) {
    vm->running = true;
    memset(&vm->mem[0], 0, sizeof(*vm->mem[0]) * 0xffff);
    vm->sp = -1;
    vm->pc = 1024;
}


De-/Serialization of structs representing TCP messages

Your code produces no memory leaks since you're not manually allocating and deleting memory.

Include all headers
Always include all the headers. In this case, you need <iostream>, string, and cstring.

Pass by const reference
You should pass your objects by const reference. For example, const std::string& buf and const PacketType& packet. You can use reinterpret_cast<const char*>.

Use std::memcpy instead of memcpy
If you're including <cstring> (which you should be since you're using C++), you should qualify your C function calls with the std namespace.

Including the C++-style header () guarantees that the entities will be found in namespace std and perhaps in the global namespace.

Compile time checks for POD structs
std::memcpy only does a shallow copy, so it only works on POD structs (i.e. C-style structs).

A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.

For example,
struct Example
{
    int a;
    std::string b;
};

is a non-POD struct since std::string is a non-POD type (has a non trivial copy constructor, non-trivial destructor).
You should make sure that PacketType is a POD struct. You can do this with a compile time check using static_assert.
You can check whether a type is POD, using is_pod type trait (deprecated in C++20) or using is_trivial && is_standard_layout. Here is a good description of what these terms mean and how they relate to POD types.


Detecting a loop in a Linked list using a hashset

I think instead of adding integers to the Hashset, what we should do is insert a LinkedListNode instance into the Hashset and then to detect a loop we check whether the current node exists in the Hashset or not, if it does then there's a loop

 HashSet<LinkedListNode> set = new HashSet<LinkedListNode>();
    LinkedListNode current = head;
    while(current != null) {
        if(current.next != null) {
            if(set.contains(current.next)) {
                return current.next; // this has been seen so there is a loop.
            }
            set.add(current.next);
        }
        current = current.next;
    }
    return null;


Best C# idiom to convert the items on an object array to a string?

There exists a method for that conversion already:
string renderedValues = string.Join(
  "-",
  Array.ConvertAll<object, string>(values, Convert.ToString)
);

Update:
In framework 4 an overload that takes an object array was added, so it will do the conversion for you:
string renderedValues = string.Join("-", values);


Get rid of the constants entirely and assign those values to the enum members themselves.
You can then use the enum everywhere.

You can cast an enum member to int to get its numeric value.


Unquoting booleans, numbers, etc. in a JSON string

I find your method for fixing invalid JSON is the worst possible because it treats JSON as a pure string and not a tree of properties/keys and values. This increases the possibility of changing values that might not be values at all. IMO the optimal approach would be to parse it with JSON.NET by using JToken.Parse and recreate the resulting tree with correct values.

You can take a look how it could be done here where I'm using the Visitor Pattern to transform JSON too.

But honestly, unless you need to be able to read some old data, you should really fix the serializer so that it outputs valid JSON instead of trying to fix its bugs with even more dirty workarounds.


Traversing a tile-based 2D-array map using keyboard controls

You could just create a function like this:

function move(directionNextTile) {
    if (directionNextTile === undefined) {
        drawNewMap();
    } else {
        // otherwise, check if we can continue to move forward (is the next tile traversable?)
        if (traversableTiles.indexOf(directionNextTile) > -1) {
            isMoving = true;
        } else {
            // if we're blocked by a non-traversable tile, stop moving
            isMoving = false;
        }
    }
}

Or simplified:

function move(directionNextTile) {
    if (directionNextTile === undefined) {
        drawNewMap();
    } else {
        isMoving = traversableTiles.indexOf(directionNextTile) > -1;
    }
}

And use it like this:

if (keyPressed == "W") {
    worldDirection = 'N';
    move(nextTileNorth);
} else if (keyPressed == "D") {
    worldDirection = 'E';
    move(nextTileEast);
} else if (keyPressed == "S") {
    worldDirection = 'S';
    move(nextTileSouth);
} else if (keyPressed == "A") {
    worldDirection = 'W';
    move(nextTileWest);
}

And your initial assignment:

var nextTileSouth;
(currentMap[currentRowTile + 1] === undefined) ? nextTileSouth = undefined : nextTileSouth = currentMap[currentRowTile + 1][currentColumnTile];

could be:

var nextTileSouth = (currentMap[currentRowTile + 1] === undefined) ? undefined : currentMap[currentRowTile + 1][currentColumnTile];

I didn't look at all the code you linked to, but I think that you would benefit from creating a map class. That way, you can encapsulate a lot of code, and get rid of a lot of global variables.


Load JSON from server using jQuery and display it in html5

Some ideas:

#1- I suggest using .map().join() or even better .reduce() which is more semantically correct for what you want to do: reduce a array to an html string.

#2 - You should also use var jsonResult = {items: []}; otherwise if the catch gets called you will have a error down the line because you expect  jsonResult to be an Object.

#3 - Another thing: I suppose your example is simplified so much it became incorrect, since the items array has strings, and not objects with key and val...

{
  "items": [
    "this",
    "that"
  ]
}

#4- You did have an error in your code, you were using function( key, val ) {, but that is not the jQuery API. The callback gets the iterated item as this and in the second argument. The first argument is the index...

You could use a callback with destructuring like this:

 var items = []
 $.each(jsonResult['items'], function(i, {key, val}){
    items.push( "
" + val + "
" );
 });

Improved code suggestion:

$.get('list.json', {}, function(data, response) {
  var jsonResult = {items: []};
  try {
    jsonResult = JSON.parse(data);
  } catch (e) {
    $('div#result').html('cannot load data because: "' + e + '"');
  };

  var html = jsonResult['items'].reduce(function(string, item) {
    return string + "
" + item.val + "
"
  }, '');

  $('ul#items').html(html);

});

#5 - About your commented code question:

You are trying to use .join() on objects. It does work if you fix what I suggested above(jsFiddle).


Methods should always be named in PascalCase.

You can condense the logic to the following:

private decimal? SelectTolerance(decimal? globalTolerance, decimal? localTolerance)
{
    if (localTolerance == null || globalTolerance == null)
    {
        return localTolerance ?? globalTolerance;
    }
    return Math.Min(globalTolerance.Value, localTolerance.Value);
}


Compare and find duplicates in 2 corresponding columns in 2 sheets

First things first, you have to figure out what your code is doing. You need to break your code up into little steps. Make sure each step makes sense and is done well. Then, you can start combining them in useful ways because it's clear what your code is doing and how.

Only then can you start really improving performance. Trying to do so before you have a clear idea of what your code is doing and how is a bad idea.

#1: Take your workbook/sheets and give them proper, descriptive names

Dim targetBook As Workbook
Set targetBook = '/ whatever xlwb is

With targetBook

    Dim resultsSheet As Worksheet
    Set resultsSheet = targetBook.Sheets("results")

    Dim masterSheet As Worksheet
    Set masterSheet = targetBook.Sheets("Master List")

    Dim followUpSheet As Worksheet
    Set followUpSheet = targetBook.Sheets("Follow Ups")

End With

#2: Find your end rows and put them in properly named variables

Dim resultsFinalRow As Long
With resultsSheet
    resultsFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

Dim masterFinalRow As Long
With masterSheet
    masterFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

Dim followUpFinalRow As Long
With followUpSheet
    followUpFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

Dim isMatch As Boolean
Dim resultsRow As Long
Dim masterRow As Long
For resultsRow = 2 To resultsFinalRow
    For masterRow = 2 To masterFinalRow

    ...

#3 Lay the framework for your loop

Dim isMatch As Boolean
Dim resultsRow As Long
Dim masterRow As Long
For resultsRow = 2 To resultsFinalRow
    For masterRow = 2 To masterFinalRow

        isMatch = (resultsSheet.Cells(resultsRow, 2) = masterSheet.Cells(masterRow, 2)) _
                And (resultsSheet.Cells(resultsRow, 1) = masterSheet.Cells(masterRow, 1))

        If isMatch Then

            '/ Do Stuff

        End If

    Next masterRow
Next resultsRow

#4: Flesh out your loop logic

Rather than remembering which rows to delete at the end, just delete them as you go. Keeps things nice and clean.

Dim copyRange As Range
Dim isMatch As Boolean
Dim matchFound As Boolean
Dim resultsRow As Long
Dim masterRow As Long
For resultsRow = 2 To resultsFinalRow

    matchFound = False

    For masterRow = 2 To masterFinalRow

        isMatch = (resultsSheet.Cells(resultsRow, 2) = masterSheet.Cells(masterRow, 2)) _
                And (resultsSheet.Cells(resultsRow, 1) = masterSheet.Cells(masterRow, 1))

        If isMatch Then

            matchFound = True

            With masterSheet
                Set copyRange = .Range(.Cells(masterRow, 1), .Cells(masterRow, 15))
            End With

            copyRange.Copy Destination:=followUpSheet.Cells(followUpRow, 1)
            followUpRow = followUpRow + 1

        End If

    Next masterRow

    If matchFound Then
        resultsSheet.Rows(resultsRow).Delete
        resultsRow = resultsRow - 1
    End If

Next resultsRow

#5: Clean Up

With resultsSheet

    resultsFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row '/ find new final row

    Set copyRange = .Range(.Cells(1, 1), .Cells(resultsFinalRow, 15))
    copyRange.Copy Destination:=masterSheet.Cells(masterFinalRow + 1, 1)

End With

Now we have a sub that's actually pretty clear and understandable:

Option Explicit

Public Sub CRquestion()

    Dim targetBook As Workbook
    Set targetBook = "" '/ whatever xlwb is

    With targetBook

        Dim resultsSheet As Worksheet
        Set resultsSheet = targetBook.Sheets("results")

        Dim masterSheet As Worksheet
        Set masterSheet = targetBook.Sheets("Master List")

        Dim followUpSheet As Worksheet
        Set followUpSheet = targetBook.Sheets("Follow Ups")

    End With

    Dim resultsFinalRow As Long
    With resultsSheet
        resultsFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    End With

    Dim masterFinalRow As Long
    With masterSheet
        masterFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    End With

    Dim followUpFinalRow As Long
    With followUpSheet
        followUpFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    End With

    Dim followUpRow As Long
    followUpRow = followUpFinalRow + 1 '/ next empty follow up row

    Dim copyRange As Range
    Dim isMatch As Boolean
    Dim matchFound As Boolean
    Dim resultsRow As Long
    Dim masterRow As Long
    For resultsRow = 2 To resultsFinalRow

        matchFound = False

        For masterRow = 2 To masterFinalRow

            isMatch = (resultsSheet.Cells(resultsRow, 2) = masterSheet.Cells(masterRow, 2)) _
                    And (resultsSheet.Cells(resultsRow, 1) = masterSheet.Cells(masterRow, 1))

            If isMatch Then

                matchFound = True

                With masterSheet
                    Set copyRange = .Range(.Cells(masterRow, 1), .Cells(masterRow, 15))
                End With

                copyRange.Copy Destination:=followUpSheet.Cells(followUpRow, 1)
                followUpRow = followUpRow + 1

            End If

        Next masterRow

        If matchFound Then
            resultsSheet.Rows(resultsRow).Delete
            resultsRow = resultsRow - 1
        End If

    Next resultsRow

    With resultsSheet

        resultsFinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        Set copyRange = .Range(.Cells(1, 1), .Cells(resultsFinalRow, 15))
        copyRange.Copy Destination:=masterSheet.Cells(masterFinalRow + 1, 1)

    End With

End Sub

Performance Improvements

Standard VBA Tune Ups

The lowest-hanging VBA performance fruit are ScreenUpdating, EnableEvents and Calculation.

Application.ScreenUpdating = False
Application.EnableEvents= False
Application.Calculation= XlManual

...

Code

...

Application.ScreenUpdating = True
Application.EnableEvents= True
Application.Calculation= XlAutomatic

Every time you access the worksheet, events trigger, formulas recalculate and
Turning those options off will make your code inordinately faster. Just make sure they get reset back to normal at the end.

Delete all in one go

To iteratively build a list of rows to delete, then delete them all at once, the best way is to use Range.Union(). So you create a range then, whenever you find a row to delete, add that row to your range. At the end, take your compound range and call Range.EntireRow.Delete once to do the whole thing in one operation.

This would modify the code like so:

        Next masterRow

        If matchFound Then
            If deleteRange Is Nothing Then

                '/ for the first time we set the range
                Set deleteRange = resultsSheet.Cells(resultsRow, 1)

            Else

                '/ add the current row to our range
                Set deleteRange = Union(deleteRange, resultsSheet.Cells(resultsRow, 1))

            End If
        End If

    Next resultsRow

    If Not deleteRange Is Nothing Then deleteRange.EntireRow.Delete


public createAccount(registrationRequest: CreateUserRequestModel): Observable<SomeType> {
  return this.apiService.post('api/register/account', registrationRequest)
    .flatMap(() => this.authenticationService.authenticate(registrationRequest.emailAddress, registrationRequest.password))
    .map(response => <SomeType>response.json())
    .catch(error => Observable.throw(error.json()));
}

@Tushar made a good point on code compactness, which can be applied to all arrow functions in the code.
TypeScript is about types. Try to not use any in return type definitions. Do define some return type and cast the result to it (see SomeType).
I'm not sure if you really want to do .catch(error => Observable.throw(error.json())) where it happens now or move it to the consumers side (e.g. .subscribe(() => {...}, error => this.handle(error))
reg is a bad name. Spell things out.


If you want to expose directory contents with stats as a Bacon EventStream or a Property, you can use the combine-family of functions to combine the filename and stats without monkey-patching:

var fs = require("fs")
var Bacon = require("../dist/Bacon.js")

// statsForFile :: String -> Property { filename :: String, stats :: Stats }
function statsForFile(filename) {
  return Bacon.combineTemplate({
    name: filename,
    stats: Bacon.fromNodeCallback( fs.stat, filename )
  })
}

You can expose directory contents as a stream of filenames:

// directoryContents :: String -> EventStream String
function directoryContents(dir) {
  return Bacon.fromNodeCallback(fs.readdir, dir)
    .flatMap(function(names) { return Bacon.fromArray(names)})
}

Then you can compose these two like

function statsForDir(dir) {
  return directoryContents(dir).flatMap(statsForFile)
}

And see what happens:

statsForDir(".").log()

So that's how you can compose these things asynchronously using Bacon.js and FRP. This is not a prime example of where FRP is really useful yet, but when more composition is involved the benefits will be greater. Hope this helps!


Solving first- and second-degree degree polynomials

As you wrote,

//TODO: check if a = 0

First degree polynomials are just a degenerate case of second degree polynomials, where the leading coefficient is 0.  Perhaps you should design your interfaces to reflect that.

I'm not sure that all those calculate… methods are appropriate.  Part of the point of object-oriented programming is to give the illusion of "smart data".  The object knows when it needs to recalculate; the caller just asks for poly.x and the answer is just there.

In first.m,

- (double) calculate {
    self.x = (self.b - 2 * self.b)/self.a;
    return self.x;

}

could just be

- (double) calculate {
    return self.x = -self.b / self.a;
}

In Objective C, it is not necessary to check if the receiver of a message is nil.  Therefore,

if (self) {
    self.a = aValue;
    self.b = bValue;

}

does not need to be in an if block.


I am not a seasoned Schemer and I think your code looks great as-is. I have only one remark.

You are sorting the list in a purely functional way in order to avoid mutating the list given in input. But I am not sure about what is your intent w.r.t. data-sharing, which is one of the strong point of purely functional data-structures (and maybe you don't want to share cons-cells, which I can understand too).

Currently, it appears to me that you can't have any sublist shared. You do    have an opportunity to share sublists between your intermediate lists, thanks to span! and append!. But if your input list is (6 5 7 8 9) and the sort <, the resulting list (5 6 7 8 9) has no way to share the same  sublist, namely (7 8 9), because you build the result from a fresh list () using cons (apologies for any misunderstanding).

A possible improvement for your implementation is to start finding the longest sublist being already sorted and build the resulting list on top of this sublist. I don't consider this to be in contradiction with the definition of insertion sort. The downside is that mutations are shared too, but this is a design decision (and this is where I failed to see if you are avoiding sharing data on purpose or not).


I like your code, and would use it myself, some thoughts:

I assume you declare url next to JSON.load because you want to declare it close to where you use it. I would still recommend using 1 comma separated list of variables on the top.
lowerCamelCase is good for you, get_follows -> getFollows -> getFollowedChannels ?
Comparing to 0 should be done with ===, if you do it for the length of an array I would go with a falsey comparison: if (!data || !data.follows.length) {

From a design perspective, you are circumventing the paging system, are you sure you always need every single channel? I hope you at least cache the retrieved information.


Iteratively determine the diameter of a binary tree

Tail calls
You have to be careful when evaluating recursive functions as there is a big difference between recursion that is tail called, and those that are not.
As the problem requires a traverse back up the tree after locating an end node the tail of the recursive function should count as an iteration.
The upward traverse
The solution to the problem requires you to traverse down the nodes until you find the end node, counting the depth as you go. When you find an end node you then traverse back until you find a node with an un-traversed node. Each step back you record the max depth from that node.
Because the non iterative version requires you to push the current node to the stack so you can travel back up the tree you are counting what the recursive function is doing after the recursion (the tail).
Basics of tail calls
A tail call is a call made at the end of a function.
Many languages allow proper tail calls, which means that a tail called function does not need to push its current state to the call stack when it makes the recursive call, and thus there is no need to pop from the call stack when returning.
Consider the following two recursive functions.
Proper tail call recursion

function recurse(sum, value){
    sum += value;
    if(value > 10) { return sum }   // Returns functions state.sum
    return recurse(sum, value + 1); // Returns function call result
    // the functions state is not required after the recurse call.
}

console.log(recurse(0,0));

Non tail call recursion

function recurse(sum, value){
    if(value > 10) { return sum + value }
    sum +=  recurse(value, value + 1); // Note that the function state
                                       // that holds sum must be retained
                                       // in order to complete the function
    return sum;  // Return function state variable
}

console.log(recurse(0,0));

The two functions return the same result, but the second function requires an additional 10 pops from the call stack.
Javaascript ES6 currently does support proper tail calls and optimization, however no engine has yet released support (too many pages rely on call stack overflow to save them from infinite recursion)
Do call stack pops count?
I do not know what the official stance is on the complexity of recursive tails. Having proper tail calls make a huge performance difference and some types of problems can not be implemented using proper tail calls so I would count them as iterations.
If you count the tail call (the pop from the call  stack) as an iteration then your recursive function has the same number of iterations as the non recursive function.
As far as i can tell the solution can not be implemented using proper tail call recursion and thus the complexity should include both sides of the recursion call to be counted as an iteration.

var count = 0;
const nullReturn = {diameter: 0, depth: 0};
function diameterOfBinaryTreeA(root) {
  count = 0;
  const diameter = diameterInternal(root).diameter;
  console.log("Iterations : " + count);
  return diameter;
};

function diameterInternal(node) {
  count += 1;
  const left = node.left ? diameterInternal(node.left) : nullReturn;
  const right = node.right ? diameterInternal(node.right) : nullReturn;
  count += 1;
  const diameter = left.depth + right.depth;
  return {
    diameter: Math.max(diameter, left.diameter, right.diameter),
    depth: Math.max(left.depth, right.depth) + 1
  };
}

function diameterOfBinaryTreeB(root) {
  count = 0;
  const stack = [[1, root]];
  const nodeDepth = new WeakMap();
  let diameter = 0;
  while (stack.length) {
    count += 1;
    const [indicator, node] = stack.pop();
    if (indicator) {
      stack.push([0, node]);
      if (node.right) { stack.push([1, node.right]) }
      if (node.left) { stack.push([1, node.left]) }
    } else {
      const left = nodeDepth.get(node.left) + 1 || 0;
      const right = nodeDepth.get(node.right) + 1 || 0;
      nodeDepth.set(node, Math.max(left, right));
      diameter = Math.max(diameter, left + right);
    }
  }
  console.log("Iterations : " + count);
  return diameter;
}

let tree = {
  val: 3,
  right: {
    val: 20,
    right: {
      val: 7,
      right: null,
      left: null
    },
    left: {
      val: 15,
      right: null,
      left: null
    }
  },
  left: {
    val: 9,
    right: null,
    left: null
  }
}

console.log("Using recursion");
console.log("Diameter : " + diameterOfBinaryTreeA(tree))
console.log("Using Stack");
console.log("Diameter : " + diameterOfBinaryTreeB(tree))

Additional notes.
See above snippet for fixes as to the points below.

Use const for constants. You had many variables that were not being changes as let
When using recursive functions terminate the recursion before that call. If you have a recursive function and the first thing you do is check for a immediate return you are wasting a whole stack push and pop.
Don't forget to put ; at the end of lines.
Only use strings for property names if they are not valid names.
Keeping the extend array and place are not needed, just push the nodes directly to the stack.
if (node.left !== null) { is noisy if you know foo is either an object or null use if (node.left) {
Try to avoid non descriptive names, or use common abbreviations. d is not a good name for the map.


Extracting values from dictionaries where the keys match

If I'm understanding it correctly, you're populating a ConcurrentDictionary from the values of two other ConcurrentDictionaries, where the keys are equal.

Try this, it's vastly faster than your loop in my tests.

var matches = FirstDictionary.Keys.Intersect(SecondDictionary.Keys);
foreach (var m in matches)
    ResultDictionary.TryAdd(FirstDictionary[m], SecondDictionary[m]);


Boolean duplicate = false;
    Set<Integer> set= new HashSet<>();
    for(int i : array){
        if(set.contains(i)){
            duplicate = true;
    } else {
        set.add(i);
    }
    }
    return duplicate;

This can be written more briefly as

    Set<Integer> seen = new HashSet<>();
    for (int i : array) {
        if (!seen.add(i)) {
            return true;
        }
    }

    return false;

You do not need to check contains before add.  The add will check contains for you.

You do not need to keep going after you've found a duplicate.  You can stop immediately and return.  Everything else will be just wasted work.

You do not need the duplicate variable.  You can just return instead.

The indent is now consistent, and I added some horizontal whitespace for readability.

Another alternative would be

    int[] seenCounts = new int[array.length];
    for (int i : array) {
        i--;
        if (seenCounts[i] >= 1) {
            return true;
        } else {
            seenCounts[i]++;
        }
    }

    return false;

The array will be more efficient than the Set.

Also, this will enforce that the numbers are in the range 1 to 9.  If you had a 0 or 10, this code would throw an exception.  This is important because an array with five 9s and four 0s would return true;


I'll typically wrap the main body of my code in a python script in a function and break the code apart into more functions, allowing me to reuse that code later.

import os
import shutil
import sys

def flattenDirectory(location, action, actuallyMoveOrCopy=True):
   """ This function will move or copy all files from subdirectories in the directory location specified by location into the main directory location folder
       location - directory to flatten
       action - string containing m(ove) or M(ove) or c(opy) or C(opy)"""
   #Your code here

if __name__ == "__Main__":
    #same code to find currentDirectory here
    actuallyMoveOrCopy = len(sys.argv)>1 and sys.argv[1] in ['m', 'M', 'c', 'C']
    flattenDirectory(currentDirectory, sys.argv[1], actuallyMoveOrCopy)

Now you can still run this code as you normally would, but should you need it in another script you can use it in an import without having to worry about the code automatically running at the time of import.


Parsing multiple line records using Java 8 Streams

Simply put, you only need a Consumer<String>-implementing class that knows what lines to read as the table name, the columns and rows.

public class StatementGenerator implements Consumer<String> {

    private static String START = " (";
    private static String END = ") ";
    private static String ROW_DELIMITER = "\n";

    private String delimiter = "\t";
    private String parameter = "%";
    private ObjIntConsumer<List<String>> parameterSupplier =
            (list, i) -> { list.add(parameter); };
    private String table = null;
    private List<String> columns = new ArrayList<>();
    private List<String> rows = new ArrayList<>();

    public void setDelimiter(String delimiter) {
        this.delimiter = delimiter;
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    }

    public void setParameterSupplier(ObjIntConsumer<List<String>> parameterSupplier) {
        this.parameterSupplier = parameterSupplier;
    }

    @Override
    public void accept(String t) {
        if (table == null) {
            table = t;
            return;
        }
        if (!t.contains(delimiter)) {
            columns.add(t);
            return;
        }
        rows.add(t);
    }

    public String getTableName() {
        return table;
    }

    public List<String> getColumns() {
        return columns;
    }

    public List<String> getRows() {
        return rows;
    }

    public String getParameterizedStatement() {
        StringBuilder result = new StringBuilder("INSERT INTO ");
        result.append(constructSegment(getTableName(), getColumns())).append(
                constructSegment("VALUES", IntStream.rangeClosed(1, getColumns().size())
                        .collect(ArrayList::new, parameterSupplier, List::addAll)));
        return result.append(";").toString();
    }

    public List<String> getRawStatements() {
        String placeholderStatement = getParameterizedStatement()
                .replaceAll(Pattern.quote(parameter), "%s");
        return getRows().stream().map(r -> String.format(placeholderStatement,
                    Pattern.compile(delimiter).splitAsStream(r)
                        .map(v -> "'" + v + "'").toArray()))
                .collect(Collectors.toList());
    }

    public String getFullStatement() {
        return getRawStatements().stream().collect(Collectors.joining(ROW_DELIMITER));
    }

    @Override
    public String toString() {
        return getParameterizedStatement();
    }

    private static String constructSegment(String prefix, List<String> list) {
        return prefix + list.stream().collect(Collectors.joining(", ", START, END));
    }
}

In my sample implementation above, I've made the delimiter configurable, but there's one other configuration I want to highlight - parameter.

SQL injection

The sample implementation provides a getParameterizedStatement() as the starting point, because by right you should let your database driver handle the escaping of quotes (and possibly other magic values). We certainly do not need Little Bobby Tables to hang around here.

The parameter list is driven by an ObjIntConsumer, because if I'm not mistaken, there are certain drivers allowing for an index-based parameter substitution. That will mean you can potentially override parameterSupplier with something like (list, i) -> { list.add("::" + i); }; (or whatever the placeholder format is).

With that said, assuming you can absolutely trust your file-based input (i.e. sanitized inputs), we can then proceed with using getRawStatements(), which performs a simple substitution on the parameter with our String.format()'s "%s" placeholder. This is more aligned with what you are asking for. getFullStatement() simply concatenates all the rows into a single String, if that is what you actually require.

Here's what I used in my main() code:

public class StatementGeneratorMain {

    public static void main(String[] args) throws IOException, URISyntaxException {
        StatementGenerator generator = new StatementGenerator();
        generator.setDelimiter(",");
        try (Stream<String> lines = Files.lines(Paths.get(
                ClassLoader.getSystemResource("sqlRecords.txt").toURI()))) {
            lines.forEach(generator);
        }
        System.out.println(generator.getTableName());
        System.out.println(generator.getColumns());
        System.out.println(generator.getParameterizedStatement());
        generator.getRawStatements().forEach(System.out::println);
    }
}

And the sample output:

STUDENTS
[ID, NAME]
INSERT INTO STUDENTS (ID, NAME) VALUES (%, %) ;
INSERT INTO STUDENTS (ID, NAME) VALUES ('1', 'Mike') ;
INSERT INTO STUDENTS (ID, NAME) VALUES ('2', 'Kimberly') ;


\(col, row) -> (take 10000 $ randomRs (-1.0, 1.0) generator)!!(col * row)

Oh man you got me going "no no no no no no" like I long haven't :D. take 10000 does nothing here. col * row is going to come out to the same when you switch row and col, perhaps you want col + inputSize * row? randomRs is going to be recalculated for each (col,row) pair - fromList fixes that. Calling the line's result weights is little more than a comment. MonadRandom can avert the generator passery, and also stop you generating the same random values for each call to randomWeights.

activate :: [Double] -> [Matrix Double] -> Matrix Double
activate i = foldl squash (fromLists [i]) where
  squash inputs weights = fmap leakyRelu $ multStd2 inputs weights
  leakyRelu a
    | a > 0.0 = a
    | otherwise = 0.01 * a

randomWeights :: Int -> Int -> IO (Matrix Double)
randomWeights rows cols = fromList rows cols <$> getRandomRs (-1.0, 1.0)

main :: IO ()
main = do
  let inputs = [0, 1]

  inputWeights <- randomWeights (length inputs) 3
  hiddenWeights <- randomWeights 3 1
  outputWeights <- randomWeights 1 1

  let outputs = activate inputs [inputWeights, hiddenWeights, outputWeights]

  print inputs
  print outputs


What is the best way to refactor out “temporal dependence” of instance methods?

You could have a flag that is set when _initUI is called.  The first line of _initUI would check the flag and exit if it's already set; the second line would set it.  Then any method which needs _initUI to have been called can simply, safely, call it without fear of double-initializing things.


Check value existence in two lists and gather the result in a csv

General problem

It's not much, but for your general problem, mathematically speaking, I'd split the logic into three steps (It might be a bit more code, but personally speaking, it keeps things cleaner):

I'd intersect list_A with list_B:

def intersect(list_A, list_B):
    return [[x, True, True] for x in set(list_A).intersection(list_B)]

Which is going to give you:

  [[3, True, True], [4, True, True]]

Then, I'd do list_A - list_B:

def a_diff_b(list_A, list_B):
    return [[x, True, False] for x in set(list_A).difference(list_B)]

Which is going to give you:

  [[1, True, False], [2, True, False]]

Then, I'd do list_B - list_A:

def b_diff_a(list_A, list_B):
    return [[x, False, True] for x in set(list_B).difference(list_A)]

Which is going to give you:

  [[5, False, True]]

Intersection

  In mathematics, the intersection A ∩ B of two sets A and B is the set
  that contains all elements of A that also belong to B (or
  equivalently, all elements of B that also belong to A), but no other
  elements.

Complement

  In set theory, the complement of a set A refers to elements not in A.
  The relative complement of A with respect to a set B, also termed the
  difference of sets A and B, written B ∖ A, is the set of elements in B
  but not in A. When all sets under consideration are considered to be
  subsets of a given set U, the absolute complement of A is the set of
  elements in U but not in A.


Compact ways to filter even numbers in Java int array

First... choose the right problem or choose what you want them to learn

Let me first question your assumptions (pure Java 7, no "extra" libraries and array filtering). I do so under the premise that you want your students not just learn "pure Java 7" (ain't best idea neither commercially nor academically, nor will it make them greater programmers).

Also, why I keep typing "extra libraries" in "":

most of the projects now have Guava or Apache Commons
new Java has lambdas (for a reason and due to serious demand)
there are at least 2 popular libraries that enable Java 7 to use FP-like programming style: Javaslang, Lambda4Java (IIRC)

This is not "for fun", but because there was need for it. Among mainstream languages none treat "backward compatibility" so seriously as Java does. Despite deprecating APIs since version 1.1, they have yet to cut a thing. This means, there's lots of OLD stuff there.

Also, the problem you have (filtering data) is VERY FP friendly. FP languages among first operations have map and filter. Java at it's inception targeted C++ people, who wrote programs iteratively (for loops, step-by-step instructions to solve problems). FP works on streams and pipelines (data flows, and while it does, we do things).

So, yes, Scheme (FP language) is awesome for your problem. So is anything that has decent FP features (JS can be argued so).

Pure Java, without Apache Commons, Javaslang, Lambdas etc. will be hard-pressed for it:

you want to filter data
you want to use arrays (in Java objects are central concept, arrays are closer to primitives)
in Java, Collections are arrays equivalents of objects

Summarizing this long intro:

Filtering is FP-concept, FP-friendly languages or strict FP languages are  therefore better. If you choose examples like that and want to work with Java, work with Java Collections, libraries geared towards filtering/collections/data pipelines and Java 8 that introduces Lambdas.

Java 8 and streams

First proposition for you, uses streams, introduced in Java 8. There's a library that tries to make lambdas (and perhaps streams?) available in Java 7, so you may be able to show same code with it.

static void java8even(int[] t) {
    IntStream iWantEvens = IntStream.of(t);

    iWantEvens
        .filter(i -> i % 2 == 0)
        .forEach(new IntConsumer() {
            @Override
            public void accept(int value) {
                System.out.println(value);
            }
        });
}

I build a java.util.Stream with Stream.of(input array). Then I filter the stream and using forEach I on the fly create an IntConsumer that just prints the value. forEach performs an action that you define on every stream element. I could've used toArray and then function would - instead of having side effect - return an array, which I'd then have to print in main, iterating over it. It might look simpler and be 1-2 lines terser, but it's less memory efficient.

Answer within all your limits

With all that said, Java 7, no "extra" libs:

/**
 * Created by LAFK on 17.11.15.
 */
public class EvenFilter {

    static ArrayList evens = new ArrayList();

    public static void main(String[] args) {
        int[] simpleTable = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        for (int i: simpleTable) {
            if (i%2 == 0) {
                evens.add(i);
            }
        }
        System.out.println(evens);
    }
}

I used ArrayList without any type-safety. I then iterated over input array and added elements meeting criteria to ArrayList. Then, I printed out ("returned") ArrayList.

Why?

Java ain't that great with arrays (try printing an array without iterating over it's elements, weak API, fixed length of an array, while Java Lists can grow and shrink over time)
even more so with primitives, like int, try getting that into collections!
Java API for collections ain't that great as well, compared to modern languages or FP ones, but it's better than what you can do with just array
I don't need the fixed size with lists

I think similar thing can be done with a StringBuffer and were you to process something more text-oriented, that would be better choice.


build a Xbonacci function that takes a signature of X elements ,each next element is the sum of the last X elements ,and returns the first n elements

I think the problem is the slice method but I don't what to use it instead.

It is, but it's not as simple as taking out the slice and using something else in its place, the problem is more fundamental than that.
This algorithm scales poorly to high values of the original length of signature, by the way let's call this value S so I don't have keep spelling it all out. There is an other approach that does not depend on S, by updating the "sum of past S values" in constant time. Instead of explicitly taking the window of S elements and summing it, the sum of the previous window can be updated: one new value enters the window (added to the sum), and one old value leaves the window (subtracted from the sum). The work done for each element of the output is only one addition and one subtraction, not S additions.