Measuring performance of code using StopWatch

Just a few little things:

A public static getInstance() method is commonly used in the singleton pattern. However, you always create a new StopWatch. At least you should name it to createNewInstance(), if you want to keep the method at all.
Many of your comments are unnecessary. For example the comment before isTimerRunning() doesn't help to understand the code. If you are generating documentation, they might be required, if not, omit such comments.
The result variable in getInterval() is not required. You can just return the result like this:

return nanoToMilliseconds(endTime - startTime);

This saves you two lines of code and makes the code clearer. The same applies to getDuration().
by using the ternary if operator, you can shorten getInterval() a bit more:

public long getInterval() {
    final long startTime = interval;
    final long endTime = isTimerRunning() ? currentTime() : end;
    interval = endTime;
    return nanoToMilliseconds(endTime - startTime);;
}

The assignment interval = endTime now also happens when the StopWatch has already been stopped but this isn't a problem.


Better way to extract country wise player list from html file using regex

Regular expressions is not the right tool when it comes to parsing HTML. There are specialized HTML parsers that would do a better job resulting into a more robust and less fragile solution.

Just to name a few problems that exists in your current approach:

what if there are more than two players for a country
what if there are 0 players for a country
what if a country name contains a space or a single quote
what if a player's name consists of more than two words or contains a single quote
what if there are newlines after the opening or before the closing li tag

Instead, you may, for instance, use BeautifulSoup library:

from bs4 import BeautifulSoup

with open('playerlist.html', 'r') as input_file:
    soup = BeautifulSoup(input_file, "html.parser")

for country in soup.select("ul > li"):
    country_name = country.find(text=True, recursive=False).strip()
    players = [player.get_text(strip=True) for player in country.select("ol > li")]

    print('{country} - {players}'.format(country=country_name,
                                         players=', '.join(players)))


This isn't a matter of security, but mashing things onto a single line

else { return $user; }

is considered poor form in most style guidelines.

public static function isUser() {
    if (!self::getUser()) { return false; } else { return true; }
}

reads a bit more naturally if you don't use an inverted condition:

public static function isUser() {
    if (self::getUser()) { return true; } else { return false; }
}

And then it's easy to see that you can simplify it to just

public static function isUser() {
    return (bool)(self::getUser());
}

Similarly,

else if ($user->role === 'admin') { return true; }
else { return false; }

can be simplified to

return $user->role === 'admin';

$user = User::where('username', $username)->orWhere('email', $username)->first();

is a bit strange.  Users can log in via either email or username?  Are they both unique?  It will simplify your life (and theirs) a lot if there's only one unique identifier for each user.

You're using password_hash and password_verify, which is good.  You may want to consider setting the cost parameter to password_hash to something other than the default to get something that makes sense for your hardware.


Rails integration testing: Should we use strings or named routes in http requests?

Use the 2nd version - i.e. use the path helper methods, don't use strings. Or use a 3rd one, detailed below.

Ideally, you test your routes separately from the controller (in test/routes//spec/routes/ files). That'll test that "/users/homer/edit" indeed routes to the users#edit action. Provided your using Rails' standard resourceful routes, you don't need further tests. Anything more would be you testing that Rails works, which should be unnecessary. You want to test your app.

Secondly, the reason Rails provides path/url helper methods is that hard-coding paths/urls is a recipe for a headache should the representation of those paths ever change. For instance, a simple resources :users, as: :people in the routes file would break all your hard-coded "/users/..." paths.

Thirdly, you're simply writing homer.id. But path helpers call to_param (which you can override in your models) on the object they're passed. So you're not accurately mimicking the way the path helper methods work.

Basically, if you make a change in routes.rb, you don't want to have to update your controller tests - after all, you didn't necessarily change your controllers! You only want to update your routing tests, if you have any.

Alternatively, (edit: this is for controller tests, specifically) you can use a third version, where you specify action and params separately:

get :edit, { id: homer.to_param }

This way, you side-step both hard-coded URLs, route matching, and path/URL helpers entirely. This is probably the "cleanest" solution.


Formatting
I'd recommend looking at the accepted PSRs - e.g. PSR-1, PSR-12. Updating the code to comply with them will help make the code readable and consistent with idiomatic PHP code.
Maybe this is just a copy-paste issue, but even if you don't strictly follow PSR-12 please indent nested lines within blocks.
Array syntax
As of the time of writing, PHP 7 has Active support for versions 7.4 and 7.3, and since PHP 5.4 arrays can be declared with short array syntax (PHP 5.4) - i.e. ["gif","jpeg","jpg","png"].
Redundant lines
If you aren't familiar with the principle Don't repeat yourself I recommend reading about it:

The Don’t Repeat Yourself (DRY) principle states that duplication in logic should be eliminated via abstraction;

Let's look at a few place that are redundant:

if ((($_FILES['upload_images']['type'][$i] == "image/gif")
|| ($_FILES['upload_images']['type'][$i] == "image/jpeg")
|| ($_FILES['upload_images']['type'][$i] == "image/jpg")
|| ($_FILES['upload_images']['type'][$i] == "image/pjpeg")
|| ($_FILES['upload_images']['type'][$i] == "image/x-png")
|| ($_FILES['upload_images']['type'][$i] == "image/png"))
&& ($_FILES['upload_images']['size'][$i] < 12000000)
&& in_array($ext,array("gif","jpeg","jpg","png"))){

The last conditional uses in_array() - why not use that for checking the type? That way there is no need to repeat $_FILES['upload_images']['type'][$i] for each type:
if (in_array($_FILES['upload_images']['type'][$i],
     ["image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/x-png", "image/png"])
    && ($_FILES['upload_images']['size'][$i] < 12000000)
    && in_array($ext, ["gif","jpeg","jpg","png"])) {

Also the switch statement has three cases that do the same thing: 'jpg', 'jpeg' and default - so those first to can be eliminated.
Tri-state variable $is_jpg
This variable has three possible values, yet has a name that might be conceived as a boolean. And somebody reading the code might not know what the values 1, 2 and 3 signify without scanning through the code to see where those values are assigned. I'd suggest eliminating it and instead of checking to see if the value is 1, 2, or 3, check to see if $ex is 'jpg', 'png', or 'gif' since those values are already being set.


Advice 1

One very useful principle is that each method should solve only one problem and not more. In this context, I suggest that you roll a static method that simply computes a desired Fibonacci sequence and returns it as an array/list. Then, another method can call the previous and output the numbers.

Advice 2

Instead of closing a Scanner explicitly, you could use a try with resources. Any Autocloseable can do and will be closed implicitly.

try(Scanner scanner = new Scanner(System.in)) {
    // Use scanner here.
}
// Scanner automatically closed here.

The above will close Scanner when exiting the block, or in the case of exception.

Advice 3

Fibonacci sequence grows exponentially. For that reason you might want to use BigInteger.

Summa summarum

An alternative implementation may look like this:

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;

public class FibonacciGenerator {

    public static BigInteger[] getFibonacciSequencePrefix(int n) {
        BigInteger[] result = new BigInteger[n];

        BigInteger a = BigInteger.ONE;
        BigInteger b = BigInteger.ONE;

        for (int i = 0; i < n; ++i) {
            result[i] = a;
            BigInteger tmp = a;
            a = b;
            b = b.add(tmp);
        }

        return result;
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int n = scanner.nextInt();
            System.out.println(Arrays.toString(getFibonacciSequencePrefix(n)));
        }
    }
}


To amplify @200_success’s comment:

Python 3.5 introduces type hints.  Eg)

>>> def foo2(x:str, y:float) -> None:
...    print(f"Hi, foo has been called with {x} {y}")
...
>>> foo2("2", 3.4)
Hi, foo has been called with 2 3.4
>>>

These type hints (the x:str, and y:float) are not used by the standard Python interpreter, but they are recorded during the parsing of the code, so they are available to the program.

>>> foo2.__annotations__
{'return': None, 'x': <class 'str'>, 'y': <class 'float'>}
>>>

Directly accessing the foo2.__annotations__ is not that interesting, but accessing func.__annotations__ in the @typecheck decorator means you don’t have to provide the argument types to the decorator; the decorator can inspect the argument types directly.  Thus you could decorate the function with simply @typecheck, instead of @typecheck(str, float).

For a variant str or float type argument, you could use the typing module to define your own STR_OR_FLOAT = TypeVar("STR_OR_FLOAT", str, float) type (or a better name if you have one), which you could decorate the argument with.

As a bonus, using type hints to provide argument type checking information — even for your do-it-yourself via a function decorator type check system — also gives you the following benefits:

IDE type hints, as you are writing code
Can be understood by standard documentation generators
Only consumes CPU time during parsing of the code; does not affect execution speed


Play With Numbers Programming Challenge (mean value of subarrays)

You are running this O(R - L) loop for each query:

for (size_t i = leftIndex; i <= rightIndex; i++)
{
    ans = ans + nums[i];
}

You could obtain each sum in O(1) time if you stored the array as cumulative sums instead.

$$
\begin{align}
S_1 =&\ A_1 \\
S_2 =&\ S_1 + A_2 \\
S_3 =&\ S_2 + A_3 \\
 \vdots& \\
S_N =& S_{N-1} + A_N
\end{align}
$$

The tricky part is that \$S_N\$ could be as large as \$10^{15}\$, which requires more than 32 bits.


Mixin both instance and class methods in Ruby

You're doing it right :) It's a very common idiom, and widely accepted as the preferred way to handle this.

In case you're still in doubt, here are a few examples of the same pattern found in major projects out in the wild: sidekiq, mongoid and datamapper.


First of all, always return def.promise() - not def itself. If you return the Deferred object itself, other code can call resolve/reject on it. So keep def to yourself, and only return its promise.

Also, why not use reject() for the Cancel buttons instead of resolve(false)? If you use reject, it'll probably make the rest of your code simpler, since you don't need to check the resolve arguments. Your "success" handler either gets called, or it doesn't.

Second, since you're building buttons in both cases, that'd probably be the part I'd extract. For instance

function makeDialogButtons(resolveTitle, rejectTitle) {
  var def = $.Deferred(),
      buttons = {};

  buttons[resolveTitle] = function () {
    def.resolve();
    $(this).dialog('close');
  };

  buttons[rejectTitle] = function () {
    def.reject();
    $(this).dialog('close');
  };

  return { buttons: buttons, promise: def.promise() };
}

And use it like so

LanguageLogosView.showConfirmEmptyRowsDialog = function () {
  var buttons = makeDialogButtons('Save', 'Cancel');
      options = $.extend(LanguageLogosView.dialogConfirmDefaultSettings, buttons.buttons);
  $("#dialog-confirm-save-with-empty-rows").dialog(options);
  return buttons.promise;
};

It's not great, but it should do the job.


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

Fix the formatting

Perhaps the indentation problem is partly a cut-and-paste problem when you put it into the question, but the resulting formatting is not good, with very little indenting of code.

Fix the bugs

In this line

if (ev.type = ALLEGRO_EVENT_KEY_DOWN)

It's likely that you don't actually mean to assign the value but to test it, so it should be written instead like this:

if (ev.type == ALLEGRO_EVENT_KEY_DOWN)

Eliminate unused variables

Unused variables are a sign of poor code quality, so eliminating them should be a priority.  In this code, d, f and ballmmoving are all unused according to my compiler also tells me that.  Your compiler is probably also smart enough to tell you that, if you ask it to do so.

Eliminate global variables

My rewrite of this code uses no global variables, so clearly they are neither faster nor necessary.  Eliminating them allows your code to be more readable and maintainable, both of which are important characteristics of well-written code.  Global variables introduce messy linkages that are difficult to spot and error prone.

Check return values for errors

The calls to al_load_bitmap, al_create_event_queue, etc. can fail.  You should check the return values to make sure they did not.

Eliminate "magic numbers"

This code is littered with "magic numbers," that is, unnamed constants such as 400, 7, 600, etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "800" and then trying to determine if this particular 800 means the width of the window or some other constant that happens to have the same value.

Break up the code into smaller functions

Rather than having everything in one long function, it would be easier to read and maintain if each discrete step were its own function.

Think of the user

Right now there is no graceful way to end the game.  This could easily be addressed by adding these three lines to the switch statment:

case ALLEGRO_KEY_Q:
    playing = false;
    break;

Additionally, the ball and the players can go off the top or bottom of the screen, making playing the game a lot more difficult and less enjoyable.

Also, I'm not an Allegro expert, but the game does not seem very responsive even though my machine is fast and has lots of memory.  Something is awry.

Use objects

Each of the players, the field and the ball could all be objects which could simplify some things here.  Consider transforming the code into a more object-oriented design.


Setting instance data attributes to None in __init__

According to PEP 526, the initializer isn't needed.  Have you tried:
class Window:
    def __init__(self):
        self.image: Optional[Image]    # <== this is just a type hint, no initialization

    def build(self, path):
        self.image = Image(path)

I don't use PyCharm, so I don't know if it would still complain.


Session generator/checker utility for a server

For the most part this looks pretty good, there are only a few things which I would recommend changing.

As Igor Soloydenko recommends, get rid of the comments which do nothing but restate the code. Though comments are certainly not a bad thing, they should instead be used to explain why some code is the way it is if another programmer in 6 months (you) looks at it and expects something different.
Don't wrap promises in new Promise(). The bluebird wiki has a good explanation of this. It essentially boils down to "if a function returns a promise, return that directly". Here's an example with your code. I have removed the check for a null session as save() will reject when there is an error and it is not necessary to check for it yourself.

exports.create = function(account_id) {
  return generate(config.session.length)
    .then(function(sid) {
      return new Session({_id: sid, account_id: account_id}).save();
    })
    // If all a method does is return, I prefer arrow functions
    .then(session => session._id);
}

If you are using Node v7.6.0 or newer, you can take advantage of async / await to further simplify the use of promises.

exports.create = async function(account_id) {
  let sid = await generate(config.session.length)
  let session = await new Session({_id: sid, account_id: account_id}).save();
  return session._id;
}

If you are using Node v8.0.0 or newer, you can use the built in promisify method to avoid wrapping callback based methods yourself.

const { promisify } = require('util');
var generate = function(length) {
  // If this is being called a lot, the promisify call should be saved
  return promisify(crypto.randomBytes)(length)
    .then(buffer => buffer.toString('hex'));
}

The check function can be simplified, there are several ways this could be written.

exports.check = function(sid) {
  return Session.findOne({_id: sid}).lean().exec()
    .then(function(session) {
      // Igor Soloydenko's suggestion
      if (!session || session.expires < Date.now()) {
        return false
      }
      return true;
    });
}

// This works better if there are many conditions which must be true
// Igor Soloydenko's check is probably better here.
exports.check = function(sid) {
  return Session.findOne({_id: sid}).lean().exec()
    .then(session => [
      session,
      session.expires > Date.now(),
    ].every(Boolean));
}


Let's start by removing print from the loop and add a return value

def censor(text,word):
    #[...]
        else:
            censored_text += x
    return censored_text

now we have a testable function. we add some tests

import unittest

class TestSome(unittest.TestCase):

    def test_not_found(self):
        self.assertEqual(censor("", "bar"), "")
        self.assertEqual(censor("f", "bar"), "f")
        self.assertEqual(censor("foo", "bar"), "foo")
        self.assertEqual(censor("fooo", "bar"), "fooo")

    def test_found(self):
        self.assertEqual(censor("bar", "bar"), "***")
        self.assertEqual(censor("bar!", "bar"), "***!")
        self.assertEqual(censor("cow bar", "bar"), "cow ***")

    def test_parts(self):
        self.assertEqual(censor("foobar", "bar"), "foobar")
        self.assertEqual(censor("bare", "bar"), "bare")

    def test_capital(self):
        self.assertEqual(censor("Bar", "bar"), "***")

    def test_multiple(self):
        self.assertEqual(censor("foo bar bar foo", "bar"), "foo *** *** foo")

if __name__ == '__main__':
    unittest.main()

Running the tests show that the functions are not meeting my expectations.

detect_word_start() does not return a value if nothing found
you miss words at the beginning of a sentence becaue of capitalization
you censor different words containing the character sequence
you miss multiple appearences


Looking for efficient python program for this following python script

I noticed one of your issues is that you are calculating the same thing over and over again when it is possible to pre-calculate the values before looping. First of all:
x = sqrt(d0(m[i], m[i]))

and:
y = sqrt(d0(m[j], m[j]))

are doing the exact same thing. You are calculating the sqrt() of dot product of the entire length of the vector length^2 times! For your 5000 element vector list, that's 25,000,000 times.
When it comes to iterating over giant mounds of data, try to pre-calculate as much as possible. Try this:
pre_sqrt = [sqrt(d0(elem, elem)) for elem in m]
pre_d0 = [d0(i, j) for i in m for j in m]

Then, to reduce the amount of repetitive calls to len() and range():
vectorLength = len(vector)
iterRange = range(vectorLength)

Finally, this is how your for loops should look:
for i in iterRange:

    tmp = []
    x = pre_sqrt[i]

    for j in iterRange:

        y = pre_sqrt[j]
        z = pre_d0[i*vectorLength + j]

        w = z / (x * y)

        tmp.append(w)

    corr_matrix.append(tmp)

When I timed your implementation vs mine these were the average speeds over 10000 repetitions:

Old: .150 ms
Mine: .021 ms

That's about a 7 fold increase over your small sample vector. I imagine the speed increase will be even better when you enter the 5000 element vector.
You should also be aware that there could be some Python specific improvements to be made. For example, using lists vs numpy arrays to store large amounts of data. Perhaps someone else can elaborate further on those types of speed increases.


Program that prints out the initials of a given name

Your code is buggy. It might seem to work, but accessing name[-1] invokes undefined behavior. You do that in the first iteration of the for loop. To fix it, start at i = 1 instead of i = 0.

The next instance of undefined behavior is when you call toupper(name[i]). The functions from <ctype.h> must not be called with a char as their argument. It must always be an unsigned char or the value of the macro EOF. To fix this, call toupper((unsigned char) name[i]).

The proper type for array indexes is not int, but size_t. Therefore the loop should start with for (size_t i = 1, n = strlen(name).

You have a typo: firts instead of first.

Other than that, the code looks good. In some months you will be able to remove all the comments because they are obvious to you. But until then, they should stay.

To make your program even more correct, you could change the condition name[i - 1] == ' ' to be more precise: !isalpha((unsigned char) name[i - 1]) && isalpha((unsigned char) name[i]). Then you won't print an "uppercase space" if the input contains several spaces in a row.


Remove contiguous elements in array in a more functional way

One neat thing about array.reduce is that the carry doesn't need to be your resulting value. You can actually hold a record of previous runs on it by carrying an object.

I would think something along the lines of:

line.reduce((carry, current, index) => {
  // If current is same a previous, increase repeats
  // If repeats === 3, splice the last 3  in result and replace with null,
  // Else, add current to the result
  // update previous and repeats a
  // return updated carry
}, {
  result: [],
  previous: null,
  repeats: 0
}).result;


Does this tkinter-based web browser widget use a well implemented class?

Class Scoping

So your comment afore your global declaration of e1 mentions how you wish for e1 to be accessible in all methods. If you want a variable to be accessible in all methods of a class, the conventional way is to assign it as a property of self:

class Foo():
     def __init__(self, bar):
         self.boz = bar * 3

     def baz(self):
         # boz is now accessible here
         print(self.boz)

Note that boz is not a global; if I create two Foo() objects, I'll end up with 2 different boz variables:

>>> f1 = Foo(3)
>>> f1.boz
9
>>> f2 = Foo(2)
>>> f2.boz
6
>>> f1.boz
9 # Still

Static Methods

To answer your (most conceptual) questions about the static method:

Potentially
The function takes some data, and then performs an operation on it. It does not rely on any other state to decide what operation to perform, so it is a perfect candidate for being static.
No, it does not need to be static; a static method is (conceptually) a function in all but name, so you could write it as a function. The main reasons to have something be a static variable is usually organizational or conceptual, so if you think that applies here, keep it as a staticmethod. Otherwise, consider making it a bog standard function.

There is no definite rule for when to write a function and when to write a static method; it's something you learn over time. The two questions I ask myself when deciding to write a static method are "Could I write this as a function?" and "Is this code very tightly linked (conceptually) to the class?". If the answer to both of those questions is yes, then I might write it as a static method.

In this case, I think a function might be more useful.

General bugs

Just some little things I noticed:

Your parsed static method says that it removes cruft from a string, but it never checks to see if the characters it expects to be there actually exist. Personally, I would use a regexp to implement this function, but regardless, it might be wise to check that the characters you are deleting are the ones you expect to be there.
In __init__ you do root.bind(...), where you could do master.bind(...), which might be better, as it would avoid using a global variable.
I'd recommend using a new style class by replacing class Browser: with class Browser(object):. The benefits of the syntax difference are subtle, but noticeable (and it helps with forward compatibility iirc).
It might be a better idea to define a main function, and then call that instead of just doing loads of stuff in the global scope. You could also add a guard case of the form if __name__ == "__main__": main() to allow you to import the script into a REPL without running the code.
Some of your variable names kinda suck. Try and find more descriptive names than e1!


Getting a transpose of a matrix of size of n*n where n=2^m using multithreading

Is it worth parallelising?

When you are parallelizing code you have to ask yourself if it's worth doing that. Parallel code doesn't magically give a speedup, because there are various things that can actually slow you down when using parallelism, for example:

Spawning and waiting for threads itself costs some time.
Threads might be fighting for resources, like locks, but even just memory access might cause contention.
Code that is not trivially parallelizable might require more computations when parallelized than when running single-threaded.

In the case of transposing matrices, there are almost no computations involved, the work is completely dominated by reading and writing to memory. A good single-threaded implementation, which reads sequentially as much as possible, will likely be able to saturate the memory bus on typical desktop machines.

In your implementation, you have a huge overhead just from starting all the async work items: you call async() more often than there are elements in the matrix. So that alone will make this horribly slow. Most good parallel algorithms try to limit the number of threads to the number of CPU cores or hardware threads that are available.

Even if you didn't parallelize, but kept the structure of the code the same (just not use async()), then the recursive divide-and-conquer approach will cause a non-sequential memory access pattern.

Code review

Nested std::vector<>s are not efficient containers for matrices

While it's convenient to declare a 2D matrix using std::vector<std::vector<T>>, it is not very efficient, since there is a lot of indirection. It is more efficient to declare a single std::vector<T> of size n * n, and index the vector using [row * n + col], or use a C++ library that provides proper matrix classes.

Use std::swap()

The standard library provides std::swap(), which swaps two variables for you.


I noticed that you use 'hard' and repeated parts of code. My way to solve this task is to write a custom validation (I try to avoid them but sometimes there no other choice).

I try to place custom validations in a separate file (in config\initializers\ directory).

ActiveRecord::Base.class_eval do
  def self.validates_dependent_fields(*attr_names)
    fields_count = 0
    attr_names.each{ |attribute| fields_count += 1 if record[attribute] }

    validates_each(attr_names) do |record, attribute, value|
      if value && fields_count < attr_names.length
        record.errors[attribute] << "Dependent fields can not be empty."
      end
    end

  end
end

Algorithm:

Get the number of not nil fields;
Validate each field (and add error message if the attribute value is not nil and one or more dependent fields are not present).

Then, in the model:

class SomeModel < ActiveRecord::Base
  validates_dependent_fields :a, :b, :c, :d
end

Note that you can reuse this validation in any other model.

P.S.: I've not tested this code yet.


Reading and displaying an image from a folder

You could simplify your getImage() method pretty significantly to just:

public IEnumerable<string> GetImage() =>
    Directory.GetFiles(rootPath + @"\lib\Images\Nature").Select(Path.GetFileName);

Things I changed:

Changed capitalization to follow .Net naming guidelines.
Removed unnecessary method ReadPhotosFromDirectory().
Removed unnecessary variable fileLocations.
Used verbatim string to avoid having to escape backslashes.
Used method group to delegate conversion instead of lambda.
Got rid of ToArray(), which didn't serve any purpose, and changed return type to IEnumerable<string>.
Used C# 6.0 expression bodied method.


Getting a random number between a min and a max

You can abstract the code in another function and then call it.

If you are using OOP, then you can either pull that in (abstract) Parent class, this way it would be accessible to everyone.

function getRandomPageNumber(){
    return getRandomIntInclusive(1, 5);
}


Program that finds the longest word not containing one of the disallowed characters

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

Fix the bug

There is a subtle bug in the original implementation.  It contains these lines:

// If the word contains one of the bad letters, don't accept it.
for (unsigned int i = 0; i < sizeof(badLetters); i++) {
    if (currentLine.find(badLetters[i]) != std::string::npos) {
        continue;
    }
}

The intent is, of course, to escape the for loop and go on if a bad letter is found in a candidate word.  However, what actually happens is that first letter is checked, and the loop continues no matter if the letter was found or not.  That's a bug and one reason I don't much like continue.  It's too easy to make this kind of error.

Don't loop on eof()

It's almost always incorrect to loop on eof() while reading a file.  The reason is that the eof indication is only set when an attempt is made to read something from the file when we're already at the end.  So instead of this:

while (!in.eof()) {
    getline(in, currentLine);
    // ...
}

write this:

while (getline(in, currentLine)) {
    // ...
}

See this question for more details on why using eof is usually wrong.

Initialize variables on declaration

The best practice is to initialize variables as soon as they're created.  In C++, this most often means initializing them in the same line as the declaration.  So instead of this:

std::ifstream in;
in.open("words.txt");

write this:

std::ifstream file2{wordsFile};

Note, too, that I use the C++11 uniform initializer syntax (with the {}) to make it clear to both the compiler and the reader that this is an initialization and not a function call.  See Stroustrup's description for more details on that.

Allow the user to specify input files

The words file name is currently hardcoded which certainly greatly restricts the usefulness of the program.  Consider using argc and argv to allow the user to specify file names on the command line.

Prefer newer structures to plain arrays

Instead of a plain array as with badLetters, one could instead use an std::array or std::string.  If your compiler has C++17 support, std::string_vew might be an even better choice.

const std::array<char, 8> badLetters = { 'g', 'k', 'm', 'q', 'v', 'w', 'x', 'z' };

Use standard algorithms

Instead of searching with a for loop for all badLetters, we can use std::find_first_of() instead.  The result would look like this:

while (getline(in, currentLine)) {
    if (currentLine.length() > longestAcceptableWord.length()
        && (std::find_first_of(currentLine.begin(),
                            currentLine.end(),
                            badLetters.begin(),
                            badLetters.end()) == currentLine.end())
    ) {
        longestAcceptableWord = currentLine;
    }
}

Note that I prefer to avoid continue and instead rely on the short-circuit evaluation of the if clauses to cause the same effect.

Don't use std::endl if you don't really need it

The difference between std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.


Disclaimer: I haven't really used YAMLFileLoader but the advice should apply for the sake of improving PHP code.
Catching Exceptions
I would consolidate the exception catching, since apparently the value of $data is always the same (other than the fact that the info value is assigned the exception message). Unless the goal is to only catch \Symfony\Component\Routing\Exception\MethodNotAllowedException and ResourceNotFoundException instances, why not just catch all Exception instances? Something like this:
catch(\Throwable $e){
    $data = [
        'status'=>404,
        'message'=>'Not found',
        'info'=>$e->getMessage()
    ];
}

And for the sake of D.R.Y. code, you could abstract setting $data in those exception handling blocks to a separate method that returns that array. Something like:
function GetFallbackDataForException(Throwable $e) {
    return [
        'status'=>404,
        'message'=>'Not found',
        'info'=>$e->getMessage()
    ];
}

I hadn't learned until testing out this code but an Error can be thrown and caught - I thought that was only possible with instances of Exception but both implement Throwable...ergo...
Method length
The method is quite long - especially considering it is a constructor. It would be advisable to break up the pieces into separate methods - e.g. one to create the request, one to take the return value from the request and send the response, etc. That way the constructor can be shorter as it calls those methods, plus those methods would hopefully lend themselves to unit testing each component of the process.
I considered suggesting that the foreach to set attributes be replaced with a call to array_walk() but that might require flipping the array keys and values, making a Callable out of the method, etc. all to save 1-2 lines...


What would the users like? It's usually an error message and a log file with the details and stacktraces for bug reports/support calls/debugging. You can throw exceptions out from main but it's not user-friendly (unless the users are the people who develop the software).
Please note that singleton nowadays is rather an antipattern. (WhateverObject.getInstance() looks like a singleton.) They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with.

What is so bad about singletons?
TotT: Using Dependency Injection to Avoid Singletons
Eliminating static helper classes
The Singleton Pattern


Properties

Currently, you're defining a public field, and then creating a property which can get and set that public field, like this:

public int SomeNumber;
public int SomeNumberProperty
{
     get { return this.SomeNumber; }
     set { this.SomeNumber = value; }
}

Firstly, the field that the property sets and gets should be private, if you choose to not use auto-properties, like this:

private int _SomeNumber;
public int SomeNumberProperty
{
    get { return this._SomeNumber; }
    set { this._SomeNumber = value; }
}

Now, while this is something that you can do, in the case of your code, there is no need to manually define the getters and setters in your properties. You can simply define an auto-property, like this:

public int SomeNumber { get; set; }

The C# compiler will automatically generate a private field in which the value for the property is stored. Do note, this value can only be accessed through the property's getters and setters.

If you're using C# 6 or later, you can also define a default value for the property, like this:

public int SomeNumber { get; set; } = 42;

Constructors

All of your classes that represent something, like a Person or a Worker are missing something rather important - a constructor. A constructor allows you to initialize the values of specific properties or fields when the object is instantiated. For example, here's a representation of a Person class using auto-properties and a constructor:

public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }

    public Person(int age, string name)
    {
        this.Age = age;
        this.Name = name;
    }
}

The constructor in question is this portion of code right here:

public Person(int age, string name)
{
    this.Age = age;
    this.Name = name;
}

It should be relatively self-explanatory what this chunk of code is doing. It's called when an instance of Person is created and sets the value of each property to the corresponding argument passed. An example of creating a new instance of this class might look like this:

Person person1 = new Person(42, "Bill");

By using the constructor to initialize values, it means that you don't have to initialize properties/fields like this:

Person person1 = new Person();
person1.Age = 42;
person1.Name = "Bill";

Side note: You can also use the object initializer syntax instead of constructors, but I'd recommend sticking with constructors for now.

Other nitpicks

The following method is the perfect candidate to be converted into a property:

public double SalaryCalcul()
{
    return this.wageHour * this.Total_Hours;
}

All this method does is return a value, so we can define a property like this:

public double Salary
{
    get { return this.wagehour * this.Total_Hours; }
}

If you are using a C# 6 or later, you can simply write the above like this:

public double Salary => this.wagehour * this.Total_Hours;

Simply attempting to convert user input to an integer isn't the best idea. What if the user enters a string, like "Hello"? To ensure that no errors are caused due to faulty user data, you should set up something like this:

int convertedUserInput;
string userInput = Console.ReadLine();

if(Int32.TryParse(userInput, out convertedUserInput))
{
    // the user entered a proper integer
}
else
{
    // the user did not enter a proper integer
}

As a side note, properties should also be named in PascalCase, along with fields.


Your code has a lot of magic numbers.  I can't tell what the significance of the number 20 that is being compared to y1, or the significance of the 20 that is being compared to x1, or whether the two numbers are the same or different (if I changed the number compared to y1 to 30, should I also change the number compared to x1?).  One of the comparisons uses > and the other uses >=.  I can't tell whether this is what you meant to do or a bug.

If you created named constants with descriptive names, probably all of those things would be obvious.

I think you have a misconception about how function arguments work.  Despite having the same name and the same type, the int x1 in main() and the int x1 in moveLine() are different, and the x1 in each recursive call of moveLine() are different.

The line moveLine(x1 += 9, y1, x2+=9,y2); should work, but writing it as moveLine(x1+9, y1, x2+9, y2); is less confusing and would also work.

Also, this code:

int x1 = 5;
int y1 = 0;
int x2 = 5;
int y2 = 10;
moveLine(x1, y1, x2, y2);

could be written like this:

moveLine(5, 0, 5, 10);

(I'm not suggesting you keep the 4 int style; Barry's suggestion is good.  I'm just pointing out what looks like a misconception and trying to clear it up.)


k th smallest element in row wise and column wise sorted matrix

heappush and heappop maintain the heap invariant; there is no need to call heapify after them. Alternatively, you could initialize the heap from an unsorted list using heapify and skip the heappush, but as the list is already sorted in this case, it is already a heap and you don't need to apply either function.
You push the whole first row to the heap but the first k elements would suffice thanks to the rows being already sorted.
Instead of

for i in xrange(n):
       heapq.heappush(hp,[mat[0][i], 0, i])

it would be more idiomatic to use

for i, value in enumerate(mat[0]):
       heapq.heappush(hp, [value, 0, i])

though as I already advised to take only k elements, you could instead use

for i, value in zip(xrange(k), mat[0]):

More idiomatic instead of while k >1: ... k-=1 would be for _ in xrange(k - 1):
Readability of
[mat[x[1]+1][x[2]], x[1]+1, x[2]]

could be improved to [mat[row + 1][col], row + 1, col]

by unpacking value, row, col = heapq.heappop(hp)

Revised code:

def kth_smallest(k, mat):
    '''Return the kth smallest element in row wise and column wise sorted matrix.
    mat represents the matrix as list of lists.
    '''
    m = len(mat)
    hp = [(value, 0, col) for col, value in zip(xrange(k), mat[0])]
    # hp is a min heap because mat[0] is assumed to be sorted
    for _ in xrange(k - 1):
        value, row, col = heapq.heappop(hp)
        row += 1
        if row < m:
            heapq.heappush(hp, (mat[row][col], row, col))

    return hp[0][0]


public bool CheckPlace(string State, string City)
{
    if (string.IsNullOrEmpty(State) || string.IsNullOrEmpty(City))
    {
        return false;
    }

    using (var data = new TestDataContext())
    {
        var ret = data.Places.Where(a => (a.State == State || a.City == City)).Select(a => a.Place).ToList().Any(x => x.ToString().ToLower() == "kochi");

        return ret;
    }
}

If the Place have a string property what can be use at the "is kochi" check then use that in the Any() and leave out the .ToList().

Instantiating the TestDataContext() in this method is bad (can not test the method) please inject it as method or class constructor parameter (you can inject a lambda for instantiating it also).

(Syntax errors maybe exists in my code [powered by Notepad].)


Partitioning input strings by even and odd indexes

One possible solution that achieves the described result is:

`${s.replace(/./g, (s, pos) => [s, ''][pos & 1])} ${s.replace(/./g, (s, pos) => ['', s][pos & 1])}`

...But in order to answer to your question:

// 0
let wordsArr = words.map((val) => {
    return val.split("");
})

// can be rewritten as
let wordsArr = words.map(val => val.split(''))

// 1
for (let i = 0, len = wordsArr.length; i < len; i++){

// personally I use
i += 1
// following to Douglas Crockford
// this is what actually happens under the hood

// 2
if (j % 2 === 0){
   even += wordsArr[i][j]
} else if (j % 2 !== 0) {
   odd += wordsArr[i][j];
}

// can be symplified to
[even, odd][j & 1] += wordsArr[i][j];

Happy coding!


Scala function to parse json with time fields to appropriate case classes. How can I write this better?

Let this be the definition of your Date types:
sealed trait Date {
  def year: Int
}

case class Year(year: Int) extends Date
case class YearMonth(year: Int, month: Int) extends Date
case class YearWeek(year: Int, week: Int) extends Date
case class YearMonthDay(year: Int, month: Int, day: Int) extends Date

In your question there are problems when value is not defined, or when it is empty string, or when value is present, but it is not a number. So you can use common function readInt to read optional integer from JSON. In case if value is not present or if value is empty or non-integer, the result of function will be scala.util.Failure.
  def parseDate(dateJson: JsValue): Try[Date] = {
    def readInt(fieldName: String): Try[Int] =
      (dateJson \ fieldName).asOpt[String].filter(_.nonEmpty).map(x => Try(x.toInt))
        .getOrElse(Failure(new IllegalArgumentException(s"$fieldName is empty")))

    val maybeDay: Try[Int] = readInt("day")
    val maybeWeek: Try[Int] = readInt("week")
    val maybeMonth: Try[Int] = readInt("month")
    val maybeYear: Try[Int] = readInt("year")

    maybeYear.map { year: Int =>
      maybeMonth match {
        case Success(month) => maybeDay match {
          case Success(day) => YearMonthDay(year, month, day)
          case _ => YearMonth(year, month)
        }
        case _ => maybeWeek match {
          case Success(week) => YearWeek(year, week)
          case _ => Year(year)
        }
      }
    }
  }

My tests:
val date1 = JsObject(Map("year" -> JsString("2001"), "month" -> JsString("11"), "day" -> JsString("30")))
println(parseDate(date1)) // => Success(YearMonthDay(2001,11,30))
val date2 = JsObject(Map("year" -> JsString("2001"), "month" -> JsString("11")))
println(parseDate(date2)) // => Success(YearMonth(2001,11))
val date3 = JsObject(Map("year" -> JsString("2001"), "week" -> JsString("51")))
println(parseDate(date3)) // => Success(YearWeek(2001,51))
val date4 = JsObject(Map("year" -> JsString("")))
println(parseDate(date4)) // => Failure(java.lang.IllegalArgumentException: year is empty)

Sorry for my English


Filtering FASTQ file based on read names from other file (how to increase performance) Python

Do not reinvent the wheel. There are bioinformatics tools that accomplish this task.
To extract reads from fastq files by IDs, use seqtk subseq.

Extract sequences with names in file name.lst, one sequence name per line:
seqtk subseq in.fq name.lst > out.fq

It works with fasta files as well.
Use conda install seqtk or conda create --name seqtk seqtk to install the seqtk package, which has other useful functionalities as well, and is very fast.
Alternatively, use BBMap filterbyname.sh, see docs:

By default, "filterbyname" discards reads with names in your name list, and keeps the rest. To include them and discard the others, do this:
filterbyname.sh in=003.fastq out=filter003.fq names=names003.txt include=t

SEE ALSO:
Extracting specific sequences from FASTQ using Seqtk
How To Extracting Fastq Sequence For Given Fastq Ids And Fastq File
How To Extract A Subset Of Reads In Fastq Using An Id List?


Can I speed up this simple versioning/backup script?

Implementing solutions to problems like this is good for exercise purposes. It is good for learning.

But it is almost never good to re-invent the wheel in production systems. Please have a look at well-established data synchronization software such as rsync and perform some research around it and other data synchronization/backup/snapshot techniques.

So, your question is good until "I intend to run this as a cron job, every 30 minutes or so." :-) I am not that bash expert myself, to others might point out the potential weaknesses of your approach.


According to my interpretation, your solution does not actually meet the specification:

  If it has 3 letters adjacent/consecutive on the QWERTY UK keyboard then it will be -5 points

For example, pas does not have three adjacent keys on a QWERTY keyboard, yet it gets penalized by your code.  On the other hand, your code fails to detect backwards adjacent sequences such as ewq.


Reverse Polish Notation evaluator in Haskell

First, I would convert all of the functions which might throw an error to return some kind of failable type, like Maybe Int or Either String Token. This includes str2tok, tokenize, and eval. This would also remove the need for the countTok function, since the program can just return an error value from eval instead. With the help of the Monad instances for these error types, this is a relatively simple change.

Next, I would use isDigit from Data.Char instead of c `elem` ['0'..'9'] because isDigit makes less comparisons in order to determine if it's a digit.

Lastly, I would change the Operator type to the function type Int -> Int -> Int. This will remove the need for applyOp and will consolidate all the places that would be necessary to change if you wanted to extend the program to accept more operators.

import Data.Char (isDigit)

data Token = TNum Int | TOp (Int -> Int -> Int)

main :: IO ()
main = do
    line <- getLine
    either putStrLn print $ do
        tokens <- tokenize line
        eval [] tokens

tokenize :: String -> Either String [Token]
tokenize = mapM str2tok . words

str2tok :: String -> Either String Token
str2tok tkn
    | (c:_) <- tkn, isDigit c = Right $ TNum (read tkn)
    | otherwise = TOp <$> case tkn of
        "+" -> Right (+)
        "-" -> Right (-)
        "*" -> Right (*)
        "/" -> Right div
        _   -> Left $ "No such operator " ++ tkn

eval :: [Int] -> [Token] -> Either String Int
eval (s:_) []                   = Right s
eval stack (TNum t:ts)          = eval (t : stack) ts
eval (x:y:stacknoxy) (TOp t:ts) = eval (t y x : stacknoxy) ts
eval _ _                        = Left "Not a correct expression."


Looking at your code, there are several things that immediately I can tell are issues. Before we even get to performance, there are basic security measures that need to be taken first.

SQL Injection

Like you've seen in the comments, your code is highly susceptible to SQL injection. But, what is it exactly? By definition, it is the

  insertion or "injection" of a SQL query via the input data from the
  client to the application.

Now how is your code affected by this? Well imagine we visit a URL like

http://rocket.com/newsite?url=google.com

That's all fine and dandy. If your connection works, "google.com" will be entered into your database.

However, imagine we visited a URL such as:

http://rocket.com/newsite?url=');

Note: You can't do this straight from the URL bar. I used PHP's get_file_contents() to test this.

Now we have a problem. Why is this such a big deal? Well let's take a look at the query when this happens:

INSERT INTO `rocket_newsites`.`sites` (`id`, `url`) VALUES (NULL, '');', '');

Even StackExchange's syntax highlighter knows this is wrong!

Well now you have a syntax error! Your string was interpreted and we were left with some left-over characters (;', '');). Now the attacker knows you're vulnerable to injection.

Contrary to popular belief, having something such as ?url=');DROP`sites`; will rarely actually delete your table. This is because MySQLi's regular query function does not handle multiple queries in one string. It will however, produce a syntax error. So neither way is a good one!

I was asked in chat:

  how can you have an answer about sql injection without the "bobby
  tables" xkcd comic?

And frankly, I agree. It demonstrates the dangers of SQL injection quite simply and shortly!

Source (CC BY-NC 2.5)

How can you solve this? Well I shouldn't have to do all the work!

Improper Error Handling

This is one many people forget, especially as beginners!

Let's take a look at your error handling:

echo "Failed to connect to MySQL: " . mysqli_connect_error();

Why is this bad? Because even if there's an error connecting, you continue to go through with the query. This means an error will be thrown to the attacker, which gives him incredibly important information. Now anyone with a little bit of intrusion knowledge could brute-force your database credentials.

Give only the information the users needs to get it right the next time. Anything more can compromise the security of your application. This is why forms never tell you if it's your username or your password that is wrong ;)

Be aware that there is also no error handling for your query. Anything that goes wrong, just goes wrong!

Got the security issues out of the way, now for what you asked for!

Performance

Here are some tips for optimizing your queries.

If you don't need the id column, don't have it. It's slowing you down by inserting NULL. And if you don't need it, then maybe you shouldn't be using a RDBMS. Perhaps look into NoSQL.
Don't start a new connection on every page, especially if each user is not unique. Utilize sessions and caching.
You might be able to use transactions, depending on the project.
Look into stored procedures.
Ask yourself why this is being called so often and see if you can change the way the application is designed to better suit such intense querying.
Look into other other server-side languages and their profiled statistics. Perhaps PHP really isn't the most optimized language for the job!


This is a critique, and a rewrite of the code you showed, that is, the code for checking if a given password only contains characters from a given character set; for an actual brute force password cracker, see e.g. this  question.

I think you should look at the problem a bit differently.

Why don't you go through the characters in the password, and check if every character is in the set of allowed characters?
If you get that every character of the password is in the set of allowed characters, then the password is valid, otherwise it isn't.

I'd implement this in the following way.

#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<numeric>

const static std::set<char> charSet = {
    '%',
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    '1','2','3','4','5','6','7','8','9','0'
};

bool checkPassword(const std::string password) {
  return std::accumulate( password.begin(), password.end(), true,
    [](bool acc, char c) { return acc && charSet.find(c) != charSet.end(); } );
}

int main() {
  for (;;) {
    std::string password;
    std::cout << "Enter password : ";
    std::cin >> password;
    std::cout << "Your password is : " << password << std::endl;
    if(checkPassword(password)) {
      std::cout << "VALID" << std::endl << std::endl;
    } else {
      std::cout << "INVALID" << std::endl << std::endl;
    }
  }
  return 0;
}

This will work with passwords of any length.
Set lookups have logarithmic complexity, so checking a password of length \$n\$ given a character set of size \$m\$ should be \$\mathcal O(n\cdot \log(m))\$.


Unit tests for methods that access the file system

Another approach is to use a wrapper for the DirectoryInfo, FileInfo and FileStream.  Then your methods can use the wrappers and inject your mocks in the unit tests. Several people have already thought of this and have written the wrappers for you.

The one I like is SystemWrapper. Their sample page shows some good examples.

Of course, you still have the challenge of refactoring your code to inject the wrappers into your method, since creating a new instance of the wrappers within the code leaves you the same problem.  The simpliest approach to injecting wrappers is to pass them in as parameters.  But, since the constructor of the wrappers needs information obtained within the method this is more difficult in your case.  You may consider breaking your method into several methods in a manner such as this...

NOTE:  This code will not compile.  I am just trying to give you an idea of how to break up the method to make it unit testable.  In the end, every method cannot be unit tested.  The key is to break it up into small enough methods so as much code as possible is tested.

public IDirectoryInfoWrap GetDirectoryInfoWrapper(string product)
{
    if(string.IsNullOrEmpty(product))
    {
        throw new ArgumentNullException("product");
    }

    string profileDirectory = _factory.GetCustomProfileDirectory(product);
    return new DirectoryInfoWrap(profileDirectory);
}

public IList<FileInfo> GetProfileFiles(IDirectoryInfoWrap di)
{
    _logger.Debug("Getting Saved profiles.");

    // NOTE:  EnumerateFiles is not in the SystemWrapper so you will have to use an alternative
    IList<FileInfo> files = di.EnumerateFiles("*.ecu").ToList();
    return files;
 }

// Left for you to do...refactor in a manner so that FileSystem is using the IFileSystemWrap
public IEnumerable<ConfigProfile> GetSavedProfiles(IList<FileInfo> files)
{
    List<ConfigProfile> profiles = Enumerable.Empty<ConfigProfile>().ToList();
    if (!files.Any())
    {
        _logger.Debug(string.Format("No custom profiles found for {0}.", product));
        return profiles;
    }

    profiles.AddRange(files.Select(LoadProfile));

    return profiles;

}


Code review:
1. Your code has a bug here for i in 1..n,
the correct version starts from zero: for i in 0..n,
Change your main to the following code and then cargo run:

fn main() {
    let mut xs = vec![
        8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,
        9, 18, 0, 18, 1, 8, 10,
    ];
    let mut v = xs.clone();
    v.sort();
    quick_sort(&mut xs);
    assert_eq!(v, xs);
}

You will see this error:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[0, 1, 2, 4, 4, 6, 6, 6, 7, 8, 8, 8, 9, 9, 10, 10, 13, 13, 13, 14, 14, 16, 17, 18, 18, 18, 19, 20, 20, 21, 23, 24]`,
 right: `[0, 1, 2, 4, 6, 6, 7, 6, 8, 4, 8, 9, 9, 10, 10, 8, 13, 13, 14, 14, 16, 17, 18, 18, 18, 19, 20, 20, 13, 23, 24, 21]`', src/main.rs:25:5

Rename i_pivot to j, since it is just an index and your pivot is a[n - 1].
Change if n > 0 to if n > 1 since the slice length should be at least two.
You don't need Ord here, PartialOrd is enough (try it here):

fn quick_sort<T: PartialOrd>(a: &mut [T]) {
    let n = a.len();
    if n > 1 {
        let mut j = 0;
        for i in 0..n {
            if &a[i] < &a[n - 1] {
                a.swap(i, j);
                j += 1;
            }
        }
        a.swap(j, n - 1); // pivot
        quick_sort(&mut a[0..j]);
        quick_sort(&mut a[j + 1..n]);
    }
}

fn main() {
    let mut xs = vec![
        8, 13, 20, 13, 4, 21, 24, 13, 18, 23, 14, 6, 10, 2, 4, 6, 16, 6, 17, 9, 8, 20, 14, 19, 7,
        9, 18, 0, 18, 1, 8, 10,
    ];
    let mut v = xs.clone();
    v.sort();
    quick_sort(&mut xs);
    assert_eq!(v, xs);
}


Drawing stars around the center of the screen

It would be user friendly and make testing easier if the program accepted the input number as a command line argument too, for example:

import sys

def main():
    if sys.argv[1:]:
        num = int(sys.argv[1])
        if not is_valid_number(num):
            warn_invalid_number()
            sys.exit(1)
    else:
        num = prompt_valid_number()

    draw_stars_in_a_spiral(num)

if __name__ == '__main__':
    main()

While doing this, to avoid code duplication, I split the original functionality to multiple functions, which is a good practice in general anyway.

For validating the number, the N < var < M operator of Python is very handy:

def is_valid_number(num):
    return 1 < num < 20

Then the warning and prompting functions:

def warn_invalid_number():
    print("Number must between 2 to 19 (inclusive)")

def prompt_number():
    return int(input("Enter a number: "))

When prompting the user until he gives a valid number, change to a while True loop to avoid the duplication when asking for a number:

def prompt_valid_number():
    while True:
        num = prompt_number()
        if is_valid_number(num):
            return num
        warn_invalid_number()

Finally, the main method to draw the stars:

def draw_stars_in_a_spiral(num):
    window = turtle.Screen()
    window.screensize(1200, 1200)

    draw = turtle.Turtle()
    draw.pensize(2)

    draw.speed('fastest')

    for _ in range(num):
        for angle in angles:
            draw.left(angle)
            draw.forward(180)
        draw.penup()
        draw.forward(60)
        draw.pendown()
        draw.left(170)

Some points to note:

I moved all the drawing operations here. If validation fails when invoking with command line parameters, there's no need to open a window and draw anything.
I replaced the unused shape variable in for shape in range(num) with _
I replaced the angle array with angles to be more intuitive, and the loop variable i with the more intuitive name angle


wait for the UI thread to complete or cancel the wait

Is there any reason you don't just use the cancellation token to stop the thread? I'm also wondering why you're using an explicit thread at all. This is asynchronous programming the hard way. async-await and Tasks are the idiomatic way to do this for the last several versions of the language & framework.

I'm imagining your code looking something like this. (Totally untested. Might not compile.)

public static void Main()
{
    var cts = new CancellationTokenSource();
    var token = cts.Token;

    Task.Run(()=>
    {
        while (!Console.KeyAvailable)
        {
            if (token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
            }

            await Task.Delay(50);
        }

        token.Cancel();
     }, token);

     Console.WriteLine("Press Any Key or don't...");

     await Task.Delay(50000, token);
     token.Cancel(); //task is still running, best to shut it down too
 }


Switching between queues in cellForIndexPath method

This is not a good solution to handle fetch requests inside scrolling cellForIndexPath.

1 Fetch request should be asynchronous, because it may take time
2 Fetch request should be called in table view datasource and not in custom cell, because cell can be reused while scrolling
3 Should apply result of fetch request if cell is visible

Code in class where UITablView datasource is implemented-

func getColor(forGroup: Int, completion: @escaping (color: UIColor) -> Void) {
  //fetch request
  //request processing...
  completion(resultColor)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! CustomCell
  let myObject = //object for indexpath
  cell.configureWith(myObject: myObject)
  self.getColor(forGroup: myObject.group) { (color) in
    DispatchQueue.main.async {
      if let cell = tableView.cellForRow(at: indexPath) {
        //this unwrapping is needed as tableview returns nil if cell is not visible
        cell.colorLable(color)
    }
  }
}

In CustomCell file:

func configureWith(myObject: MyObject) {
  titleLabel.text = myObject.text
}
func colorLable(_ color: UIColor) {
  self.titleLabel.textColor = color
}


You could get slightly closer with the [] command pair.

It's actually quite trivial:

Add an indexer to your brainfuck class (public void this[Action bf]) and put your while loop in there.

The indexer would look like:

public brainfuck this[Action action]
{
    get
    {
        while (this)
        {
            action.Invoke();
        }

        return this;
    }
}

You would call it as:

_ = _[() => {
    _ =     + + + + +    + +       (_ > 1)              ; // add 7 to #1
    _ =     + + + + +    + + + + + (_ > 1)              ; // add 10 to #2
    _ =     + + +                  (_ > 1)              ; // add 3 to #3
    _ =     +                      (_ > 1)              ; // add 1 to #4

    _ =     -                      (_ < 1 < 1 < 1 < 1)  ; // decrement 0
}];

Is it a pain in the rear to use? Yes. Is it in the Brainfuck spirit? Yes.

It's still not true brainfuck syntax, but you won't get there with C#.

After that, you have a real mess here that needs cleaned.

First: capitalization. In C# we PascalCase public members and types (and all methods), and camelCase private and local members and types.

public class Brainfuck
private bool HasData()

Since "Brainfuck" is one word, the "F" in "fuck" is not capitalized.

The optional argument defaults in operator > and operator < are not at all going to work, remove them.

public static brainfuck operator > (brainfuck bf, int pos)
{
    bf.right();
    return bf;
}
public static brainfuck operator < (brainfuck bf, int pos)
{
    bf.left();
    return bf;
}

Always use braces, even when you don't need them.

private void Right()
{
    if (currentCell + 1 == cells.Count)
    {
        cells.Add(0);
    }

    currentCell++;
}

Use int instead of Int32 everywhere.

int value = int.TryParse(input, out value) ? value : 0;

Once we apply all these changes, fix some spacing, we end up with a not-so-bad looking class:

public class Brainfuck
{
    private List<int> cells;
    private int currentCell;

    public Brainfuck()
    {
        cells = new List<int>{0};
    }

    public Brainfuck this[Action action]
    {
        get
        {
            while (this)
            {
                action.Invoke();
            }

            return this;
        }
    }

    public static Brainfuck operator + (Brainfuck bf)
    {
        bf.Plus();
        return bf;
    }

    public static Brainfuck operator - (Brainfuck bf)
    {
        bf.Minus();
        return bf;
    }

    public static Brainfuck operator > (Brainfuck bf, int pos)
    {
        bf.Right();
        return bf;
    }

    public static Brainfuck operator < (Brainfuck bf, int pos)
    {
        bf.Left();
        return bf;
    }

    public static Brainfuck operator ~ (Brainfuck bf)
    {
        bf.Write();
        return bf;
    }

    public static Brainfuck operator ! (Brainfuck bf)
    {
        bf.Read();
        return bf;
    }

    public static implicit operator bool (Brainfuck bf)
    {
        return bf.HasData();
    }

    private int Plus()
    {
        return ++cells[currentCell];
    }

    private int Minus()
    {
        return --cells[currentCell];
    }

    private void Right()
    {
        if (currentCell + 1 == cells.Count)
        {
            cells.Add(0);
        }

        currentCell++;
    }

    private void Left()
    {
        if (currentCell > 0)
        {
            currentCell--;
        }
    }

    private int Current()
    {
        return cells[currentCell];
    }

    private void Write()
    {
        Console.Write((char)Current());
    }

    private void Read()
    {
        var input = Console.ReadLine();
        int value = int.TryParse(input, out value) ? value : 0;
        Current(value);
    }

    private bool HasData()
    {
        return Current() > 0;
    }

    private void Current(int value)
    {
        cells[currentCell] = value;
    }

    public override string ToString()
    {
        return String.Join(",",cells);
    }
}

And our code for the "Hello World" looks like:

void Main()
{
    /*
    *   Write `Hello World!`
    *           using operators overloading for brainfuck symbols
    */
    var _ = new Brainfuck();

    _ = + + + + +    + + + + +     _        ; // set cell #0 to 10

    _ = _[() => {
        _ =     + + + + +    + +       (_ > 1)              ; // add 7 to #1
        _ =     + + + + +    + + + + + (_ > 1)              ; // add 10 to #2
        _ =     + + +                  (_ > 1)              ; // add 3 to #3
        _ =     +                      (_ > 1)              ; // add 1 to #4

        _ =     -                      (_ < 1 < 1 < 1 < 1)  ; // decrement 0
    }];
    _ =     ~   + +                    (_ > 1)              ; // write 'H'
    _ =     ~   +                      (_ > 1)              ; // write 'e'
    _ =     ~   + + + + +    + +        _                   ; //write 'l'
    _ =     ~                           _                   ; //write 'l'
    _ =     ~   + + +                   _                   ; // write 'o'
    _ =     ~   + +                     (_ > 1)             ; // write ' '
    _ =     ~   + + + + +    + + + + +   + + + + +      (_ < 1 < 1)     ; // write 'W'
    _ =     ~                           (_ > 1)             ; // write 'o'
    _ =     ~   + + +                   _               ; // write 'r'
    _ =     ~   - - - - -    -          _               ; // write 'l'
    _ =     ~   - - - - -    - - -      _               ; // write 'd'
    _ =     ~   +                       (_ > 1)         ; // write '!'
    _ =     ~                           (_ > 1)         ; // write '\n'
}

Overall, not too bad. I wouldn't have done it, but that's because I wrote a Brainfuck to C# transpiler. Good work. :)


Style

In Python, there is usual style guide called PEP8 : I think you should follow it to make your code more consistent with all the Python code out in the wild out there. If you want to, you'll find various tools to help you check your Python code : pep8, pycheck, pylint, pyflakes.

Global variables

The fact that you are using a global variable is a good hint that your are probably doing something wrong. It makes your code harder to track but also harder to test and to benchmark.

Also, your should be moving your code which actually performs computations behing an if __name__ == "__main__": : this allows one to easily find where stuff are triggered in your code but also and more importantly to be able to re-use your code by importing your project without re-launching all the computations you might not care about while solving a different project euler problem.

At this point, your code looks like :

import math

def is_prime(n, dict_primes):
    if n in dict_primes:
        return dict_primes[n]

    for num in range(2, math.floor(math.sqrt(n)+1)):
        if n % num == 0:
            dict_primes[n] = False
            return False
    dict_primes[n] = True
    return True

def main():
    """Main function"""
    print("Hello, world!")
    count = 0
    dict_primes = {}

    for num in range (2, 1000000):
        q = False
        num = str(num)
        for i in range(len(num)):
            if is_prime(int(num[i:]+num[:i]), dict_primes):
                q = True
            else:
                q = False
                break
        if q:
            count += 1
    print (count)

if __name__ == "__main__":
    main()

Optimisations : different algorithm

You are using some kind of cache to remember the different numbers you've checked and this is a good idea. Also, you are using a quite efficient way to check if a single number is prime, stopping at sqrt(n) + 1.
However, the best way to do this would probably be to implement a Sieve of Eratosthenes : we build it once and for all and we don't need to compute things later on. This is especially convenient here because we know that we will not need to check for any number bigger than one million.

This is already much faster :

import math

def sieve(limit):
    primes = [True] * limit
    primes[0] = primes[1] = False
    for i in range(2, math.floor(math.sqrt(limit))):
        if primes[i]:
            for j in range(i*i, limit, i):
                primes[j] = False
    return primes

def main():
    """Main function"""
    print("Hello, world!")
    limit = 1000000
    count = 0

    primes = sieve(limit)
    for num in range (2, limit):
        q = False
        num = str(num)
        for i in range(len(num)):
            if primes[int(num[i:]+num[:i])]:
                q = True
            else:
                q = False
                break
        if q:
            count += 1
    print (count)

if __name__ == "__main__":
    main()

Details

At the moment, you are using q to store whether all permutations of num where prime numbers so far. It might be interesting to point out that in Python, you can add an else to loops signifying that that was no break in the loop. Thus, you could write something like :

    for i in range(len(num)):
        if not primes[int(num[i:]+num[:i])]:
            break
    else:
        count += 1

Alternatively, you could use the all function to write it in a clean and concise way :

    if all(primes[int(num[i:]+num[:i])] for i in range(len(num))):
        count += 1

Another optimisation

I haven't checked that this really makes the code faster but let's assume that 193939 and all its permutations are prime. Instead of checking all permutations for each permuation and adding one each time every thing is fine, we could only check that we are considering the smallest permutation and add the number of permutations directly. This would look like :

   perm = {int(num_s[i:]+num_s[:i]) for i in range(len(num_s))}
    if all(n >= num and primes[n] for n in perm):
        count += len(perm)

(Please note that I have used a set as I don't want 11 for instance to be counted multiple times just because it is its own permutation).

Another optimisation

If all permutations are supposed to be primes : we know that the first itself must be prime : we can get rid of even numbers : for num in range(3, limit, 2): (you have to initialise count with 1 to count 2).

Also, we know that no even numbers must be in the string : you can add : odd_numbers = {1, 3, 5, 7, 9} out of the loops and if {int(n) for n in num_s}.issubset(odd_numbers): in the loop.

Similarly, 5 can be excluded from the list of allowed numbers as anything ending with 5 with be a multiple of 5 : you can change odd_numbers for final_numbers = {1, 3, 7, 9} and start counting from 2.

Again, this is not benchmarked but you can give it a try if you want.

And now for something different

Instead of going through all numbers and checking conditions that will most of the time not be true, you can use the fact that you already know that for numbers bigger than 9, only {1, 3, 7, 9} are allowed. Thus, you could try to go through the carthesian product of theses numbers using itertool.product.

When considering numbers with n digits, you'll only consider 4**n numbers instead of 10**n (when n = 6 for instance, it makes the difference between 4096 and 100000).

Once this is done, you can even afford to check for much bigger numbers :

def main():
    """Main function"""
    print("Hello, world!")
    count = 4
    nb_digits = 8
    primes = sieve(10**nb_digits)
    final_numbers = {'1', '3', '7', '9'}
    for l in range(2, nb_digits+1):
        for p in itertools.product(final_numbers, repeat=l):
            p_int = int(''.join(p))
            perm = {int(''.join(p[i:]+p[:i])) for i in range(len(p))}
            if p_int == min(perm) and all(primes[n] for n in perm):
                print(p, len(perm))
                count += len(perm)
    print (count)

This code checks for numbers of 8 digits by doing 13939 prime checks. Thus, it is not worth using the Eratosthene sieves anymore.

Using your initial code with no cache, we can achieve great performances :

def is_prime(n):
    for num in range(2,math.floor(math.sqrt(n)+1)):
        if n%num == 0:
            return False
    return True

def main():
    """Main function"""
    print("Hello, world!")
    count = 4
    nb_digits = 9
    final_numbers = {'1', '3', '7', '9'}
    for l in range(2, nb_digits+1):
        for p in itertools.product(final_numbers, repeat=l):
            p_int = int(''.join(p))
            perm = {int(''.join(p[i:]+p[:i])) for i in range(len(p))}
            if p_int == min(perm) and all(is_prime(n) for n in perm):
                print(p, len(perm))
                count += len(perm)
    print (count)


Static site generator using JavaScript Promises

First thing that bother me is why let SSG? Why is it an object? If you're using ES6+ (as you do), I'd go with making this a class. It's more obvious and more readable. Note that while doing this, you'll have to alter the function signature, i.e. generateHtmlFile: async function (file) { ... } becomes async generateHtmlFile(file) { ... }.

Since you have folder names stored as a properties of your object (outputFolder, contentFolder and assetsFolder), they should be moved now to the constructor. There is also a good candidate for another new property on line 51: ../templates/ should be also extracted. This is because there are no properties in JS class ATM. Also, while we're on the topic of class properties, I'd suggest that you should pass an object with folder names as a constructor argument. That way you can easily change the folders you're using by just instantiating an object with another folder names. When we sum up the info about properties, here's what it should look like:

class SGG {
  constructor(folders = {}) {
    this.outputFolder = folders.outputFolder || '../output/'
    this.contentFolder = folders.contentFolder || '../content/'
    this.assetsFolder = folders.assetsFolder || '../assets/'
    this.templates = folders.templates || '../templates/'
  }
}

The second thing that I didn't notice when I looked at the code here is that you have a some implicit variables: files on line 19 and it on line 45. So just add const in front of those two and you'll be fine.

At line 49, there is a require. I'd move it to the top of the file because that way you know right on what are the dependencies of your file. And it's more cleaner code without some unexpected turns.

Now, to the methods. First one is contentFiles which is just a recursive call to find out all the files in a contentFolder directory. I see that you are probably confused with promises because you use async and new Promise in the same function. When making function an async, you should know that whatever you return from the function, it will be wrapped inside a promise and it also gives you the ability to use await inside it. But since you don't have await here, then there is no need for making this function an async one. You are already returning a promise. But, I think that you don't need a promise at all! You are using these fs-extra methods that are not returning a promise nor have a callback, so they are perfectly synchronous functions. Also, the .forEach got all of this tangled a bit, so if you remove it and use for..of, you can untangle yourself and get a cleaner code.

The next method, generateHTMLFile has similar issue with promises as the one above. From ejs' github, I noticed that if you don't pass the callback function, it will return a promise. So what should be done here is to remove new Promise... thing and keep async and rewrite the ejs.renderFiles not to use the callback function.

The method saveHTML is confusing a bit: you're using sync methods everywhere, but here you decided to go with mkdir instead of mkdirSync or writeFileSync.

Once you apply all of what I've said, you should get something like this:

const yaml = require('js-yaml');
const fs = require('fs-extra');
const ejs = require('ejs');
const md = require('markdown-it')({
    html: true,
    linkify: true,
    typographer: true,
});
const funs = require('./functions.js');

class SSG {
    constructor(folders = {}) {
        this.outputFolder = folders.output || '../output/'
        this.contentFolder = folders.contentFolder || '../content/'
        this.assetsFolder = folders.assetsFolder || '../assets/'
        this.templateFolder = folders.templateFolder || '../templates/'
    }

    contentFiles(dir, filelist) {
        const files = fs.readdirSync(dir)
        filelist = filelist || []
        for (const file of files) {
            if (fs.statSync(dir + '/' + file).isDirectory()) {
                contentFiles(dir + '/' + file, filelist)
            } else {
                filelist.push(file)
            }
        }
        return filelist
    }

    async generateHTMLFile(file) {
        const fstream = fs.readFileSync(file, 'utf8');
        let params = fstream.match(/\+Params\+([\s\S]*?)\+\+\+/g);
        let content = fstream.match(/(\+Content[0-9]*\+|\+Content\+)([\s\S]*?)*(\+\+\+)/g);
        let contents = [];

        params = params[0].replace('+Params+', '').replace('+++', '');
        content = content[0].split('+++');

        try {
            params = yaml.safeLoad(params, 'utf8');
            for (let it of content) {
                it = it.replace('+++', '').replace(/(\+Content[0-9]*\+|\+Content\+)/g, '');
                contents.push(md.render(it));
            }

             const html = await ejs.renderFile(this.templateFolder + params.template + '.ejs', {
                funs: funs,
                params: params,
                content: contents,
            }, {})

            return {
                html,
                url: params.url,
            }

        } catch (e) {
            console.log(e);
        }
    }

    async saveHTML(html, url) {
        if (!fs.existsSync(this.outputFolder)) {
            await fs.mkdirSync(this.outputFolder, {recursive: true});
        }
        await fs.writeFileSync(this.outputFolder + url + '.html', html);
    }

    saveStaticAssets() {
        fs.copySync(this.assetsFolder, this.outputFolder);
    }

    async start() {
        try {
            let time = Date.now();
            console.log('Génération des fichiers HTML...');

            const files = this.contentFiles(this.contentFolder);

            for (const file of files) {
                await this.generateHTMLFile(this.contentFolder + file).then(({html, url}) => {
                    this.saveHTML(html, url);
                });
            }

            this.saveStaticAssets();

            console.log('Généré en ' + (Date.now() - time) + 'ms');
        } catch (e) {
            console.error(e.message);
        }
    }
};

(async () => {
    const ssg = new SSG()
    await ssg.start();
})();

Last note that I'd like to make is that Node already has a pretty decent file system utilities. The only thing that I've noticed that is different from fs-extra is that sync functions do not return promises, but they rather act as a regular functions. Anyhow, I'd argue that you don't need fs-extra and use fs instead. But it's up to you.

I maybe missed something or maybe got into details and nitpicking more than needed, but this is a basic refactor that I would do to your code. I hope that I didn't break some things while doing this :)

Edit:
While looking at the code for the second time, I noticed that I've missed this line in start:

await this.generateHTMLFile(this.contentFolder + file).then(({html, url}) => {
    this.saveHTML(html, url);
});`

It's maybe just me, but I don't like this mixture of await and then.
I'd just suggest that if you're going with await, keep it that way.
My suggestion here would be to go with something like this:

const {html, url} = await this.generateHTMLFile(this.contentFolder + file)
await this.saveHTML(html, url)

I've also just noticed that you can optimize the solution for speed by awaiting on multiple promises:

await Promise.all(files.map(async (file) => {
    const {html, url} = await this.generateHTMLFile(this.contentFolder + file)
    await this.saveHTML(html, url)
}))

This way you start multiple promises in parallel (again, not a true parallelization since JS is single threaded) and await on all of them to finish before moving on. This way you'll get a bit faster execution. Note that if one promise throws and error, this line will also throw an error before waiting on the other promises to end.


Care to review my immutable singly linked list?

The constructor with one argument is never used and doesn't make much sense (list with a head but no tail?).
You shouldn't use Count in your own methods unless absolutely necessary, because it's O(n). Or you should cache the result in a field.
Because you use Count so often, your Insert() walks through the whole list three times! The second time it's because of completely unnecessary Count. You should completely rewrite it, Insert() can be done in O(index), which can be much better than your O(n).


It looks fine. Some readability improvements:

I'd rename some variables first:

mismatches should be tolerance, mismatchTolerance or allowedMismatches. For me mismatches sounds like a counter but it never changes which is confusing somehow.
iter and ator do not make the code easier to read. textIndex (maybe searchIndex) and patternIndex would be better since they are more meaningful and explains the purpose.

Then extract out some named variables like

final int textIndexMax = text.length() - pattern.length() + 1;
final char textChar = text.charAt(textIndex + patternIndex);
final char patternChar = pattern.charAt(patternIndex);
final String match = text.substring(textIndex, textIndex + pattern.length());

Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler

  Put the result of the expression, or parts of the expression,
  in a temporary variable with a name that explains the purpose.

The condition of the do-while loop could be rewritten as a usual (and a not so complex, therefore an easier to understand and less error-prone) for (i = 0; i < x; i++) loop and a break statement.

Here is my version:

final int mismatchTolerance = 1;
final String text = "bubbles";
final String pattern = "bu";

final int textIndexMax = text.length() - pattern.length() + 1;
for (int textIndex = 0; textIndex < textIndexMax; textIndex++) {
    int missed = 0;

    for (int patternIndex = 0; patternIndex < pattern.length(); patternIndex++) {
        final char textChar = text.charAt(textIndex + patternIndex);
        final char patternChar = pattern.charAt(patternIndex);
        if (textChar != patternChar) {
            missed++;
        }
        if (missed > mismatchTolerance) {
            break;
        }
    }

    if (missed <= mismatchTolerance) {
        final String match = text.substring(textIndex, textIndex + pattern.length());
        System.out.println("Index: " + textIndex + " Match: " + match);
    }
}


Project Euler # 29: Distinct powers in Python

Your docstring is misleading.

The function does not return a sequence; it returns a generator.
It states “for a and b in range(n)”, which is incorrect.  They are in range(2, n+1).  If you don’t want to confuse the issue with range() excluding the last value, say “for a and b in the range from 2 to n, inclusive”.
The problem refers to a “sequence”, where the values are in ascending order and duplicates have been removed, which is completely different from the sequence of values produced by the generator, which is not sorted and can have duplicates.

time1 is a terrible variable name; there is no time2.  Perhaps use start_time.

print((len(...))) has an unnecessary extra pair of parenthesis.

Is distinct_terms(n) too specific of a function?  Perhaps distinct_terms(m, n) could be more general, where you can generate terms for m <= a,b <= n, instead of always the lower limit of m=2.  Or with separate limits for the a and b values.

Python is an easy language to solve this problem in, because \$100^{100}\$ is just another integer in Python, despite having 201 digits.  If you were to solve this in another programming language, one where integers were restricted to (say) 128 bits, what would you do?

With 99 different values for a and b, you have \$99^2 = 9801\$ different \$a^b\$ expressions.  How many of those will be equivalent?  Ie, \$a^b = c^d\$?  For example, \$2^4 = 2^{2*2} = {(2^2)}^2 = 4^2\$.  Can you generalize that?  Can you count the number of occurrences where that happens, and subtract that from 9801?


I'd highly suggest learning comprehensions. The simplest is a list comprehension. This allows you to change say:

list = []
for x in string:
    list.append(dic[x])

To:

list = [dic[x] for x in string]

However, you can get better memory usage by using a generator comprehension, this works in roughly the same way as a list, however you can't index it. Which for this code is fine. To do this replace the square brackets with curved ones:

gen = (dic[x] for x in string)

You can also use a dictionary comprehension to simplify your creation of dic2:

dic2 = {v: k for k, v in dic.items()}

Purge all memory of eval, it leads to poor code and has severe security vulnerabilities. Instead cast the users input to an int. This can simplify decoding too. However you have to make sure the user does actually enter a number.

I don't like list = [] being outside the if statement. There's not much of a need for this. However it's fixed when using comprehensions.

I also think you should use while True rather than while program:. As you never change program.

Merging this all together gets you:

dic = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25, " ": 26}
dic2 = {v: k for k, v in dic.items()}

while True:
    task = input("Would you like to encode or decode?: ").lower()
    if task == "encode":
        string = input("What would you like to encode?: ").upper()
        while True:
            try:
                key = int(input("What key would you like to use?: "))
                break
            except ValueError:
                pass
        list = (dic[x] for x in string)
        encodeNums = ((x + key) % 27 for x in list)
        encodeStr = (dic2[x] for x in encodeNums)
        print("".join(encodeStr))

Going forward, I'd change your code to encode and decode with the same code. This is as the Caesar cipher is a symmetric cypher, so simply using key = -key allows you to decode the encoding.

Allowing:

dic = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25, " ": 26}
dic2 = {v: k for k, v in dic.items()}

while True:
    string = input("What would you like cypher?: ").upper()
    task = input("Would you like to encode or decode?: ").lower()
    while True:
        try:
            key = int(input("What key would you like to use?: "))
            break
        except ValueError:
            pass
    if task == "decode":
        key = -key

    list = (dic[x] for x in string)
    encodeNums = ((x + key) % 27 for x in list)
    encodeStr = (dic2[x] for x in encodeNums)
    print("".join(encodeStr))


Calculate the statistical mean of different files and save it into a CSV file

As the code cannot be run, here is a wild guess on a way to restructure it:

def mean(fileResults, data):
    result = 0
    # do computation
    fileResults["mean"].append(result)

def standard_deviation(fileResults, data):
    pass

def afd(fileResults, data):
    pass

def norma_afd(fileResults, data):
    pass

def asd(fileResults, data):
    pass

def norma_asd(fileResults, data):
    pass

def calculation(file):
    """
    Get the DataFrame and calculate for ever column the different statistical mean
    :param file: DataFrame 56x7681
    :return: 6 different 56x1 lists for (mean, std, afd, norm_afd, asd, norm_asd)
    """
    fileResults = {
        "mean": [],
        "std": [],
        "afd": [],
        "norm_afd": [],
        "asd": [],
        "norm_asd": [],
        }

    functionCallList = [
        mean,
        standard_deviation,
        afd,
        norma_afd,
        asd,
        norma_asd,
        ]

    for column in file:
        data = file[column].to_numpy()

        for functionCall in functionCallList:
            functionCall(fileResults, data)

    return fileResults

def run(load_path, save_path):
    """
    Get (yield) all the different DataFrame from a folder
    and calculate for each file the statistical mean and save it in a csv file

    :param load_path: the folder path to load all the different files
    :param save_path: the folder save path
    :return: none
    """
    results = {}

    for current_path, file in yield_data(load_path, data_type="data"):
        fileResults = calculation(file)

        for key, value in fileResults.items():
            if key not in results:
                results[key] = []

            results[key].append(value)

    if not os.path.exists(save_path):
        os.makedirs(save_path)

    for key, value in results.items():
        pd.DataFrame(value).to_csv(save_path + os.path.sep + key + ".csv", index=False, header=False)

So, instead of repeating function call, mostly when function prototypes are the same, you can use a list of function callbacks. Then just iterate it.

You can also use a dictionnary to store your data, instead of n lists. It's a little bit more scalable, and clearer than returning a 6-tuple. It also avoids a lot of copy-paste when you save csv files.


Improving iterative manipulation on XML elements

Let us say you have a node like this which is having two nodes , node1 and node 2, you need to specify xpath using "|" seperated . here is an example .

XPathSelectElement should be replaced with XPathSelectElements.

<?xml version="1.0" encoding="utf-8" ?>
<customer>
  <node1>
  </node1>
  <node2>
  </node2>
</customer>

//all you need sepcify is a "|" to work it out.
doc.XPathSelectElements("//node1 | //node2").Remove();


Customizing output in accordance to the input

Let's start off with a few general hints and tips:

First of all, as πάντα ῥεῖ already stated in the comments, using using namespace std is not a good idea, and doing that in a header if a lot worse. You're begging to introduce subtle bugs into your code as time goes on and things are added to your project and the standard libraries. Typing std:: a few times is not going to kill you, I'm sure.
#include"..\..\Header.h" is a code smell; relative paths in an include often indicate that your project structure is not good or your compile flags are not complete. You should specify all necessary include directories in the compiler invocation command line.
system("pause"); is not portable and should thus not be used unless absolutely necessary. Is this the case here? I don't think so. Make users of other operating systems (i.e. operating systems that aren't Microsoft Windows) happy and remove that line.
What happens if I enter the string "0" to your program? Whoops, undefined behavior! Why? if (da[1] == 'x') requires da to be at least two characters long, which in my case it simply doesn't happen to be. You should add a check to verify that this condition is satisfied.
Header.h seems redundant and superfluous. All of those includes should be at the top of your implementation file, not in the header. All includes that are not used (e.g. fstream) should be removed. The function error doesn't serve any real purpose, except obscuring the fact that something throws and exception, which can lead to people wondering where those exceptions come from. Also it isn't used, so it should be removed as well.

Now, let's talk about print_number in particular. One issue I have with this function is that type should never, ever be a string. You're wasting performance and causing binary bloat, when the fix would be to simply add an enum class with three members HEX, OCT and DEC. The other big issue is that this function limits its own usability by necessarily writing to std::cout. This has the potential to cause people using that function and wanting to separate outputs much grief, and is easily circumvented by having the function take a std::ostream& as parameter and writing to it instead. When invoking the function, you then simply pass std::cout as an argument.

Finally, this function does a little bit too much; two completely separate tasks, to be precise. One is taking a number in a given format and converting it to decimal, and the other is actually printing that number in a nicely formatted way. You should thus split it up into two functions: One which does the extraction, and one which does the output.


Here is how i'd approach it

// Make all those units constants
var SECOND = 1000;
var MINUTE = SECOND * 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
var YEAR = DAY * 365;

// store the string variations in a table, seperate from the code
TIMES = [
    {min: 0, text: "right now", unit: SECOND},
    {min: 2 * SECOND, text: "@ seconds ago", unit: SECOND},
    {min: MINUTE, text: "about 1 minute ago", unit: MINUTE},
    {min: 2 * MINUTE, text: "@ minutes ago", unit: MINUTE},
    {min: HOUR, text: "about 1 hour ago", unit: HOUR},
    {min: 2 * HOUR, text: "@ hours ago", unit: HOUR},
    {min: DAY, text: "yesterday", unit: DAY},
    {min: 2 * DAY, text: "@ days ago", unit: DAY},
    {min: YEAR, text: "over a year ago", unit: YEAR}
];

// use the table to generate the date
function timeAgoText(diff) {
    var use;
    for(var index = 0, length = TIMES.length; index < length; index++)
    {
        if( TIMES[index].min < diff )
        {
            use = TIMES[index];
        }
    }
    units = Math.floor(diff / use.unit)
    return use.text.replace("@", units)
}

function timeAgo(dateText)
{
   var then = new Date(dateString);
   if ($.browser.msie) {
      then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
   }
   var diff = new Date() - then;
   if( isNaN(diff) || diff < 0 )
   {
       return ""
   }
   else
   {
       // seperate the time check and the text generation
       return {
           tAgo: timeAgoText(diff),
           timeCheck: diff > HOUR * 2
       }
   }
}


Strings are immutable so whenever you're concatenating them you're effectively creating new instances every time, this can slow down performance a lot, instead use StringBuilder and it's method Append() to build strings.
Avoid duplicate operations per each cycle unless it's necessary, such as Convert.ToInt32(textBox1.Text) convert the value to int before the for loop and save the value in variable, than later use the variable instead of converting the value every time. Another example is comboBox1.SelectedItem.ToString().