Move all your Javascript out of the way.
From Yahoo's Best Practices for Speeding Up Your Web Site:

Make JavaScript and CSS External
Many of these performance rules deal with how external components are managed. However, before these considerations arise you should ask a more basic question: Should JavaScript and CSS be contained in external files, or inlined in the page itself?
Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.

Obviously, what's more important right now is to minimize that glorious readability mess, hopefully the (small) performance gain might be just the incentive you needed.
Cache your jQuery objects
You are using $('#inputs') in $("#mysubmitIndexForm").submit( ... ); and twice in $("#inputs").change( ... );. That's three times jQuery traverses the DOM to find #inputs, what you need to do is:
var inputs = $("#inputs");

at the top of your (external) script, and then use $(inputs) instead. Do it for all your objects, even if you're using them once, it will stay with you as a (good) habit.
Avoid inline CSS
Consider moving all your style declarations into an external CSS file. Other than a slight performance gain (similar to external JavaScript), you'll have all your style declarations in one, easy to find, place.

If you do all of the above, your code would look like:

    <link rel="stylesheet" type="text/css" href="myFunkyStyles.css" />

    ...

        <?php
        echo $this->Form->create('mysubmit');
        echo $this->Form->input('inputs', array('type' => 'select', 'id' => 'inputs', 'options' => $inputs));
        echo $this->Form->input('Fields', array('type' => 'select', 'id' => 'fields', 'empty' => '-- Pick a state first --'));

        echo $this->Form->input('inputs2', array('type' => 'select', 'id' => 'inputs2', 'options' => $inputs2));
        echo $this->Form->input('Fields2', array('type' => 'select', 'id' => 'fields2', 'empty' => '-- Pick a state first --'));

        echo $this->Form->end("Submit");
        ?>

        <?php echo $this->Html->link("Error Results", "#"); ?>

and what's up with that empty

? If you just want to add some margin-bottom, why not do that on .notice instead?


Solving an ODE numerically with forward Euler method

The smallest change that might make it more readable is to resize the vectors first, so you can index the elements rather than calling push_back.

It's generally a good idea to reserve vectors before a loop anyway if you know how big they're going to end up, and resize will handle that too.

void calculate(std::vector<double>& time, std::vector<double>& velocity,
               const double t_max, const double dt, const double a, const double b)
{
    const int iterations(t_max / dt);
    time.resize(iterations, 0.);
    velocity.resize(iterations, 0.);

    for(int i(1); i < iterations; i++)
    {
        time[i] = time[i-1] + dt;
        velocity[i] = a * dt + (1 - b*dt) * velocity[i-1];
    }
}

if you're keeping two vectors synchronized like this, it's sometimes nicer to replace them with a single vector whose elements have two fields:

struct step {
    double time;
    double velocity;
};

void calculate(std::vector<step>& steps,
               const double t_max, const double dt, const double a, const double b)
{
    const int iterations(t_max / dt);
    steps.resize(iterations);

    for(int i(1); i < iterations; i++)
    {
        steps[i].time = steps[i-1].time + dt;
        steps[i].velocity = a*dt + (1 - b*dt) * steps[i-1].velocity;
    }
}

this is more of an aesthetic preference though, and it isn't clearly better in your case.


I think you may be complicating things a lot. If I understand correctly you are basically after groupBy which you can find in lodash, or implement in a few lines of code:

function groupBy(coll, f) {
  return coll.reduce(function(acc, x) {
    var k = f(x);
    acc[k] = (acc[k] || []).concat(x);
    return acc;
  }, {});
}

var test = {
  items: [{
    company: "A", name: "Prod_A01"
  }, {
    company: "A", name: "Prod_A02"
  }, {
    company: "B", name: "Prod_B01"
  }]
};

var result = groupBy(test.items, function(x){return x.company});

JSON.stringify(result);
/*^
{
  "A": [
    {
      "company": "A",
      "name": "Prod_A01"
    },
    {
      "company": "A",
      "name": "Prod_A02"
    }
  ],
  "B": [
    {
      "company": "B",
      "name": "Prod_B01"
    }
  ]
}
*/

You can use this to group a collection (array of objects) by some property, test.items in this case. Also, I would leave the JSON part out of it, because it is irrelevant to the grouping algorithm.


unique_ptr basic implementation for single objects

Don't mark your class final without a good reason. It inhibits user-freedom.
The default-access for members of a class is already private.
Explicitly deleting copy-constructor and copy-assignment-operator is superfluous, as you define move-constructor and move-assignment, which already suppresses them. Still, some assert being explicit adds clarity.
I wonder why you didn't declare construction from T* to be constexpr...
Try to consistently use the injected class-name (unique_ptr), instead of sporadically naming the template-arguments (unique_ptr<T>).
You are missing implicit upcasting in the move-ctor and move-assignment-operator.

template <class U, class = std::enable_if_t<
    std::has_virtual_destructor<T>() && std::is_convertible<U*, T*>()>>
unique_ptr(unique_ptr<U>&& other) noexcept
: ptr_(other.release())
{}

template <class U>
auto operator=(std::unique_ptr<U>&& other) noexcept
-> decltype((*this = unique_ptr(other))) {
    return *this = unique_ptr(other);
}

Take a look at std::exchange(object, value) from <utility>. It allows you to simplify some of your code.
If you use move-and-swap, you could isolate freeing of the referee to the dtor. Having it at only one place ensures you always do it the same, and is a good first step for retrofitting custom deleters. Not to mention that it in many cases simplifies the implementation.
(ptr != nullptr) can be simplified to ptr. In contexts where you have to force the type, !!ptr.
Why are op==() and op!=() inline-friend-functions, but swap() isn't? That's inconsistent. It's especially puzzling as they are all written to use the public interface only.
There is exactly one place where you don't have a single empty line between two functions, but two. Yes, that's nothing big.


Naming

According to the Swift API Design Guidelines, variable names are lower camel case (not alphabet_array),
and types should not be part of the variable name (not caesarNumber, inputString, resultString).

It is also clear that the first (and only) argument of encode() and decode()
is the input string, here we can omit the argument label:

func encode(_ input: String) -> String

which is then called as

let encodedString = encode("zacharias")

Improving the API

The current API has two drawbacks:

It uses the global variable caesarNumber to pass information to the
functions.
The function names (“encode”, “decode”) are too common, they to not tell
what the function actually does.

Here are two alternative suggestions:

Make the function names more specific, and pass the shift amount as an
additional argument.

You can also define a default parameter value for the shift amount.

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String
func caesarDecode(_ input: String, shiftBy: Int = 7) -> String

Define a cipher type with parameters, and encode/decode methods.

That would allow to substitute the Caesar cipher by other methods easily.

struct CaesarCipher {
    let shiftAmount: Int

    init(shiftAmount: Int = 7) {
        self.shiftAmount = shiftAmount
    }

    func encode(_ input: String) -> String { ... }
    func decode(_ input: String) -> String { ... }
}

Example usage:

let rot13 = CaesarCipher(shiftAmount: 13)
let encrypted = rot13.encode("Hello World")

I'll stick with the first API for the remainder of this review.

Simplify the code

The alphabet can be initialized simply with

let alphabet: [Character] = Array("abcdefghijklmnopqrstuvwxyz")

because a String is a sequence of its Characters. Locating a character
in the array can be done with

if let idx = alphabet.index(of: char) { ... }

instead of a loop. The test for

 if (i + caesarNumber < alphabet_array.count-1)

is not needed, because the “else case” (with the modulo arithmetic) works actually in both cases, with or without wrap-around.

Summarizing the above suggestions so far, we have for the encoding method:

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String {
    var result: String = ""
    for char in input {
        if let idx = alphabet.index(of: char) {
            let newIdx = (idx + shiftBy) % alphabet.count
            result.append(alphabet[newIdx])
        }
    }
    return result
}

Decoding is the same as encoding, only with a shift in the opposite direction.
If we modify the encoding method slightly to work with negative shift amounts then it can be used for the decoding as well:

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String {
    var result: String = ""
    for char in input {
        if let idx = alphabet.index(of: char) {
            var newIdx = (idx + shiftBy) % alphabet.count
            if newIdx < 0 { newIdx += alphabet.count }
            result.append(alphabet[newIdx])
        }
    }
    return result
}

func caesarDecode(_ input: String, shiftBy: Int = 7) -> String {
    return caesarEncode(input, shiftBy: -shiftBy)
}

Improve the performance

For optimal performance on really long strings you can operate on the
UTF-16 view instead, that allows to determine the offset within the alphabet with pure integer arithmetic instead of the array lookup.

Enumerating the UTF-16 view also seems to be faster than enumerating
the characters (which represent extended grapheme clusters).

A possible implementation could look like this:

func caesarEncode(_ input: String, shiftBy: Int = 7) -> String {
    let letterA = Int("a".utf16.first!)
    let letterZ = Int("z".utf16.first!)
    let letterCount = letterZ - letterA + 1

    var result = [UInt16]()
    result.reserveCapacity(input.utf16.count)

    for char in input.utf16 {
        let value = Int(char)
        switch value {
        case letterA...letterZ:
            let offset = value - letterA
            var newOffset = (offset + shiftBy) % letterCount
            if newOffset < 0 { newOffset += letterCount }
            result.append(UInt16(letterA + newOffset))
        default:
            break
        }
    }

    return String(utf16CodeUnits: &result, count: result.count)
}

On my computer this was faster than the previous method (3 milliseconds
instead of 11 milliseconds for a string with 100,000 characters).

For shorter strings that probably won't matter, and you can choose what you
feel more familiar with.


Class for returning a different value every so often

I might be completely off with this, but I'll try to propose an alternative design for your problem.

It seems to me that you have two independent tasks in your application:

Fetching the data from the DB (user triggered?, frequent)
Updating the DB from the AD periodically (time consuming)

Define a flag in your application, say, UpdateInProgress. Update task would set it to true before running and reset it after it's done. Every Fetch request that comes while an update is in progress would be queued and executed after the update has completed.


Roughly removing 'duplicate' photos based on filename

If you're only dealing with only .jpg files then it will be better to use the glob module:

import glob

for filepath in glob.iglob(os.path.join(directory), '*.jpg'):
   ...

Don't use dict.keys() to check for the existence of a key in dictionary, it is inefficient in Python 2(created a whole list first and then searches for key in that list) and requires an unnecessary call to .keys() in Python 3. Or even better use collections.Counter to keep counts of objects:

from collections import Counter

dt_counter = Counter()

for filepath in glob.iglob(os.path.join(directory), '*.jpg'):
    dt_rounded = os.path.split(filepath)[1][:16]
    dt_counter[dt_rounded] += 1
    if dt_counter[dt_rounded] > 1:
         # if `directory` is actually a `pathToPhotos` then you
         # don't need to call os.path.join anymore
         os.remove(filepath)


Regarding the data structure: In cases like this where you always use the same keys for the hashes (i.e. :answers and :question in this case), it is often a good idea to use a simple class instead, which has accessors for the given properties. You can use Struct to easily create such classes. In this case this would look like this:

SurveyResultInformation = Struct.new(:question, :answers)

Using a class instead of a hash is more robust as mistyped attribute names will cause an exception. It is also more extensible as it allows you to add methods to the class - like for example most_common_answer.

However in this particular case where the method is called survey_results and there exists a class called SurveyResult one has to wonder whether survey_results couldn't/shouldn't return instances of the existing SurveyResult class instead.

My guess is you should be returning an array of SurveyResult objects and extend that class to offer the functionality you need. Though without knowing more of your code it's hard to say for sure.

At the very least you should rename the method or the class to avoid the impression that the method returns instances of that class.

Now to your code:

First of all your method names sounds like it would return the collected survey results, but in fact it just stores them in an instance variable and apparently returns nothing of consequence. You should either make it return the results (possible caching them in the instance variable) or change its name to something imperative-sounding like initialize_survey_results instead.

You're creating an empty array and then appending to it once per iteration in an each-loop. If you do this you can (and should) almost always use map instead.

answers[survey_result_answer.response] ||= 0
answers[survey_result_answer.response] += 1

As you already pointed out this is a bit ugly. Luckily ruby's Hash class has a feature that gets rid of the need for ||= here: It allows you to set default values which will be returned instead of nil if a key was not found. If we replaces answers = {} with answers = Hash.new(0) to set the default value to 0, you can just get rid of the ||= line.

SurveyResult.find_by_step_survey_id(params[:step_survey_id]).step_survey

This line stumped be a bit when I first read it. It is not apparent why you're not just calling StepSurvey.find(step_survey_id). First I thought maybe you don't want to get the step survey when there is no survey result pointing to it, but in that case the above code would cause an exception, so that can't be it.

If I were to write this, I would do something like this:

def survey_results
  if params[:step_survey_id].blank?
    []
  else
    StepSurvey.find(params[:step_survey_id]).step_survey_questions.map do |survey_question|
      survey_result = SurveyResultInformation.new(survey_question.value)
      answers = Hash.new(0)
      survey_question.survey_result_answers.each do |survey_result_answer|
        answers[survey_result_answer.response] += 1
      end
      survey_result.answer = answers
      survey_result
    end
  end
end


HTMLAudioElement sound delay on keyboard clicks

SFC

Consider using Single File Components instead of the declarative syntax you are using right now. It removes a lot of the headache of dealing with the this keyword, and removes the necessity of having to deal with handlers. See the documentation for more information.

Life cycle hooks

Vue has a couple of life cycle hooks. You are currently using two of them. However, your code currently only works, because your html is not part of the component you just wrote. The destroyed life cycle hook is called after everything has been torn down, so there would be no html element to remove the handler from. You should be using the beforeDestroy hook instead. See this lifecycle diagram for more information.

Internal data

Your sound filenames should be internal data of your component, not some random variables outside it. They should also have descriptive names.

Sound playback delay

You are experiencing playback delay, because you load the sounds when you want to play them, instead of pre-loading them. You have two ways of dealing with this problem. If your sound file names are hardcoded, you can simply use the data initialisation function to create HTMLAudioElement s you can then later start or stop. See mdn for more information.

data () {
  return {
    sounds: {
      enter: new Audio('sound1.wav'),
      whatevercode12is: new Audio('sound2.mp3')
    }
  }
}

If you pass these sounds as properties, you need to be a bit more clever about it. You can use the created lifecycle hook to fill the sounds object like we created above, but would instead be initialised as an empty object, or you could put a watcher on the property with the immediate flag on true, and fill the sounds object as needed.

In either case you must play and immediately pause them once so they are downloaded. Then you can look them up and play them whenever you like:

this.playSound('enter')

and

playSound (soundName) {
  const playableSound = this.sounds[soundName];

  if (!playableSound) {
    throw new Error(`Called 'playSound' with unknown identifier [${soundName}]`);
  }

  playableSound.play();
}

Implementing it all

When you implement all that, you will end up with something like this:

<template>
  <div id="app">
    <input v-on:keydown.prevent="onKeyDown" value="Just focus me and press keys" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      sounds: {
        enter: new Audio(
          "http://www.pacdv.com/sounds/miscellaneous_sounds/air_blower_1.wav"
        ),
        shift: new Audio(
          "http://www.pacdv.com/sounds/miscellaneous_sounds/bottle_pop_1.wav"
        )
      }
    };
  },

  created() {
    for (const sound of Object.values(this.sounds)) {
      // This makes sure the sounds are loaded, but not played
      sound.play().then(() => {
        sound.pause();
      });
    }
  },

  methods: {
    playSound(soundName) {
      const playableSound = this.sounds[soundName];

      if (!playableSound) {
        throw new Error(
          `Called 'playSound' with unknown identifier [${soundName}]`
        );
      }

      if (!playableSound.paused) {
        // The previous sound is playing. We could reset the current sound with
        // playableSound.currentTime = 0
        // but we probably don't want to cut off that sound, so lets make a copy of the
        // sound and dereference the previous one
        this.sounds[soundName] = new Audio(playableSound.src);
      }

      this.sounds[soundName].play();
    },

    onKeyDown(e) {
      switch (e.keyCode) {
        case 13:
          return this.playSound("enter");
        case 16:
          return this.playSound("shift");
        default:
          // Do nothing
          break;
      }
    }
  }
};
</script>


Hackerrank "Hash Tables: Ransom Note" Javascript Solution

Your solution may work for valid inputs, but you are not checking invalid input situations such as when the ransom letter contains more words than the ones in the magazine:

if(n > m):
    throw new Error("ransom can not be written from magazine");

You can even go further by checking if the first line corresponds to what it pretends to be:

if (magazine.length !== m)
    throw new Error("Wrong words number in magazine");
if (ransom.length !== n)
    throw new Error("Wrong words number in ransom");

You can refactor the above conditions in one single line:

if(n > m || agazine.length !== m || ransom.length !== n):
    throw new Error("Invalid input");


Populate an ArrayList of different instances of a class

Good effort to get your code working so far. But your code is highly unusual.

You've got the class Question which has an id and question_txt, but each Question also has a reference to a JSONArray of all the questions. Worse than that, for each Question, when you create a new Question and set its reference to all questions, it will come from the API each time.

You've recognised that the behaviour of getting Questions from the API might belong in the Question class (or related class), instead of forcing main (or whatever consumer) to know the details of the API. But it's surely not the responsibility of a single Question instance to fetch all the Questions.

You want the class Question to hold it's data first (and later, some behaviour), so here's a typical data class.

public class Question {

    private int id;
    private String text;

    public Question (int i, String s) {
        this.id = i;
        this.text = s;
    }

    public int getId() {
        return id;
    }

    public String getText() {
        return text;
    }

}

You'll see this type of class referred to  as Java Bean or POJO. In this case, because we've used private and only provided get methods, this is a read-only object after its been created.

Then add some behaviour to the class (meaning we're going to use the static keyword) for retrieving the questions:

public static List<Question> fetchQuestions () throws JSONException, IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL("url_to_my.php").openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-length", "0");
    connection.setUseCaches(false);
    connection.setConnectTimeout(0);
    connection.setReadTimeout(0);
    connection.connect();
    int status = connection.getResponseCode();
    if (!(status == 200 || status == 201)) {
        throw new IOException("Bad status code: " + status);
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();
    String response = sb.toString();

    List<Question> questions = new ArrayList<Question>();
    for (Object arrayItem: new JSONArray(response)) {
        JSONObject questionAsJSON = (JSONObject) arrayItem; // throws on unexpected response format
        questions.add(new Question(questionAsJSON.getInt("id"),
                questionAsJSON.getString("Question")));
    }

    return questions;

}

And then when we want to grab the questions from the API, it's just a case of invoking the static method:

List<Question> questionnaire = Question.fetchQuestions();


std::accumulate alternative for the C programming language

When using the do { ... } while (0) idiom for macros, we don't generally include the terminating semicolon in the definition.  That's so we can use it like a function call:
if (condition)
    ACCUMULATE(result, a, b, 0, add);
else
    ACCUMULATE(result, a, c, 10, add);

There's a typo in the ARRSIZE() macro: where we protect X from misbinding - should be (X)[0], not (X[0]):
#define ARRSIZE(X) (sizeof (X) / sizeof (X)[0])

Also, be careful with this macro when its argument isn't a whole, completely defined array.  In particular, it will be wrong when the argument is a variable-length (dynamically-allocated) array, or when the argument is a pointer (perhaps the array decayed to pointer - that can easily catch you out!).
In the sample usage:

Identifiers ending in _t are reserved for future use by the standard library, so str_t should be renamed.
It's a shame, after being so careful to use snprintf() avoid overflow, that we  we then use unchecked strcat();strcat();strcat(); in sumStr()  - why not snprintf() there, too?
A lot of needless parens around the arguments to sizeof.  Just write sizeof sumstr instead of sizeof(sumstr), for example.


This looks fine. There is some replication in processPackageOptions, but that's manageable. Your syntactical variant isn't possible, though, since Idris isn't an instance of Alternative. type Idris = StateT IState (ExceptT Err IO) would only be an instance of Alternative if Err was an instance of Monoid, which it isn't.

You could wrap Idris in another short-circuiting monad, for example Either ExitCode (Idris a) or a transformer variant, but you have to replace all runIO with liftIdrisIO or similar. That might be too much.

But I concur, the exitSuccess in check isn't that obvious and should be made more obvious at type level.


Name: I would call it an "Unordered Set"
You have a container that you can add items to. Duplicates are not accepted and return the index of the existing value. New values are added to the container in the order they are inserted.
Because items can be inserted in any order iterating through the container returns the values in insert order (somewhat random) so the container is not sorted in any way.
Issues: You keep two copies of each value.
There is a copy in the map and a copy in the vector. So your container uses twice as much spaces it needs too (especially for big objects).
What you have implemented looks like  std::set
But it has worse space requirements.
Comparison to std::set
std::set<int>   c1;                  OrderedList c1;

auto p1 = c1.insert(5);              auto p1 = c1.Insert(5);
auto p2 = c1.insert(5);              auto p2 = c1.Insert(5);
if (p1.first == p2.first) {          if (p1 == p2) {
    std::cout << "Equal\n";              std::cout << "Equal\n";
}                                    }

auto p3 = c1.find(6);                auto p3 = c1.find(6);
if (p3.first == c1.end()) {          if (p3 == -1) {
    std::cout << "Not Found\n";          std::cout << "Not Found\n"
}                                    }

auto p4 = c1.find(5);                auto p4 = c1.find(5);
if (p4 == p1.first) {                if (p4 == p1) {
    std::cout << "Already there\n";      std::cout << "Already there\n"
}                                    }

std::cout << c1.size() << "\n";      std::cout << c1.Size() << "\n";

std::cout << *(p1.first) << "\n";    std::cout << c1[p1] << "\n";


Congratulations on finding code you enjoy!

This appears to be walking through a binary tree you have defined (or possibly from toytree?).  Walking through this with an explicit stack is one way of thinking of the problem, and the code can be a good learning experience.

An alternate method would be to use the Python's recursion system, where you make code vaguely like:

   def walk(tree):
        if tree is not None:   # ignore walking into an empty node
            walk(tree.left)
            walk(tree.right)
            print(tree.val)

It takes a a little brain stretching to see these as equivalent.  As an exercise you should explore making the function a generator.  That is, would call it as:

  for value in tree.walk():
      print(value)

To do this, you need to replace a print with a yield, and a recursive call with a yield from.   Try it: it does a different stretch on the brain.

As far as efficiency, you need to use the the timeit module to see what does run fast.   In general, tree structures with a single value do poorly for really large numbers because memory access is a bit slow.  However, profiling is necessary for optimizing by less than factors of n (the size of the tree).  Orders of magnitude can be judged by eye and logic while unexpected internals might double the speed of some code.

You might notice that your code will currently fail on being passed an empty tree (root=None), as popped will be checked before it is assigned.  I am not sure why you are checking if popped equals the right node.

Keep hacking!  Keep notes.


With QuickSort, the complexity always comes down to two things:

how you deal with equal numbers (duplicates)
which index you use to return from the partition (left or right)

You need to decide up-front whether the pivot value is going to be in the left partition, or the right partition. If the pivot is going to be in the left, then you need to return left index, and the left partition is values <= the pivot.

In my 'education', all the examples I looked at, and all the implementations I have done since then, have always returned the left index.... and they have always included the pivot in the left side.

There are a number of things that stand out to me in your code:

you do not start with the left at left + 1 (you know that list[left] == pivot for the first check...)
It is common practice for the 'right' index to start at the length (i.e. to be 1 after the last member).
you have odd handling for the duplicate value case
you are returning right instead of left
you are not swapping the pivot to where it belongs.... The point of the partitioning is that you are supposed to end up with the pivot value where it belongs.
you are not checking for left >= right on the increment side of the partition loops

The odd handling of duplicates is because the 'left' loop should be a <= loop, not a < loop:

        while(list[left] <= pivot)
            left++;

and you should get rid of the condition:

        if(list[right] == pivot && list[left] == pivot)
            left++;

You should return left.

Then, in the Recursive call, you have the constant value 1 which you use to test the left-condition.... This is a big bug, because the pivot will only return 0 for the left-most partition. The 1 constant should be left ....

I ended up ideoning your code to play with it. IU shuffled around a lot of the logic.

Have a look...

This is the code that does the sort closer to the way that I expect:

using System;
using System.Collections.Generic;

public class Test
{
    static List<int> RandomList(int size) {
        List<int> ret = new List<int>(size);
        Random rand = new Random(1);
        for (int i = 0; i < size; i++) {
            ret.Add(rand.Next(size));
        }
        return ret;
    }

    static int MyPartition(List<int> list, int left, int right)
    {
        int start = left;
        int pivot = list[start];
        left++;
        right--;

        while(true)
        {
            while(left <= right && list[left] <= pivot)
                left++;

            while(left <= right && list[right] > pivot)
                right--;

            if(left > right)
            {
                list[start] = list[left - 1];
                list[left - 1] = pivot;

                return left;
            }

            int temp = list[left];
            list[left] = list[right];
            list[right] = temp;

        }
    }

    static void MyQuickSort(List<int> list, int left, int right)
    {
        if(list == null || list.Count <= 1)
            return;

        if(left < right)
        {
            int pivotIdx = MyPartition(list, left, right);
            //Console.WriteLine("MQS " + left + " " + right);
            //DumpList(list);
            MyQuickSort(list, left, pivotIdx - 1);
            MyQuickSort(list, pivotIdx, right);
        }
    }

    static void DumpList(List<int> list) {
        list.ForEach(delegate(int val)
        {
            Console.Write(val);
            Console.Write(", ");
        });
        Console.WriteLine();
    }

    public static void Main()
    {
        List<int> list = RandomList(100);
        DumpList(list);
        MyQuickSort(list, 0, list.Count);
        DumpList(list);
    }
}


import qualified Data.Char as C
import qualified Data.List.Split as L
import qualified Test.QuickCheck as Q
import qualified Test.HUnit as T

The qualified import here is good, but your module header is missing. Since there is no documentation you don't want to export some functions, for example the partial chunkToBrain.

oToBrain :: String -> String
oToBrain = map chunkToBrain . L.chunksOf 3 . filter isAlphabetic

While this might seem correct, the combination of chunkToBrain and L.chunksOf doesn't end well. According to esolangs, oOo code may have a non-divisible number of letters. The remaining ones are discarded. More on that later on chunkToBrain.

brainToO is fine, but isAlphabetic isn't, as elem ['a'..'z'] is C.isAsciiLower:

isAlphabetic = C.isAsciiLower . C.toLower

We will now take a look at your source of duplication, singleCharToO and chunkToBrain. Both suffer from somewhat the same problem: you need to define the map from Brainfuck instructions to oOo instructions and vice-versa. So let's define them:

oOoCode :: [String]
oOoCode = ["ooo", "ooO", "oOo", "oOO", "Ooo", "OoO", "OOo", "OOO"]

bfCode :: [Char]
bfCode  = [  '>',   '<',   '[',   ']',   '-',   '+',   '.',   ',']

bf2oOo :: [(Char, String)]
bf2oOo = zip bfCode oOoCode

oOo2bf :: [(String, Char)]
oOo2bf = zip oOoCode bfCode

Now singleCharToO is

singleCharToO x = fromMaybe "" (lookup x bf2oOo)

where fromMaybe is from Data.Maybe. You can use maybe "" id instead if you don't want to import another module.

Now to chunkToBrain. We will write a single helper beforehand:

toO :: Char -> Char
toO x = if C.isUpper x then 'O' else 'o'

I think you can already guess what happens next:

chunkToBrain :: String -> Maybe Char
chunkToBrain xs = lookup xs oOo2bf

You can of course use other data structures with better asymptotic complexity, but since there are only \$2^3\$ instructions this might be an overkill and should be benchmarked.

But wait a minute: the return type has changed. That's because the text is allowed to have superflous characters. "oOoOO" and "oOo" are the same programs in oOo. This leads to a slight change in oToBrain:

oToBrain = mapMaybe chunkToBrain . L.chunksOf 3 . filter isAlphabetic

Where mapMaybe is again a function from Data.Maybe, that discards Nothing from the list. This version of oToBrain has the right semantics, it doesn't throw an error.

Last but not least, your tests are sufficient for this code, although you should include tests that have oOo programs with a length that's not divisible by three.

  I am also worried that I did not declare any types as Haskell is type-centric.

At this point, we're slowly drifting out of the simple exercise and completely into parsing, pretty printing and (possibly) interpretation. What's a fitting data type for your code? No, let's have a look at the greater picture. What's a fitting data type for a Brainfuck or oOo program?

type Program = [Instruction]
data Instruction = IncVal | DecVal
                 | IncPos | DecPos
                 | Put    | Get
                 | Repeat Program

You'll notice that this will only allow syntactic correct programs, e.g. those that have the right pairings of [ and ]. You can use StartRepeat and EndRepeat instead, but that could make evaluation tricky.

You can then define two parsers:

-- or any other type with an erroneous state
oOoParser :: String -> Either String Program
bfParser  :: String -> Either String Program

Getting code again can be done similar to your previous code, although you need to apply the codegen recursively for Repeat.

toBF  :: Program -> String
tooOo :: Program -> String

The conversions can be defined in terms of the other four:

bf2oOo, oOo2bf :: String -> Either String String
bf2oOo = fmap toBF . oOoParser
oOo2bf = fmap tooOo . bfParser

This approach also allows you to define your own evaluation function without worrying about the loops:

eval :: Program -> String -> String
eval prog input = ...

But that's out of scope of this answer. Note that eval gets harder if you don't use the recursive Repeat variant, but parsing gets easier (and vice-versa).


So you're fetching 70k pages.  You could half that if you only fetch the page once and then do what get_headers and get_meta_tags do manually.  That will presumably take now 20 minutes.

Then you can try doing this in parallel, so run two instances of the script with one half of the URLs each.


Project Euler 81 (minimum path sum through a matrix)

That's a nice, elegant algorithm! I can only nitpick.

file is not a good name for a file handle because it shadows a built-in with the same name. (I use fh for this kind of thing.)

It would be good to extract the file reading logic from the if __name__:

def read_matrix_from_path(path):
    with open(path) as fh:
        return [list(map(int, line.strip().split(","))) for line in fh]

if __name__ == '__main__':
    print(min_path_sum(read_matrix_from_path("matrix.txt")))

Perhaps most importantly, you can blend this loop into the other one:

for i in range(1, size):
    matrix[i][0] += matrix[0][i-1]

Like this:

for i in range(1, size):
    matrix[i][0] += matrix[0][i-1]
    for j in range(1, size):
        matrix[i][j] += min(matrix[i-1][j], matrix[i][j-1])


Disclaimer: I can read Python, but I'm not a Python developer.

First of all, your code follows PEP8, which is a plus (although a second empty line before is_prime is necessary). And it's great that you try static type hints.

However, there are two things amiss here. First of all, Optional isn't honest at that point. We always return a value. And we always return a str, not AnyStr. We should therefore change the type hints accordingly:

from typing import Union

def is_prime(num: int) -> (Union[bool, int], str):

If there was a path where we could accidentally return None, None or None, b"12343", a static checker should warn us. So no Optional or AnyStr.

Since the types are now out of a way, let's have a look at documentation before we head to algorithms. A docstring is a nice addition:

def is_prime(num: int) -> (Union[bool, int], str):
    """Checks whether the given number is prime."""

    if num <= 1:
    ...

You can probably come up with a more detailed one so that the code itself contains the meaning of True, False and 0.

Now to the algorithm. Your algorithm has \$\mathcal O(n)\$ worst time complexity. However, for any pair \$x\$,\$y\$, such that \$x < y\$ and \$ x y = n \$ we must have \$x \le \sqrt{n}\$. Therefore, we can stop at math.ceil(sqrt(n)), not n. This yields \$\mathcal O(\sqrt{n})\$ worst time complexity.

For very large numbers this will still be too slow. There are other algorithms for that, which are out of scope for a small review.


Your code is incredibly fragile

directory = ThisWorkbook.Sheets("Macro").Range("D576").Value
rdate = ThisWorkbook.Sheets("Macro").Range("E47").Value

If a single row/column gets added or deleted or moved, those ranges are going to move and your code is going to fail completely.

If you can, those values should be in a dedicated sheet, not buried below 500 lines of other stuff. If not, name your ranges.

So, let's say you take cell D576 and name it Directory_Path or something similar. Now, rather than

directory = ThisWorkbook.Sheets("Macro").Range("D576").Value

which is incredibly fragile, you can use

directory = ThisWorkbook.Range("Directory_Path").Value

and so long as nobody actually deletes said row/column, that will always point to the right place.

Use With

Rather than re-referencing the same object over and over, you can use a With statement to hold a reference. Like so:

Application.ActiveWorkbook.SaveAs Filename:=xTextFile, FileFormat:=xlText
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close

Becomes

With Application.ActiveWorkbook
    .SaveAs Filename:=xTextFile, FileFormat:=xlText
    .Saved = True
    .Close
End With

much clearer and easier to read.

Handle things in the right order

Specifically your Application.[Settings]. Anything *meta* like that should go right at the start and right at the end of the method(s) it applies to. This allows you to confirm, at a glance, what the internal state of your method is and check that things are set/reset correctly. You should also disable Application.EnableEvents and Application.Calculation for significant extra speed. Like so:

Sub xlsxTotxt()

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With

    ...

    Code

    ...

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub

Use descriptive naming

Code should be written for other people (including future you) to read. Names should be descriptive, unambiguous and concise. In that order. I highly recommend the excellent, classic article on naming by Joel Spolsky. But in short, things should sound like what they are.

xTextFile. What on earth is that? Looking at it I have no idea. If I had to guess, I'd say it's some kind of file object. Oh, it's the filename you want to save your text file under? Why not call it newFilename? Since it's a full filename (including directory path). Maybe newFullfilename or just fullFilename might be even more descriptive.

xWs suffers from the same problem. I can guess it's a worksheet object but beyond that? no idea. Since you just use it to iterate over the sheets in your workbook, maybe just call it currentSheet?

fname. Same thing. filename. Since it's the filename for the workbook you're opening, how about targetWorkbookFilename? Sure, it's long, but screen real estate is cheap, cognitive processing is not and that name's an awful lot easier to understand and work with.

Also, move your declarations near to where they're used. This helps you *see* the different parts of your method and helps you keep track of where you are, refer back to your declarations and see ways to split things up into logical sub-methods. Personally, I prefer to keep declarations outside of Loop structures, but that's personal preference.

Objects are your friend

VBA has a huge, extensive, comprehensive object model for every Office Application. Use it.

ThisWorkbook.Sheets("Macro")

You refer to that sheet multiple times. Rather than continually repeating that reference, put it in a worksheet object and then just refer to the object.

Dim macroSheet As Worksheet
Set macroSheet = ThisWorkbook.Sheets("Macro")

Dim dateString As String
dateString = macroSheet.Range("E47").Value

Same with Workbooks.

Do While ThisWorkbook.Sheets("Macro").Range("D577").Offset(i).Value <> ""
fname = Sheets("Macro").Range("D577").Offset(i).Value
Workbooks.Open (directory & fname)
For Each xWs In Workbooks(fname).Worksheets
xWs.Copy
xTextFile = directory & rdate & " - " & xWs.name & ".txt"
Application.ActiveWorkbook.SaveAs filename:=xTextFile, FileFormat:=xlText
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close

Relying on ActiveWorkbook being the one you want is very fragile. Just make it a proper object and then your references will always be accurate:

Dim targetWorkbook As Workbook
Set targetWorkbook  = Workbooks.Open (directory & fname)

...

For Each currentSheet In targetWorkbook.Sheets()

    ...

    With targetWorkbook
        .SaveAs filename:=xTextFile, FileFormat:=xlText
        .Saved = True
        .Close
    End With

Indenting

Indenting is a wonderful way to let you see the structure of your Sub. It'll let you pick out nested-logic (Loops, Ifs, Fors, Withs etc.) and very quickly get a rough idea for where the important stuff in your sub is. Compare:

Do While ThisWorkbook.Sheets("Macro").Range("D577").Offset(i).Value <> ""
fname = Sheets("Macro").Range("D577").Offset(i).Value
Workbooks.Open (directory & fname)
For Each xWs In Workbooks(fname).Worksheets
xWs.Copy
xTextFile = directory & rdate & " - " & xWs.name & ".txt"
Application.ActiveWorkbook.SaveAs filename:=xTextFile, FileFormat:=xlText
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
Workbooks(fname).Close
i = i + 1
Loop

With

Do While ThisWorkbook.Sheets("Macro").Range("D577").Offset(i).Value <> ""

    fname = Sheets("Macro").Range("D577").Offset(i).Value
    Workbooks.Open (directory & fname)

    For Each xWs In Workbooks(fname).Worksheets

        xWs.Copy
        xTextFile = directory & rdate & " - " & xWs.Name & ".txt"

        With Application.ActiveWorkbook
            .SaveAs Filename:=xTextFile, FileFormat:=xlText
            .Saved = True
            .Close
        End With

    Next

    Workbooks(fname).Close
    i = i + 1

Loop

And suddenly you can see your program flow, and where the real work is happening, and where loops start/end, in just a glance. Adding some whitespace also goes a long way to helping readability.

Putting it all together

Sub xlsxTotxt()

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With

    Dim parentDirectoryCell As Range
    Set parentDirectoryCell = ThisWorkbook.Range("Directory_Path")

    Dim parentDirectoryPath As String
    parentDirectoryPath = parentDirectoryCell.Value

    Dim dateString As String
    dateString = ThisWorkbook.Sheets("Macro").Range("E47").Value

    Dim fullFilename As String
    Dim currentSheet As Worksheet
    Dim targetWorkbook As Workbook
    Dim targetWorkbookFilename As String

    Dim rowOffset As Long
    rowOffset = 1

    targetWorkbookFilename = parentDirectoryCell.Offset(rowOffset).Value
    Do While targetWorkbookFilename <> ""

        Set targetWorkbook = Workbooks.Open(parentDirectoryPath & targetWorkbookFilename)

        For Each currentSheet In targetWorkbook.Sheets()

            currentSheet.Copy
            fullFilename = parentDirectoryPath & dateString & " - " & currentSheet.Name & ".txt"

            With targetWorkbook
                .SaveAs Filename:=fullFilename, FileFormat:=xlText
                .Saved = True
                .Close
            End With

        Next currentSheet

        targetWorkbook.Close

        rowOffset = rowOffset + 1
        targetWorkbookFilename = parentDirectoryCell.Offset(rowOffset).Value

    Loop

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub


As discussed in comments with @scsimon and @Milney, I've created the following table:

CREATE TABLE [dbo].[file_write]
(
  [ID] bigint NOT NULL IDENTITY(1,1) ,
  [PATH_FILE] nvarchar(500) NOT NULL ,
  [TEXT_FILE] nvarchar(500) NOT NULL ,
  [DATE_WRITE] datetime NOT NULL ,
  PRIMARY KEY ([ID])
)

After that, i've written a stored procedure in order to insert into this table using only PATH_FILE and TEXT_FILE as parameters. This procedure replaces the one I had written in my question.

CREATE PROCEDURE [dbo].[insertFileWrite]
(
  @PATH_FILE nvarchar(500),
  @TEXT_FILE nvarchar(500)
)
AS
BEGIN
  DECLARE @NOW datetime = CURRENT_TIMESTAMP

  INSERT INTO dbo.file_write(PATH_FILE, TEXT_FILE, DATE_WRITE)
         VALUES (@PATH_FILE , @TEXT_FILE , @NOW)
END

Finally, i've written a second stored procedure in order to write the lines that are in my table. This stored procedure is executed every 5 minutes by a scheduled task on the server.

CREATE PROCEDURE [dbo].[writeAllIntoFile]
AS
BEGIN
  DECLARE @PATH_FILE nvarchar(500)
  DECLARE @PATH_FILE_PREV nvarchar(500)
  DECLARE @TEXT_FILE nvarchar(500)
  DECLARE @ID bigint

  DECLARE @OLE int
  DECLARE @FileID int

  BEGIN TRANSACTION t_writeAllIntoFile
  BEGIN TRY

    DECLARE c_writeFile CURSOR FOR
      SELECT PATH_FILE,
             TEXT_FILE,
             ID
      FROM dbo.file_write
      ORDER BY PATH_FILE ASC,
               DATE_WRITE ASC

    OPEN c_writeFile
    FETCH NEXT FROM c_writeFile INTO @PATH_FILE, @TEXT_FILE, @ID

    SET @PATH_FILE_PREV = @PATH_FILE

    EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
    EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, @PATH_FILE, 8, 1

    WHILE @@FETCH_STATUS = 0
    BEGIN
      IF (@PATH_FILE <> @PATH_FILE_PREV)
      BEGIN
        EXECUTE sp_OADestroy @FileID
        EXECUTE sp_OADestroy @OLE

        EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
        EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, @PATH_FILE, 8, 1
      END

      EXECUTE sp_OAMethod @FileID, 'WriteLine', NULL, @TEXT_FILE
      DELETE FROM dbo.file_write WHERE ID = @ID

      SET @PATH_FILE_PREV = @PATH_FILE
      FETCH NEXT FROM c_writeFile INTO @PATH_FILE, @TEXT_FILE, @ID
    END

    CLOSE c_writeFile
    DEALLOCATE c_writeFile

    EXECUTE sp_OADestroy @FileID
    EXECUTE sp_OADestroy @OLE

    COMMIT TRANSACTION t_writeAllIntoFile
  END TRY
  BEGIN CATCH
    ROLLBACK TRANSACTION t_writeAllIntoFile

    IF (SELECT CURSOR_STATUS('global','c_writeFile')) >= -1
    BEGIN
      IF (SELECT CURSOR_STATUS('global','c_writeFile')) > -1
      BEGIN
        CLOSE c_writeFile
      END

      DEALLOCATE c_writeFile
    END

    RETURN -999
  END CATCH
END

Whis this solution, I don't have to open and close my file everytime I want to write one line into it. Since writing is now running on its side, performances have been a lot improved.


Non-re-indexing List with defragmentation

It's not complete BS. Your use-case is somewhat surprising, and your disregard for using a Map is also surprising, but given those, you're left with little option other than a completely custom implementation.... but, let's look at the issues you currently have...

People need to do a round-trip query-before-inserting operation - they need to call getSafeIndex() before setting a new value.

People can't use all the methods available to them. For example, they can't call:

clear() (See code)
add(int, obj) (See code)
..... none of the iterator, or stream-related methods (foreach, etc.) because they will return null values mixed in the wrong places.
size() will lie to them.

... in fact, the only methods that can be used reliably are set(...), get(...), and similar ones.

Extending ArrayList seems to introduce a lot of ways to break the code/data integrity.

I recommend encapsulation instead. In fact, this is a common "debate": Inheritance vs. Composition/Encapsulation (search for those topics on google).

In this case, composition/encapsulation would remove a lot of your issues, and reduce the class to just what you need.

Underlying your class you could still have the ArrayList and Stack, (except Stack class is deprecated in favour of Deque interfaces) but it would look something like:

@SuppressWarnings("serial")
public class SafeIndexList<E> {

    List<E> data = new ArrayList<>();
    Deque<Integer> safeIndexes = new ArrayDeque<>();

    public E remove(int index){
        if(index < data.size())
            // check double-removes.
            if (!safeIndexes.contains(index)) {
                safeIndexes.push(index);
            }
            return super.remove(index);
        }
        return null;
    }

    public int add(E value){
        int idx = safeIndexes.isEmpty() ? data.size() : safeIndexes.pop();
        data.set(idx, value);
        return idx;
    }

}

You can add methods for other features you need, as needed. Note, that having abstracted/encapsulated the underlying data store mechanism, you can easily replace the array/deque with a Map now, and not notice.

Edit: to add in the combined constructor/index problem, a solution like this may help, adding the method:

    public int construct(IntFunction<E> factory) {
        int idx = safeIndexes.isEmpty() ? data.size() : safeIndexes.pop();
        data.set(idx, factory.apply(idx));
        return idx;
    }

Now, you can call that with something like:

int id = mylist.construct(i -> new MyObject(..., i, ...));

The above constructs the inner object with the index, but "internal" to the list too. Alternatively, you can return the constructed object if that makes more sense....

MyObject obj = mylist.construct(i -> new MyObject(..., i, ...));


Class decorator in Python to set variables for the constructor

The parameters to autofill could have better names: args gives the argument names to the constructor, and kwargs gives the keyword names and their default values, so perhaps argnames and defaults would be better. This will also help to distinguish them from the parameters to the filler function.
The function filler is used to implement the __init__ method, so its first argument should be named self, not cls.
The original __init__ method is recorded in the super_init property of the filler function. I think that's needlessly tricky. It would be simpler to record it in a local variable:

def init_switcher(cls):
    original_init = cls.__init__

    def init(self, *args, **kwargs):
        for k, v in InputSanitizer(*args, **kwargs)._asdict().items():
            setattr(self, k, v)
        original_init(self)

    cls.__init__ = init
    return cls

The implementation mechanism is quite ingenious! It would not have occurred to me to delegate the argument processing to collections.namedtuple. However, I think that it is clearer to delegate it to inspect.Signature:

from inspect import Parameter, Signature

def autofill(*argnames, **defaults):
    """Class decorator that replaces the __init__ function with one that
    sets instance attributes with the specified argument names and
    default values. The original __init__ is called with no arguments
    after the instance attributes have been assigned. For example:

    >>> @autofill('a', 'b', c=3)
    ... class Foo: pass
    >>> sorted(Foo(1, 2).__dict__.items())
    [('a', 1), ('b', 2), ('c', 3)]

    """
    def init_switcher(cls):
        kind = Parameter.POSITIONAL_OR_KEYWORD
        signature = Signature(
            [Parameter(a, kind) for a in argnames]
            + [Parameter(k, kind, default=v) for k, v in defaults.items()])
        original_init = cls.__init__

        def init(self, *args, **kwargs):
            bound = signature.bind(*args, **kwargs)
            bound.apply_defaults()
            for k, v in bound.arguments.items():
                setattr(self, k, v)
            original_init(self)

        cls.__init__ = init
        return cls
    return init_switcher

There's no test case that checks that the original __init__ method is called.


Copy a file, renaming it if the destination already exists.

Original Answer:

I'd put in some extra brackets in your while-loop for radability:

while ( file_exists($new_name)
        && (sha1_file($src) != sha1_file($new_name))
      );

And you shouldn't set file-permissions to 777 by default (660 or even less). Everything else looks quite ok in my eyes (although I don't like the do/while construct, but I guess that's more a personal thing)

Update for comment:

$srcSH1 = sha1_file($sec);
do
{
    // ...
}
while ( file_exists($new_name)
        && (sha1_file($new_name) != $srcSH1)
      );

You should move out the sha_file($src) as this doesn't change but is recalculated each iteration. And that's the case why I don't like do/while. Splits the $srcSH1 and the while-condition where it is used.


refactor javascript - show and hide fields based on current selection

I will give you a sample which is very simplified. I hope you can understand what I am doing here.

HTML

<select class="toggle-data">
    <option></option>
    <option value="1" data-toggle="#foo-one">foo one</option>
    <option value="2" data-toggle="#foo-two">foo two</option>
</select>

    foo one

    foo two

JS/jQuery

$('.toggle-data').on('change', function() {
    var toggle = this.options[this.selectedIndex].getAttribute('data-toggle'),
        toggle_class = 'unique_classname';
    $('.'+toggle_class+', '+toggle).toggle().removeClass(toggle_class);
    $(toggle).addClass(toggle_class);
});

Now you have a single function to do all of your show/hiding and you would just format you html accordingly.


Simple input and output in assembly x86_64

Three small errors

section .data
   text db "You wroted: "
   text_len equ $ - text

A small spelling error (typo). Correct is: "You wrote: " without the d.

mov rax, SYS_READ
mov rdi, STDOUT
mov rsi, uinput
mov rdx, uinput_len
syscall

For SYS_READ you need to use STDIN instead of STDOUT.

mov rax, SYS_EXIT
mov rsi, 0 ; successful exit
syscall

The first parameter goes in the RDI register instead of RSI.
Three small improvements

section .bss
   uinput resb 24 ; 24 bytes for user string
   uinput_len equ $ - uinput ; get length of user input

It's strange to see a calculation for the uinput_len variable given that the length is a hardcoded 24. What you can write is:
section .bss
    uinput_len equ     24         ; 24 bytes for user input
    uinput     resb    uinput_len

Be nice for the person that uses your program and show a prompt of some kind before expecting an input.

For the final result you currently show the whole inputbuffer. What if the user didn't input that much characters? Best to only show the characters that were effectively inputted. You obtain this count in the RAX register upon returning from SYS_READ. e.g. If the user inputs 5 characters then RAX will hold 6. Those 5 characters plus the terminating newline character (0Ah).
Same code, different style
You should offset you tail comments so that they all start in the same column. This will improve readability.
And because readability is very very important, I've applied the same rule to the labels, mnemonics, and operands.
    SYS_READ   equ     0          ; read text from stdin
    SYS_WRITE  equ     1          ; write text to stdout
    SYS_EXIT   equ     60         ; terminate the program
    STDIN      equ     0          ; standard input
    STDOUT     equ     1          ; standard output
; --------------------------------
section .bss
    uinput_len equ     24         ; 24 bytes for user input
    uinput     resb    uinput_len ; buffer for user input
; --------------------------------
section .data
    prompt     db      "Please input some text: "
    prompt_len equ     $ - prompt
    text       db      10, "You wrote: "
    text_len   equ     $ - text
; --------------------------------
section .text
    global _start

_start:
    mov     rdx, prompt_len
    mov     rsi, prompt
    mov     rdi, STDOUT
    mov     rax, SYS_WRITE
    syscall

    mov     rdx, uinput_len
    mov     rsi, uinput
    mov     rdi, STDIN
    mov     rax, SYS_READ
    syscall                      ; -> RAX
    push    rax                  ; (1)

    mov     rdx, text_len
    mov     rsi, text
    mov     rdi, STDOUT
    mov     rax, SYS_WRITE
    syscall

    pop     rdx                  ; (1)
    mov     rsi, uinput
    mov     rdi, STDOUT
    mov     rax, SYS_WRITE
    syscall

    xor     edi, edi             ; successful exit
    mov     rax, SYS_EXIT
    syscall

Instead of mov rdi, 0, I've used xor edi, edi which is shorter and faster and leaves the same result (0) in the RDI register.
I always prefer to write the function number directly above the syscall instruction. I find this clearer. As a consequence I've also inversed the order of the other parameters, again for clarity.

You can learn a lot about 64-bit Linux programming from the .PDF that you can download here
It provides good examples that deal with console input and console output and more.


Base case first

It really helps to get a clear idea of a recursive function when the base case is the first thing you see. In your code it is even worse, as h is mutated before the base case, so it looks like the base case is -1 and not 0.

Smallest scope possible

Declare loop counters inside the for loop statement. It is more efficient and reduces mental load when reading the code.


So your probably asking why im using a Queue as a buffer? Basically the Queue allows me to more efficiently store bytes in an array format. byte[] is un-acceptable due to the fact its size can't be changed dynamically (you would have to make a new byte, move over the old data, add the new, replace the old byte[], in-efficient)

Well if you read the docs for Stream.ReadByte() you would see this

  Notes to Inheritors

  The default implementation on Stream creates a new single-byte array and then calls Read(Byte[], Int32, Int32). While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.

and if we dig into the reference source of Stream we would stumble over the default implementation

public abstract int Read([In, Out] byte[] buffer, int offset, int count);

// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer.  Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
    Contract.Ensures(Contract.Result<int>() >= -1);
    Contract.Ensures(Contract.Result<int>() < 256);

    byte[] oneByteArray = new byte[1];
    int r = Read(oneByteArray, 0, 1);
    if (r==0)
        return -1;
    return oneByteArray[0];
}

which isn't overwritten neither by NetworkStream nor by AuthenticatedStream (which is inherited by SslStream).

That beeing said, let's dig into the code...

Region's are considered as an antipattern especially if they occur inside a method. Take a look at Are #regions an antipattern or code smell?

Take e.g

    #region If Byte is \n or \r
    if (b == 10 || b == 13)
    {

this should be replaced by either

    if (b == '\n' || b == '\r')
    {

or by

    const char NewLine = '\n';
    const char Return = '\r';

    if (b == NewLine || b == Return)
    {

I don't really like the catch here because it isn't specific. You should consider to remove the try..catch completely and let the calling code handle any thrown exception. This leads to another problem: The method is public but you don't validate if stream is null. You will just let the exception be thrown and catched by the catch I mentioned.

I would add two overloaded ReadLine() methods to distinguish between needing the bodySize and let these methods return an IEnumerable<byte> which I would then convert to a byte[]. The methods would be called like so

 public static string ReadLine(this Stream stream, ref int bodySize, Encoding encoding)
{
    if (stream == null) { throw new ArgumentNullException("stream"); }

    byte[] result;

    if (bodySize > 0)
    {
        result = stream.ReadLine(bodySize).ToArray();
        bodySize -= result.Length;
    }
    else
    {
        result = stream.ReadLine().ToArray();
    }

    return encoding.GetString(result);

}

which is much easier to read.

The methods themself could look like so

private const char NewLine = '\n';
private const char Return = '\r';

private static IEnumerable<byte> ReadLine(this Stream stream, int bodySize)
{
    int i;
    int counter = 0;
    while (bodySize > 0 && (i = stream.ReadByte()) > 0)
    {
        byte b = (byte)i;
        if (b == NewLine || b == Return)
        {
            // Break only if it isn't the first byte.
            if (counter > 0 || b != NewLine) { yield break; }

            continue;

        }
        counter++;
        bodySize--;
        yield return b;
    }
}

private static IEnumerable<byte> ReadLine(this Stream stream)
{
    int i;
    int counter = 0;
    while ((i = stream.ReadByte()) > 0)
    {
        byte b = (byte)i;
        if (b == NewLine || b == Return)
        {
            // Break only if it isn't the first byte.
            if (counter > 0 || b != NewLine) { yield break; }

            continue;

        }
        counter++;
        yield return b;
    }
}

or if we want to be clever we could change the second method like so

private static IEnumerable<byte> ReadLine(this Stream stream)
{
    return stream.ReadLine(int.MaxValue);
}

Please note that the provided code isn't tested.


What you want to do is called "globbing". It's actually quite easy to do with a Regex.

There are a few code smells here. The recursion is the obvious one. The other is the special-cases. When you special-case the single-character wildcard, it suggests that you're thinking about the problem wrong. There's no reason why they would need to -- or even should -- be specialcased.

If you really want to reinvent the wheel, the "right way" is to build a state machine and backtrack. I combined @NotPro's answer and @svick's hint to get http://ideone.com/VUDFIw but that uses backtracking. Check out http://swtch.com/~rsc/regexp/regexp1.html to see why backtracking is a bad idea, and how we can get an O(n) state machine.


C++ string tokenizing without streams, with certain conditions

Well, it seems to do what you want. But, we can do better.

Review:

Avoid dynamic allocation where possible.

string backToBackDelim;
backToBackDelim += delimiter;
backToBackDelim += delimiter;
auto res2 = rawInput.find(backToBackDelim)

becomes

const char backToBackDelim[] = {delimiter, delimiter};
auto res2 = rawInput.find(backToBackDelim, 0, 2)

Don't pass std::string by constant reference unless you depend on the terminator. Pass a view by value instead, specifically C++17 std::string_view. It is more flexible and tends to be more efficient.
An empty line directly after the prototype is curious. Either remove it, or move the opening brace { for the function there.
Define your variables in the smallest scope you can, and invest in good names. What is res / res2, and why do you initialize it all the way up there, and only use it the once down here?
You know what, eliminate it completely, it's bloat.
Choosing good names should also be applied to the function itself. Yours seems to be a placeholder.
Consider marking things const to ease comprehension. No Need to search for possible sites of modification then. That is, if having that extra-variable actually pays for itself with clarity.
You have a bunch of conditions under which you error out. The curious Thing is that you manually duplicated the handling block. Consider merging the conditions so you only need it once.
Don't use else if control-flow doesn't resume after the code-block anyway. Less indentation is better.
You know .substr() will adjust the second argument, if provided, to not leave the string? So, don't try so hard in your last call.

Re-Design:

Mull over your spec. And now try to simplify it. Doing so leads to a simpler, more efficient design, which is optimized for legal input:

Too large or empty => illegal.
Tokenize.
Empty token => illegal.

Rewrite:

bool GcodeParser::tokenize_input_refactored(std::string_view s) {
    // Consider adding here: tokensVec.clear();
    if (auto pos = size(s); pos && pos <= maxCharAmount) {
        while ((pos = s.find(delimiter))) {
            tokensVec.push_back(s.substr(0, pos));
            if (pos == std::string_view::npos)
                return true;
            s = s.substr(pos + 1);
        }
        tokensVec.clear();
    }
    tokensVec.push_back("INVALID_COMMAND!");
    return false;
}


Calculating the 'binary gap' of a number

I think using Regex will be too much for this little task. A simple split by 1s should suffice.

public static int ComputeLargestBinaryGap2(int value)
{
    return Convert
            // convert to binary
            .ToString(value, 2)
            // remove leading and trailing 0s, as per requirement
            .Trim('0')
            // split the string by 1s
            .Split(new [] { '1' })
            // find the length of longest segment
            .Max(x => x.Length);
}

We can also solve the problem from a mathematical approach, with logical operators and bit-shiftings :

public static int ComputeLargestBinaryGap3(int value)
{
    // casting it to uint while keeping the same binary value, like reinterpret_cast<unsigned int>
    //var unsigned = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0);
    var unsigned = unchecked((uint)value);
    // flag used to ignore counting trailing 0's
    var pastTrailing0 = false;

    int max = 0, count = 0;
    while(unsigned > 0)
    {
        if ((unsigned & 1) == 1)
        {
            if (count > max)
                max = count;

            count = 0;
            pastTrailing0 = true;
        }
        else if (pastTrailing0)
        {
            count++;
        }

        unsigned = unsigned >> 1;
    }

    return max;
}

EDIT: After this answer was posted, OP updated on his definition of "best", which leans toward readability. I'll add my comments on his code here :

There is no benefit in declaring the variable, regexp , for the regular express, without giving a meaningful name to it, other than stating the obvious. It should be renamed to binaryGap.
valueAsBinary is a quite misleading name. One would think it the value stored in the binary format, which is pretty much how every number is stored... However, it stores the binary string of value. Therefore, it should be renamed to binaryString, or valueAsBinaryString.
The Match class already have a Length property that could be used instead of the long way match.Value.Length. This property is cached, so we are not re-measuring the length of the string, as you can see here.

And, here is the final result :

public static int ComputeLargestBinaryGap(int value)
{
    var binaryGap = new Regex("(?<=1)(0+)(?=1)");
    var binaryString = Convert.ToString(value, 2);
    return
        binaryGap.Matches(binaryString)
            .Cast<Match>()
            .Select(m => m.Length)
            .DefaultIfEmpty(0)
            .Max();
}


OOP and connecting to multiple databases using PDO

This is not how things are done in the programming world. You don't write a dozen functions doing the same thing. You write just one function.

Speaking of OOP, there is no use for it here. Given your class consists of just one method, just make it a function:

function connnect($dbName, $userName, $userPass)
{
    $host = 'localhost';
    $charset = 'utf8mb4';
    $opt = [
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES   => false,
                  ];
    $dsn = "mysql:host=$host;dbname=$dbName;charset=$charset";
    return new PDO($dsn, $userName, $userPass, $opt);
}

and then create your connections:

$dbRead = connnect(NAME1, USER2, PASS2);
$dbWrte = connnect(NAME1, USER1, PASS1);
$db3 = connnect(NAME3, USER2, PASS2);
$db4 = connnect(NAME4, USER3, PASS3);
$db5 = connnect(NAME5, USER4, PASS4);


Avoid so many temporary variables

In Python, temporary variables are used only if they benefit readability, not if they hurt it:

def getDateFromCin():
    s = input()
    nums = [int(n) for n in s.split(" ")]
    return datetime.date(nums[2], nums[1],nums[0])

Becomes:

def getDateFromCin():
    nums = [int(n) for n in input().split(" ")]
    return datetime.date(nums[2], nums[1], nums[0])

Actually, @QPaysTaxes suggested to use the splat (*) operator, and I also think it is a good idea, this shortens to function further to just:

return datetime.date(* [int(n) for n in reverse(input().split(" "))])

And:

def testFunc():
    testline = input()

    print (testline + "test")
    return

Becomes:

def testFunc():
    print (input() + "test")
    # return is not needed

And:

def cinMain():
    returnDate = getDateFromCin()
    dueDate = getDateFromCin()
    fine = getFine(dueDate, returnDate)
    print (fine)

Becomes:

def cinMain():
    returnDate = getDateFromCin()
    dueDate = getDateFromCin()
    print( getFine(dueDate, returnDate) )

Small simplifications like this are nothing interesting on their own but when you make a lot of them they start to add up making the code cleaner.

Simplify your booleans

if (returnDate.year == dueDate.year and returnDate.month == dueDate.month and returnDate.day > dueDate.day):
    return 15*(returnDate.day-dueDate.day)

If you got here, then returnDate.year == dueDate.year is surely True, as True and x == x you can simplify:

if (returnDate.month == dueDate.month and returnDate.day > dueDate.day):
        return 15*(returnDate.day-dueDate.day)

Remember to add:

if returnDate <= dueDate:
    return 0

At the start of the function to preserve correctness.

Use a testing framework

You made some work to run the automated tests, but there are already tools for that, I suggest doctest, it is very easy to use and doubles as documentation:

def book_return_fine(dueDate, returnDate):
    """
    >>> book_return_fine(datetime.date(2015,5,5), datetime.date(2016,5,6))
    10000
    """
    if (returnDate.year > dueDate.year):
        return 10000

    if (returnDate.month == dueDate.month and returnDate.day > dueDate.day):
        return 15*(returnDate.day-dueDate.day)

    if (returnDate.month > dueDate.month):
        return 500*(returnDate.month-dueDate.month)

    return 0

Just add import doctest at the start and doctest.testmod() at the end.

Naming

Naming is hard, I really do not like your names.

get is a specific OO concept and gives almost no info about what the function does.
cin is a C++ term, not everyone may remember what it stands for.
nums well, if you convert them to int they are nums but this really does not give me much info...
snake_case is the common Python naming style, not camelCase.

Spacing

Asinnaturallanguage,spacingthingsouthelpsthereaderreadfasterandeasier.

   As in natural language, spacing things out helps the reader read faster and easier.

For example:

return 15*(returnDate.day-dueDate.day)

Becomes:

return 15 * (returnDate.day - dueDate.day)


How to refract a while loop with a necessary initial setting?

I'm having trouble figuring out exactly what your code is doing. It's called get_exception_region but it appears to do a lot of printing. Is that just for debugging purposes? I'm going to assume that's the case, and thus that get_exception_region returns the row (line number?), text, and region of the line following the exception. Here are my suggestions, given that assumption:

Change the docstring to reflect what get_exception_region does, not how it does it. From another angle, describe why someone would choose to call get_exception_region, not what code they would have to write in its place. If there's any code in the docstring, it should show how to call the function, not reminders on functions it may call to implement itself. If you need the latter, comments are more appropriate for that.
If you have control over it, the name except_region.a doesn't convey much. Consider using a more descriptive name than a.
As mentioned by @ChrisWue, drop the True and from your while condition. At best it does nothing; at worst it distracts readers and slows the program.
Consider if rewriting your while loop as a for loop (for row in range(start_row, start_row + max_lines_in_exception): ...) would add or diminish clarity. This would avoid code with a slight smell (row = row + 1), but in this case I'm uncertain whether the replacement would be better.
Avoid catching Exception; if you must suppress most exceptions, it's typically better to catch BaseException (at least in python 3). That said, since this code quickly re-raises the exception, this advice is less crucial than usual.
Avoid accessing attributes like tb_frame, f_code, and co_filename in a function not specifically geared towards this. Instead for the usage in your exception handler, prefer using tools from traceback such as print_exc; in other cases inspect can be similarly useful.
Remove dead code. Having raise e followed by sys.exit(e) is misleading, since the raise will unconditionally prevent the exit from executing. Similarly the pass after return will never be reached.
If all you are really doing in this handler is printing out a partial trace, consider omitting the try/except handler entirely, and letting the caller be fully responsible.


flip

For starter, you can swap two variables in Python without using a temporary one:

>>> a = 3
>>> b = 5
>>> a, b = b, a
>>> print(a, b)
5 3

But above all, this function is better implemented using slices:

def flip(arr, i):
    arr[:i] = reversed(arr[:i])

Or

def flip(arr, i):
    arr[:i] = arr[i-1::-1]

findMaxUpTo

Same here, slices and builtin functions can go a long way into simplifying the code. A "max" function that doesn't use the max builtin feels wrong to me.

A naïve rewrite would be:

def findMaxUpTo(arr, i):
    val = max(arr[:i])
    return arr.index(val)

It is good for now. But a better rewrite would make use of enumerate and the key argument of max. Possibly involving operator.itemgetter in the process and itertools.takewhile to avoid copying the array.

pancake_sort

Not much to add here, except a note on your return value. Since you are mutating the array in-place, there is absolutely no reason to return a value. Once you call the function on an array, it will be sorted and all previous references to this array will now hold the sorted version. Returning a value can mislead the users that the original array remain untouched, which is false.

Similarly, you never make use of the output variable.

miscelaneous

Your naming style is inconsistent and some variable names don't convey much meaning, please fix it.


Project Euler #1 Sum of multiples of 3 and 5

Meta comments

Is your intention to create a separate Java program for each of the hundreds of Project Euler problems? If you plan on completing more than a handful of them, I would recommend finding a way to consolidate your solutions to all problems into a single program. You will find a significant amount of overlap between certain questions, so being able to create "helper" routines will benefit you greatly. Consider adding in some testing, validation, and timing framework to make sure your results are correct and being solved within a reasonable amount of time (i.e., PE's suggested 1-minute duration).

Algorithmic Comments

As this is a code review, and not an algorithm review, and because I don't want to spoil yours or anyone else's Project Euler experience, I'll keep this brief. Your algorithm is good; you've already used the closed-form equation for these triangle numbers and done some math. You can actually take the math a step further, but then the programming is trivialized and entirely problem #1-specific.

Code Comments

Creating the general sumMultiple() routine is good, as it is general enough to probably prove useful later on.

I would highly recommend factoring this line into its own problem001() subroutine:

 sumMupltiple(3, 1000) + sumMupltiple(5, 1000) - sumMupltiple(15, 1000));

Then in your main() function, you need only do:

System.out.println(problem001());

And the self-documenting nature of that naming scheme makes it pretty clear that you are printing the result of problem 001. It might seem a little silly in this case, but not all problems will be one-liners, and consistency is probably better than brevity in this case.

If you do decide to take some of my "meta comments" advice later, it will be even easier to organize your program.


I would pass the className to the logClass method. Because how you wrote the method you enforce that the color name is the second class applied on the control. This is very fragile, as there is no direct relation between the class order in the an element and the result apply to them. So I would do:

vm.logClass = function(className) {
...
}
//template


I would think that a major time complexity comes from the usage of Regex which involves 'steps' in the processing of the expression, meaning the complex the statement, the more steps it can take.

Instead of using a Regex for when settings.globally is false, a normal String.replace can be done.

And instead of using a Regex for the global checks, I would suggest using a String.prototype.replaceAll polyfill like the following:

String.prototype.replaceAll = function(search, replace){
    var string = this;
    var index = 0;
    while ((index = string.indexOf(search)) !== -1) {
        string = string.replace(search, replace);
    }
    return string;
}

Which would change the settings.globally block into:

if(settings.globally) {
    $(node).replaceWith(text.replaceAll(settings.textToReplace, settings.replaceWithText));
} else {
    $(node).replaceWith(text.replace(settings.textToReplace, settings.replaceWithText));
}

I would also suggest removing jQuery from the solution as well. extend, $ (the element fetching), match and each can be polyfilled in, or simply converted to vanilla JavaScript.

function $(selector, el) {
    if (!el) { el = document; }
    return Array.prototype.slice.call(el.querySelectorAll(selector));
}
var extend = function(out) {
  out = out || {};
  for (var i = 1; i < arguments.length; i++) {
    if (!arguments[i])
      continue;
    for (var key in arguments[i]) {
      if (arguments[i].hasOwnProperty(key))
        out[key] = arguments[i][key];
    }
  }
  return out;
};
if (!String.prototype.includes) {
  String.prototype.includes = function() {'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}

and for each: you can use Array.prototype.forEach (The polyfill is quite large, so I didn't include it) or a simple for loop.


Method 1 (Sieve of Eratosthenes) is definitely the faster method to use.

Starting point on my computer, summing primes less than 100,000 takes 39.916 seconds.

List to Set

The problem is basically this line:

primes_in_range = [2]

This creates a list, to which you add all odd numbers above 1, and then repeatedly search for existence of a number within (d in primes_in_range),  then for all multiples of that number, search for the multiple (j in primes_in_range), and then search for it a second time in the process of removing it (primes_in_range.remove(j)).  Searching a list is an \$O(n)\$ operation.  When you do it approximately once for every number in the list, your algorithm devolves to \$O(n^2)\$.

On top of this, you’re computingmath.sqrt(n) many, many times - a relatively expensive operation - yet the value does not change.  You only need to compute it once.

The second item you can solve by computing the \$\sqrt n\$ once, and store it in a local variable.

For the first issue, there are a few possibilities.  One, you could use a set, instead of a list.  A set has approximately \$O(1)\$ lookup time, which is much faster than \$O(n)\$.

primes_in_range = { 2 }

Since sets are not ordered, you don’t "append()" items to it, you "add" them instead.

Time has now dropped to 0.020511 seconds

Since the time has dropped to under a second, let's increase to primes less than 10,000,000 for better time measurements.

Time for summing primes less than 10,000,000: 3.519 seconds

Search to Remove

When removing, you are checking for the existence of the item in primes_in_range before removing it, since removing it when it is not present will raise an exception.  The set class has a discard method, which will only remove an item if present.  No need to check for it to be present ahead of time.

Time for summing primes less than 10,000,000: 3.453 seconds

Removing Multiples

When you find a prime, d, you cross off multiples of that prime, starting at 2*d, and going 3*d, 4*d, 5*d, and so on.  But when you determined 3 was a prime number, you crossed off all multiples of 3, so crossing off 3*d is a waste of time, for d > 3.  Similarly, crossing off multiples of the prime 5 means crossing off 5*d for d > 5 is also a waste of time.  The first multiple of d that hasn't been crossed off will be d*d, so you can remove starting at that point:

        for j in range(d * d, n + 1, d):
            primes_in_range.discard(j)

Time for summing primes less than 10,000,000: 3.305 seconds

Similarly, since you are only considering odd prime candidates in your sieve, you don't need to cross off any even multiples.  Starting at d*d, the next multiple you need to remove would be (d+2)*d, not (d+1)*d.  Your step size can be 2*d.

        for j in range(d * d, n + 1, 2 * d):
            primes_in_range.discard(j)

Time for summing primes less than 10,000,000: 2.105 seconds

Loop Like a Native

Python has its own looping, which includes incrementing loop indexes.  This native Python looping is usually faster than writing loops with their own index manipulation:

primes_in_range = {2}
primes_in_range.update(x for x in range(3, n+1, 2))

for d in range(3, math.isqrt(n) + 1, 2):
    if d in primes_in_range:
        primes_in_range.difference_update(j for j in range(d * d, n + 1, 2*d))

Here, constructing the set is done with a generator expression in primes_in_range.update(...), and removing prime multiples is done with a generator expression in primes_in_range.difference_update(...) which adds and removes entire swathes of items in a single operation:

Time for summing primes less than 10,000,000: 2.049 seconds

Direct Indexing

However, a set is still an expensive memory structure to maintain.  It requires hashing the values which are being added, creating bins to store the values in, rebinning as the set size changes, and so on.  An array of flags is much more efficient, time-wise:

primes_in_range = [False] * n
primes_in_range[2] = True
for x in range(3, n, 2):
    primes_in_range[x] = True

for d in range(3, math.isqrt(n) + 1, 2):
    if primes_in_range[d]:
        for j in range(d * d, n + 1, 2 * d):
            primes_in_range[j] = False

total = sum(idx for idx, flag in enumerate(primes_in_range) if flag)

The first line, above, allocates an array of n items, each containing the flag value False.  Then, indexing into the array is an \$O(1)\$ operation.  Set the flag to True for all odd numbers above 3, and then proceed to set the appropriate flags to False based on the Sieve of Eratosthenes algorithm.

Time for summing primes less than 10,000,000: 1.398 seconds

Bit Array

That last approach is a little inefficient when it comes to memory.  It requires a list of n 28-byte items to store one True/False flag.  These flags could be packed 8 to a byte, resulting in a 99.5% reduction in required memory!  The bitarray package provides such an array of flags.

from math import isqrt
from bitarray import bitarray

def sum_of_primes_below(n):
    primes_in_range = bitarray(n)
    primes_in_range.setall(False)

    primes_in_range[2] = True      # 2 is a prime
    primes_in_range[3::2] = True   # Odd numbers starting at 3 are prime candidates

    for d in range(3, isqrt(n) + 1, 2):
        if primes_in_range[d]:
            primes_in_range[d*d::2*d] = False    # Reset multiples of prime candidate

    return sum(idx for idx, flag in enumerate(primes_in_range) if flag)

Time for summing primes less than 10,000,000: 0.455 seconds


Holy comments Batman!

You have too many useless comments which makes your code harder to follow.

  Comments should explain why something is done, not what is done.

Good code makes it obvious what is done, if you feel that you need to comment what is being done then your code can be improved instead.

I'm going to link an answer to another question that explains commenting in a very good way (IMHO).

Prefer && to and

This code if(sidea == 0 and sideb == 0 and sidec == 0) had me do a double take, the and totally threw me off as I'm very used to see && used instead.

Keep it simple

One simplification you can make is to change bool error_check() into float read_real(). You should also extract your exit critera into a function and use it as a loop condition instead of breaking out of an infinite loop. This makes it much more clearer and removes the need for the comment. You can also extract computations from the conditional block when calculating the unknown side.

Like this:

float read_real(){
    float ans;
    std::cin >> ans;
    if(!std::cin){
        std::cin.clear();
        std::cin.ignore(256,'\n');
        throw std::invalid_argument("Please enter a real number");
    }
    return ans;
};

bool should_exit(float a, float b, float c){
    return a == 0 && b == 0 && c == 0;
}

...

float sidea = 1.0f;
float sideb = 1.0f;
float sidec = 1.0f;
while(!should_exit(sidea, sideb, sidec)){
    try{
        std::cout << "side a: ";
        sidea = read_real();

        std::cout << "side b: ";
        sideb = read_real();

        std::cout << "side c: ";
        sidec = read_real();

        // The unknown side must be 0, so this will work for all cases.
        float unknown = sqrt(abs(sidea*sidea + sideb*sideb - sidec*sidec));
        if(sidea == 0){
            std::cout << "side a= " << unknown << "\n" << std::endl;
        }
        else if(sideb == 0){
            std::cout << "side b= " << unknown << "\n" << std::endl;
        }
        else if(sidec == 0){
            std::cout << "side c= " << unknown << "\n" << std::endl;
        }
        else{
            throw std::invalid_argument("You must enter zero for an unknown side length.");
        }
    } catch (std::invalid_argument e){
        std::cout<<"\n Error: "<<e.what()<<std::endl;
    }
}


Small fast pseudorandom number generator in C++

The SmallPrng(std::random_device &rd) constructor seems like an utility method. It spares the client a single call to seed = rd(), but forces an inclusion of (otherwise unnecessary) <random>. IMHO, this constructor is absolutely unnecessary.
The purpose of the

        for(size_t i = 0; i < 20; ++i)
            (*this)();

loop in the constructor is seems useless; it amounts to passing a different seed. In any case, use {} around the loop body.
An asymmetry between

        b = c + d;

in prng32() and

        b = c + rot<N>(d, 37);

in prng64() is striking. Needs a comment, at least.
As mentioned in comments, the static_assert(!(N != 32 && N != 64), ....) is equivalent to static_assert((N == 32 || N == 64), ....) which is IMHO much cleaner.


First of all, your indentation is odd. Use a beautifier tool like JSBeautifier. If you use Sublime Text 3, there's an HTML-CSS-JS Prettifier plugin which uses the same tool internally.

Next, dat and val don't really tell anything about your data. Name it meaningfully. It's a timestamp, maybe date? And value for val? If you worry about size on transmission, just use gzip. It's better than losing hair on misnamed data.

Next, you're using moment.js in one of the loops. Moment.js is very slow based on personal experience. It tries to do as much as possible to get dates correctly, sacrificing execution speed. If you profile your code, you'll see a lot of internal extend calls in moment to generate your date. Since you're just getting year and month, why not use native getFullYear and getMonth?

Now you look like you're just operating on arrays. You can use the native array methods instead of underscore (unless you're still trying to support IE8???)

So if I understand your code correctly, this should do the same thing with lesser loops.

// Because JS doesn't have a nice way to name months because they may differ per locale
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// Use reduce to aggregate your data. Pass around a hash so that we have
// direct access to groups as well as ensure groups appear just once.
var dataByMonth= data.reduce(function(dataByMonth, datum){
  var date  = new Date(datum.dat);
  var value = datum.val;
  var month = monthNames[date.getMonth()];
  var year  = ('' + date.getFullYear()).slice(-2);
  var group = month + '\'' + year;

  dataByMonth[group] = (dataByMonth[group] || 0) + value;

  return dataByMonth;
}, {});

// Now just turn the hash into an array.
var finalResult = Object.keys(dataObjectByMonth).map(function(group){
  return { name: group, value: dataByMonth[group] };
});


Interesting question, I would rewrite

try{
    var arr = JSON.parse(data);
}catch(e){
    callback(e, false);
}
callback(null, arr.uid);

as

try{
    var arr = JSON.parse(data);
    callback(null, arr.uid);
}catch(e){
    callback(e, false);
}

Actually, I would probably go even a step further and write it as

try{
    callback(null, JSON.parse(data).uid);
}catch(e){
    callback(e, false);
}

Otherwise in case of an error, you will have 2 callbacks, which could cause all kinds of trouble, perhaps even make the CPU spike to 100% ;)

Furthermore, I would also put a try/catch around http.get itself, if there is a hardcore http layer problem, then you might not even get to 'close' or 'error'.

Then some other minor items are

Most of the options could be set outside of checkPHPSession, you should do so and prevent the repeated determinations of host, port, etc.
Why are you checking for 'close', it seems like one more way to potentially have too many calls to the callback function