A recursive_transform for std::vector with various return type

I'm afraid this is reaching the limits of my knowledge about templates in C++, but I'll try to answer it anyway as best as I can:
Use std::back_inserter() to fill the vectors
Instead of constructing a vector of a given size, just declare an empty vector, but reserve enough capacity, and then use std::back_inserter() to fill it:
std::vector<decltype(recursive_transform(std::declval<value_type&&>(), f))> output;
output.reserve(input.size());

std::transform(input.begin(), input.end(), std::back_inserter(output),
    [f](auto& element)
    {
        return recursive_transform(element, f);
    }
);

However, if you don't use std::vector but a different container type, reserve() and/or std::back_inserter() might not be appropriate.
Determining the container type
So ideally, we don't want to declare a std::vector, but rather the outer container of type T. You can use template template parameters to deconstruct templated types:
template<template<class> class Container, class ValueType, class Function>
requires is_iterable<Container<ValueType>>
auto recursive_transform(const Container<ValueType> &input, const Function &f)
{
    // You want to be able to write this:
    using TransformedValueType = decltype(recursive_transform(*input.begin(), f));
    Container<TransformedValueType> output;
    ...
}

Unfortunately, that doesn't work, at least not with Clang, because a std::vector actually has two template parameters, and other containers might have more or less template parameters. So the solution to that problem is to declare ValueType as a template parameter pack:
template<template<class...> class Container, class Function, class Ts...>
requires is_iterable<Container<Ts...>>
auto recursive_transform(const Container<Ts...> &input, const Function &f)
{
    using TransformedValueType = decltype(recursive_transform(*input.begin(), f));
    Container<TransformedValueType> output;
    ...
}

Although of course this doesn't forward the second template parameter. Putting everything so far together:
template<typename T>
concept is_iterable = requires(T x)
{
    *std::begin(x);
    std::end(x);
};

template<class T, class Function>
auto recursive_transform(const T &input, const Function &f)
{
    return f(input);
}

template<template<class...> class Container, class Function, class... Ts>
requires is_iterable<Container<Ts...>>
auto recursive_transform(const Container<Ts...> &input, const Function &f)
{
    using TransformedValueType = decltype(recursive_transform(*input.begin(), f));
    Container<TransformedValueType> output;

    std::transform(std::begin(input), std::end(input), std::back_inserter(output),
        [&](auto &element)
        {
            return recursive_transform(element, f);
        }
    );

    return output;
}


One idea would be to maintain a distance to the nearest seat, rather than simply an occupancy list (you can recover the same information since seats with zero distance are occupied). Then finding the seat with the furthest distance and updating the list reduces to:

finding the maximum element in the array
Traversing left and right from that element and updating the distances until the stored distance is already less than the distance to the newly added seat.

One more code review comment:
It may be nicer to either (1) template these functions on the parameter N, rather than declaring it at the beginning, so that they can be called later on a different sized array or (2) use std::vector so that the size of the seats container doesn't need to be known at compile time.


Recursive method to return a set of all combinations

Basically the algorithm returns all subsets of groupSize (which should really be renamed to group), that have k elements.

The method works recursively. To do so it needs two things : establish primitive cases that end the recursion, and a way of formulating the problem in terms of itself, yet closer to the primitive form.

This algorithm has two primitive cases :

k == 0 : there is only one set that has 0 elements : the empty set.
k > size of the group : there are no subsets that have more elements than the original set

So there are two ways we can get to a primitive case : formulating it in terms of smaller sets (smaller group), or in terms of smaller subsets (smaller k)

The formulation in terms of itself for this algorithm is : given an element x from the group, its combinations are : all subsets that contain x, and all subsets that do not contain x.

All subsets that do not contain x, is really all subsets of the group without x of size k (moves closer to second primitive case)
All subsets that contain x, is all subsets of the group without x of size k-1 with x added to those subsets. (moves closer to both primitive cases)

The algorithm takes the last element of the group as x (but could just as well take another) : Integer x = groupWithoutX.remove(groupWithoutX.size()-1);

An example will make this clearer :

for groupSize = [1, 2, 3, 4, 5] and k = 3 the output would be

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [2, 3, 4], [2, 3, 5], [1, 4, 5], [2, 4, 5], [3, 4, 5]]

Picking the last element x = 5

this is

all subsets of [1, 2, 3, 4] of size k = 3 : i.e. [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
and all subsets of [1, 2, 3, 4] of size k = 2 and 5 added i.e. [[1, 2, 5], [1, 3, 5], [1, 4, 5], [2, 3, 5], [2, 4, 5], [3, 4, 5]]


If you have the list of files you want to add to the array, then you can fast enumerate through them:

NSArray *fileArray; //List of file name here
NSMutableArray *stampList = [NSMutableArray array];
for (NSString *fileName in fileArray)
{
    [stampList addObject:[UIImage imageNamed:fileName]];
}


From a once over:

Review your comments, some of them just take up space and are not very valuable:

// update scrollbar
$el.tinyscrollbar_update();

Indentation ( this might be because of copy pasting ) is off in your code, making it hard(er) to read
TEST.notif is a mouthful, I would just go for notifications
_el, _sum, _defaultVPHeight should all loose their underscore, they dont make sense. Also I would go either for the Spartan e or the full out element.
TEST.notif._notifOpen -> why notifOpen, it's already part of an object called notif, just call it open
Use lowerCamelCase consistently: tinyscrollbar_update -> tinyScrollbarUpdate

Other than that, your code is well structured and easy to follow.


In all reality the safety of the Data can be affected by any part of the transportation process, So just seeing how you encrypt and decrypt the information doesn't really help us help you in determining the safety of the data.

Nothing to do with the Security of the Functions

what you should do is create one function that will accept a parameter of encrypt or decrypt most of the information that you are using in both functions is duplicated.

function encryptOrDecrypt($mprhase, $crypt) {
     $MASTERKEY = "KEY PHRASE!";
     $td = mcrypt_module_open('tripledes', '', 'ecb', '');
     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     mcrypt_generic_init($td, $MASTERKEY, $iv);
     if ($crypt == 'encrypt')
     {
         $return_value = base64_encode(mcrypt_generic($td, $mprhase));
     }
     else
     {
         $return_value = mdecrypt_generic($td, base64_decode($mprhase));
     }
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     return $return_value;
}

obviously some of the variables have been changed to protect the innocent, (in other words you should change the variable $return_value to something more meaningful)

(another note: you might want to fiddle around with the input parameter that I added as well.)

Additional Important Information

As Corbin Pointed out, this should be a class/object that has methods for encrypting and deciphering and the whole works that go along with a class/object, unfortunately I don't know PHP syntax well enough to write it out.

a Function can do this, but it is sloppy coding, and I should have said this from the get go, I apologize.

I will look into the syntax when I have time or you can Visit this Fun page Or you can use ol' reliable


There is nothing wrong in general with for loops. If you have to iterate over some elements there is no magic that can avoid this. So why is your function "not very efficient"? And why is this because of the for-loop?

However you asked for a pythonic solution. In Python explicit for loops are avoided by using list comprehension. Internally Python again loops over all elements, however slightly more efficient. Better readability is the other big gain.

So let's measure (I did some renaming for readability). I compare

your original explicit for loop
a 1:1 translation to a list comprehension
further improved by extraction of the default lookup
also apply Jean-François Fabres strip()

.

import timeit

def encode(tokens, dictionary):
    ids = []
    for token in tokens:
        if len(token) == 0 or token == " ":
            continue
        ids.append(dictionary.get(token, dictionary.get('UNK')))
    return ids

def encode1(tokens, dictionary):
    ids = [dictionary.get(t, dictionary.get("UNK")) for t in tokens if t and t != " "]
    return ids

def encode2(tokens, dictionary):
    unk = dictionary.get("UNK")
    ids = [dictionary.get(t, unk) for t in tokens if t and t != " "]
    return ids

def encode3(tokens, dictionary):
    unk = dictionary.get("UNK")
    ids = [dictionary.get(t, unk) for t in tokens if t.strip()]
    return ids

def test(tokens, dictionary, result, encoders):
    for encode in encoders:
        assert result == encode(tokens, dictionary)

def time(tokens, dictionary, encoders):
    print(tokens)
    print(encoders[0](tokens, dictionary))
    for encode in encoders:
        print(timeit.timeit(lambda: encode(tokens, dictionary)))

encoders = [encode, encode1, encode2, encode3]

tokens = ["asdf", "qwer", "yxcv", " ", ""]
dictionary = {"UNK": 0, "asdf": 1, "qwer": 2}
test(tokens, dictionary, [1, 2, 0], encoders)

string = "asdwerasfeqtdfgrtzdfhetzufgjhtzui"
tokens = list(string)
dictionary = {k: v for v, k in enumerate(["UNK"] + list(dict.fromkeys(tokens)))}
time(tokens, dictionary, encoders)

tokens = [" "] * len(string)
time(tokens, dictionary, encoders)

tokens = [""] * len(string)
time(tokens, dictionary, encoders)

results on my machine

['a', 's', 'd', 'w', 'e', 'r', 'a', 's', 'f', 'e', 'q', 't', 'd', 'f', 'g', 'r', 't', 'z', 'd', 'f', 'h', 'e', 't', 'z', 'u', 'f', 'g', 'j', 'h', 't', 'z', 'u', 'i']
[7, 9, 6, 11, 10, 12, 7, 9, 8, 10, 5, 14, 6, 8, 15, 12, 14, 1, 6, 8, 2, 10, 14, 1, 3, 8, 15, 4, 2, 14, 1, 3, 13]
7.497583819553256
5.152629452757537
3.7371353656053543
4.100516518577933
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
[]
1.744785476475954
1.0442649777978659
1.1422674069181085
1.721993056125939
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
[]
1.2569031789898872
0.6375910267233849
0.7521892953664064
1.699515514075756

which shows:

list comprehension is indeed significantly faster than the explicit for-loop
avoiding the evaluation of the default also has significant impact
strip() is a little slower than your explicit test (while more generic)
for the explicit tests the order of evaluation is important

Altogether this is doubling the speed, but there is no magic to find magnitudes.


Pair elements of two lists by condition without reusing elements

Theory

It might not be clear at first, but you're basically describing a bipartite graph.

You're interested in finding the maximum matching and if it's perfect.

NetworkX is a great Python library for graphs, and the maximum_matching function is already implemented. It uses the Hopcroft-Karp algorithm and runs in \$O(n^{2.5})\$ where \$n\$ is the number of nodes.

You only have to preprocess your lists into a graph and let networkx do its job.

Code

Here's a slightly modified version of a previous answer on Stack Overflow:

import networkx as nx
import matplotlib.pyplot as plt

def has_a_perfect_match(list1, list2):
    if len(list1) != len(list2):
        return False

    g = nx.Graph()

    l = [('l', d['name'],  d['amount']) for d in list1]
    r = [('r', d['color'], d['amount']) for d in list2]

    g.add_nodes_from(l, bipartite=0)
    g.add_nodes_from(r, bipartite=1)

    edges = [(a,b) for a in l for b in r if a[2] == b[2]]
    g.add_edges_from(edges)

    pos = {}
    pos.update((node, (1, index)) for index, node in enumerate(l))
    pos.update((node, (2, index)) for index, node in enumerate(r))

    m = nx.bipartite.maximum_matching(g, l)
    colors = ['blue' if m.get(a) == b else 'gray' for a,b in edges]

    nx.draw_networkx(g,
                     pos=pos,
                     arrows=False,
                     labels = {n:"%s\n%d" % (n[1], n[2]) for n in g.nodes()},
                     edge_color=colors)
    plt.axis('off')
    plt.show()

    return len(m) // 2 == len(list1)

As a bonus, it displays a diagram with the graph and maximum matching:

list1 = [{'amount': 124, 'name': 'john'},
         {'amount': 456, 'name': 'jack'},
         {'amount': 456, 'name': 'jill'},
         {'amount': 666, 'name': 'manuel'}]
list2 = [{'amount': 124, 'color': 'red'},
         {'amount': 456, 'color': 'yellow'},
         {'amount': 456, 'color': 'on fire'},
         {'amount': 666, 'color': 'purple'}]

print(has_a_perfect_match(list1, list2))
# True

list1 = [{'amount': 124, 'name': 'john'},
         {'amount': 456, 'name': 'jack'},
         {'amount': 457, 'name': 'jill'},
         {'amount': 666, 'name': 'manuel'}]
list2 = [{'amount': 124, 'color': 'red'},
         {'amount': 458, 'color': 'yellow'},
         {'amount': 456, 'color': 'on fire'},
         {'amount': 666, 'color': 'purple'}]

print(has_a_perfect_match(list1, list2))
# False

Notes

The desired matching is in m and has a slightly different format than what you mentioned:

{('l', 'jack', 456): ('r', 'yellow', 456), ('l', 'jill', 456): ('r', 'on fire', 456), ('l', 'john', 124): ('r', 'red', 124), ('l', 'manuel', 666): ('r', 'purple', 666), ('r', 'red', 124): ('l', 'john', 124), ('r', 'yellow', 456): ('l', 'jack', 456), ('r', 'purple', 666): ('l', 'manuel', 666), ('r', 'on fire', 456): ('l', 'jill', 456)}

It does have enough information, though.

Note that the edge generation isn't optimal (it's \$O(n^{2})\$ and could be \$O(n)\$ with dicts) but it's concise and still faster than the matching algorithm. Feel free to modify it!

Optimization

@Peilonrayz' answer has a better performance because your problem is easier than the general matching problem : there are no connections between nodes with distinct ids, so a greedy algorithm works fine.

Actually, it's possible to check in 2 lines if the lists match. With a Counter,  you just need to check if the distribution (e.g. Counter({124: 1, 456: 2, 666: 1})) is the same for both lists:

from collections import Counter
Counter(map(key, list1)) == Counter(map(key, list2))
# True


A simple template engine to display value

1. Introduction

This code looks mostly fine to me. I make a bunch of points below, but it's a case of tightening things up rather than fixing mistakes.

2. Review

The Template class is misleadlingly named. Normally the term template refers to the string into which the parameters are substituted. But an instance of the Template class actually represents the settings controlling the substitution. A better name for the class would be TemplateProcessor.
Since the only thing you can do with a Template object is to call its substitute method, it would simplify things to use __call__ instead.
The parameter name template to the substitute function is misleadingly named: this isn't the template, but actually the parameters to be substituted into the template. A better name would be params.
It would be simpler to take the substitution parameters as keyword arguments rather than a dictionary. This would slightly simplify the callers because instead of writing:

processor(string, {'var': 'Try'})

you could write:

processor(string, var='Try')

The value of result is a match object and so match or m would be a better name.
The code takes four steps to match a word against the syntax rules:

if word.startswith(self.delimiter_start) \
        and word.endswith(self.delimiter_end):
            word_without_delimiter = word[1:-1]
            result = re.match(
                self.identifier, word_without_delimiter)

But this could all be done in a single step using a regular expression that matches the initial delimiter, the identifer or nonidentifier, and the final delimiter: that is,

\[(?:([^\d\W]\w*)|(.*))\]$

See the revised code below for how this regular expression can be built and used.
The error message ought to include the incorrect identifier, for assistance with debugging.
Instead of:

'{value}'.format(value=template[word_without_delimiter])

use the format function and write:

format(template[word_without_delimiter])

3. Revised code

(Docstrings omitted—they were fine in the original.)

class TemplateProcessor(object):
    def __init__(self, delimiter_start='[', delimiter_end=']',
                 identifier=r'[^\d\W]\w*'):
        self.identifier_re = re.compile(
            '{}(?:({})|(.*)){}$'.format(re.escape(delimiter_start),
                                        identifier,
                                        re.escape(delimiter_end)),
            re.UNICODE)

    def __call__(self, string, **params):
        words = string.split(' ')
        for i, word in enumerate(words):
            m = self.identifier_re.match(word)
            if not m:
                continue
            identifier, nonidentifier = m.groups()
            if identifier is None:
                raise ValueError("{!r} is not a valid identifier"
                                 .format(nonidentifier))
            elif identifier in params:
                words[i] = format(params[identifier])
        return ' '.join(words)


Dead Lock Bug

If the queue is empty and the consumer thread is waiting in the condition variable. If you Queue goes out of scope the main thread will enter the detructor and perform join(). At this point you are locked. As both threads are waiting for the other.

Use of condition can be simplified.

    while(queue.empty())
    {
        cv.wait(lock);
    }

Can be replaced with:

    cv.wait(lock, [&queue](){return !queue.empty();});

When poping things from a queue use move.

// this performs a copy.
int i = queue.front();

// this should move the value from the que.
int i = std::move(queue.front());

Note: It makes little difference for an integer but if there is an object in the queue then it might.

Formatting

Your code is horribly formatted. Please do a better job in the future. Formatting is a critical part of coding. This is because your code will be read fro decades aftr you have written it by other humans.


In Python, if you do not specify the return value of a function, then by default it will return None. So no need to hard code return in your case.

You do not need to create the extra variable points_list  as you can directly write:

  if len(x['polygon']) < 3:
        raise ValueError('More than two points required.')

and:

 for x, y in x['polygon']:
    if type(x) != int or type(y) != int:
        raise ValueError('integer (x,y) pairs required.')

Of course, choosing a meaningful and significant name for the object x will be better.

When we check if stuff in some_iterable we get True or False. I mean that a ValueError exception is not the most suitable thing that can happen here.

isnstance() returns True or False, and may raise a TypeError exception under certain conditions (check the link), so here also raising a ValueError may not be appropriate.

Because when you raise the exception, you communicate to the user only what he needs to know (through the messages you specified for each case) and because of the last 2 points I mentioned previously, I suggest you to create a custom exception which message can be overridden for each situation:

class InvalidPolygonObject(Exception):
   pass

And your function can be written this way:

def validate_object(polygon_object):
    if type(polygon_object) != dict:
        raise InvalidPolygonObject('dict type input required.')

    if 'polygon' not in polygon_object:
        raise InvalidPolygonObject('polygon object required.')

    if not isinstance(polygon_object['polygon'], (list,)):
        raise InvalidPolygonObject('list type polygon object required.')

    if len(polygon_object['polygon']) < 3:
        raise InvalidPolygonObject('More than two points required.')

    for x, y in polygon_object['polygon']:
        if type(x) != int or type(y) != int:
            raise InvalidPolygonObject('integer (x,y) pairs required.')


Helper function to make `setTimeout` synchronous

The Eval

Eval is indeed, the monster. There are plenty of reasons why you should not use it, although there are some situations where you are forced to use it. For sure, this is not the requirement in yours situation. If func is a function, you can call it using .apply.

function syncSetTimeout(func, ms, callback) {
    (function sync(done) {
        if (!done) {
            setTimeout(function() {
                func.apply(func);
                sync(true);
            }, ms);
            return;
        }
        callback.apply(callback);
    })();
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

Or event without apply:

function syncSetTimeout(func, ms, callback) {
    (function sync(done) {
        if (!done) {
            setTimeout(function() {
                func();
                sync(true);
            }, ms);
            return;
        }
        callback();
    })();
}

The synchronous

You need to know, that trying to make setTimeout() sync means that you have some very bad design idea behind. You should not do it and you will not be able to make it really sync without killing performance of the browser and UX of your app.

I believe that you would like to create sync delay in your application. You are not the first who wants to do it (most of beginners or people with background from different language). You can take a look at answers to this question from stackoverflow: https://stackoverflow.com/questions/6921895/synchronous-delay-in-code-execution

From the answer to linked question (by OverZealous):

  JavaScript is a single-threaded language. You cannot combine
  setTimeout and synchronous processing. What will happen is, the timer
  will lapse, but then the JS engine will wait to process the results
  until the current script completes.

One reason people are trying to take advantage of sync delays is returning result from async code. This is not good strategy in JS. If you would like to return async results just use callbacks or more likely - Promises or Observables.


Read a csv file and insert into DB table

What I found to greatly improves the speed of insert queries, is inserting multiple rows using a single query. You seems to have found the same solution, but it is implemented in a very roundabout way.
Your code could also benefit a lot from using functions. So, let's start with the most important one: How to insert multiple rows. It could look something like this:
function insertRows($db, $table, $rows)
{
    $values    = '(' . implode(',', array_fill(0, count($rows[0]), '?')) . ')';
    $query     = 'INSERT INTO '.$table . ' VALUES ' .
                 implode(',', array_fill(0, count($rows), $values));
    $statement = $db->prepare($query);
    $index     = 1;
    foreach($rows as $row) {
        foreach($row as $value) {
            $statement->bindValue($index++, $value);
        }
    }
    $statement->execute();
}

This bit of code has only one function: Insert a certain number of rows into the database as quickly as possible. This function doesn't read data, change it in any way, but it does use parameter binding for extra security. That's probably not needed in this case, but it also doesn't hurt. No more problems with quotes.
You can insert quite a few rows using this function, somewhere around 50 to 150 rows, depending on what your input looks like. Above a certain number the speed simply won't increase anymore, so there's no point in going to extremely large number of rows.
I would create another function for changing the row data from the format you received to the format you want to insert:
function reformatRow($row)
{
    // <...put your code here...>
    return $row;
}

We can now also implement a function that does the above for multiple rows:
function reformatRows($rows)
{
    foreach ($rows as $key => $row) {
        $rows[$key] = reformatRow($row);
    }
    return $rows;
}

Functions don't have to be complex to be useful. I actually will not use this function, but I thought it was nice to show it.
All that's now left to do is to read the input, so let's do that. I will use parts of your code:
const MAX_ROWS = 100;

fgetcsv($handle, 2000, ";", chr(8)); // read header and dump it

$rows = [];
while (($row = fgetcsv($handle, 2000, ";", chr(8))) !== FALSE) {
    $rows[] = reformatRow($row);
    if (count($rows) >= MAX_ROWS) {
        insertRows($db, $table[$i], $rows);
        $rows = [];
    }
}

if (count($rows) > 0) {
    insertRows($db, $table[$i], $rows);
}

I haven't fully tested all this code.
I also don't think this code will be any quicker than yours. There's also no way for me to test any optimization, since I don't have your data, so I'm afraid I can't help you there. Reading data into a database just takes time. It is possible that fgetcsv() is not the optimal way to read a big CSV file, but I haven't tested that.
What I have tried to make clear is that by splitting your code into functional parts it become easier to understand, and more reusable. The insertRows() is, for instance, is, partly, reused from my own code. Once you've written a function like that, and it works, you can reuse it everywhere.


Please fix your indentation all over the header.  It should be consistent with everything else.
You don't need the return 0 at the end of main().  Reaching this point implies successful termination, and the compiler will just insert it for you.
In common stack implementations, pop() is void (merely pops off the top element).  This is useful as it'll be much easier to terminate the function early if the stack is empty.

For getting an element from the top, you would also have a top() function.  It will also have to account for an empty stack, but it would be best to check for an empty list first.
As @ChrisW has mentioned, the node class should be defined within the stack class as private.  Also, there shouldn't be anything public inside the node class.  If you put it within stack, its private data can still be accessed without an accessor.
A member function like getdata() should be const as it doesn't modify any data members.  You also don't need the () around data.

int getdata() const
{
    return data;
}

Moreover, you shouldn't have this function at all.  A basic node structure should just have a data field and a pointer to the next/previous node in the list.  As mentioned, anything containing this class will have access to its data.
Prefer an initializer list instead of the constructor assignments:

node(int element) : data(element), next(NULL) {}

One advantage to this is that if you have any const data members, you'll be able to initialize them within this list.  But with a constructor like yours, that won't work.
You must have a destructor for a data structure that utilizes manual memory allocation.  What happens if your structure object goes out of scope, but you haven't already popped every element?  You'll have a memory leak.

To prevent this, have the destructor traverse the list, using delete on each node.
You can make your structure more intuitive and safer with a empty() function:

bool empty() const { start == NULL; }

This can just be defined within the class declaration and should be public.

It is assumed that the list is empty if the head points to NULL, otherwise you can instead compare a size member to 0 (if you even want to bother with maintaining a size).


Calculating the average of all nodes in a Binary Search Tree using visitors

You are doing it somewhat right, somewhat wrong.

Your visitor is more of a Mapping transformer: it is converting Node into an int.  How it gets that int value from the Node is left up to the implementation.

Unfortunately, all of your average calculation is still inside inOrder().  Worse, your sum, count and average values are static members of Node, so you cannot do two parallel average calculations.  There is no resetting of the sum or count so a subsequent average calculation is going to compute the average of the aggregate of all data, not just the most recent tree.

Your Visitor visit() method should return nothing:

public interface Visitor {
    void visit(Node node);
}

Then, you can create an AveragingVisitor which averages the data it extracts from Node objects:

static class AveragingVisitor implements Visitor {
    int sum = 0;
    int count = 0;

    @Override
    public void visit(Node node) {
        sum += node.getVal();
        count++;
    }

    public double average() {
        return (double) sum / count;
    }
}

Each time you create a new AveragingVisitor, it will start new count & running total at zero.

To compute the average, you would create this averaging visitor, and perform some kind of traversal (inOrder is fine) of the tree:

AveragingVisitor visitor = new AveragingVisitor();

root.inOrder(visitor);

System.out.println(visitor.average());

Of course, Node::inOrder(Visitor vistor) will need to be rewritten as non-static, and call the visitor.visit(node) method on each node:

public void inOrder(Visitor visitor) {
    if (left != null)
        left.inOrder(visitor);
    visitor.visit(this);
    if (right != null)
        right.inOrder(visitor);
}

With this visitor, you could easily make a PrintingVisitor to print all of the nodes.  No change would need to be made to inOrder().


Correctness:

Project Euler Problem #3 asks for
the largest prime factor of 600851475143, and that number exceed the range
of the int data type. (Your program aborts with an exception for this input value.) You have to use long instead.

In

for (int i = 3; i < Math.sqrt(input); i = i + 2) { ... }

the < should be replaced by <=, otherwise you get a wrong result if the
input is the square of a prime number (such as 25). To avoid a loss of precision if input is converted to a floating point
number, it should be

for (long i = 3; i * i <= input; i = i + 2) { ... }

Efficiency:

The problem is about the largest prime factor. Your algorithm already
determines the prime factors in increasing order. Therefore there is no need
to store the prime factors in a collection to get its maximum value.
It is sufficient to remember the last prime factor found.

Putting it together:

Your function (renamed slightly) would then look like

public static long calculateLargestFactor(long input) {
    long largestFactor = 1;
    while (input % 2 == 0) {
        largestFactor = 2;
        input = input / 2;
    }
    for (long i = 3; i * i <= input; i = i + 2) {
        while (input % i == 0) {
            largestFactor = i;
            input = input / i;
        }
    }
    if (input > 2) {
        largestFactor = input;
    }
    return largestFactor;
}


'join' MongodDB collections with a for loop

The nested loops perform books.length * favorites.length iterations (up to 4 million).

Instead build a dictionary of id -> rating, so total iterations max is a sum of lengths.

var favRatings = {}, i, len;

for (i = 0, len = favorites.length; i < len; i++) {
    var fav = favorites[i];
    favRatings[fav.bookId] = fav.myRating;
}

for (i = 0, len = books.length; i < len; i++) {
    var book = books[i];
    var rating = favRatings[book._id];
    if (rating !== undefined) {
        book.userRating = rating;
    }
}


Render dynamically vertical tabs and set classes depends on if statement

Helper methods are good for this.  In your view's helper file:

def task_link_class(task)
  if @current_user_tasks.include?(task)
    ''
  else
    'inactive'
  end
end

Some would prefer the trinary operator instead:

def task_link_class(task)
  @current_user_tasks.include?(task) ? '' : 'inactive'
end

And in your view:

= link_to task.name, "#tab#{task.id}", data: { toggle: 'tab' }, class: task_link_class(task)


You must allow the escape character for { and } otherwise this doesn't works.

Console::WriteLine("int {0}(){ return 0; }", function_name);

Apart from that I would add an override to specify the output stream.

std::ofstream logger("log.err");
Console::WriteLine(logger, "String");

It must be a class? Probably it's only a style issue, but I don't like class with only static methods. I prefer namespace and a console_details namespace for private functions.


Reconstruct a string, given a list of subsequence triplets

It looks like you have implemented Kahn's algorithm for topological sorting.

By PEP 8, the official Python style guide, function names should be lower_case_with_underscores.  Also, since the code would work equally well with an n-tuples as inputs, I'd rename triplets to subsequences.

For building secret_dict, I suggest:

using collections.defaultdict(set)
iterating by index, so as to avoid calling x.index(y).

The removeChar() function does not actually return a dict, as claimed — there's no return statement!  For clarity, I'd avoid the bogus use of a set comprehension that actually surreptitiously mutates secret_dict's values as a side-effect, and just write it as a loop.

I don't think that removeChar() and findChar() need to be defined as inner functions, especially since they are both short.  The functions don't really help with code clarity, since they act on secret_dict by closure.

from collections import defaultdict

def recover_secret(subsequences):
    preceding_chars = defaultdict(set)
    for subseq in subsequences:
        for i in range(len(subseq)):
            preceding_chars[subseq[i]].update(subseq[i - 1] if i else '')

    secret = []
    while preceding_chars:
        c = next(k for k, v in preceding_chars.items() if not v)
        del preceding_chars[c]
        for prec in preceding_chars.values():
            if c in prec:
                prec.remove(c)
        secret.append(c)
    return ''.join(secret)


Create a Tree Node from JavaScript Array

Your code seems to only support 2 levels down. Also, the second loop is costly because it has to search through the array if the path already exists.

I believe your structure can be better represented using an object. Lookups won't need searching through, and there's still room for path metadata.

var goal = {
  // Room for "goal" metadata.
  "/": {},
  "A": {
    // Room for "A" metadata.
    subpaths: {
      "A": {},
      "B": {},
      "C": {},
    }
  },
  "B": {},
  "C": {},
}

Here's an example

var paths = [
  {path: "/"  },
  {path: "A"  },
  {path: "A.A"},
  {path: "A.B"},
  {path: "A.C"},
  {path: "A.D.C"},
  {path: "B"  },
  {path: "C"  }
];

// Move out or template into a creator function.
function createPath(){
  return {
    subpaths: {}
  };
}

// Resolves the path into objects iteratively (but looks eerily like recursion).
function resolvePath(root, path){
  path.split('.').reduce(function(pathObject, pathName){
    // For each path name we come across, use the existing or create a subpath
    pathObject.subpaths[pathName] = pathObject.subpaths[pathName] || createPath();
    // Then return that subpath for the next operation
    return pathObject.subpaths[pathName];
  // Use the passed in base object to attach our resolutions
  }, root);
}

var goal = paths.reduce(function(carry, pathEntry){
  // On every path entry, resolve using the base object
  resolvePath(carry, pathEntry.path);
  // Return the base object for suceeding paths, or for our final value
  return carry;
// Create our base object
}, createPath());

document.write(JSON.stringify(goal));


Binary search on a uniformly distributed vector

Bug
Generally code should prevent stack overflows from occurring. The search implemented here causes a stack overflow when the item searched for is not in the array. I tested the code using 8 as the value to search for which caused a recursive stack overflow.

I searched the internet for Weighted Binary Search and couldn't find it, instead I found Weighted Binary Tree.

Wikipedia defines a binary search as "In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. ..."

The search implemented is not a binary search. A binary search always divides the search area by two.

I'm not really sure why there is a for loop in the function weighted_binary_split(), it doesn't comply with a binary search.

Handling Errors
Since the code is keeping track of the depth of the search a possible solution to a stack overflow problem would be to check the value of depth against Log(N) where N is the number of items in the array. A secondary check might be to check the value of depth against N itself because N would be the limit in a linear search.

The function weighted_binary_split() could return -1 in the case of an error or use setjmp(jmp_buf env) and longjmp(jmp_buf env, int value) if negative values are valid in the search.

Always check for possible errors when developing code.

Array Initializations
In the function example_split() the following line:

    int x[10] = { 0, 1, 2, 2, 4, 5, 6, 6, 7, 9 };

would be easier to modify if it was written as:

    int x[] = { 0, 1, 2, 2, 4, 5, 6, 6, 7, 9 };

There is no need to include the size of the array for x because the compiler does it for you.

The size of the array can be calculated:

    int arr_size = (sizeof(x) / sizeof(x[0]));

The variable end_idx can then be calculated as well.

    int end_idx = (sizeof(x) / sizeof(x[0])) - 1;

For Loop Control Variables
In the function example_split() there is no need to create the variable i at the top, it can be created inside the for loop itself:

    for (int i = 0; i < arr_size; i++) {
        printf("%d,", x[i]);
    }

It's generally better to create the variables as they are needed. This is a change from the original version of the C Programming Language that was quite helpful.


Counting occurrences of "A…Z" substrings

The second solution seems to be clearer and more efficient.
In both cases, a few details can be improved:

variable names
removing useless whitespaces
removing useless parenthesis
removing useless tests (no need to call find before calling count)
using the start parameter of count (suggestion of @SolomonUcko).

You'd get something like:

def substring_counter(string):
    counter = 0
    for num, c in enumerate(string):
        if c == 'A':
            counter += string.count('Z', num)
    return counter

def substring_counter2(string):
    counter = 0
    nb_a = 0
    for c in string:
        if c == 'A':
           nb_a += 1
        elif c == 'Z':
           counter += nb_a
    return counter


Review Python script for getting the stats of codereview.SE into a file for analysis

Firstly, you don't need to store the last date at the beginning of the file since it's already at the end.

Secondly, you shouldn't compute today's date twice.

Thirdly, you should use Stack Exchange's API instead of trying to extract information from Code Review's home page. It has everything except visitors/day.

Fourthly, the date format %Y-%m-%d is better than %d-%m-%Y because it allows string comparison of dates.

So, here's what I came up with:

#!/usr/bin/env python3

import datetime
import gzip
import json
from urllib.request import Request, urlopen

FILE_NAME = 'data_file.txt'
API_URL = 'http://api.stackexchange.com/2.1/info?site=codereview'

def last(iterable, default):
    r = default
    for v in iterable:
        r = v
    return r

def main():
    today = datetime.date.today().strftime('%Y-%m-%d')
    with open(FILE_NAME, 'a+') as f:
        f.seek(0)
        last_date = last(f, '').split(',')[0]
        if last_date == today:
            return  # we already have the data for today
        elif last_date > today:
            raise Exception('last date is in the future')

        req = Request(API_URL, headers={'Accept-Encoding':'gzip'})
        r = gzip.decompress(urlopen(req).read()).decode('utf8')
        d = json.loads(r)['items'][0]
        print(today,
            d['total_questions'],
            d['total_answers'],
            d['total_unanswered'],
            d['total_users'],
            sep=',', file=f)

if __name__ == "__main__":
    main()

The gzip stuff is to work around a bug in Stack Exchange's API server: it always compresses the response even if you don't ask, which is a protocol violation. Using the requests library might make it easier.

The way I get the last line of the file isn't the most efficient but it should be good enough.


I'd like to suggest the opposite of Sᴀᴍ Onᴇᴌᴀ: Since you are using jQuery for selecting only, you can drop it altogether.

const icons = $(".magic");

becomes either

const icons = document.getElementsByClassName("magic");

or

const icons = document.querySelectorAll(".magic");

However you shouldn't use on... properties to assign event handlers. on... properties can only hold a single handler so if you or another script would attempt to assign another click handler then they'd overwrite each other. Instead use addEventListener.

Alternatively to avoid assigning seperate event handlers to each icon you could use event delegation. This means assign an single event handler to a surrounding element (or simply document) and check the target element:

document.addEventListener("click", function (event) {
  if (event.target.classList.contains("magic")) {
    event.target.classlist.toggle("enabled");
  }
};

Finally you could avoid using JavaScript altogether by using an HTML element that has the toggle functionality built in: a checkbox:

  <input type="checkbox">

Hide the actual checkbox with:

.magic-wrapper > input {
  opacity: 0;
  position: absolute;
}

(This is more accessable than just using display: none;)

And replace the selector .enabled with input:checked + .magic in the CSS.

Complete example: https://jsfiddle.net/rhy6gfn4/

A small points about the CSS:

You should select not just .enabled but use .magic.enabled, because then it's more obvious that these rules belong to the animated icons. Also "enabled" is a common class name and you don't want those styles apply to unrelated elements.

It would be a tiniest bit more performant to select the i elements using .magic > i and not just .magic i.


Rather than nesting if-else blocks it sometimes helps to cut the problem into independent slices and deal with them one by one, starting with the fairly exceptional ones:

private boolean useCachedReportBeanRefact(BeanReport cachedReportBean,
        String strRequestedReportID) throws ExceptionInvalidReportRequest {
    // validate input arguments
    if (cachedReportBean == null
            && StringUtils.isBlank(strRequestedReportID)) {
        throw new ExceptionInvalidReportRequest(
                "The request ID is invalid and no cached report exists.");
    }

    // corner case #1
    if (cachedReportBean == null) {
        return false;
    }

    // corner case #2
    if (StringUtils.isBlank(strRequestedReportID)) {
        return true;
    }

    // after all corner cases are dealt with, just go ahead and compare the id
    return strRequestedReportID.equalsIgnoreCase(cachedReportBean
            .getConfigBean().getReportID());
}

I think the real problem is that this function does too much and is poorly named (it doesn't really use the cached report, it only checks if... a bean, if not null, has a config object whose ID is same as the other input parameter... on the condition that this other parameter is not blank either... I think?). It's not immediately obvious where it would be used and what the returned boolean would mean, it doesn't seem to translate to any real-life concept.

Making ExceptionInvalidReportRequest a checked exception feels like a bad idea, too (difficult to say without knowing the context); wouldn't unchecked IllegalArgumentException do?

Working code including unit tests: http://pastebin.com/pCXQXLee


Writing a safe class method in terms of a dangerous one

As hinted to in the Ruby Style Guide, the Object#dup method returns a duplicate of self to be passed to other methods without danger of altering self. The solution is as simple as moving the trim logic into the trim! function and having trim call dup.trim!

class String
  def trim!(amount=1)
    self[0..-1] = self[0..-(amount+1)]
  end

  def trim(amount=1)
    dup.trim! amount
  end
end

This returns the same sample output as above.


JSON storage of data for a to-do list application

You are on the right track! Your hunch is correct that JSON doesn't really have a "root" element the way XML does. Actually, it does have a root - the opening {. Read that as "I am starting an object", the way you'd read the opening element in XML. (The thing about JSON that feels weird if you're used to XML is that you don't actually specify what type of object it is. That's the beauty [and danger] of playing fast and loose with types the way JavaScript does.)

Here's a suggested revision:

{
  "id": 100,
  "belongsToUser": "782950ce-f920-4f98-a69e-a899729e6267",
  "created": "2015-02-05T02:40:31Z",
  "lists": [{
      "name": "Home",
      "tasks": [
        {
          "name": "Clean room",
          "done": false

        }, {
          "name": "Get storage unit",
          "done": false
        }
      ]
    }, {
      "name": "Work",
      "tasks": [
        {
          "name": "Analysis",
          "done": false
        }, {
          "name": "Sorting",
          "done": false,
          "subtasks": [
            {
              "name": "Save files",
              "done": false,
              "subtasks": [
                {
                  "name":
                  "Pull from computer 1",
                  "done": false

                }, {
                  "name": "Walk to computer 2",
                  "done": false

                }, {
                  "name": "Save on computer 2",
                  "done": false

                }]
            },
            {
              "name": "Sort files",
              "done": false

            }, {
              "name": "Plot data",
              "done": false
            }]
        }]
    }]
}

A few things of note:

There's no need for a root todoList attribute, but there's plenty of other good metadata that could go at the root level: primary keys or IDs, timestamps, ownership information, and so on.
I think it makes sense to have a lists array at the root, and then have object for each clade (the Home and Work blocks) under that.
Each list object can have metadata of its own (name, creation timestamp, etc), in addition to an array of tasks.


It is good practice in Haskell to separate the functional code from the IO. In this case, you could (and therefore should) define a lolcat :: String -> String function.  Be sure to put a type declaration on all functions — you didn't write one for your main.

Defining variables a, b, c, and d is overkill. I would write this as a composition of functions.

lolcat :: String -> String
lolcat = strReplace " A " " " .
         strReplace "CHEESEBURGER" "CHEEZBURGER" .
         strReplace "CAN I" "I CAN" .
         strReplace "HAVE" "HAS" .
         strToUpper


Simple multithreaded chat server in Rust

I made some changes to your code (see below). You can check the code for what I've done so far: I added some comments on it so you can compare it with your version.  I'll note some important points in here. Please ask if you have any questions; I will try to explain or we can improve the code together.

Propagating error to the main function from a spawned thread is not possible. It's only possible after joined to the main thread (you can use join handler then propagate your anonymous function's return value to the main).
Created ConnectionsSync struct as helper to get rid of Arc<RwLock<HashMap< initialization: it was looking too messy; also with this way you can add behaviors like (add_user, broadcast_message, remove_user, ... )
Incoming has Iterator implementation so I can use it as iterator and I used try_for_each to tell that I am going to apply fallible function, then it will be propagated to main.

Code

use std::collections::HashMap;
use std::env;
use std::io;
use std::io::{BufRead, BufReader, LineWriter, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, RwLock};
use std::thread;

type User = Arc<String>;
struct ConnectionsSync(Arc<RwLock<HashMap<User, LineWriter<TcpStream>>>>);
impl ConnectionsSync {
    fn new() -> Self {
        ConnectionsSync(Arc::new(RwLock::new(HashMap::new())))
    }
}

fn main() -> io::Result<()> {
    let port = env::args().nth(1).unwrap_or("8080".to_string()); //default port 8080
    let connections = ConnectionsSync::new();

    TcpListener::bind(&format!("localhost:{}", port))?
        .incoming()
        .try_for_each(|socket| -> io::Result<()> {
            let socket = socket?;
            let connections = connections.0.clone(); //increases ref count

            thread::spawn(move || {
                let (mut reader, writer) = socket
                    .try_clone()
                    .map(|socket1| (BufReader::new(socket1), LineWriter::new(socket)))
                    .unwrap();

                // read nick
                let mut nick = String::new();
                reader
                    .read_line(&mut nick)
                    .and_then(|_| Ok(nick.pop()))
                    .expect("Not able to read user nick");

                let current_user = Arc::new(nick);
                //add user
                connections
                    .write()
                    .unwrap()
                    .insert(current_user.clone(), writer);

                //read user input
                reader.lines().into_iter().for_each(|line| {
                    let line = line.expect("Not able to read user input");
                    connections
                        .write()
                        .unwrap()
                        .iter_mut()
                        .filter(|(other_user, _)| **other_user != current_user)
                        .for_each(|(_, peer)| {
                            writeln!(peer, "{} \t-> {}", current_user, line);
                        })
                });

                //discard user
                connections.write().unwrap().remove(&current_user);
            });

            Ok(())
        })
}

Edit for questions in comment section

  Can we get rid of nick.clone() and keep a simple reference? I guess not because cannot move out of borrowed content despite nick being
  immutable.

Actually cannot move out of borrowed content error is not related being immutable or mutable. Consider this; Your friend borrowed a phone from you and moved it's battery out physically to use somewhere else. Then your friend gave it your phone back to you without a battery. You would probably give an instant error. So due to safety, Rust watches your friend and warns: "Hey your friend is going to need that part in the future, so stop it!"

Besides the error you mentioned, another error will be occurred if we get rid of nick.clone() and keep a simple reference: We'll face with "borrowed value does not live long enough". This happens because we have a HashMap which it's reference counted, so we don't exactly know when it is going to die. If we put our nick's simple reference into HashMap, the compiler will tell that: "Hey HasMap is the owner of nick's reference but nick is gonna die in that block and HashMap will live after that, so what i am gonna do with this reference in the future ? ". We can solve this problem with 2 solution.

With cloning because we have 2 ownership of nick (HashMap, Thread Block). I believe you don't want this solution due to overhead of copying String.
With Smart Pointers Like Rc(Reference Counted), we will give nick's ownership to the Rc and share it across the HashMap and Thread. But Rc is not thread safe so we need to use Arc instead of it.i updated code with Arc version, there will be still cloning in code but it will just increase the reference count instead of copying the whole String.

  Can we filter on value references instead of key objects?

Sure you can do it simply you need to change your code like this:

.filter(|(_other_user, other_users_value)| other_users_value != current_users_value)

But in our case this will not work because Eq is not implemented for TCPStream, if you implement it by yourself it will work.

Edit: Added unsafe version with raw pointers instead of clone

let mut users = HashMap::new();

let nick = "SomeInput".to_string();
let nick_ptr = &nick as *const String;

users.insert(nick, "SomeValue".to_string());

unsafe {
    users.remove(&*nick_ptr);
    println!("{:?}", users.get(&*nick_ptr)); //output None
}


Calculating linux based octal file permission

My thoughts for improvement:

You don't need to run ToArray() on your string to loop through it. Plus, it seems like CalculatePermissionSum() is expecting a single permission string like "rwx" or "r-x", so in a fixed-length situation like this (where the flags are also in a predefined order), don't bother with a loop.

int octalPerm = 0;
octalPerm += (permString[0] == 'r') ? 4 : 0;
octalPerm += (permString[1] == 'w') ? 2 : 0;
octalPerm += (permString[2] == 'x') ? 1 : 0;
return octalPerm;

SymbolicToOctal doesn't account for permission representations where the first character is a non-permission flag, like a directory "drwx-x--r-"
There's no error-checking in case an unexpected value comes through. If I ran SymbolicToOctal("Hello World"), I should really get an exception of some kind.
I disagree with the previous comment about using regular expressions to validate the input. Validation is good, but regular expressions would add a (relatively) huge amount of overhead for such simple validation. Code that works on file permissions isn't likely to be run a couple times here and there - it's more likely to be used as part of something that might run a LOT, so every inefficiency will add up. If you validate, just check the length and the expected individual characters. It might be more code compared to a regex, but it'll run a LOT faster.
If I was an interviewer, I would give a LOT of brownie points to the interviewee who threw in some unit-testing code.


MSSQL query to look for duplicate record

As mentioned in the comments, there are benefits to casting/storing that unique key in the table during the ETL process, especially if it's going to be used in other places than just this query.

Most likely, the performance hit is coming from using IN (typically results in a row by row lookup) and from de-duping with the casted key.  You could get a performance gain from JOINing the subequery instead of using IN.  You could also use ROW_NUMBER which, in my experience, is typically more performant than the GROUP BY with HAVING clause.

Here's my example using ROW_NUMBER and CTE's for easier reading:

--Calculate Unique NVARCHAR key
;WITH cte_lf_transit_cage AS (
    SELECT
      ltrim(rtrim(CAST(cageID as nvarchar(max))))+ltrim(rtrim(CAST(trayNo as nvarchar(max)))) as _unique,
      *
    FROM
      lf_transit_cage
)
--Get the Row Count
, cte_rowcount AS (
  SELECT
    _unique,
    ROW_NUMBER() OVER (PARTITION BY _unique ORDER BY cageID, trayNo) AS rowcnt
  FROM
    cte_lf_transit_cage
)
--Grab all instances of duplicate rows
SELECT
  ltc.*
FROM
  cte_lf_transit_cage ltc
WHERE
  EXISTS
    (SELECT unique FROM cte_rowcount rc WHERE rc._unique = ltc._unique AND rc.rowcnt > 1 )
ORDER BY
  ltc.cageID,
  ltc.trayNo

Also, was mentioned in the comments that you may not need to generate the _unique key depending on how the data is stored.  Might compare results to confirm:

--Get the Row Count
;WITH cte_rowcount AS (
  SELECT
    cageID,
    trayNo,
    ROW_NUMBER() OVER (PARTITION BY cageID, trayNo ORDER BY trayNo) AS rowcnt
  FROM
    lf_transit_cage
)
--Grab all instances of duplicate rows
SELECT
  ltrim(rtrim(CAST(ltc.cageID as nvarchar(max))))+ltrim(rtrim(CAST(ltc.trayNo as nvarchar(max)))) as _unique,
  ltc.*
FROM
  lf_transit_cage ltc
WHERE
  EXISTS
    (SELECT * FROM cte_rowcount rc WHERE rc.cageID = ltc.cageID AND rc.trayNo = ltc.trayNo AND rc.rowcnt > 1 )
ORDER BY
  ltc.cageID,
  ltc.trayNo


Avoid printing attributes of the nil object in Rails

You are right, you code is too verbose. This is a pretty common pattern and you have some alternatives. For example, active_support has the abstraction Object#try:

<%= @person.team.try(:name) %>

Another alternative is the Object#maybe proxy: https://github.com/bhb/maybe

<%= @person.team.maybe.name %>


Avoid partial functions like head and last.
http://chat.stackoverflow.com is repeated twice in searchLast. Maybe throw it into its own let-binding to make the function more DRY.


Looks pretty good to me.  Personally, I would get rid of the found variable and just return True if item is found.

I would also use a more descriptive name for the list.  a just doesn't say list to me.  If you want to keep it short, use something like l or borrow Haskell's convention and use something like as or xs.

Finally, if you wanted, you could use an if/elif/else instead of the if/else with nested if/else inside.  But I can't think of any compelling reason to do so.

As an answer to an interview question, I think you'll want to do a better job of indicating coverage of the case where the list is empty.  Your code covers this case perfectly (last will be -1 and first will be 0, so first <= last is False), but it's not obvious.  So it probably wouldn't hurt to add an explicit check or add a comment with a brief explanation why that case is covered.  Then there's no doubt that you considered that case.


Why are you passing a file name?

void storeOddElements(NODE *head, char *FileName)

A file stream is the same concept as a stream. So writ the code to use a stream. Then you can pass std::cout while you are testing then swap in std::ofstream object when you are ready to pass a file.

Technically this is illegal C++;

int odd_store[count];

To be legal count must be determined at compile time. Though some compilers support this as an extension. It is better to use std::vector<> for this situation.

BUT why are you counting and storing the output values into an array in the first place? That seems like a redundant waste of time. Just print them directly to the file stream.

Then you sort the stored values. I see no requirement that the data be sorted.

Looking at your sort you implement a swap operation rather than using std::swap(). But you don't even need to implement a sort function there is a standard one std::sort that implements a better algorithm than the bubble sort you are using.

Bu the easiest way is to store them in a sorted container when you retrieve them from the list std::set would work for that.

Lastly the copy from the container to the output uses a loop. Learn how to use the standard algorithm or the range based for to make the code easier to read.

Also prefer to use "\n" rather than std::endl. Using std::endl will only slow your code down.

Personally I would write it like this:

void storeOddElements(NODE *head, std::ostream& output)
{
    std::copy_if(NodeIterator(head), NodeIterator(),
                 std::ostream_iterator<int>(output, "\n"),
                 [](auto const& val){return val % 2 == 1;});
}

Now you only need to define a NodeIterator that can iterate over a list of Node. :-)

OK Got bored. Here is a NodeIterator.

class NodeIterator
{
    Node* current;
    public:
        NodeIterator(Node* begin = nullptr)
            : current(begin)
        {}
        NodeIterator& operator++()   {current = current->next;return *this}
        NodeIterator  operator++(int){NodeIterator result(*this); (*this)++; return result;}

        bool operator==(NodeIterator const& other) const {return current == other.current;}
        bool operator!=(NodeIterator const& other) const {return !(*this == other);}
        int operator*()                       {return current->data;}

        // iterator traits
        using difference_type   = long;
        using value_type        = int;
        using pointer           = int*;
        using reference         = int&;
        using iterator_category = std::forward_iterator_tag;
};

If we need to sort the data before output then we can use:

void storeOddElements(Node *head, std::ostream& output)
{
    std::set<int>  sortedData;
    std::copy_if(NodeIterator(head), NodeIterator(),
                 std::inserter(sortedData, sortedData.end()),
                 [](auto const& val){return val % 2 == 1;});

    std::copy(std::begin(sortedData), std::end(sortedData),
              std::ostream_iterator<int>(output, "\n"));
}


Creating HTML table with JSON data using pure JS

The seven columns of items are basically treated identically.  You should handle them using a loop instead of duplicating the code seven times.


It would be a whole lot better this way:

import sys

def main(filename_in, filename_out):
    with open(filename_in) as fh_in:
        with open(filename_out, 'w') as fh_out:
            count = 1
            for line in fh_in:
                parts = line.strip().split()
                if count < 10:
                    bra = "Bra100000" + str(count)
                else:
                    bra = "Bra10000" + str(count)
                count += 1
                test = "{:10s}" .format(bra)
                fh_out.write("\t".join(parts[0:3]))
                fh_out.write("\t")
                fh_out.write(parts[1])
                fh_out.write("\t")
                fh_out.write(test)
                fh_out.write("\t")
                fh_out.write("\t".join(parts[4:12]))
                fh_out.write("\n")

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])

Improvements:

Use with open(...) as ...:. This way the file handles will be correctly closed when exiting the block
Drop the unused variable final
Also drop the pointless variable dict
Since both branches of the if-else increment count, you can move it outside
Instead of count = count + 1, it's simpler as count += 1
Instead of the repetitive write, simplify with join
Do not just dump the code in the global namespace: put it inside a function. This way the command line arguments will have meaningful names
Instead of stripping and splitting line in 2 steps, do it in one: line.strip().split()
It's not a good practice to overwrite loop variables and function parameters. line is a good name for a line of input, splitting that becomes something else and "line" is no longer an appropriate name, so I called it "parts" instead


Try this one:

        var filteredResults =
        (from r in results
         where r.Average > 0 &&
               r.EventID == "333" &&
               r.RoundID == "f"
         select r).ToList();

        List<Results> bestResults = new List<Results>();
        var resultsInCompenitions = filteredResults.GroupBy(r => r.CompetitionID);
        foreach (var resultsInCompetition in resultsInCompenitions)
        {
            var bestResultInCompetition = resultsInCompetition.OrderBy(r => r.Average).FirstOrDefault();
            if (bestResultInCompetition != null)
            {
                bestResults.Add(bestResultInCompetition);
            }
        }

        var femaleBestResults =
            from r in bestResults
            join p in persons on r.PersonID equals p.ID
            where p.Gender == "f"
            select r;

       return femaleBestResults;


Using two wordlists to search a list of texts

Algorithm
You enumerate items within a loop also enumerating items. This means your algorithm is quadratic in the length of each sentence, which is bad. I think you can improve your algorithm to make only a single pass over items by creating a dict which stores unique words as keys, and lists of word indices as the values. Then you can lookup the appropriate indices of the items in your wordlists and perform the distance calculation. Since dict lookups are a constant-time operation, this reduces the complexity to linear in the length of each sentence. Do note that the algorithm is still quadratic in the length of your word lists, so there may be some improvement to be had if your word lists are long.
Correctness and Edge Cases
It's hard to tell exactly what this code is supposed to do, so I will be making a few assumptions. The handling of edge cases will vary depending on the requirements.
You likely have at least one bug in your code, which is reflected in your example output: you check if x in item, which will evaluate True for the string 'use' in the word 'because'. If this is not the desired behavior, you may want a stricter check like checking equality x == item, or something based on Levenshtein distance for a less strict evaluation.
Another possible bug is that you never include the first word of a sentence in your results. Your check if first_int: will be False for every word whose index is 0.
Code Style
Holy indentation, Batman! Deeply nested code is hard to read and understand, and usually indicates you can organize your code better. Usually the inner loops can be brought into their own function. You can sometimes reduce nesting by consolidating conditional statements. For example, an if statement immediately followed by another if with no else can be brought onto one line:
if first_int: if second_int != first_int:

can be written on one line as
if first_int and second_int != first_int:

Short variable names like w, t, and x aren't very descriptive, and make it hard for others to understand the code. Try to pick more descriptive names.
Make sure you don't include unnecessary logic. For example, your check if dist in relations will always be False, since you only insert tuples, and dist is a float. It can be removed, saving you a line of code and a level of indentation.


Bug: off by one

In both your loops, you fail to loop to index 0.  For example, if the length of array A is 5, then your loop:

for (int i = A.length-1; i >0; i--) {

will cover indices 4,3,2,1 and then stop.  It should be written like this in order to also loop to index 0:

for (int i = A.length-1; i >= 0; i--) {

Bug: array out of bounds error

You made a copy and paste error here:

    for (int j = A.length-1; j >0; j--) {

This should have been:

    for (int j = B.length-1; j >= 0; j--) {

In other words, you used the length of A where you should have used the length of B.  Thus, if array A is bigger than array B, you would index past the end of array B and get an out of bounds error.

Useless statements

Your code contains a few useless statements:

Arrays.sort(A);
Arrays.sort(B);
int sumMax = A[0]+B[0];

There is no need to sort the arrays since the order in which you loop through the arrays doesn't matter.  The sumMax variable is never used after it is initialized.

Better algorithm

I suspect this may be a current programming challenge so I won't write any code or go into too much detail here.

The current solution is \$O(N*M)\$ where \$N\$ and \$M\$ are the sizes of the arrays.  Instead of comparing one number with one number, if you could compare one number to a whole array, you could reduce your complexity by a lot.

How could you do this?  Suppose for one whole array, you compute and remember all the possible divisors for each number in that array.  Then if you go through the other array, you can compute the divisors for each number and see if each divisor appeared in the first array.  If it did, then you have found a possible GCD for an A/B pair.  If you can ensure that your divisor lookup is \$O(1)\$, then your total complexity should be:

\$O(N*F(N) + M*F(M))\$ where \$F(N)\$ is the amount of time it takes to factor a number (i.e. find its divisors).  The normal way to factor a number would take \$O(\sqrt N)\$ time, but there may be faster ways of doing it, especially if the number range is limited.


I wouldn't recommend C or C++ as a starter language.
Try to reimplement the game in Python or Java or some other high level language.

You can use a loop instead of repeating yourself with die 1 die 2 and die 3.
Use a function for rolling and reporting.
The main loop can be a for loop that scanf()s the number of guesses and counts down.
A switch statement on the guess token could come in handy.

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

#define N_DICE 3

/* Conveniently return the sum. */
int roll_dice(int *dice)
{
    int i, sum;
    for (i = sum = 0; i < N_DICE; i++)
    {
        dice[i] = rand()%6 + 1;
        sum += dice[i];
    }
    return sum;
}

void print_dice(int *dice, int sum)
{
    int i;
    printf("\n\n");
    for (i = 0; i < N_DICE; i++)
        printf("Die %d: %d\n", i + 1, dice[i]);
    printf("-------------------\nTotal: %d\n\n", sum);
}

int main()
{
    int runs, dice[N_DICE], sum, old_sum, correct, correct_guesses;
    char guess;

    srand(time(NULL));
    correct_guesses = 0;
    sum = roll_dice(dice);

    printf("How many times do you want to play? ");
    for (scanf("%d", &runs); runs; runs--)
    {
        print_dice(dice, sum);
        old_sum = sum;
        sum = roll_dice(dice);

        printf(
            "Do you think the next total will be higher, "
            "the same, or lower than the previous total? "
            "(h, s, l)\n"
        );
        scanf(" %c", &guess);
        switch (guess)
        {
            case 'h': correct = sum > old_sum; break;
            case 's': correct = sum == old_sum; break;
            case 'l': correct = sum < old_sum; break;
            default: correct = 0; printf("Not h, s or l.\n");
        }
        if (correct)
        {
            printf("You guessed correctly!\n");
            correct_guesses++;
        }
        else
            printf("You guessed incorrectly!\n");
    }
    printf("You got a total of %d guesses correct!\n", correct_guesses);
}


Optimizing nested "Select Distinct" query

Nitpicking
Aliases/notation
Single-letter alias names are not very helpful. Aliases should at least give Mr. Maintainer a clue what it stands for. What if you had a table called family along with friends... would you call it F2?
FROM friends F
LEFT JOIN message_share S ON S.ouid_fk <> F.friend_two
LEFT JOIN messages M ON M.msg_id = S.msg_id_fk AND M.uid_fk = S.ouid_fk
LEFT JOIN myusertable U ON U.uid = M.uid_fk AND U.status1='1'

Also, I find it good practice to use the optional AS keyword, just looks better in my opinion. How about:
FROM friends AS Frnd
LEFT JOIN message_share AS Share ON Share.ouid_fk <> Frnd.friend_two
LEFT JOIN messages AS Msg ON Msg.msg_id = Share.msg_id_fk AND Msg.uid_fk = Share.ouid_fk
LEFT JOIN myusertable AS User ON User.uid = Msg.uid_fk AND Usr.status1 = '1'

Column names
Some of your column names are pretty cryptic. I realize you may not have any say into it, but if this is your database you may consider changing names like ouid_fk and such to something more meaningful, if a bit more verbose.
Indentation/spacing
Use line breaks and indentation to facilitate reading of your queries. Also consistent spacing is an improvement.
(SELECT DISTINCT M.msg_id, M.uid_fk, M.message, S.created, M.like_count,M.comment_count,M.share_count, U.username,M.uploads, S.uid_fk AS share_uid,S.ouid_fk AS share_ouid

Why not instead:
(SELECT DISTINCT
  Msg.msg_id,
  Msg.uid_fk,
  Msg.message,
  Share.created,
  Msg.like_count,
  Msg.comment_count,
  Msg.share_count,
  Usr.username,
  Msg.uploads,
  Share.uid_fk AS share_uid,
  Share.ouid_fk AS share_ouid

INT in a VARCHAR column?
I find this odd:
AND Usr.status1 = '1'

To me in a well-designed database, this status1 column should be int (4 bytes), smallint (2 bytes) or tinyint (1 byte). Not to mention, status1 is not a very good column name.
SELECT DISTINCT
I don't feel that this is needed at all, for a couple of reasons:

Do you expect multiple messages to have the same msg_id? Wouldn't that completely defeat the purpose of an ID?

Your GROUP BY msg_id already does this, but it does the work on the result set rather than the source data set, which will likely be much faster.

Here is what I would refactor to. However there is no way for me to test performance since you did not provide DDL or sample data.
(SELECT
  Msg.msg_id,
  Msg.uid_fk,
  Msg.message,
  Share.created,
  Msg.like_count,
  Msg.comment_count,
  Msg.share_count,
  Usr.username,
  Msg.uploads,
  Share.uid_fk AS share_uid,
  Share.ouid_fk AS share_ouid
FROM friends AS Frnd
LEFT JOIN message_share AS Share ON Share.ouid_fk <> Frnd.friend_two
LEFT JOIN messages AS Msg ON Msg.msg_id = Share.msg_id_fk AND Msg.uid_fk = Share.ouid_fk
LEFT JOIN myusertable AS User ON User.uid = Msg.uid_fk AND Usr.status1 = '1'
WHERE Frnd.friend_one='199095' AND Frnd.role='fri'
GROUP BY Msg.msg_id
ORDER BY Share.created DESC LIMIT 10)
UNION
(SELECT
  Msg.msg_id,
  Msg.uid_fk,
  Msg.message,
  Share.created,
  Msg.like_count,
  Msg.comment_count,
  Msg.share_count,
  Usr.username,
  Msg.uploads,
  Share.uid_fk AS share_uid,
  Share.ouid_fk AS share_ouid
FROM friends AS Frnd
LEFT JOIN message_share AS Share ON Share.ouid_fk <> Frnd.friend_two
LEFT JOIN messages AS Msg ON Msg.msg_id = Share.msg_id_fk AND Msg.uid_fk = Share.ouid_fk
LEFT JOIN myusertable AS User ON User.uid = Msg.uid_fk AND Usr.status1 = '1'
WHERE Frnd.friend_one='199095'
GROUP BY Msg.msg_id
ORDER BY Share.created DESC LIMIT 10)


if (this.heapType == 0) {

and

    } else if (this.heapType == 1) {

Rather than using magic numbers, it is typical to use Enum values for this in Java.

    if (heapType == HeapType.MIN) {

and

    } else if (heapType == HeapType.MAX) {

or in the latter case, just

    } else {

Presumably there are only two types of heap.

You don't have to say this.heapType.  It's enough to just say heapType if there is no conflict.  You can add the this. if you find it makes things clearer, but it's not functionally necessary.  You only need to specify this. if there is another variable with the same name as the object field.

Another way to do this would be with an interface and separate implementations for Max and Min heaps.  That may not be better though.  It's hard to comment with so little context.  It would save the if/else here but might cause problems elsewhere.

In general, I can't comment on how this method works with other methods like the caller or swapValues, as those definitions are not included.  Should you work directly with the value rather than the node?  Should this be integrated into the caller's logic?  I can't really tell.


What should I change in my currency converter?

First, there's very little point in using a class like you are here. You're essentially just using the constructor as a function to ask for input. You're also needlessly making some variables attributes of the object, like self.features, self.x, and self.d. The only use of features is to be iterated over within the constructor, and the only use of the latter two are inside of input_process. Even if this were an appropriate use of a class, that data doesn't need to be retained in the object itself. That just wastes memory.

To remedy this, I'd take everything in __init__, and move it into a regular function. To store the data, I'd use a NamedTuple returned from the function.

Your prints are also needlessly verbose. You're using print("") as a way to print newlines. Newlines can simply be added using "\n" though.

print("")
print(Fore.GREEN + "-" * 76)
print("")

Can simply be:

print("\n" + (Fore.GREEN + "-" * 76) + "\n")

And since you use (Fore.GREEN + "-" * 76) multiple times, I'd save that into a string at the top of the file:

SEPARATOR = "\n" + (Fore.GREEN + "-" * 76) + "\n"

Your loop over features is also unnecessary. It can be done simply using join:

print("\n".join(features))

Your names are also poor. c1, c2, c, x and d are very vague and give little information about what they hold. I would make those names much longer.

After making the mentioned changes, and I ended up with:

from currency_converter import CurrencyConverter
from datetime import date
from colorama import Fore
import datetime
from typing import NamedTuple, Optional, Tuple

# These are constants. They should be defined externally, and have capitalized names
FEATURES = ["1. Convert using the last available rate.", "2. Convert using specific dates."]
SEPARATOR = "\n" + (Fore.GREEN + "-" * 76) + "\n"

class ConversionInformation(NamedTuple):  # A simple class to hold information
    feature_type: str
    amount: str
    source_currency: str
    target_currency: str
    conversion_date: Optional[Tuple]

def ask_for_input() -> ConversionInformation:
    print(SEPARATOR)
    print("\n".join(FEATURES))

    feature_type = input("Select a feature: ")

    print(SEPARATOR)

    amount = input("Amount: ")
    source_cur = input("Currency1: ")
    target_cur = input("Currency2: ")

    conversion_date = None

    if feature_type == "2":
        conversion_date = (int(input("Year: ")),
                           int(input("Month: ")),
                           int(input("Day: ")))

    return ConversionInformation(feature_type, amount, source_cur, target_cur, conversion_date)

def process_input(info: ConversionInformation):
    conv = CurrencyConverter()  # This wasn't needed when asking for input

    if info.feature_type == "1":
        # Note the more descriptive names
        result = round(conv.convert(info.amount, info.source_currency, info.target_currency), 2)
        cur_date = datetime.datetime.now()

        print(f"{info.amount} {info.source_currency} is {result} {info.target_currency} on {cur_date}")

    elif info.feature_type == "2":
        result = round(conv.convert(info.amount, info.source_currency, info.target_currency,
                                    date=date(*info.conversion_date)))

        print(f"{info.amount} {info.source_currency} was {result} {info.target_currency} in" +
              "-".join(str(d) for d in info.conversion_date))

    else:
        print("Illegal Feature Type:", info.feature_type)  # Tell the user that they entered an illegal type

# Also a constant
CURRENCIES = ["USD", "SEK", "GBP", "EUR"]

if __name__ == '__main__':
    print(Fore.GREEN + f"This is a Currency converter, the main currencies are {', '.join(CURRENCIES)}")
    print(SEPARATOR)

    while True:
        info = ask_for_input()
        process_input(info)

        print(SEPARATOR)

        if input("Finished. Do another? (Y/N)\n").lower() != 'y':
            break

It's far more verbose, but I believe it's much cleaner and easier to understand.

My main issue with what I've done here is package all the data into ConversionInformation just so it can be passed into process_input. You may find that it ends up being cleaner to make this all one large function.


A shorter way of Enablling/Disabling a text box from RadioButton selections

This cleans it up a little.  Removes the if statement at least:

private void AllowMissingData()
{
    MissingDataValueTextBox.Enabled = AllowBlankRadioButton.Checked;
    MissingDataValueTextBox.Text = AllowBlankRadioButton.Checked ? MissingDataValueTextBox.Text : System.String.Empty;
}


The code itself is readable: it makes sense to check if the thread is still running before doing extra work. It's not the usual if spaghetti, and is, I think, a common threading idiom. But it's hard to understand the logic behind the code and I'm not sure it works as intended.

The first issue is that you're emitting the uploading signal only when processing has been done, but it's theoretically possible that upload happens even without processing, if the first if not self.stopped is false. If you don't want this to happen, I suggest that you move the do_upload_task() call in the second if not self.stopped.

The second issue is that it's very unlikely that self.stopped would be false just after run() has started, so this does not make much sense and suggests you don't really have a valid mental model for threads.

Now, concerning notify_cancelled, you have two (invalid) options:

either you simply set stopped to True, which can only have an effect when the thread goes through your if not self.stopped statements, so it won't interrupt the processing: you don't want that.
either you also self.thread.exit(), but this is can interrupt both the processing and the upload... and you don't want that either.

What I would do is having a processing thread and an uploading thread: you could exit() the first one, but not the other one.


null/undefined checking for checking seats

var seat = $("input[id*=" + seatPrefix + "]");
    if (seat != 'undefined') {

First off, an extra level of indentation has crept in here. Let me assume this is just a copy/paste error.

Any chance you could be using classes here instead of prefixed IDs? Best case: a single ID you know in advance. It seems that you assume there's only one match anyways.

jQuery, when it doesn't find anything, returns an empty collection, not undefined (or 'undefined'; did you get confused by typeof x !== 'undefined'?). To test if a jQuery collection is empty, you can use seat.length === 0 or even ! seat.length.

I don't normally use hungarian notation, but I do use it for jQuery objects, especially when I'm dealing with native elements as well: $seat. On a side note, shouldn't the variable name be $seatInput or something, rather than just $seat?

I recommend against the coercing equality operator (==). Use === instead. == can be a bit... unpredictable at times. There are some special cases or case where I find == acceptable (== null for null or undefined) but this is not one of them (if only because undefined != 'undefined')

seat = seat[0].value;

You can use seat.val() here. This has a positive side-effect that val returns undefined if the jQuery object holds no elements. Your code will attempt to dereference undefined in that case.

Also, you are reusing the same variable to mean a jQuery object at one point, then to mean a string in the next line. You should use two separate variables (or inline the first one) here.

if (seat != "") {

If you use val, you can move it outside its condition block, and merge the condition with this one:

if(seat !== undefined && seat !== "")

Since both undefined and the empty string are falsy and all other strings are truthy, this will work as well:

if(seat)

Of course, @retailcoder's suggestion to invert the condition and return early still applies.

if (seat != "red" && seat != "blue" && seat != "silver" && seat != "gold") {

You can use indexOf to shorten that code and make it more readable:

if (["red", "blue", "silver", "gold"].indexOf(seat) == -1)

if you like shortcuts,

if (!~["red", "blue", "silver", "gold"].indexOf(seat))

At this point, the array definition can (and should) be moved outside the condition. It is marginally nicer to the memory, but more importantly it's easier to find the array in case you want to ever change it if you put it at the beginning of the file.

if(...){
    chooseSeat(seat, "2");
} else {
    chooseSeat(seat, "1");
}

Shouldn't this logic be part of the chooseSeat function?

Also, 1 and 2 are non-obvious. Since you're passing a string anyways (why?), perhaps chooseSeat should accept "basic" and "premium" as its arguments?

If I couldn't modify the chooseSeat function or your HTML, I would probably refactor your code like this:

var basicColors = ["red", "blue", "silver", "gold"];
var seat = $("input[id*=" + seatPrefix + "]").val();
if (!seat) return;

if (~basicColors.indexOf(seat)) {
    chooseSeat(seat, "1");
} else {
    chooseSeat(seat, "2");
}

or, if return cannot be used (this is not the whole body of the function it is in),

var basicColors = ["red", "blue", "silver", "gold"];
var seat = $("input[id*=" + seatPrefix + "]").val();

if (seat) {
    if (~basicColors.indexOf(seat)) {
        chooseSeat(seat, "1");
    } else {
        chooseSeat(seat, "2");
    }
}


Overall it looks like you're missing out on most of the benefits of a functional approach and over-complicating your code. First glance it's basically impossible to work out what it's all doing without following each variable through everything.
Per the previous answer you don't seem familiar with common functional techniques like using .map, pipelines, or avoiding side-effects
Below is less a review of your code but a different solution that highlights the  techniques you're missing so you can see them in action
const fizzOrBuzz = (a, b, aPhrase, bPhrase) => (
    (n) => (
        (n % (a*b) === 0) ? aPhrase + bPhrase :
        (n % a === 0) ? aPhrase :
        (n % b === 0) ? bPhrase :
        n
    )
)

const generateNLengthArray = (n) => [ ...Array(n).keys()].map(i => i + 1)

const mapArrayTo = (f) => (array) => array.map(i => f(i))

const joinArray = (array) => array.join('\n')

const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x) // One-liner pipeline pattern

const fizzbuzz = pipe(
    generateNLengthArray,
    mapArrayTo(fizzOrBuzz(3, 5, 'fizz', 'buzz')),
    joinArray
)

console.log(fizzbuzz(100))

One of the benefits of functional programming is breaking everything down into discrete, easily understandable functions, and then composing them together so it's crystal clear what's happening.
In this case defining fizzbuzz as a pipeline of three separate functions makes it clear that you're 1. creating an array of a specific length. 2. mapping the values of that array to either fizz or buzz and 3. joining the results together


I have three main remarks:

Recursion is not really an appropriate retry mechanism.

Try this: hold down Enter for a dozen responses, then hit ControlC.  As you see, the stack trace is quite deep.  It would be better for the call stack to be the same regardless of how the user arrived at a certain point in the code, because invariants make software easier to test and debug.  You're using recursion as a GOTO, except it's worse because it leaves a trace.  Instead, the validation should be done in a loop, which you break out of when valid input is obtained.
The code structure is a bit repetitive.

The routines to input the distance and gas consumption are actually quite similar, and could be written using shared code.
Trial division is a poor way to test for a zero value.

You test whether dist is zero with

# if dist is 0.0, print error and restart
try:
    x = 1 / dist
except ZeroDivisionError:
    print('Miles traveled cannot be 0!')
    main()

There are more straightforward ways to test for a zero value!  You end up discarding x, so the trial division isn't even useful work.

On further thought, your validation is not quite right.  If you're going to validate your input, you might as well prohibit negative numbers.  It is possible for the distance to be zero, when the car has been idling.  (The zero-distance case would only be problematic when displaying efficiency in "metric" units of L / 100km.)

In conclusion, your use of exceptions for validation is partly inappropriate (catching ZeroDivisionError to test for zero, especially for dist, from a logical viewpoint as well as a code expression viewpoint) and partly appropriate (catching ValueError to test for strings that cannot be interpreted as numbers).  I don't see any alternative to catching ValueError, except perhaps checking the input string against a regular expression \d+(?:\.(?:\d*))?, and I would consider ValueError to be the superior approach.  I think it would be fair to challenge your professor to propose a better alternative — in my opinion, the ball is in her court.

A minor note: your comments are inconsistent with your code.  Your code has a variable named gcon; the comments mention guse.

Suggested solution:

def ask(prompt, typeconv, typeconv_err, validation=None, validation_err=None):
    """
    Displays the prompt and asks for user input.  The result is passed through
    the typeconv function, then possibly a validation function as well.  If
    either the type conversion fails (with a ValueError) or the validation
    fails (by being false value), then the respective error message is
    displayed, and the prompt is displayed anew.
    """
    while True:
        val = input(prompt)
        try:
            val = typeconf(val)
        except ValueError:
            print(typeconv_err % (val))
        else:
            if validation is not None and not validation(val):
                print(validation_err % (val))
            else:
                return val

def main():
    dist = ask('Enter distance traveled(in miles): ',
               float,
               'Distance traveled must be a number! You did not travel "%s" miles!',
               lambda dist: dist >= 0.0,
               'Miles traveled cannot be negative!')

    gcon = ask('Enter gas consumed traveling(in gallons): ',
               float,
               'Gas consumed must be a number. You did not use "%s" gallons of gas!',
               lambda gcon: gcon > 0.0,
               'Gas consumed cannot be 0 or negative!')

    # print mpg
    mpg = dist / gcon
    print('Average miles per gallon(mpg):', format(mpg, '5.2f'))

    # print request for enter keypress to end
    input('press enter to continue')

# Call main function
main()


Simple calculator in Object-oriented JavaScript

I don't really see any purpose to forcibly using a class setup here. All that's doing is allowing you to provide the data before result is called. That's not necessary here though, and there are other ways of achieving that. If you needed to create multiple Calculate objects, and retain them, and call result on them multiple times, there may be a purpose. I can't see any gain here though.

I would just collapse everything down to a function that accepts the three bits of data (op, num1 and num2) and just call the function directly when needed.

There's cleaner ways of handling the "dispatching" than a switch. I'd just use a regular JavaScript object here:

// Associate the operator strings
//  with functions
var strToOp = {"+": (x, y) => x + y,
               "-": (x, y) => x - y,
               "*": (x, y) => x * y,
               "/": (x, y) => x / y};

var num1 = 2;
var num2 = 5;
var op = "*";

// Get a function from the map
var func = strToOp[op];

// func will be undefined if they supply a bad operator string
// This is roughly equivalent to your "default" case
if(func) {
    // And give the numbers to it
    var result = func(num1, num2);

    // Prints 10
    console.log(result);

} else {
    // Handle bad operator
}


Finally: Can you suggest any improvements to my code?

Fair warning ahead: I've only tried the following with Rebol 3. That said: going into a different direction than the improvements suggested by @HostileFork, here's an alternative approach:

arity: func [
    "Returns the arity of a function, disregarding refinements."
    f [any-function!]
] [
    -1 + index? find join words-of :f /sentinel refinement!
]

(No get-/lit-argument tricks here, sorry. Also refer to @HostileFork's answer for that particular aspect.)

The Gory Details

For those not that familiar with Rebol, let's dissect that step by step. First, a fully parenthesised variant of the core expression:

-1 + (index? (find (join (words-of :f) /sentinel) refinement!)

@HostileFork's answer already mentions WORDS-OF, which is a convenient way to get only the core parts of a function spec:

>> words-of :append
== [series value /part length /only /dup count]

>> words-of :+
== [value1 value2]

Building on that, the core idea is to use FIND with a datatype, to position to the first refinement! argument:

>> find words-of :append refinement!
== [/part length /only /dup count]

Great! But what about functions which have no refinements at all, like + shown above?

>> find words-of :+ refinement!
== none

To counter that, we simply add a sentinel value at the end, so that we can ensure that there'll always be a refinement! present:

>> join words-of :+ /sentinel
== [value1 value2 /sentinel]

>> find join words-of :+ /sentinel refinement!
== [/sentinel]

For our final step, we utilise the fact that Rebol blocks are "cursor-like". FIND does not return a copy of the original block with just the remaining elements after and including the match, FIND returns a new block "cursor" which is positioned right after the match within the original data. We can use INDEX? to ask this "cursor" its current position:

>> index? find join words-of :+ /sentinel refinement!
== 3

As we can see, this expression using INDEX? gives us the (1-based) position of the first refinement. Subtract 1 from that, and we have the count of non-refinement arguments. (If we'd have zero-based functions already, we could get rid of that final step.)

Et voilà:

>> -1 + index? find join words-of :+ /sentinel refinement!
== 2

I hope you enjoyed the ride :)


Globals
Since target, numbers and math_functions are global constants, they should be all-caps - e.g. TARGET. That said, you should refactor this so that the target and numbers are parametric, so that they can (eventually) be randomly generated.
Solution does not belong as a global, since it is mutable - its presence prevents your program from being re-entrant.
Likewise, the globally-scoped code starting with for x should be moved into a function.
Use of operators
This falls into the category of "code as data". This block:
            if function[1] == "+":
                value += permutation[function[0]+1]
            elif function[1] == "-":
                value -= permutation[function[0]+1]
            elif function[1] == "/":
                value /= permutation[function[0]+1]
            else:
                value *= permutation[function[0]+1]

can be greatly simplified if you change your math_functions to be a tuple (or maybe dictionary) of character-operator pairs, where you import your operators from https://docs.python.org/3/library/operator.html .


Probability of event using Central Limit Theorem + plotting results

You seem to know about str.format (since you use it), yet you are still doing string addition:

title1 = 'Probability of making loss: ' + '{0:.4g}'.format(P1*100) + '%'
title2 = 'Probability of earning more than $20k: ' + '{0:.4g}'.format(P2*100) + '%'

Just make it a single string:

title1 = 'Probability of making loss: {0:.4g}%'.format(P1*100)
title2 = 'Probability of earning more than $20k: {0:.4g}%'.format(P2*100)

You could also use the % formatting option for floats (described in the fifth table here), which automatically multiplies with 100 and adds the % sign. The number of digits after the decimal point work differently, though, compared to the g format:

"{:.4%}".format(0.5)
# '50.0000%'
"{:.4g}%".format(0.5*100.)
# '50%'
"{:.4g}%".format(0.5123123*100.)
# '51.23%'
"{:.4%}".format(0.5123123)
# '51.2312%'

You should also re-organize your code according to the following scheme:

import something

GLOBAL_CONSTANT = "value"

class Definitions

def functions()

if __name__ == '__main__':
    main()
    # or some small code using the stuff defined above

That last part is there to protect your code from being executed if you want to import some part of this script from another script. At the moment if you want to do from laplace import Z, your whole code would run. With the if __name__ == '__main__' guard, it will only run when you execute this script.

You should add docstrings to your functions, describing what they do, what arguments they take and what they return. Have a look at PEP257 for the guidelines regarding docstrings.

And, in order to answer my own question from the comments:

Yes, it is justified to use the normal distribution here, since the Central Limit Theorem guarantees that the sum of random variables tends towards a normal distribution. The approximation is quite good for \$N = 100\$, as can be seen with the following small script:

import numpy as np
import matplotlib.pyplot as plt

mu = 95.7
sigma = 1247.
n = 100    # how many random variables to sum for each value
N = 1000    # how many values to generate

x_l = np.random.laplace(mu, sigma/np.sqrt(2), (n, N)).sum(axis=0)
x_g = np.random.normal(n*mu, np.sqrt(n)*sigma, N)

plt.hist(x_g, label="gaus")
plt.hist(x_l, label="sum(laplace)", histtype='step')
plt.legend()
plt.show()


This line here:

return EXIT_SUCCESS

Is equivalent to this:

return 0;

Which is automatically inserted by the compiler if it isn't found. In short, return EXIT_SUCCESS can be removed.

In addition, a few of your error messages don't include a newline at the end, as seen in this line here, and two other places:

std::cerr << "compilation terminated.";

I'd just add a newline to the end of the output string to not annoy the user when the program completes/fails, like this:

std::cerr << "compilation terminated.\n";

Instead of requiring the user to provide a file in the command line arguments, you can just do, well, nothing. This is the language Nothing after all. This means that this piece of code here:

if (argc < 2)
{
    std::cerr << "nothing: fatal error: no input files\n";
    std::cerr << "compilation terminated.";
    return EXIT_FAILURE;
}

Can just become this:

if (argc < 2)
{
    return 0;
}

Other than those two nitpicks, there really isn't much else for me to review here. As far as I can tell, you've followed the language specification just fine, and produced some readable code.


PHP form validation and db insertion, one page or two

You don't need to have your validation codes written in different page. But if you want to organize your code, you can go and separate your validation block.
Consider changing your validation. Your preg_replace is quite limiting. An example would be for names. Spaces, numbers, special characters are not allowed. Don't forget that there are names that has the mentioned above. It would work. Your validation could be written better if you want to increase security. There are tons of practice for validation of data and securing it for SQL query.
You could add some client side validation using HTML5 such as pattern, and required attribute.
You said you want to output what has been submitted in the form. Do you really need to output it in the validation/insertion page and then get redirected to the other page? You can instead put the details on sessions and head directly to the page you need to be and output what you have put on the sessions.
It is best to avoid putting PHP variables inside the quotation marks. "Your name is $name". Instead you can use {} to include it. "Your name is {$name}". However, it is recommended that you concatenate it instead "Your name is" . $name.
When including database page, it is also recommended to use require instead of include. This is to make the script stop upon error on getting the file.