Copy and in-place transformation of strings to lowercase/uppercase

What you can do is combine the two methods toLower and toUpper into one method, say transform, to which you pass the method by which to transform (std::tolower or std::toupper) as arguments. The same can be done for toUpperCopy and toLowerCopy. Passing functions allows you to be more flexible as you are now able to not only use std::tolower and std::toupper but also any other function which transforms a character.

You can combine everything into one method and use something like a boolean parameter to tell if it should copy or not but I would advise against it. The functions are short functions so they will still be readable and you keep the responsibility for copying in a separate function.

Passing the functions would look something like this:

namespace ae
{
    template <typename charT>
    auto transform(std::basic_string<charT>& str, charT charMap(charT, const std::locale&))
    {
        std::transform(str.begin(), str.end(), str.begin(), [&charMap](const auto& c)
        {
            static const auto loc{ std::locale() };
            return charMap(c, loc);
        });
    }

    template <typename charT>
    auto transformCopy(std::basic_string<charT>& str, charT charMap(charT, const std::locale&))
    {
        auto newStr{ str };
        std::transform(str.begin(), str.end(), newStr.begin(), [&charMap](const auto& c)
        {
            static const auto loc{ std::locale() };
            return charMap(c, loc);
        });
        return newStr;
    }
}

int main()
{
    std::wstring my_str{ L"Test" };
    ae::transform(my_str, std::tolower);
    std::wcout << my_str << std::endl;

    std::string my_str2{ "This is a test aswell" };
    auto new_str{ ae::transformCopy(my_str2, std::toupper) };
    std::cout << new_str << std::endl;

    return 0;
}

Note that I changed the template variable from StrT to charT as the charT was needed for the charMap. Using both StrT and charT, the compiler was not able to infer the template argument for charT so you had to manually add the template arguments each time you called ae::transform.


Improve this numeric solver for properties of geometric objects

A few suggestions on the first code fragment:

Change type names to upper case
Change record field names to upper case
Change fields of line to Begin and End to be descriptive
Use pattern matching on records instead of . access

The updated code fragment is as follows:

type Parameter =
    | Fixed of double
    | Free of double ref

let free v = Free (ref v)
let fix v = Fixed v

type Point  = { X: Parameter; Y: Parameter }
type Line   = { Begin: Point; End: Point }
type Circle = { Center: Point; Radius: Parameter }

type Shape =
    | Parameter of Parameter
    | Point of Point
    | Line of Line
    | Circle of Circle

let rec freeVars v = seq {
    match v with
    | Parameter p ->
        match p with
        | Free v -> yield v
        | _ -> ()
    | Point {X = x; Y = y} ->
        yield! Parameter x |> freeVars
        yield! Parameter y |> freeVars
    | Line {Begin = p0; End = p1} ->
        yield! Point p0 |> freeVars
        yield! Point p1 |> freeVars
    | Circle {Center = c; Radius = r} ->
        yield! Point c |> freeVars
        yield! Parameter r |> freeVars
    }

And here are comments on the second code fragment.

You mistakenly assume that Line, Circle, Point, etc as sub types of shape. They are just union cases, so your type definition doesn't make sense.

You can change shape to be recursive:

type shape =
    | Parameter of parameter
    | Point of shape * shape
    | Line of shape * shape

but it allows more cases than it should.

You can use tuples instead of records:

type shape =
    | Parameter of parameter
    | Point of parameter * parameter
    | Line of (parameter * parameter) * (parameter * parameter)
    | Circle of (parameter * parameter) * parameter

but it is less desirable since Point, Line and Circle deserve to be types on their own rights.

  Are discriminated unions not appropriate for this code perhaps?

It depends. If you have fixed number of cases, then DUs and pattern matching are great to use. Otherwise, you have to fall back to class hierarchy which is much more painful to deal with.


Why is this code to paste into a DataGridView so slow?

I wasn't convinced that the code per se, besides what could be done to improve it, would take this long under 'normal' circumstances. I thought I'd actually test this myself before bed and so threw something together, here's what I did...

I created a WinForms application with the appropriate controls and then used a Stopwatch, only modifying your code (forgetting names of controls) by placing it in a method named PasteData which returned lineCount:

private readonly Stopwatch stopWatch = new Stopwatch();

private int PasteData()
{
    //Your code.
}

private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.V)
    {
        int linesExisting = dataGridView.RowCount;
        stopWatch.Restart();
        int linesPasted = PasteData();
        stopWatch.Stop();
        TimeSpan timeElapsed = stopWatch.Elapsed;

        //UI Updates.
    }
    e.Handled = true;
}

I fired up excel and created 700+ rows of data; 5 columns of random text pasted repeatedly:

  Axdcfg vkhjbkljhgvf hghbjkl;jbhg vguyhjknjhbgvyhjknb hkghjlkh,njjk;olkm,nhn
  ghvbnmkl;kknjbhvghcgv gbhnmkknkjhbghfvghjkljhgfvhjklhbgvhkjlmnjbhgfcfgyhjknlmnn
  ghvjbkmjnhyuiytui89766890i09u8y675tfvghbjnmkl,;m,nbhh
  tf678cfghjbkm,.g90u87ygybihuionjhgvfctfygyuhio;jolkkjnhbvfc
  iouy43212345678987654321234567890009876543212w3erfghgfdffcv

I then copied the whole collection from the clipboard and proceeded to flood our application with it up to a count of almost 300,000 rows, and here are the results:

Performance degradation was absolutely negligible. If anything, it was the amount of memory being consumed that was to become a concern.

Do you have any more specific information regarding your predicament? We need to define you 'normal' circumstances. The format and nature of the test data would be nice to know, ideally a sample could be supplied. You could define expected amounts of data that the view might contain. Also, some hardware details, here's some of my basic info:

RAM: 2.00GB
Processor: AMD Turion 64 X2 TL-60 2.0Ghz
OS: Windows 7 Ultimate 64bit


Let's "Iterator" through Fibonacci, forever and ever

Judging by the title of the question and the main class, I expected to see a simple iterator over Fibonacci numbers to infinity. Instead I see a class with too many responsibilities. It would be better to separate these concerns:

the infinite iterator
one class to get the nth Fibonacci number with caching
a utility class that implements the cache storage from a linked list of segments, the logic of which is encapsulated and hidden from users
the runner class with the main method

The Iterator<BigInteger> is a very good idea. I thought of perhaps providing an Iterator<Integer> too, but then, Fibonacci numbers tend to get very big very fast, so there's probably not much point. So just the Iterator<BigInteger> makes sense.

What you did with the sequence parts is an interesting way to implement a dynamically growing array-like storage without resize operations. As mentioned, this has nothing to do with Fibonacci numbers, and this logic could live in its own utility class. But I think it's probably not worth it. You can use a simple ArrayList instead. When the performance of the ArrayList becomes a real concern, you could try your alternative List implementation.


Naming

The name cake_index is very long and makes things hard to read - maybe i would be enough without making things confusing.

The names  prev_cake_size and current_cake_size are very misleading are we are not really handling sizes.

More generally, I think we could use more generic terms. My preference is to use the following names:

cakes becomes lst
prev_cake_size and current_cake_size become prev_elt and curr_elt
cake_index becomes i

Style

A few things are unusual in your code regarding style. I suggest reading PEP 8, the style guide for Python code.

Among the things I'd change:

use the # comment syntax for comments (instead of literal strings)
use 4-space indentation

Also, it may be clearer to replace your continue by a simple else to make the 2 different situations more explicit.

Useless code

The special case for small lists (size equal to 0 or 1 is not required).

Flipping pancake

The code used to flip pancakes is very complicated and does not really show the kind of operation we perform on your pancake stack.
I'd rewrite this:

        lst[:i+1] = reversed(lst[:i+1])
        lst[:i+2] = reversed(lst[:i+2])

Then, the code would look like:

def pancake_sort(lst):
    leng = len(lst)
    i = 0
    while i < leng-1:
        prev_elt, curr_elt = lst[i], lst[i+1]
        if prev_elt > curr_elt:
            # move the highest element to the beginning by reversing
            # the list from 0 to highest element(including) and then move
            # the highest element to the end by reversing the subarray
            lst[:i+1] = reversed(lst[:i+1])
            lst[:i+2] = reversed(lst[:i+2])
            i = 0
        else:
            i += 1
    return lst

Tests

Your tests are complicated because of the amound of calls to random, in particular testing a random number of times.

I'd also suggest using a real testing framework.

It would be a nice youch to also test explicitly edge cases : empty list, list with one element, list with the same elements multiple times.

Finally, instead of calling randint multiple times, you could use random.shuffle(range(50)).


Cleanest way to place values into strings

For simple straightforward string concatenation like your "persian" cat example, I agree with @Malachi - being slightly memory-inefficient over a few bytes will not hurt anyone, and if there's a gain in readability then it's worth it.

However, since you're looking to standardize the way you're doing string concatenations, you should go with string.Format() all the way, without hesitation*.

Say you're writing a program for some petshop (say, one that only sells cats), you'll potentially want to format/concatenate the cat's breed, birthdate/age and price tag. With string + string your only option is essentially to hard-code the date and currency formats, while this:

string.Format("{0} cat, born {1:d} ({2} weeks) | {3:C2}", cat.Breed,
                                                          cat.BirthDate,
                                                          cat.AgeInWeeks,
                                                          cat.Price)

...has an obvious advantage, especially when you consider that

"{0} cat, born {1:d} ({2} weeks) | {3:C2}"

is a string all by itself (as mentioned by Daniel Cook).

*At the end of the day, common sense should prevail. If you end up doing this:

var result = string.Format("{0}{1}", string1, string2);

...then you know you've gone overboard.


Read date from a file and rename two files using the date

Important change

I would suggest you look at the Path class. A lot of your logic is about manipulating filename and this class does it all for you.

Less important change

Depending on how big the file is, doing File.ReadAllLines might take more memory than needed. Reading one line at a time would be better.

GetFilesInDirectory function name isn't true. It also renames the file.

You could use a bit of error checking. For example, what happen if the string "exif:DateTimeOriginal=" can't be found in the file. What if there's no xmp file to the nef file.


I believe you are on the right track.

The only thing that I would do different would be to add a library folder in which I would store all my common stuff like models, utility classes, helpers etc. I would also namespace everything so as to avoid collisions with any other application or piece of code out there.

My preferred app structure for your app would be as follows

app/
    mail/
        controllers/
            MailController.php
    web/
        controllers/
            WebController.php
library/
    MyAPI/
        models/
            Users.php   <- The model accessing the users table
        Auth.php        <- Authentication
        Controller.php  <- A master controller where all controllers inherit from
        Model.php       <- A master model that all models inherit from
        Locale.php
        Utils.php
var/
    config/
        collections.php
        db.php
        config.php
    cache/
        dummy.txt
    metadata/
        dummy.txt
    logs/
        dummy.txt
public/
    index.php

Your controllers inherit from the base controller in the library folder. In that controller you can do common tasks for all collections. The same applies to the master model.

You can remove the controllers/ folder under each module in the app folder and have them all right under mail, web etc. It's up to you.


There're some bugs in the code. For example, if the user provides more inputs than needed, which the program could safely ignore (or warn about), it'll still exit with an error and an incorrect message.

The comparison should be updated to: if (argc < 3)

Although I think the first answer is ok, I think the readability of the code counts, and proper indentation makes a huge difference. You should develop this habit from the start and I'd find the following minor modifications slightly more preferable, IMHO:

#include <stdio.h>
#include <error.h>

int main(int argc, char *argv[]) {
    /* notice the logical operator update here; prevents bogus error
       message if user provides more than 2 inputs */
    if (argc < 3)
        errx(1, "Give a holiday and a name as arguments.");

    printf(
        "Happy %1$s to you.\n"
        "Happy %1$s to you.\n"
        "Happy %1$s, dear %2$s!\n"
        "Happy %1$s to you.\n",
        argv[1],
        argv[2]
    );

    return 0;
}

Also, I'd recommend that you get in the habit of writing user-visible messages using user-friendly terminology, especially when error conditions are detected.

For example, instead of saying "Give a holiday and name as arguments", which relies on programmer terminology (e.g. non-programmers are unlikely to know what "arguments" are), try to be user-friendly. Consider if the program instead said the following during the error and helped the user correct it:

Some inputs appear to be missing. Please enter the holiday and your name.
Usage: HappyToYou <holiday> <name>
Example: HappyToYou Birthday Bob

Few things are more frustrating than error messages that are uninformative or wrong because the former doesn't help you resolve the issue and the latter sends the user down the wrong path in trying to find a solution.


First, there is no need to use index() method for finding the position of next and next delimiter (and then use it for slicing) - Python is able to split the string at a higher level - pinpoint the delimiter and then use the split() method:

   DELIMITER = " | "                        # we will use it for splitting the string

   "XBOX 360 | 150 | New".split(DELIMITER)  # the result will be ["XBOX 360", "150", "New"]

As you may see from the comment, the result is a list of individual parts.

Second - so we now have the list of the appropriate parts of the string.
Let give it the name parts - so parts will be the list:

   ["XBOX 360", "150", "New"]

(You may obtain it by the command parts = data[0].split(DELIMITER) in your code.)

Now instead of using indices for getting individual parts, i. e. "XBOX 360", "150", and "New":

   product   = parts[0]
   price     = parts[1]
   condition = parts[2]

you may just unpack the parts list:

   product, price, condition = parts

Third, fourh, fifth, ... - I'm not going to overload you :-)


Finding the sum of all the multiples of 3 or 5 below 1000, using list comprehension

Correctness:

Many reviewers will not bother to comment on code that is not correct.
I might have kept this brief, myself, except that it was only in the process of considering optimization that I discovered that this code contains two bugs that prevent correct answers.

It shares one of those bugs with the simpler sumProgressions. The benefit of the simplicity of sumProgressions is that the bug has fewer places to hide there.
Hint: Why does sumProgressions 3 5 1000 give the same answer as sumProgressions 3 5 1001?

Nothing about this bug changes my comments below about style or optimization, so I might have pointed it out and moved on, even if I had caught it up front.

The more serious bug is unique to sumProgressions2.
Hint: Why does sumProgressions 3 6 20 give a different answer from sumProgressions2 3 6 20?

If I had noticed this earlier, my answer might have ended here.

But it seemed a shame to throw the rest of this away, so, (mostly) ignoring the cases in which the code fails...

Style:

I don't see the benefit to the function type declarations all at the top separated from their implementations where they could have had some minor self-documentation effect.

You seem to be following the Haskell tradition of using one-letter symbols and minimal explanatory comments, as if it was obvious from the context that a1 is the first element of a progression and d is its delta and n is the number of elements.  To me, these things were not all obvious, especially when n is either n1 or n2 and the '1' in n1 has nothing to do with the '1' in a1.  I think that n' and n would have been a more idiomatic naming than n1 and n2, since they are variants of each other. Function header comments describing the input arguments would not have been out of place, nor would spelling out "delta" and "limit", but that may be an "m o" (meaning "minority opinion" -- obviously).

The formulas used in pSum are sufficiently complicated and their syntax not quite algebraic, so their intent is obscured. A comment explaining the intent in plain language like "multiplying ... first and last elements..." or pure algebra would help.

Since both aN and pSum are short and used only within pSum and sumProgressions2, respectively, I'd have opted for defining them under a where clause. In the case of pSum, that allows lim to be referenced in the parent scope so it doesn't need to be explicitly passed. This makes the structure of the code more readable, making it clear that aN and pSum serve sumProgressions2 and sumProgressions2 only. I'm guessing (mostly from the presence of a1) that this may not have been your intent, in which case you should have made that intent clear by exporting these functions or showing other uses within the module.

In fact, the purpose of a1 is confounded by the fact that a1 is only ever passed the same value as d by the 3 callers of pSum, and since pSum isn't exported from the module, those seem to be the only cases. From that perspective, a1 is only used once, in an equality test that always passes, so it seems that you could eliminate it and with it half the complexity of pSum.

Even if your intent is to provide pSum as a useful function outside of sumProgressions2, the usage of pSum in sumProgressions2 is so specialized and falls so cleanly into the "simplified" case that it still warrants its own separate truly simplified pSum function that takes no a1 argument.

Whether the existence of another more general pSum implementation is justified and whether its a1 == d case is worth optimizing -- or (as I suspect) similar simplification applies equally to the general case -- is outside the scope of the current problem.

Yet I think that there is a point to be made here about over-generalization.
You could argue that you are doing a good thing by providing and using a more general solution that does not require a1 to equal d, but I don't think that argument holds up. It sounds like the same argument that justifies writing sumProgressions2 as a general solution that does not depend on the values 3, 5, and 1000. But consider the following:

sumProgressions3_5_1000 3   5 1000 = correctAnswerForEuler1
sumProgressions3_5_1000 d1 d2 lim   = let d3 = d1 * d2
    in (pSum d1 d1 lim) + (pSum d2 d2 lim) - (pSum d3 d3 lim)

or even

sumProgressions3 3  d2 lim = specialCaseOptimizedFor3 d2 lim
sumProgressions3 d1 d2 lim = let d3 = d1 * d2
    in (pSum d1 d1 lim) + (pSum d2 d2 lim) - (pSum d3 d3 lim)

Do you consider these to have the same benefits of generality as your original solution?
To me, if (a1==d) in pSum defeats the purpose of the generalized solution just as much as this last example does. Your pSum just hard-codes for an arbitrary argument relationship rather than for an arbitrary argument value, but it's still arbitrary hard-coding for an arbitrary case.

There is danger in over-generalization. Testing and correctness is more difficult for a general function than for a more constrained or hard-coded function. Case in point,  the bug triggered by arguments 3 6 20 does not effect cases like 3 5 1000.  Also, optimization may be completely different when targeting all cases vs. average or typical cases vs. the special case that is going to be exercised in the benchmark.  Case in point, it was only in considering an optimization that would benefit cases like 3 6 20 while slightly penalizing cases like 3 5 1000 that I discovered that I wasn't really optimizing this new case at all -- I was correcting it. And given the context/contest, I wasn't sure that optimizing or correcting the 3 6 20 case was really "in scope". I decided that what was in scope was a style critique along the lines of:

  The good work of substituting code that works in many general cases for code that only needs to handle a specific case may not be worthwhile unless the code is correct for the general case or guards against the cases it does not handle correctly.

You've got a good solution to the problem of sumProgressions2 3 5 1000 disguised as a faulty solution to the problem of sumProgressions2 d1 d2 limit. So, technically, you'd be in better shape if you had been less ambitious.

Optimization:

There's not much to say here, except that the correction for the 3 6 20 case (arguably out of scope and counter-productive to the optimization of the 3 5 1000 solution) was originally mis-identified as a missing optimization. As it turns out, there seem to be multiple edge cases that require either more processing or less processing than 3 5 1000.

Eliminating a1 from pSum would help to focus the effort on the calculation of n1 and its use rather than on dead code.
As far as I can see, there's no better formulation -- no reason to prefer (n*n+n) over n*(n+1) or to prefer (lim - (lim `mod` d))*(n+1) over d*(lim `div` d)*(n+1), given that n+1 requires (lim `div` d) to be calculated in either case. But I could be wrong, and easily proven wrong by some quick benchmarks. So, your solution seems optimal within the current structure of sumProgressions2 as 3 calls to pSum.

The only other way I could see to further optimize the code would be IF there was an alternative way of expressing the third call to pSum so that it eliminated some operations in favor of re-using sub-expressions from the first two pSum calls. I don't know if this is possible. What I'm imagining is something like a reformulation of the pSum functions, especially the one used in the 3rd call, that took advantage of a fact like (d1*d2)*(d1*d2) == (d1*d1)*(d2*d2) (assuming that result to be useful) to reuse (d1*d1) and (d2*d2) values calculated already in the first two (reformulated) pSum calls.  I don't know enough about Haskell internal optimizations to know if it can access function results "recently memoized" in called "sibling" functions. If not, I'd guess you would pass the useful sub-expressions like (d1*d1) from sumProgressions2 into the pSum calls. This whole idea could turn out to be too ugly for serious consideration, so you might be better off where you are.


Using argparse with parameters defined in config file

The use of a json file/expression as a source for defining argparse arguments is clever, and I think sound.  ipython defines many of its commandline arguments from values in a config file.

I commented that we need to be careful about what type does.  It's a frequent point of confusion.  It is a callable, usually a function, that takes a string, and converts it to the kind of value you want in the args namespace.  Its relation to builtin types and the the Python type function is only tangential.

int and float work because those functions take a string and return a desired value (or raise an error).  bool does not because it does not take string and return a True/False (try bool('False').

argparse has an undocumentated registries mechanism that maps from strings to callables.  Mostly it is used for the action parameter, but can also be used with type.  Basically it's a dictionary.

Here's a quick session to illustrate its use.

In [2]: parser=argparse.ArgumentParser()

parser.register is an undocumented method, used internally, but available to the user (no _):

In [3]: parser.register?
Type:       instancemethod
...
File:       /usr/local/lib/python2.7/argparse.py
Definition: parser.register(self, registry_name, value, object)
Docstring:  <no docstring>

It sets an entry in a dictionary that the parser owns.  Notice all the familiar action values.  This maps from those strings to the Action subclasses.  There is only one type entry, the default case that does nothing (leaves a string unchanged).

In [4]: parser._registries
Out[4]:
{'action': {None: argparse._StoreAction,
  'append': argparse._AppendAction,
  'append_const': argparse._AppendConstAction,
  'count': argparse._CountAction,
  'help': argparse._HelpAction,
  ...
 'type': {None: <function argparse.identity>}}

So let's add some entries to the register:

In [5]: parser.register('type','float',float)
In [6]: parser.register('type','int',int)
In [7]: parser.register('type','str',None)

and create some Actions to use them:

In [8]: parser.add_argument('-i',type='int')
....
In [9]: parser.add_argument('-f',type='float')
...
In [10]: parser.add_argument('-s',type='str')
...
ValueError: None is not callable

Oops, it didn't like my None.  I was intending the None to map on to the existing None mapping in the registries, but it does not do that kind of double mapping.

I think the str() function will work.  It takes a string and returns it unchanged.  The argparse identity is more like a do nothing lambda x:x.

In [12]: str('astirng')
Out[12]: 'astirng'

In [13]: parser.register('type','str',str)

In [14]: parser.add_argument('-s',type='str')
Out[14]: _StoreAction(option_strings=['-s'], dest='s', nargs=None, const=None, default=None, type='str', choices=None, help=None, metavar=None)

Now let's test:

In [15]: parser.parse_args('-i 1 -f 23 -s 23'.split())
Out[15]: Namespace(f=23.0, i=1, s='23')

If you don't want to use register, I'd recommend a dictionary over eval.  As another answer notes there aren't that many types, and you have more control over the translation.

A recent SO question suggests on potential difficulty with your json-argparse mapping.  Not all Actions take a type parameter.  Your set of parameters is fine for the defaultstoreaction.  But astore_trueaction raises an error if you give it atype` parameter.

https://stackoverflow.com/questions/33574270/typeerror-init-got-an-unexpected-keyword-argument-type-in-argparse

I'd prefer calling add_argument with:

parser.add_argument(*args, **kwargs)

and build up args as a list, and kwargs as a dictionary. For example instead of :

for key, val in arguments.items():
    parser.add_argument('-%s' % key,
                        type=eval(val["type"]),
                        help=val["help"],
                        default=val["default"])

use something like:

for key, val in arguments.items():
    args = ['-%s'%key]
    kwargs = {<some defaults>}
    kwargs.update(val)
    parser.add_argument(*args, **kwargs)

This would allow me to use json strings like

'foo': {'action': 'store_true',
           'help': 'True/False values'},
   'bar': {'type': 'int',
           'default': 2},
   'baz': {'nargs': '+',
           'help': 'multiple values'}

I haven't tested this yet, but if I've got it right, it would give more flexibility.  Internally argparse uses **kwargs a lot to handle the large numbers of parameters that its methods take.


zeros or zeroes? Better make up your mind and stick with one.
str.join is good when you want to join an iterable. For two strings, just use +.
Instead of always reencoding and rehashing the input string, you can do it once and then copy the resulting hasher (state) for different extensions.
Instead of creating random bytes and then elaborately turning them into a string and back to bytes, just use the bytes. Since that's also just a single function call, you can ditch your gen_keys_06 and its overhead.
str.startswith is at least simpler, don't know about speed.
For measuring performance, create a benchmark that runs the function much more than just once, as a single time is rather random. Or change the function so it tries a fixed number of random extensions (let's say a million) instead of stopping at the first successful one.
You ask us "On what should I work to make it faster?". That's a question to ask a profiler.
Producing random values takes time. Check the profiler's results (or leave out the randomness when doing the million-extensions thing) to see whether it's significant here. If it is, maybe try a different randomness source (I think I've seen someone say that os.urandom is slow on Linux). Or if you don't actually need randomness, try increasing bytes instead.
Do you really want zero-nibbles? Or would zero-bytes work as well, i.e., are you maybe really only interested in even numbers of zero-nibbles? Then you could use digest instead of hexdigest, which is probably faster because bytes are probably what the hasher actually works with and because it makes digests half as large and you'd check for fewer zeros.

A version incorporating some of those points:
def search_matching_random_str(input_str, zeros, _sha1=hashlib.sha1, _urandom=os.urandom):
    leading_zeros = "0" * zeros
    hasher_copy = _sha1(input_str.encode()).copy
    while True:
        my_random_bytes = _urandom(4)
        hasher = hasher_copy()
        hasher.update(my_random_bytes)
        hashval = hasher.hexdigest()
        if hashval.startswith(leading_zeros):
            return hashval, my_random_bytes


Test 2 time ranges to see if they overlap

As s3rius pointed out, you don't need the $timeCheck variable. You can just use return true; or return false;.
To parse a time use the DateTime class. You can find the supported time formats here. The constructor will throw an exception if it cannot parse the string. Consider if you want to handle the exception yourself or let the caller handle it.
What if the start time is after the end time? You can throw an exception, switch the start and end times, or not handle the error.
The meaning of the return value is not obvious based on your function name. How does it test the range? Change it to something like rangesNotOverlap or something similar so that it is apparent that true means they don't overlap.
Are time ranges open or close intervals? If one range ends at 10:00 and the other starts at 10:00, do they overlap?
Lets consider all cases:

.

             1
Case 01:  |-----|
          |-----|
             2

             1
Case 02:  |-----|
             |-----|
                2

                1
Case 03:     |-----|
          |-----|
             2

               1
Case 04:  |---------|
            |-----|
               2

               1
Case 05:    |-----|
          |---------|
               2

             1
Case 06:  |-----|
                  |-----|
                     2

                     1
Case 07:          |-----|
          |-----|
             2

             1
Case 08:  |-----|
                |-----|
                   2

                   1
Case 09:        |-----|
          |-----|
             2

             1
Case 10:     |
          |-----|
             2

             1
Case 11:  |-----|
             |
             2

          1
Case 12:  |
          |-----|
             2

                1
Case 13:        |
          |-----|
             2

             1
Case 14:  |-----|
          |
          2

             1
Case 15:  |-----|
                |
                2

          1
Case 16:  |
          |
          2

        |                         |    Operlap    |     Overlap
  Case  |         Example         | Open Interval | Closed Interval
--------|-------------------------|---------------|-----------------
Case 01 | 09:00-11:00 09:00-11:00 |      Yes      |        Yes
Case 02 | 09:00-11:00 10:00-12:00 |      Yes      |        Yes
Case 03 | 10:00-12:00 09:00-11:00 |      Yes      |        Yes
Case 04 | 09:00-12:00 10:00-11:00 |      Yes      |        Yes
Case 05 | 10:00-11:00 09:00-12:00 |      Yes      |        Yes
Case 06 | 09:00-10:00 11:00-12:00 |      No       |        No
Case 07 | 11:00-12:00 09:00-10:00 |      No       |        No
Case 08 | 09:00-10:00 10:00-11:00 |      No       |        Yes
Case 09 | 10:00-11:00 09:00-10:00 |      No       |        Yes
Case 10 | 10:00-10:00 09:00-11:00 |      Yes      |        Yes
Case 11 | 09:00-11:00 10:00-10:00 |      Yes      |        Yes
Case 12 | 09:00-09:00 09:00-10:00 |      No       |        Yes
Case 13 | 10:00-10:00 09:00-10:00 |      No       |        Yes
Case 14 | 09:00-10:00 09:00-09:00 |      No       |        Yes
Case 15 | 09:00-10:00 10:00-10:00 |      No       |        Yes
Case 16 | 09:00-09:00 09:00-09:00 |      No       |        Yes

Your function returns the correct result on the closed interval for all cases.

We can make your code simpler by noticing that we only have to check for two cases. The ranges don't overlap only if end1 < start2, (the same as your first if), or if end2 < start1 (which is included in your second if). The other check you do start1 > start2 is redundant, because it is always true if end2 < start1.

Put it all together:

function rangesNotOverlapClosed($start_time1,$end_time1,$start_time2,$end_time2)
{
  $utc = new DateTimeZone('UTC');

  $start1 = new DateTime($start_time1,$utc);
  $end1 = new DateTime($end_time1,$utc);
  if($end1 < $start1)
    throw new Exception('Range is negative.');

  $start2 = new DateTime($start_time2,$utc);
  $end2 = new DateTime($end_time2,$utc);
  if($end2 < $start2)
    throw new Exception('Range is negative.');

  return ($end1 < $start2) || ($end2 < $start1);
}

function rangesNotOverlapOpen($start_time1,$end_time1,$start_time2,$end_time2)
{
  $utc = new DateTimeZone('UTC');

  $start1 = new DateTime($start_time1,$utc);
  $end1 = new DateTime($end_time1,$utc);
  if($end1 < $start1)
    throw new Exception('Range is negative.');

  $start2 = new DateTime($start_time2,$utc);
  $end2 = new DateTime($end_time2,$utc);
  if($end2 < $start2)
    throw new Exception('Range is negative.');

  return ($end1 <= $start2) || ($end2 <= $start1);
}


You can create a block without an if statement.
For example, these are equivalent:

{
    // some code
}

if (true) {
    // some code
}

But it's not a good practice to create blocks like this.
It's a code smell,
suggesting to wrap // some code in a dedicated function instead.

Anytime you think some neat trick is "unconventional",
it's most probably a bad practice. Don't do it, fix it.


Reading entire contents of file at a given java.no.file.Path into a String

I believe you are missing a relatively obvious, although somewhat memory-inefficient Files.readAllBytes(...) .... Consider this:

public String readFile(Path path, Charset encoding) throws IOException {
    return new String(Files.readAllBytes(path), encoding);
}

In your code you also have two full copies of the file in-memory at one time, so the files can't be huge. The code I suggest also pulls all the data in to memory twice, once as a byte[] array, which gets converted to a String, and the byte[] array is discarded.

There would be a loopy way to solve it by using a StringBuilder and a smaller byte[] array, or ByteBuffer, but, if your files are smallish, I would not worry about the byte[] size.


if result is False:
    raise Exception('diff found between the files')
else:
    return 'files are identical'

Why would a difference be considered Exceptional? Given that nothing else happens in the program, there isn't much difference at this point between raising an error and just printing the message, but it seems like an odd way to do things.

Also, you shouldn't test for False by identity, if not result is the usual method.

Have you considered allowing the user to select branches to compare? You could use the current value as a default, e.g.

 def diff_versions(file_to_be_compared, directory, branch="origin/master"):


I only have a few quibbling remarks:

Don't Repeat Yourself (D.R.Y.)

Declare $url = $host . $request->key unconditionally at the start of your method (say, after $host).  Then append text to it if/when needed $url .= '/' . $payload['id'];.
strtoupper($request->method) is done in each conditional expression.  It is better practice to mutate the string once.  You're also checking the same data for different strings, this is what switch-case blocks are for.
Rather than writing $data (a non-descriptive variable name) over and over, omit the variable declaration entirely and write the data directly into the return.  I regularly advise against single-use variable declarations unless they valuably reduce code width or improve readability.

else if should be elseif in PHP to comply with the PSR-12 coding standard.
All of your thrown exceptions are handled identically, so it seems to be a much cleaner choice to wrap your whole switch block in a single try-catch block.
Maybe you'd like to see the payload when there is a thrown exception; if so, use "data" => $payload ?? [] in the return.

Your code might be rewrite as:
public function bridge(Request $request)
{
    $host = "http://127.0.0.1:8000/api/";
    $url = $host . $request->key;

    if ($request->has("payload")) {
        $payload = json_decode(html_entity_decode($request->payload), true);
    }

    try {
        switch (strtoupper($request->method)) {
            case "POST":
                return Route::dispatch(Request::create($url, 'POST', []));
            case "PUT":
                $url .= '/' . $payload['id'];
                return Route::dispatch(Request::create($url, 'PUT', []));
            case "DELETE":
                $url .= '/' . $payload['id'];
                return Route::dispatch(Request::create($url, 'DELETE', []));
            default:
                if ($request->has("payload")) {
                    $url .= "/" . $payload['id'];
                }
                return Route::dispatch(Request::create($url, 'GET'));
         }
     } catch (\Throwable $th) {
         return [
                    "data" => $payload ?? [],
                    "success" => false,
                    "code" => 500,
                    "message" => $th->getMessage(),
                ];
     }
}


All subsets of a String in java using recursion

If I have understood correctly, you're aiming for all subset of a String.
Through  your code for String = "ABC"; //Result is -- >  A AB ABC AC B BC C

However, for

String = "ABB";
// Result is --> A AB ABB AB B BB B (You see AB twice as well as letter B).

So to make it more clear for unique subsets, added a set implementation.

TreeSet (extra sorted feature over hash), as below : (using same recursion)

public class Test {

 public static void allSet(String s, String t, Set<String> set) {
     // System.out.print(t + " ");   will print later.
      if(!"".equalsIgnoreCase(t))
      set.add(t);
      if (s.length() > 0) {
          for (int i = 0; i < s.length(); i++) {
              allSet(s.substring(i + 1, s.length()), t + s.charAt(i),set);
          }
      }
  }
public static void main(String args[]) {
    String a = "ABB";
    String t = "";
    Set<String> set = new TreeSet<String>();
    allSet(a, t, set);
    System.out.println(set.toString());
   }

// Now, result --> [A, AB, ABB, B, BB]


Guard against ../ in the uri_req parameter

I'm seeing a possible security hole. A big one. Consider the following URL:

http://yoursite.com/index.php?uri_req=../../hacking_scripts/dump_database.php

Now let's pretend for a moment that I'm criminal who has previously breached the web server that hosts your web application. Your app is stored at:

/www/himanshu/index.php

Now when I breached the web server, I created the following file:

/hacking_scripts/dump_database.php

Which contains PHP code to connect to your database as the same username and password as your web site, because after all, I can view the raw PHP code and found a database connection string with a username and password.

The dump_database.php script basically queries for all the tables your web site's user has available to it, does a SELECT * on the table and dumps out the raw data in the resulting HTML file. Upon hitting the URL above, your router gleefully loads that file and executes the PHP inside because I placed ../../ in the uri_req parameter.

Some other improvements:

Don't redirect to a 404 Not Found page, because the HTTP status will first be a 301 redirect to a GET request that results in a 200 OK response. Your intended response is 404 Not Found, so set the HTTP status to that value and simply include the 404.html file.

Web crawlers and search engines, when encountering a 404 Not Found, will not attempt (or should not attempt) to hit that URL again. In your setup, they will be back to the same "Not Found" URL over and over again.
The _PageCall function name doesn't really tell you what it does. It routes the request. Why not call it something like routeRequest?
Add a try-catch around the calls to other PHP files, then return a 500 Server Error response. This way you don't get ugly stack traces showing up in production, and you can create your own custom, prettier looking error page for unhandled catastrophic errors.

function _PageCall($file_name=null) {
    try {
        // route the request
    } catch (Exception $ex) {
        http_response_code(500);
        require_once($pagedir . "500.html");
        // Log the error message and stack trace
    }
}

Remove duplicated 404 Not Found logic by separating the detecting of a file to load versus the actual executing of that file

function _PageCall($file_name=null) {
    try {
        $pagedir = ROOT.DIRECTORY_SEPARATOR.PAGEDIR;
        $page = getFullFilePath($pagedir, $file_name);

        if (!isset($page)) {
            $page = $pagedir . '404.html';
            http_response_code(404);
        }

        require_once($page);
    } catch (Exception $ex) {
        http_response_code(500);
        require_once($pagedir . "500.html");
        // Log the error message and stack trace
    }
}

function getFullFilePath($pagedir, $file_name=null) {

    /* Every File Request Must Be in HTML */
    if(".html"===substr($file_name, -5)):
        $file_name = trim($file_name,'.html');
        if(file_exists($pagedir.$file_name.'.php')):
            return $pagedir.$file_name.'.php';
        else:
            return null;
        endif;
    else:
        if(NULL==$file_name||$file_name=='index.html'):
            return $pagedir.'index.php';
        elseif($file_name=='a'):
            return $pagedir.'ajax.php';
        else:
            return null;
        endif;
    endif;
}

Whitespace is your friend. For readability put spaces around all operators and the conditions for if statements:

if(".html"===substr($file_name, -5)):

Becomes:

if (".html" === substr($file_name, -5)):

And put some empty lines between IF statements:

$file_name = trim($file_name,'.html');

if (file_exists($pagedir . $file_name . '.php')):

Add additional functions for detecting certain kinds of files so that:

if (".html" === substr($file_name, -5)):

Becomes:

if (isHtmlFile($file_name)):

Use a consistent variable naming convention. I see $pagedir and $file_name. In the very least avoid using all lower case letters. Separate words by an underscore or use camelCase.

This isn't a bad script to do simple routing. Really the most important change is to fix the security flaw allowing you to specify any file path in the URL parameter.


<limits> already provides a set of limits on values that can be stored in the various types. It's also a template, so it's easy to invoke on a template parameter. As a quick demo of that particular part of things:

template <class T>
void showminmax(T) {
    std::cout << "min: " << std::numeric_limits<T>::min() <<
               "\nmax: " << std::numeric_limits<T>::max();
}

int main() {
     std::cout << "int\n";
     showminmax(1);

     std::cout << "\nunsigned long long\n";
     showminmax(1ULL);
}

I believe the code to normalize the number to the range [0..1] can be simplified quite a bit as well, to something on this order:

template <class T>
float normalize(T t) {
    static_assert(std::is_integral<T>::value, "Input must be integral");
    float min = std::numeric_limits<T>::min();
    float max = std::numeric_limits<T>::max();
    float range = max - min;

    return (t - min) / range;
}

This should work for either signed or unsigned types. Here's a quick bit of demo code to exercise it, and show the results:

int main() {
    std::cout << "char(min):   " << normalize(std::numeric_limits<char>::min()) << "\n";
    std::cout << "char (1/4):  " << normalize(char(std::numeric_limits<char>::min() >> 1)) << "\n";
    std::cout << "char (0):    " << normalize('\0') << "\n";
    std::cout << "char (3/4):  " << normalize(char(std::numeric_limits<char>::max() >> 1)) << "\n";
    std::cout << "char (max):  " << normalize(std::numeric_limits<char>::max()) << "\n\n";

    std::cout << "int(min):   " << normalize(std::numeric_limits<int>::min()) << "\n";
    std::cout << "int (1/4):  " << normalize(std::numeric_limits<int>::min() >> 1) << "\n";
    std::cout << "int (0):    " << normalize(0) << "\n";
    std::cout << "int (3/4):  " << normalize(std::numeric_limits<int>::max() >> 1) << "\n";
    std::cout << "int (max):  " << normalize(std::numeric_limits<int>::max()) << "\n\n";

    std::cout << "uint (0):   " << normalize(0U) << "\n";
    std::cout << "uint (1/4): " << normalize(std::numeric_limits<unsigned int>::max() / 4) << "\n";
    std::cout << "uint (mid): " << normalize(std::numeric_limits<unsigned int>::max() / 2) << "\n";
    std::cout << "uint (max): " << normalize(std::numeric_limits<unsigned int>::max()) << "\n\n";

    std::cout << "ULL (0):   " << normalize(0ULL) << "\n";
    std::cout << "ULL (1/4): " << normalize(std::numeric_limits<unsigned long long>::max() / 4) << "\n";
    std::cout << "ULL (mid):  " << normalize(std::numeric_limits<unsigned long long>::max() / 2) << "\n";
    std::cout << "ULL (max):  " << normalize(std::numeric_limits<unsigned long long>::max()) << "\n";
}

Note that twos complement is asymmetric, so the values produced are technically just a tiny bit off (well, off from what you might expect, anyway). This will normally be lost in the rounding for any type with more than ~24 input bits, but if the input type is smaller than that (e.g., most implementations of char and short) a signed value of 0 won't give precisely 0 as the result (unless you have a machine with something like signed-magnitude or ones complement int, anyway).


Part 2: Send HTTP request for each row in Excel table

Your code is pretty solid. I so have a couple of minor tweaks.

Function CodeName() As Worksheet
Set CodeName = DataSheet
End Function

This function is just adding a layer obfuscation.   You should just change the worksheets code name.

Ctrl + R will Open the Folder Explorer
Alt + F4

From here you can change the Worksheet's Name property.

Combining lines should be avoided. It detracts from the readability of the code.  I am not opposed to declaring a variable and initiating its value in one line but only because you are allowed to assign values when declaring variables in most other languages.
Dim Target as Range: Set Target = Sheet1.Range("A1")
Here you are combing two actions into a single line.  Not only does it make it harder to read but it may run into problems later on when you are writing similar code.

.Open "GET", url, False: .Send

Consider for instance that weeks down the you are having problems writing a new function because you forgot to .Send your request.  So what do you do?  You reference your code base.  Combing the .Open and .Send request into one line makes it hard to distinguish the ↑code above↑  from the ↓code below↓.

.Open "GET", url, False

Although you never asked about speed I think its worth mentioning.
Adding Application.ScreenUpdating = False to the beginning of your code will make it run considerably faster.
Setting the varAsync parameter of the MSXML2.XMLHTTP.Open() method to True will allow the rest of the code to run while the HTTP XMLHTTP.Request() is processing.  This will allow you to create more connections.  Having 50 or more connections processing at once will greatly sped up the code.

Sub open(bstrMethod As String, bstrUrl As String, [varAsync],
[bstrUser], [bstrPassword])

In my answers to the questions below I create a connection pool.  I initiate the pool with x number of connections.  As the requests are completed the newly freed connection is given a new request.
Shameless plug:

Data scraping from Internet with Excel-VBA
Retrieve data from eBird API and create multi-level hierarchy of locations

In truth, setting up a connection pool, is probably over kill.  But it is nice to know that it can be done in case you every need the extra speed boast.


Computing the Fourier transform of a distribution of electron charge (represented by atomic positions in space)

The most immediate optimization is to use coalesced reads by switching to array of structs form to structure of arrays.


A few comments, wrt style.

#include <iostream>
using namespace std;

You don't need a forward declaration of struct Node.

//struct Node;

You could add a constructor here just like in class. So your initialization
is simpler.

struct Node {
    int data;
    Node* next;
    Node(int d):data(d), next(0){}
};

It may be a good idea to write an abstract class as an interface, and then write
the concrete class to conform to it. Another idea is to try to templatize Node so that the data can be any type. Also look at the stack class in STL

You may also want top() and empty() methods

on logic: If you are going to implement a stack using a linked list, you don't really need to keep a first and a last. Just keep the reference to the top element. On push, create a new node, set its next to the current top, and set it to top. On pop, set the top to the next of current top, and delete the node. Something along the lines of: (may contain bugs.)

struct Node {
    int data;
    Node* next;
    Node(int v, Node* n):data(v),next(n) {}
};

class Stack {
  public:
    Node* top;
    Stack():top(0){}
    ~Stack() {
      while (top != 0) pop();
    }
    Stack& push(int value) {
      top = new Node(value, top);
      return *this;
    }
    Stack& pop() {
      if (!top) throw "No nodes to pop.";
      Node* t = top;
      top = top->next;
      delete t;
      return *this;
    }
};


Random tone generator using Web Audio API

Reusable code

You code is not very flexible, and the frequencies somewhat arbitrary and spanning a large 6 octaves.

You can encapsulate the code in a function that creates an object you use to play the random tone as needed, allowing you to add features as you need.

Note friendly

Consider using standard musical notes rather than random frequencies.

To get the frequency of a note you use the expression

freq = 2 ** (note / 12) * 440;

where note is the number of semi tones from A4 440Hz. So to find C4 which is 3 notes up  2 ** (3 / 12) * 440;

To get the closest note to a frequency you use

note = Math.round(Math.log2(freq / 440) * 12);

Basic example

The example creates that object randomNotes and plays musical notes rather than random tones.

const randomNotes= (() => {

    /* Create the objects needed to play a tone */
    const audio = new AudioContext();
    const volume = audio.createGain();
    volume.gain.value = 0.5;
    volume.connect(audio.destination);

    /* Function to calculate frequency of a note starting at A4 and stepping semi tones*/
    const freq = note => 2 ** (note / 12) * 440; // 440 is the frequency of A4
    const randomNote = () => notes[Math.random() * notes.length | 0]; // the bitwise Or does the same as Math.floor
    const notes = [-25, -2, 22, 46]; // Close to your 100, 400, 1600 and 6300

    /* Create and return the object that is the randomNote */
    return {
        play(startIn = 1, playFor = 4) { // startIn and playFor is time in seconds
            const now = audio.currentTime;
            const oscillator = audio.createOscillator();
            oscillator.type = "sine";
            oscillator.connect(volume);
            oscillator.frequency.value = freq(randomNote());
            oscillator.start(now + startIn);
            oscillator.stop(now + startIn + playFor);
        }
    };
})();

Then to play a random note just call

randomNotes.play();

or playing two tones

randomNotes.play();
setTimeout(randomNotes.play, 6000);

or overlapping tones

randomNotes.play();
setTimeout(randomNotes.play, 3000); // starts half way through the first

Reusing the code

The Advantages of using this approch is that it becomes very easy to extend the functionality. Say you want to add volume control, or be able to add notes to the random list, just add a setter to the object returned,

// from above snippet
/* Create and return the object that is the randomNote */
return {
    set volume(value) { volume.gain.value = value },
    set note(value) { notes.push(value) }

    // continue on from above snippet
    play(startIn = 1, playFor = 4) { ...

You can then set the volume in a more abstract way and add notes to the random set with ease.

randomNotes.note = 12; // Add note A5 to the random set
randomNotes.volume = 0.8; // Increase the volume

More sound.

You will notice that there is a new oscillator created each time, and that the audio context's current time continues to tick. It is much more efficient to create one oscillator and change its frequency as needed and using timers to change the volume to start stop the sound. An oscillator can not restart after it has been stopped.

But this is not the best either as the audio context can chew some serious power and CPU even when not playing sound (On some audio hardware). Ideally you suspend the audio context and resume it as needed, in conjunction to using the gain control to start and stop the oscillator, as the audio context can sometimes be a little slow when suspending .

Personally I would create this type of thing using an audio buffer and just write the waveform directly to the buffer then play it.


Multi-threaded code to handle messages from a provider

There are some things to adress.
"synchronized"
Like you recognized: Using synchronized variants of certain maps or set classes will not get you away from the burden to define a proper "monitor". Often these variants are not even neccessary to solve the problem so that the synchronization elements will only reduce performance without participating within the synchronisation neccessity. A monitor is an area of code execution that has some assertions to the behaviour of the code under concurrency situations. The simplest situation would be "restrict access to the monitor to only one thread". So putting a synchronized-keyword "somewhere" will not solve the problem until your monitor is properly defined.
Responsibilities
You have to be clear about what are critical code fragments that should properly behave under concurrency. I do not want to say that I am THE reference but for me it took a while to interprete your code and identify what it is all about. Even (I would say especially) in concurrency we should be aware of clear responsibilities.
Busy waiting
Some other thing is "busy waiting" (while (true)). I reject those constructs. You should always provide a loop exit AND a mechanism to avoid busy waiting.
Usecase
As far as I understood your code you have a stream of elements from multiple arbitrary sources to print out or do whatever you want to do with it. It seems to me like a "Buffer" but currently I am not that sure about it.
Abstraction from element sources
Currently the elements of the stream come from 2 sources:

A http request, returning a set of elements that are provvided asynchronously to the stream
from multiple threads that provide message elements

My suggestion is to abstract from the sources where the elements come from. So the first responsibility will be a class that can asynchronously receive elements and output them in a sequence. Following algorithms now only need to depend on objects of this class:
public static class ElementJoiner {

    private BlockingDeque<String> queue;
    private String code;

    public ElementJoiner(String code) {
        this.queue = new LinkedBlockingDeque<>();
        this.code = code;
    }

    public void registerElement(String element) {

        try {
            this.queue.put(element);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public void registerElements(Collection<String> elements) {
        elements.forEach(element -> registerElement(element));
    }

    public String getElement() {

        try {
            return this.queue.pollFirst(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

}

The internal deque will have a special behaviour if no elements are in the queue: If no element is available it will block a certain amount of time (here 5 seconds). Either a new element was insert that can be returned OR it will return null.
Abstract from Thread "this" and other threads
After all the only difference between registering elements from other "Threads" (UUIDs) and registering the elements of the http request is that you perform the registration in "this" Thread (the main-Thread). You only delay registration for a second (Thread.sleep(1000)).
So the task is to abstract from where elements are received. Furthermore it doesn't matter from which thread the elements come from. We have to tell one thread...

... where to receive or how to produce elements (supplier)
... where to register the received or produced elements (consumer)

Now it is easy to formulate the start and behaviour of a thread:
private void startAsynchronousElementSource(Consumer<Set<String>> consumer, Supplier<Set<String>> supplier) {

    Runnable r = () -> {
        while (true) {
            consumer.accept(supplier.get());
        }
    };

    new Thread(r).start();

}

You can see a high symmetry as we input a set of elements and pass these elements immediately to the consumer. The only thing we define here is what to do asynchronously (maybe starting the thread, but I ignore that for now).
Stream preparation
We have "ElementJoiner"-class that does pretty well. Now we want it to work together with a stream. A standard stream cannot exit as long as there is no indicator for exiting. If you have a Ranged-Stream you limit the stream through the boundaries defined. The stream we want to have has a special indicator so we have to define a so called Spliterator.
public class ElementSpliterator extends Spliterators.AbstractSpliterator<String> {

    private Supplier<String> elementSupplier;

    protected ElementSpliterator(Supplier<String> elementSupplier) {
        super(Long.MAX_VALUE, Spliterator.SIZED);
        this.elementSupplier = elementSupplier;
    }

    @Override
    public boolean tryAdvance(Consumer<? super String> action) {

        String element = elementSupplier.get();

        if (element != null) {
            action.accept(element);
            return true;
        } else {
            return false;
        }

    }

}

The tryAdvance-method handles the case if the supplier returns null to end the stream.
The supplier in our case will be the "ElementJoiner" which getElement-method will return null if the timeout has passed.
Defining simulation data
Here I harmonized the return value to be a Set.
private Set<String> getElementsFromOtherSource() {
    return Collections.singleton(UUID.randomUUID().toString());
}

public Set<String> getElementsFromHttpRequest(){

    Set<String> resultsFromHttpRequest = new HashSet<>();

    resultsFromHttpRequest.add("B");
    resultsFromHttpRequest.add("C");
    resultsFromHttpRequest.add("D");
    resultsFromHttpRequest.add("E");
    resultsFromHttpRequest.add("F");

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    return resultsFromHttpRequest;
}

Reformulating the init-method
I don't think we need the "code"-attribute in this use case neither the data-HashMap.
The first thing we will do is instantiating the ElementJoiner:
ElementJoiner elementJoiner = new ElementJoiner(forCode);

Then we can instantiate the stream with the "elementJoiner" as an element supplier AND the ElementSpliterator with the handle to identify the stream end.
Stream<String> elementsStream = StreamSupport.stream(new ElementSpliterator(elementJoiner::getElement), true /* parallel */);

After that we can start to produce elements asynchronously that will be registered in the "elementJoiner". You see that there is no difference in formulating the element source for the "other" and the "http request".
    // Other sources

    Consumer<Set<String>> consumer = elements -> elementJoiner.registerElements(elements);

    Supplier<Set<String>> otherSupplier = () -> getElementsFromOtherSource();

    startAsynchronousElementSource(consumer, otherSupplier);
    startAsynchronousElementSource(consumer, otherSupplier);
    startAsynchronousElementSource(consumer, otherSupplier);
    startAsynchronousElementSource(consumer, otherSupplier);

    // http request source, while other source already supply elements

    Supplier<Set<String>> httpRequestSupplier = () -> getElementsFromHttpRequest();

    startAsynchronousElementSource(consumer, httpRequestSupplier);

The final statement produces the output on the console:
elementsStream.map(e -> e + "_MAPPED").forEach(System.out::println);

Where is the synchronizsation???
The work of synchronisation is done by the "LinkedBlockingDeque". As we only delegate to ONE synchronized method of the "LinkedBlockingDeque" in "getElement" and "registerElement" we do not need our own synchronisation.


BigInteger class, supporting addition only

Abusing the use of macros

I think there is no good reason for implementing to_int() and to_char() as macros - such an implementation may result in hard to find bugs as you don't have any type checking. Lack of parameter types also makes it harder to understand what the function is expected to do in case of more complex functions.

Also, the names of these functions are misleading as they don't inform in a clear way that you are expecting an input to represent a single digit and any other input is invalid.

If you stick to the macro anyway, it's a common convention to use uppercase letters for macro names - most people would expect an ordinary function after seeing lowercase to_int()/to_char().

Single responsibility principle violation

Using catch this way:

catch (InvalidBigInt)
        {
            std::cout << "*****************      Input invalid integer      *****************" << std::endl << \
                "*****************      Please input again         *****************" << std::endl;
        }

you are restricting the use of your class to console applications. Things such as text display should be moved outside of your class as the responsibility of your class is to calculate numbers, not display them nor interact with a user via an interface.

Unclear variable names

Tha name flag is very vague and it's necessary to read the code to see what it's supposed to do (assuming it is used in the intended way). I'm not sure what is its purpose anyway since it's only set and not referred to anywhere in the code. I also suspect it shouldn't be a static variable.

Organizing code into headers and implementation files

Don't put all your code within your main.cpp file. It's more versatile and easier to manage if you separate it and put declarations in headers and definitions in .cpp files - you'll see that as soon as you decide to separate the text display functionality mentioned above from your main class.

Inconsistent and uncommon naming convention

Here:

for (auto IteratorMore = more.begin(), IteratorLess = less.begin();
    IteratorMore < more.end() && IteratorLess < less.end();
    IteratorMore++, IteratorLess++)

the names of the variables IteratorMore and IteratorLess start with a capital 'I', whereas it is a common practice to start the name of a class with the capital letters and start variable names with a lowercase. You are also following this convention correctly throughout your code, except in this part.

Const correctness

You don't always adhere to the concept of const correctness: your operators don't modify the BigInteger argument and thus it should be passed as a const reference to avoid unnecessary copies and make room for possible compiler optimizations.

Code lines' length

In some places in your code, you are writing very long lines, such as:

auto more = b.vnum.size() >= this->vnum.size() ? b.vnum : this->vnum, less = b.vnum.size() < this->vnum.size() ? b.vnum : this->vnum;

Even though most modern IDE's have built-in line wrapping, it's a good practice to write your code in such a way that a single line comprises approximately 80 characters. It's more comfortable and faster to read and comprehend the code if you are not forced to scroll it or move your eyeballs repeatedly from one side of a wide screen to another. Also that way you have control over where you wrap your code, whereas line wrapper functionality may visually organize the code in a way that makes it less readable. Also it's easier to use diff tools and open several editor windows side-by-side if you stick to this rule. See the discussion e.g. here:

https://stackoverflow.com/questions/276022/line-width-formatting-standard

Redundant variables

It seems you are not using snum anywhere in your code right now and even if you do use it in the future, it is probably to serve exactly the same puropse
as vnum, so it's better to convert one type to another instead of keeping both and using only one of them depending on what's passed to the constructor - right now you would have to double your code by checking which variable is set inside each of your functions.

I would ditch vnum and use snum everywhere instead as std::string is a semantic equivalent of std::vector<char>, except you can benefit from small string optimization.


Dynamically inserting html from external file and updating the database

This looks very clean, there is not much to improve upon.

However, there is a glaring security issue:
https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)

Your code should not allow malicious JavaScript to be stored inside of the db.


I gave it a try compiling it on my machine, but there are too many things still missing, so this will be mainly based on visual inspection of the code.
Functions
I would break out various pieces of this into separate named functions. It will greatly improve readability, and likely they'll be small enough that they'll be inlined, anyway, so it probably won't hurt speed. First, reading the header line could be its own function:
bool check_SLK_header(std::fstream file)
{
    bool header_is_good = false;
    std::string line;
    if (std::getline(file, line)) {
        if (line.substr(0, 2) == "ID") {
            header_is_good = true;
        }
    }
    return header_is_good;
}

I would leave printing the error message to the caller of the main function (which you haven't named, so I can't reference it). That separates out the logic of parsing the file from the display of data to the user, which is usually a good thing.
Next I would break out the various cases of the switch statement into their own functions, too. I would name them something like parse_dimensions_record() for the B case, and parse_cell_record() for the C case. I'll talk about the E case below.
Avoid Infinite Loops
This pattern of writing an infinite loop that has some special "break-out" criteria hidden in the middle of it is extremely hard to read and follow. This is one of the problems with using goto, break (outside of a switch statement), continue, etc. It obscures the flow of the code. You can almost always rewrite an infinite loop better with an actual exit criteria. Here's how I'd write the parse_dimensions_record() function for the B case:
void parse_dimensions_record(const std::string& line, std::vector<std::vector<std::string>>& table_data)
{
    int columns = -1;
    int rows = -1;
    size_t position = 2;
    while (((columns < 0) && (rows < 0)) && (position < line.size() - 1))
    {
        switch (line [ position ])
        {
            case 'X':
                columns = parse_int_part();
                break;
            case 'Y':
                rows = parse_int_part();
                break;
        }
        position++;
    }

    if ((columns >= 0) && (rows >= 0))
    {
        table_data.resize(rows, std::vector<std::string>(columns));
    }
}

It now becomes clear that there are some edge cases that might warrant handling. First, does it make sense to have 0 columns or 0 rows? If not, you should be returning an error and stop parsing, probably, when you hit that case. If so, then you can also probably end early, as there's no point in reading the rest of the file, as there's no columns or rows to hold any data.
You also don't handle malformed data, such as an invalid specifier in the B record, for example. Is it safe to ignore those? Does it indicate a corrupted file? You probably need to return an error code and handle that case in some way.
I mentioned above that I'd talk about the E case below. Well here we are. The main loop for parsing the file isn't an infinite loop which is good, but you still don't need the goto you have in there. You can end it by just keeping around a variable that says whether you've hit the end record. Something like this:
bool hit_end = false;
while ((std::get line(stream, line)) && (!hit_end)) {
    position = 2;

    switch (line.front()) {
        case 'B':
            parse_dimensions_record(line, table_data);
            break;
        case 'C':
            parse_cell_record(line, table_data);
            break;
        case 'E':
            hit_end = true;
            break;
        default:
            // Got some sort of invalid record here. Should probably stop parsing
            break;
    }
}

This is much easier to read and understand and avoids the various goto calls that made the other version difficult to understand.


I have rewritten the script in another fashion. Beware all your code is almost exactly the same, but not entirely. If you are looking to just improve your script a bit, look closely at the parser.

A number of personal preferences I would like to share that I thought while reading your code but which I did not fix in my own code in all cases:

I like (foo === false) better then (! foo) or (foo !== true).
Strings like '%%' should be replaced with constants, preferably some of the numbers also.
Complex logic should be split up. Even my example does fully split up the responsibilities.
Comments should be plentiful (and meaningful!).

The code example is obese compared to the fine script you made. But I find it

Faster to debug
Testable
Easy to replace dependencies
Easy to change how the converter works (just write a couple parsers and converters)

My code example is far from done. The code should strive towards SOLID principles (which this does not). The main issue I've addressed is to clarify some of the mixed responsibilities in your code. But the new code still has some issues, mainly missing tests and SRP violations (in my code the parser is doing the converter's job). This is to show the disadvantage of bundled complex code that handles too many responsibilities.

I used 5.4 array syntax. PHP 5.3 series will enter an end of life cycle and has only received critical fixes as of March 2013.

As mentioned the code is undone (as in breaks SOLID). If you want to further improve it, you could start by moving the converting part (toArray) of the algorithm into the ToArray class.

namespace jarrecord;

Interface Parser {
    public function parse($parsable);
}

Interface Converter {
    public function convert($convertable);
}

class StringParser implements Parser {
    const RECORD_SPLIT_TOKEN = '%%';
    const KEY_VALUE_SPLIT = ':';
    /**
    * Splits and trims unparsed lines and returns array with key value pair.
    *
    * @return array
    */
    private function splitUnparsedLineToKeyAndValue($line)
    {
        return  array_map('trim', explode(self::KEY_VALUE_SPLIT, $line, 2));
    }

    private function splitToUnparsedRecords($recordJar)
    {
        return explode(self::RECORD_SPLIT_TOKEN, $recordJar);
    }

    private function splitToUnparsedLines($unparsedRecord)
    {
        $lines =  explode(\PHP_EOL, $unparsedRecord);
        // filter to remove null lines

        return array_filter($lines);
    }

    /**
    * Takes a array of strings and returns a record-like array
    * @param string $unparsedLines
    * @return array
    */
    private function unparsedLinesToRecord($lines)
    {
        $record = [];
        foreach($lines as $line)
        {
            $partialRecord = $this->splitUnparsedLineToKeyAndValue($line);
            if(count($partialRecord) === 2)
            {
                list($key, $value) = $partialRecord;
            }
            else
            {
                // $key retains its value from the previous iteration.
                $value = $partialRecord[0];
            }
            if(isset($record[$key]) === false)
            {
                $record[$key] = '';
            }
            $record[$key] .= $value;
        }

        return $record;
    }

    public function parse($parsable)
    {
        $unparsedRecords = $this->splitToUnparsedRecords($parsable);
        foreach($unparsedRecords as $unparsedRecord)
        {
            $unparsedLines = $this->splitToUnparsedLines($unparsedRecord);
            $record = $this->unparsedLinesToRecord($unparsedLines);
            $records[] = $record;
        }

    return $records;
    }
}

class ToArray implements Converter {
    private $parser;

    /**
    * @param Parser $parser
    */
    public function __construct(Parser $parser)
    {
        $this->parser = $parser;
    }

    /**
    * Parses a Record-Jar string and returns it as a array.
    * @throws InvalidArgumentException
    * @param string $unparsedRecordJar
    * @return array
    */
    public function convert($unparsedRecordJar)
    {
        return $this->parser->parse($unparsedRecordJar);
    }
}

$parser = new StringParser();
$Converter = new ToArray($parser);
$array = $Converter->convert($source));


How should I structure my Unit tests for minimal Asserts?

In this case, what you're really trying to do is validate three MessageDays, as the return values of one method. As you are only testing one thing (the successful return of a method), you need not worry about testing too many things. I would, however, reduce the amount of asserts to three by implementing .Equals() on MessageDay.

While it may seem like overkill, .Equals() is a virtual method on System.Object, so you do already have an implementation of it available (just not the one you need, as it is currently a reference comparison).

I can't predict whether or not you'll need it again in the future, but I don't consider that a problem when implementing the method in question, because all objects have it. The effort is small, and the chances of using it somewhere other than just testing are high.

The downside is, of course, that your test will have to declare expected values, which may mean that it becomes no shorter, and the reduced number of asserts means your test is slightly less granular. For the second point, that's probably fine, because it also frees you to redesign the class without changing the test. The length could be reduced by  comparing with values saved in the test initialization.


The performance issue and the bug

The program essentially looks for the minimum operations to reduce the numbers to some base line.
There are two problems with the choice of base lines.

The performance issue is that you try base lines from 0 until the minimum value.
Consider this input:

999

The program will check base lines from 0 to 999, in vain.
You need up check only the 3 baselines: min, min - 1 and min - 2.

The second problem is a bug, and it is a related issue.
Consider this input:

0 4 4

The program will check only one base line, 0.
And that will give the incorrect result 4.
Checking -1 would give the correct result 3.

Working with user input

The readInt method is deprecated in favor of StdIn.readInt.

The way you parsed the input is unnecessarily complicated.
This line is commented out,
even though it was really on the right track:

val numbers = scala.io.StdIn.readLine().split(" ").map(s => s.toInt);

Scala style

Some of the var could have been val or unnecessary altogether,
and semicolons at end of lines are not recommended.
Also, you used Range(0, numOfTestCases) at one point,
even though you used the more idiomatic x.until(y) syntax elsewhere.

Alternative implementation

Putting the above tips together:

import scala.io.StdIn

object Solution {

  def main(args: Array[String]): Unit = {
    val numOfTestCases = StdIn.readInt()
    0.until(numOfTestCases).foreach(_ => {
      StdIn.readInt()
      val numbers = StdIn.readLine().split(" ").map(s => s.toInt)
      println(calOpCount(numbers))
    })
  }

  def steps(i: Int): Int = {
    if (i == 0) 0
    else if (i == 1 || i == 2 || i == 5) 1
    else i / 5 + (i % 5) / 2 + ((i % 5) % 2)
  }

  def calOpCount(source: Array[Int]): Int = {
    val min = source.min
    (for {base <- 0.to(2)} yield source.map(s => steps(s - min + base)).sum).min
  }
}


Create a C++ string using printf-style formatting

I agree with you that 'printf-style' formatting was by many aspects better than C++'s manipulators: more concise, more varied, etc. That said, I feel like it's a step backwards if we port them into C++ without upgrading the C logic behind it. In my opinion, your code fails to do that for two reasons: lack of automatic memory management, and lack of type safety.

About type safety, I believe we now must use variadic templates when dealing with an unknown number of arguments. Variadic macros have too many shortcomings for us to continue using them. With variadic templates, we're able to verify if format directives and arguments match in number and types in a more reliable way (although I agree that when you can rely on a format chain the risk is manageable even with C-like macros).

About memory management: I believe we must avoid explicit memory management whenever we can. std::stringstream is a good way to do that when one wants to build a string progressively from heterogeneous arguments.

So here's an embryo of what I would consider more modern C++:

#include <string>
#include <sstream>
#include <iostream>
#include <type_traits>
#include <exception>

// base case of recursion, no more arguments
void format_impl(std::stringstream& ss, const char* format) {
    while (*format) {
        if (*format == '%' && *++format != '%') // %% == % (not a format directive)
            throw std::invalid_argument("not enough arguments !\n");
        ss << *format++;
    }
}

template <typename Arg, typename... Args>
void format_impl(std::stringstream& ss, const char* format, Arg arg, Args... args) {
    while (*format) {
        if (*format == '%' && *++format != '%') {
            auto current_format_qualifier = *format;
            switch(current_format_qualifier) {
                case 'd' : if (!std::is_integral<Arg>()) throw std::invalid_argument("%d introduces integral argument");
                // etc.
            }
            // it's true you'd have to handle many more format qualifiers, but on a safer basis
            ss << arg; // arg type is deduced
            return format_impl(ss, ++format, args...); // one arg less
        }
        ss << *format++;
        } // the format string is exhausted and we still have args : throw
    throw std::invalid_argument("Too many arguments\n");
}

template <typename... Args>
std::string format(const char* fmt, Args... args) {
    std::stringstream ss;
    format_impl(ss, fmt, args...);
    return ss.str();
}

int main() {
    auto display = format("My name is %s and I'm %d year old", "John", 22);
    std::cout << display;
}


I like the formatting, use of white space and tabs.

I'm not sure what THRESHOLD is supposed to represent or where its set, but in the example, I'd make it a const.

I would do the check for 0 right below the assignment:

if (THRESHOLD == 0)
{
    ...

    return;
}

This will un-nest the main logic of your function and catch the error before any processing is done.

The logic should be moved out into their own functions:

var subsets = (channels < 1) ? ProcessWholeList(...) : ProcessPartialList(...);

This will better portray then intention of the logic and remove most of the unimportant variables out of the function cleaning it up quite a bit.

I like that you have created an extension to do the split, not many people think of that.

I would change the bool even ... into a check for odd numbers.  That what you could change the

if (!even)

to

if (odd)
{
    ....
}

Again, expresses the intent a little better.  I would also either move the assignment to right above the check.

This assignment:

int allocLength = length;
if (!even && i == totalLength - 1)
    allocLength = arrayIn.Length % length;

Should be changed to:

var allocLength = (!even && i == totalLength - 1) ? arrayIn.Length % length : length;

There are just a few simple changes that will clean it up quite a bit.  I hope this is a good start and gives you some ideas.

I have another question, is there a reason why you are using a 2 dimensional array rather than one of the build in IEnumerables (i.e. HashTable)?  I think for performance purposes, the two dimensional array would be the slowest way of doing it.


Could anyone say if this is a reliable shuffling code?

your code is pretty neat and readable. Shuffling algorithm looks reliable to me, however I have a few comments to your C# code.

You pass the argument numberOfTries as ulong type, but correctHits and wrongHits are int. It could lead to wrong output if the numberOfTries is large enough to overflow int.MaxValue.
Variable doors are initialized in each loop. It could be initialized once in higher scope, e.g. before the for loop.
I can see repetetive code doors[prizeIndex.Next(0, doors.Length)]. This piece of code could be refactored to isolated method. For example:

private static int GetDoorNumber() => _doors[_prizeIndex.Next(0, _doors.Length)];
You can save couple of code lines introducing ternary operator. Then you do not need variable correctGuess.

correctHits += (selectedDoor == prizeDoor) ? 1 : 0;

You can calculate wrongHits as a difference of numberOfTries and correctHits. But your solution works too.


Finding the first triangle number with over five hundred divisors

Code

total += 2 is a bug. In case sum is a perfect square, and c happens to be its root, total shall be incremented by 1.
Using floating point (sqrt) in a number theoretical problem is dubious at best.
You don't need overallAdd. sum += i; suffices.
Naming looks arbitrary. The sum is a triangular number, total is a sum of divisors, so call them appropriately. Single-letter identifiers, like c shall be avoided.
Add your operators some breathing space.
Inner loop computes the number of divisors. Better factor it into a separate function.

Algorithm is brute force, which is never good, especially for Project Euler problems. This problem was discussed here many times. See this shameless self-plug for example.


You can improve your ternary operator by using it like this :

$today = new DateTime();
$this_months_friday = new DateTime('first friday of this month');
$next_months_friday = new DateTime('first friday of next month');
echo 'Friday, '. (($today < $this_months_friday) ? $this_months_friday->format('M j') : $next_months_friday->format('M j')) . ' at 7pm';

which can them become :

echo 'Friday, '. (($today < $this_months_friday) ? $this_months_friday : $next_months_friday)->format('M j') . ' at 7pm';


You could simplify entire test class by extracting part responsible for general configuration. Then you can easili split your test into two, first verifying that your IRestClient is properly called during the process and second that assures tested method returns result provided by this client. For tests that require specific configuration, like throwing exceptions and so on, I found it a nice way to extract this configuration to separate, private methods and calling them when necessary instead of configuring all the scenarios in the Setup method.

[TestFixture]
public class ClientTest
{
    private const long SessionId = 123;
    private Mock<IRestClient> _clientMock;
    private List<string> _expectedSources;
    private Session _session;

    [SetUp]
    public void Setup()
    {
        _expectedSources = new List<string>
                {
                    "Scanner1",
                    "Scanner2"
                };
        _clientMock = new Mock<IRestClient>();
        _clientMock.Setup(x => x.Execute<SessionPrototype>(It.IsAny<IRestRequest>()))
                   .Returns(new RestResponse<SessionPrototype>()
        {
            Data = new SessionPrototype
            {
                Id = SessionId,
                InstalledSources = _expectedSources
            },
            StatusCode = HttpStatusCode.OK
        }).Verifiable();

        _session = new Session(SessionId, _clientMock.Object);
    }

    [Test]
    public void GetAvailableSources_MustCallTheClientUsingProperRequest()
    {
        _clientMock.Verify(
            m => m.Execute<SessionPrototype>(
                It.Is<IRestRequest>(
                r => r.Resource == $"session/{SessionId}" &&
                     r.Method == Method.GET)));
    }

    [Test]
    public void GetAvailableSources_ReturnsSourcesProvidedByClient()
    {
        var sources = _session.GetAvailableSources();

        CollectionAssert.AreEquivalent(_expectedSources, sources);
    }
}


Some suggestions:

IP addresses are only formatted as octets (0-255) for human readability - they actually just represent integers. Instead of for example 127.0.0.1 you can use 2130706433 (127*2^24+1). In other words, range(2^32-1) represents the entire range of IPv4 addresses.
Using a Python library to ping hosts is very likely going to be much faster than starting a shell command.
Use multiprocessing rather than Python threads to avoid running into the global interpreter lock
response_array will end up taking many gigabytes of memory. If you really need the kind of detail you're logging you should be writing each entry to disk ASAP (keeping the file open all the while). You could also look into simplifying your reporting, such as only saving the IP addresses which don't respond, or saving to two files, one with responding IPs and the other with non-responding ones. You'll have to store a file (or a pair of files) per process, to avoid them clobbering each other.


Update database, reload page then show a success message

What you're doing is extremely typical. So typical that a language was made specifically for it: Ajax!
I'll make some comments here, starting from the top.
Your method
It's close, but it can be simplified even more. For reference, here's your method:

Make your Ajax call and reload on success
Set a session in your php code with a variable
Check the session is set and output the necessary message
Empty the session

and then I'll make my own so we can see the differences.

Make an Ajax call
Update the database and return a response
Output the respective message

A quick re-write
I thought that rewriting this would be the best way to show how things could be done differently.
Ajax
$(".active_button").on("click", function() {

    var articleID = $(this).attr("name");
    var active = $(this).val();
    $.post("controllers/articlecontrol.php", {articleID: articleID, active: active}, function(data) {
        var response;
        var class = "success";
        if (data === "deactivated") {
            response = "Deactivated Successfully";
        } else if (data === "activated") {
            response = "Activated Successfully";
        } else {
            response = "Whoops!";
            class = "failure";
        }
        $("Some DOM item").before('<div>' + response + '</div>').addClass(class);
    });
});

articlecontrol.php
if (isset($_POST['active'])) {
    $where = array('article_id' => $_POST['articleID']);

    $active = ($_POST['active'] == 'YES') ? '0' : '1';

    $update = array('article_active' => $active);

    if ($database->update('wcx_articles', $update, $where)) {
        if ($active == '0') {
            echo "deactivated";
        } else {
            echo "activated";
        }
    }
}

Inline PHP
Gone! Not even needed anymore!
Changes made:
A lot, right? Well it's okay, I'll try and explain why I modified your code like this.
First off, I placed the button handler directly onto the class and avoided dealing with the document call. It cleared things up a little!
I changed your $.ajax call into a $.post call. For your implementation here, I found it to fit real nice. It's the exact same functionality, just in a way I believe to be more clear and readable.
Inside of this Ajax call, I added a lot of business logic. It now accepts data from the PHP page and then decides how to display the action. The error handler on this is very primitive and could be improved. Note that you must define where in the page the messages will pop up. It appears you have the knowledge to know what I've done here, however if you need me to reference anything or clarify, just ask!
Look at that! Done with the jQuery already!
The biggest change I made with your PHP was taking out the need for sessions. Everything else is simply topical and hopefully more clear than the original code. Let me know if you don't understand anything. Do note however, I have echoed the response that the Ajax will receive. If you needed, you could also format it in JSON, more on that here.
And since we cleared out the sessions, the inline PHP is gone!
I don't normally just rewrite people's code, but I felt this could have used multiple alterations which wouldn't make sense if I din't have complete context!


You should relearn design patterns.  Until you do this, your framework is bound to be messed up and poorly architected, if only because of your flawed axioms.

The Adapter Pattern is for taking class A implements InterfaceA and wrapping it inside a class Adapter so that you can use it with the same API as class B implements InterfaceB. It has nothing to do with executing different code or whatever inside another class.

The Strategy Pattern is meant to reduce cyclomatic complexity (basically, lots of nested if statements). It works like this:

interface BasicLogicI {
    public function execute();
}

class GreetingLogic implements BasicLogicI {
    public function execute() { echo "Hi!\n"; }
}

class DismissLogic implements BasicLogicI {
    public function execute() { echo "Bye!\n"; }
}

class Speaker {
    protected $strategy;

    public function __construct($strategy) {
        $this->changeContext($strategy);
    }
    public function changeContext($strategy) {
        unset($this->strategy);
        $this->strategy = $strategy;
    }
    public function speak() {
        $this->strategy->execute();
    }
}

$speaker = new Speaker(new GreetingLogic);
$speaker->speak();
$speaker->changeContext(new DismissLogic);
$speaker->speak();
// Output: Hi!
//         Bye!


This can be order of magnitudes simpler.  You want a function that takes a width, height, and optional fill character, and returns a string (your box).

Try this:

function box(w, h, fill='░░') {
  const top    = '╔' + '══'.repeat(w-2) + '╗\n'
  const row    = '║' + fill.repeat(w-2) + '║\n'
  const bottom = '╚' + '══'.repeat(w-2) + '╝'
  return top + row.repeat(h-2) + bottom
}


You have a lot of repeated code. If you follow the same design you will end up with a huge list of create???() functions

You could simplify to a single function, and pass tag name and an optional properties containing element and style properties.

const createTag = (tag, props = {}) => {
    const style = props.style;
    if (style) { delete props.style }
    const el = Object.assign(document.createElement,props);
    if (style) { Object.assign(el.style, style) }
    return el;
}

Thus you can create tags

createTag("input", {type : "button", id : "buttonId"});
createTag("button", {value : "Click me"});
createTag("div", {textContent: "abc", id: "abcId", className: "abcDiv", style: {width: "10px"}});

If you did want to have a function to create each type then it would pay to put them together.

const createDOM = {
    label(...
    button(...
    input(...
    div(...
    // and so on
}


I took your code and started condensing it, and came up with the following improvements that could be made:

Change the inner loops to use the string constructor that takes a character and a count instead of using a loop
Give the method and variables more meaningful names
Add a size parameter that can be passed to the method
Put declarations and incrementing of variables in the for statement
Use math operations on the counter rather than tracking multiple variables that increment at constant rates relative to the counter
Use Enumerable.Range as a looping mechanism to select the strings along with string.Concat to join them together
Have the method return a string so it can be written by the client to other things (like a log file or another control)

Code:

public static string GetPyramid(int size)
{
    return string.Concat(Enumerable.Range(0, size).Select(count =>
        new string(' ', size - count) +
        new string('*', count * 2 + 1) +
        Environment.NewLine));
}