You are not always returning anything

private function checkUrlAction($sAction) {
    if(true){
        return true;
    }

    //but else?
}

Dependency injection

$objShowPDO = new mShowPDO(); is bad a mShowPDO instance should by injected via method or constructor argument see dependency injection topics

private function checkUrlItem(mShowPDO $objShowPDO, $sItem){
    if($sItem == 'imagelist' || $sItem == 'mkdir' || $sItem == 'rdir'){
        return true;
    }

    //redundand else removed

    $result = $objShowPDO->allTables(); //maybe you can inject only the result
    while($array = $result->fetch()){
        if($array[0] == $this->sItem){
            return true;
        }
    }

    return false;
}

Hard coding

The checklists are really hard coded (long if with OR relations), try use some container for them (an array and use in_array() for example).


Preventing duplicate numbers from being entered

Use prepared statement

You should never ever formulate an SQL string from variables.
You should use parameterized prepared statements,
and let a library fill in the parameters using the right native types.

Instead of this:

  string query = "SELECT CNIC FROM `voters`.`voters` WHERE ID=" + k.ToString() + ";";
  MySqlCommand cmd = new MySqlCommand(query, def);
  cmd.ExecuteNonQuery();

You should do like this:

var cmd = new MySqlCommand("SELECT CNIC FROM `voters`.`voters` WHERE ID=@id");
cmd.Parameters.AddWithValue("@id", k);
cmd.Prepare();
MySqlDataReader Reader = cmd.ExecuteReader();

This technique effectively prevents the most malicious SQL injection attacks.

Apply this to all your queries.

Extremely confusing code

What is the purpose of setting query when k == 0 in this code?

if(k==0)
{
   query = "DELETE FROM `voters`.`voters`;" + "INSERT INTO `voters`.`voters`(`ID`,`Name`,`CNIC`) VALUES(" + i.ToString() + ",'Random'," + CNIC + ");";
   MySqlCommand comd = new MySqlCommand("DELETE FROM `voters`.`voters`;", conn);
    comd.ExecuteNonQuery();
    i++;
}else{
  query = "INSERT INTO `voters`.`voters`(`ID`,`Name`,`CNIC`) VALUES(" + i.ToString() + ",'Random'," + CNIC + ");";
  i++;
}

=> Nothing. That query is not used, instead, DELETE FROM voters.voters is executed, wiping out the table. Extremely confusing.

read_data

You want to make your program more efficient,
and as you commented to @Hosch,
you want to know the logic is correct.
But the problem is,
without well-named functions and variables,
it's really hard to figure out what your intended logic is.
A function called as vague as "read data",
returning a variable named "yes",
is really hard to review.
We literally have to decipher your intentions,
as it was an encrypted message.

Let's first go over everything that's wrong with this method:

Variables

Not declared in the smallest necessary scope. This is a problem, as readers have to read the entire function to understand all the impact of a variable
Poor names, as mentioned, because it's impossible to guess the intention behind a variable named "yes", or "loop", or "k"
Unused variables, that have no purpose at all, like "loop"

Flow control: what is going on in that while loop? Count up k from 0, select CNIC where ID=k. Exit the loop when there is no match with ID=k. For each row selected one by one, check if CNIC is equal to the value in textBox1, and set yes = true.

This is far more convoluted than it needs to be
After you set yes = true, it's pointless to continue looping, since at that point you already have the final return value for the function
Having Reader.Close() twice is a huge warning sign, you can probably refactor this to close only in one place
For all operations that open resources, you should wrap in a using block

Mixture of SQL and conditions in code: It's inefficient to do a SELECT, and then do additional filtering using conditionals in code. It's best to do all filtering in the WHERE clause of the SELECT, so that the data you get from the query is ready to use, and you also don't waste bandwidth in the communication with the database.

This is untested, but I think should at least point you in the right direction:

private bool HasAlreadyVoted(MySqlConnection conn, string cnic)
{
    string query = "SELECT 1 FROM voters.voters WHERE CNIC = @cnic LIMIT 1";
    using (MySqlCommand cmd = new MySqlCommand(query, conn))
    {
        cmd.Parameters.AddWithValue("@cnic", cnic);
        cmd.Prepare();
        using (MySqlDataReader Reader = cmd.ExecuteReader())
        {
            return Reader.Read();
        }
    }
}

Preventing duplicate votes

First of all, you should use unique constraints on the database table itself. Then when you try to insert a duplicate vote, the query will throw a unique constraint violation exception, which you can catch and respond to.

Another thing, when you do multiple operations in the database that must be all executed without interruption, or not execute at all, such as a delete followed by an insert, then you should wrap these operations in a transaction.

Cleaning up the rest

Apply the same logic to button1_Click as I showed above for read_data.
Some tips:

Start by renaming everything. Go over every single element in your code, the class name, method names, variable names, and ask yourself:

What is the purpose of this class/method/variable?
Does the name reflect that purpose? Would another person understand the purpose by looking at the name?
Is this the right place to declare this variable? Can it be moved to a smaller scope, to avoid exposing it to places where it's not used at all?

Check that all resources are correctly closed. Almost everything that needs to be closed can be put in a using block, which is better, and it also saves you from explicitly calling Close()
All parameterized queries should use prepared statements, and never be constructed as a simple string.


Building balanced BST from sorted array: recursive and iterative approaches

Let me start with an all too common hindsight:
your code lacks test support and scaffold.

The most basic test support for a class is a succinct __str__, for class Node:

def __str__(self):
    return '<' + ('.' if not self.left else (str(self.left) + '|')) \
        + str(self.value) + ('.' if not self.right
                             else ('|' + str(self.right))) + '>'

(a more elaborate one would allow to limit recursion.) The result for

if __name__ == '__main__':
    ascending = [chr(x) for x in range(ord('a'), ord('g'))]
    print(build_bst_recursive(ascending))
    print(build_bst_iterative_one_stack(ascending))

  <<.0|<.1.>>|2|<<.3.>|4|<.5.>>>
  <<<.None.>|a|<.b.>>|c|<<.d.>|e|<.f.>>>

highlights an oversight with _build_bst() (not using node = Node(array[mid])) and a problem in the stack variants with always creating two child nodes (or with the handling commented # The segment is degenerated. Do nothing.).

Your code is more or less in line with the Style Guide for Python Code (good - do you use an IDE, your IDE's PEP8 support?); make it a habit to provide documentation strings for everything public, too.

If I was serious about comparing alternative implementations, I'd try to define an interface and hope to avoid names like build_bst_iterative_one_stack.
I got used to the builtin len(), I don't see an advantage to introducing size = len(array) where used once.

_build_bst() is pretty basic; if it was public, it would need a doc string specifying last to be inclusive. I don't like the name array - would prefer values or ordered (ascending would be misleading, as _build_bst() works perfectly for descending values).

I'd hesitate to roll my own stack class, more so if the stated purpose was something else, entirely. If I did, I'd just extend list:

class Stack(list):
    ''' syntactic sugar: adds push(), is_empty() to list's pop() '''
    push = list.append

    def is_empty(self):
        return not bool(self)

(Skipping build_bst_iterative().)
In build_bst_iterative_one_stack(), I'd prefer toDo over stack. The comment stack stores […and…] indices of half-segments is funny in the first tuple pushed two statements down not being a half.
I don't have an inspiration how to fix the introduction of None-Nodes without duplicating the check.

Your "build_bst_iterative*()" implementations are straightforward conversions of the basic recursive approach (see Create Balanced Binary Search Tree from Sorted linked list for one working without "random" access); I would not expect insights beyond doesn't get prettier for explicit stack handling.

Much to my dismay, I didn't find a decent web reference for a genuine iterative approach (numerous weird ones, some as new as 2019/3/2):
First consider the case of 2ⁿ-1 nodes: with levels numbered from 0 for bottom (up to n-1), the level of each node is the number of trailing zeroes in its ordinal. Have an array to reference one node for each level, initialised to Nones. For each value, create a Node. Check the reference at the level indicated by the number of trailing zeroes in its ordinal: if None, just plant the node there and make whatever is one level lower its left descendant. If not None, make node the right descendant of the node at the next higher level an set this level to None. (As an alternative to checking this reference, you can inspect the bit in the ordinal just two above the trailing zeroes.)
There are numerous ways to handle N ≠ 2ⁿ-1; one being to aim for a complete binary tree: compute the ordinal rb of the rightmost node at the bottom level. Proceed as above to rb+1, and increase the "ordinal number" by two instead of one thereafter.
(Finally, return the node at the highest level as the root of the tree built…)


Right now selectedList is a string that seems to be put together solely for searching through it. That has the potential to be a big performance bottleneck.

If you change it to an array, you can squeeze a bit more efficiency into your code by sorting the array and then using a binary search method to detect whether it contains the desired value.

Here's an example of a binary search method.

// Accepts a sorted array, an object, and an optional comparator method
// Returns index of detected object, or a negative value if not found (binary complement of proper index)
function getIndex(arr, target, comparator) {
    var l = 0,
    h = arr.length - 1,
    m, comparison;
    comparator = comparator || function (a, b) {
        return (a  b ? 1 : 0));
    };
    while (l <= h) {
        m = (l + h) >>> 1;
        comparison = comparator(arr[m], target);
        if (comparison < 0) {
            l = m + 1;
        } else if (comparison > 0) {
            h = m - 1;
        } else {
            return m;
        }
    }
    return~l;
};

You'll find that although there's a small performance penalty resulting from the need to sort the array, you'll be able to look up the indices of elements much faster this way. Check out the code snippet embedded below for some dramatic proof!

var log = (function (output) {
    return function (text) {
        output.insertAdjacentHTML("beforeend", text + "
");
    };
})(document.getElementById("output"));
document.getElementById("RunTests").onclick = function () {
    document.getElementById("output").innerHTML = "";
    var numWords = document.getElementById("NumWords").value;
    var numTestWords = document.getElementById("NumTests").value;
    var str = "";
    var arr = [];
    log("Creating a list of " + numWords + " items:");
    var start = Date.now();
    for (var i = 0; i < numWords; i++) {
        var word = randomString();
        arr.push(word);
    }
    log("Time to build array: " + (Date.now() - start));
    start = Date.now();
    for (var j = 0, len = arr.length; j < len; j++) {
        var temp = randomString(); // just to be fair to testing time
        str = str + "," + arr[j];
    }
    str = str.substr(1);
    log("Time to build string: " + (Date.now() - start));
    start = Date.now();
    arr.sort();
    log("Time to sort array: " + (Date.now() - start));

    var test = [];
    for (var k = 0; k < numTestWords; k++) {
        test.push(arr[Math.random() * arr.length >>> 0]);
    }
    log("Searching for " + test.length + " test words: ");

    var index = test.length;
    start = Date.now();
    while (index--) {
        str.search(test[index]);
    }
    log("Time to search string: " + (Date.now() - start));

    index = test.length;
    start = Date.now();
    while (index--) {
        getIndex(arr, test[index]);
    }
    log("Time to search array: " + (Date.now() - start));
}

function getIndex(arr, target, comparator) {
    var l = 0,
        h = arr.length - 1,
        m, comparison;
    comparator = comparator || function (a, b) {
        return (a  b ? 1 : 0));
    };
    while (l <= h) {
        m = (l + h) >>> 1;
        comparison = comparator(arr[m], target);
        if (comparison < 0) {
            l = m + 1;
        } else if (comparison > 0) {
            h = m - 1;
        } else {
            return m;
        }
    }
    return~l;
};

function randomChar() {
    return "abcdefghijklmnopqrstuvwxyz" [Math.random() * 26 >>> 0];
}

function randomString() {
    return "" + randomChar().toUpperCase() + randomChar() + randomChar() + randomChar();
}
Number of words in list:
<input type="text" value=5000 id="NumWords">

Number of tests to run:
<input type="text" value=5000 id="NumTests">

<input type="button" value="Run Test" id="RunTests" />

To use that in your code, you'd need to change the selectedList string to an array and sort it, as in the code below.

    /* Gathers an array consisting of all the selected values */
    var selectedList = [];
    for (var h = 0; h < selected.length; h++){
        selectedList.push(selected.options[h].value.toLowerCase();
    }
    selectedList.sort();

Then your loop to check whether a given string exists in the array would look like this:

//Loop JSON query structure and reload select
for (var i=0, count = query.ROWCOUNT; i < count; i++){
    var id = query.DATA.ID[i];
    if(getIndex(selectedList, id.toString().toLowerCase()) < 0){
        element.options[element.options.length] = new Option(query.DATA.NAME[i], id);
        var optionLength = element.options.length;
        optionLength--;
        if(query.DATA.title != undefined  && element.options[optionLength] != undefined){
            element.options[optionLength].setAttribute("title",query.DATA.title[i]);
        } else {
            element.options[optionLength].setAttribute('title',query.DATA.NAME[i]);
         }
    }
}


Generate power sets given a set of elements in java

Your code contains some unnecessary assignments, where the value assigned to a variable is never used before it is being overwritten. These are the first assignment of index in the line int index = -1; and the first assignment of current in the line int current = 0;. With the assignments gone, only the declarations int index and int current are left, and since it generally makes code easier to understand to reduce the scope of variables to the smallest possible extent and to keep them out of places where they are not needed, I suggest you move the declarations of these variables inside the for loop, since they are not needed outside it and don't need to keep their value from one loop iteration to the next, as they are assigned a new value at the beginning of each loop iteration. The same goes for the variable tempSubset.
You are treating the empty subset as a special case by adding it manually before the for loop and then initializing i to 1 instead of 0. However, this is not necessary. The code would work just as well if you removed the line subsets.add(new ArrayList<>()); and initialized i to 0. This would not only save one line of code, but with one algorithm that works for all cases, and not only for all cases except one, the code will be easier to understand.
A for loop might be more fitting for what your are doing with a while loop. Instead of this:

index = -1;
tempSubset = new ArrayList<>();
current = i;
while(current != 0){
    index++;
    if((current & 1) != 0){
        tempSubset.add(nums[index]);
    }
    current = current >> 1;
}
subsets.add(tempSubset);

You could do this:

tempSubset = new ArrayList<>();
for (int index = 0; (i & 0xFFFFFFFF << index) != 0; index++) {
    if ((i & 1 << index) != 0) {
        tempSubset.add(nums[index]);
    }
}

After these changes, your code will look like this:

public List<List<Integer>> subsets(int[] nums){
    int numOfSubSets = 1 << nums.length;
    List<List<Integer>> subsets = new ArrayList<>();

    for(int i = 0; i < numOfSubSets; i++){
        List<Integer> tempSubset = new ArrayList<>();
        for (int index = 0; (i & 0xFFFFFFFF << index) != 0; index++) {
            if ((i & 1 << index) != 0) {
                tempSubset.add(nums[index]);
            }
        }
        subsets.add(tempSubset);
    }
    return subsets;
}


Constructing polygons from the edges in a Voronoi diagram

To improve the speed of your code, you'd really have to profile it, and know what the bottleneck is (use a profiler, and find out in what methods most of the time is spent).

Here's what I would have a look at (no promise it will yield significant improvements).

polygonsList.get(n) is evaluated twice per iteration.
The polygon class you're using (I assume java.awt.Polygon) takes ints as coordinates, while the library calculates them in doubles. Yo may want to consider writing a custom Polygon class that takes doubles, in order to avoid the casts.
if you only need the Polygon class for drawing, you may even forego that entirely and make a class that can draw a line given a GraphEdge. This will avoid creating Polygon objects, and you can reuse the same drawing instance.


Merge sort implementation using iterators

You should prefer to move values whenever possible.

std::move(begin, mid, std::back_inserter(left));
std::move(mid, end, std::back_inserter(right));

size_t j = 0, k = 0;
auto i = begin;

for (; i != end && j < left.size() && k < right.size(); ++i) {
    *i = std::move(comp(left[j], right[k]) ? left[j++] : right[k++]);
}

while (j < left.size()) {
    *(i++) = std::move(left[j++]);
}

while (k < right.size()) {
    *(i++) = std::move(right[k++]);
}

Every call of mergeBack will end up allocating 2 new buffers. You can avoid that by preallocating the secondary buffer and flip flopping between them but that is tricky to do in the recursive version. Which is why I prefer the iterative version that goes bottom up.


Bash script that can uncompress: tar, gzip, rar

Don't use cut and grep, use parameter substitution and a case statement over the file extension to decide the file type (or use the file command if you want to be really clever, but I recommend the former actually)
Don't use [ "${foo}" != "" ], use [ -n "${foo}" ]
Don't mix test and [, just stick to [ unless you want to write code that looks autoconf generated
Quote all your variables, especially the ones containing filenames to account for spaces, e.g. tar xzf "$1" > /dev/null
Don't parse command line options yourself, use getopts (or getopt, in case you really, really want GNU-style options)
Improve your indentation


Well, the most obvious fix is indeed map-invert-preserving-dups - the whole thing could be more easily written as:

(defn map-invert-preserving-dups [m]
  (apply merge-with into
         (for [[k v] m]
           {v [k]})))

The for expression yields a sequence of maps like [{a [1]} {b [2]} {a [5]}]. Apply calls merge-with into on all of those maps. If you look up the definition of merge-with, you can see that this means basically: "Merge all of these maps together, and if the same key exists twice, with values x and y, then make its value (into x y)".


Got it:

Rails.application.routes.draw do
  root 'home#index'

  resources :articles, except: [:index, :show]
  constraints section: /section1|section2|section3|section4/ do
    constraints year: /\d{4}/ do
      constraints month: /\d{1,2}/ do
        resources :articles, only: [:index, :show], path: '/:section/:year/:month', as: :my_articles
        get ':section/:year/:month', to: 'articles#by_month', as: :month
      end
      get ':section/:year', to: 'articles#by_year', as: :year
    end
    get ':section', to: 'articles#by_section', as: :section
  end

I feel this is much cleaner :)


Connected components algorithm does not scale past 10,000 nodes

In algorithm implementation there are usually subtleties that are difficult to spot in a code review. In these cases, I always recommend to have a look at the implementation in other libraries in which smarter people have already spent time to get a good performance.

In this case, I think the library to look at is NetworkX and the implementation for the algorithm you're working on is here.

I hope this helps.


Bug

At the end of the first loop,
how many numbers will be in numbers_entered?
10? Hopefully.
In reality: 10 minus invalid entries,
and I'm not sure that was your intention.

This way the invalid entries will be skipped, and there will always be 10 entries in list:

while True:
    number = raw_input('Enter an integer: ')
    if number.isdigit():
        number = int(number)
        numbers_entered.append(number)
        break
    else:
        print 'That was not an integer!'

Handling invalid input

The user input should be valid,
invalid inputs should be the exception.
So you can simplify the handling of invalid user inputs using exceptions:

try:
    number = int(raw_input('Enter an integer: '))
    numbers_entered.append(number)
except ValueError:
    print 'That was not an integer!'

See also the glossary, and search for the word "forgiveness" in it.

Using list comprehensions

List comprehensions are awesome.
The loops could be replaced by list comprehensions
(with the help functions), for example:

def read_int():
    while True:
        try:
            return int(raw_input('Enter an integer: '))
        except ValueError:
            print 'That was not an integer!'

numbers = [read_int() for _ in range(10)]

odd_numbers = [item for item in numbers if item % 2]

if odd_numbers:
    print 'The largest odd number entered was {}.'.format(max(odd_numbers))
else:
    print 'No odd number was entered.'

Prefer .format(...) for formatting

Instead of formatting with %,
the new preferred way is using .format(...):

print 'The largest odd number entered was {}.'.format(max(odd_numbers))

Notice that there's no need to call str(...) when using this style.

Readability

This statement would have been better on a single line:

print 'The largest odd number entered was %s.' % str(max(
        odd_numbers))


What do you mean by "reduce the size"? Code or byte-code?
If it's code you can easily remove a few lines by merging your System.out.print*():

System.out.printf("Wins: %d %.2f%%\nLosses: %d %.2f%%\nDraws %d %.2f%%",
    wins, winP, losses, loseP, draws, drawP);

Also, what is the use of transforming Integer into a String for the switch()? switch() on String was introduced in Java 7. A better-optimized version would be to use int directly:

int choice = random.nextInt(3); // (n-1) 0 = rock, 1 = paper, 2 = scissors
switch (choice) {
    case 0:
        ...
}

You can also have a String[] to store what you want to display:

String[] rps = { "rock", "paper", "scissors" };
if (choice >= 0 && choice < rps.length)
    System.out.println("Computer chose "+rps[choice]);
else
    System.out.println("Wrong choice!");
// Or use ternary operator:
//System.out.println(choice >= 0 && choice < rps.length ? "Computer chose "+rps[choice] : "Wrong choice!");

For byte-code size you can use primitive int instead of class Integer. And also int for your wins, losses, draws and games variables: ++ incrementation is a lot faster on int than on double. You can convert them to double only when computing the percentage (and correct a potential percentage calculation bug when using integer arithmetics):

loseP = 100.0 * losses / games; // 100.0 is a double, so 100.0 * losses is a double and (100.0 * losses) / games is also a double
// loseP = losses/games*100 will always be an int: losses and games are int, losses/games is an int, 100 is an int and losses/games*100 is an int

I'll let you figure out the rest :)


Having a class return a single database instance or list of all database instances

First, I don't like the concept of mixing "Models" with "Repository".

One principle that, from my point of view, should be followed, is the Single Responsibility (the S in SOLID). It means that one class should have one responsibility, and only one. Therefore yours would be against this principle, simply because you are holding your data, and loading data from the database.

If you want to follow this Principle, you would have one class "PersonRepository", that handles getting/updating data to the database, and a second class "Person", which is the person itself.

PersonRepository personRepository = new PersonRepository();
Person person = personRepository.Find(1); // Would return a person
List<Person> persons = personRepository.FindAll(); // Would return all records

Anyway, regarding your implementation, the point that are bad :

Constructors --> Never do any database related/IO operation in constructor. How would you handle the exception ? You would have an object created (as you cannot destruct them), but actually a "not working" object. Bad practice. And as said by Nick, it will not be clear for the user of the class that this load the user from database. Imagine he wants to create a Person with a predefined ID, he may think using the "ID" for the constructor would be the way to go
As said before, Load and List should be static.
Why is the "LoadFromDatabase" id mandatory ? Use optional parameters, in example :

... LoadFromDataBase(int personId = 0);

Same for the constructor
Imagine now you have a webpage/grid in an application that should display some filtered value, or paginated. How would you handle this ? You would create tons of method within your person class to "LoadFromDatabaseFilterByName(String name)", "LoadFromDatabasePage(2)",... And this would mess up with real method of the class (see first paragraph.
As said by Nick, the LoadFromDataBase is really... strange.


Is there a better, more efficient way to write this loop?

Some guesswork here but I think what you want is actually something like this:

def match_something(file, match):
    """ Finds a line in file starting with 'RESULTS:' then checks the following 50
    lines for match; if it fails returns None, otherwise it returns
    how many lines down from the 'RESULTS:' heading the match is found
    """
    in_results_section = False
    results_counter = 0
    for line in file:
        if line.strip():
            if results_header_found:
                if line.split()[1] == match:
                    return results_counter  # found a match
                else:
                    results_counter += 1
                    if results_counter > 50:
                        return None
# I'm assuming in the above that there can only be one results section in each file

            elif line.startswith('RESULTS:'):
                results_header_found = True

matched_results = []
for i in range(BestX):
    thing = model[BestFitsModel[0][i]]

    # make variables with descriptive names
    directory, input_thing, match = thing[0], thing[2], thing[6]
    list_of_matches = np.append(list_of_matches, match)
    with open(directory.replace('inp', 'out', 1), 'rb') as file:
        m = match_something(file, match)
        if m is not None:
            matched_results.apppend((i, m))
    stb_directory = directory.replace('inp', 'stb', 1), 'rb')
    np.append(directory_list, stb_directory)
    with open(stb_directory, 'rb') as file:
        spectrum = [line.split() for line in file]

This uses a function match_something to go through the file. As soon as a result is found, the function exits (return i, results_counter) and then the main loop adds this result to a list of matched results. If no result is found within 50 lines of the line starting 'RESULTS:' then the function returns None, and the loop moves to the next line of BestFitsModel[0]. (If, on the other hand, there can be more than one results section within each file, then you need to alter this accordingly; it should carry on checking the rest of the file rather than returning, which will be slower.) I hope it should be fairly clear what is happening in this code; it should avoid looping through anything unnecessarily (assuming I've guessed correctly what it's supposed to do)

In the original code, it seems that the files are not closed (T.close()), which could cause problems later on in the programme. Using the with notation avoids the need for this in the above code.


Putting in order my two packages and possibly merging them

The ideal package structure is one which indicates usage. Classes such as these which exclusively contain static methods are definitely utility classes, which I usually put in a util subpackage of your main application.

From what it sounds like, you don't have a main package at the moment which ideally would be your website (in reverse domain order), e.g. com.stackexchange.codereview so that the more specific elements are later, then on top of that you'd have the name of your application which may make it something like com.stackexchange.codereview.tweettrends.

This would be the core of your program, and from here you could then add on your extras.

The Twitter package in particular doesn't sound helpful: your entire program seems to relate to Twitter so it doesn't really convey what that part of the program does. Frankly, I'd just put all those classes under com.stackexchange.codereview.tweettrends.util and add in more sub-packages if you add more classes.

And generally speaking, in Java packages should be exclusively lowercase.


Make two random enemies shoot projectiles every second

Games
Performance
Writing games using JavaScript presents some unique problems.

Jank and slowdown due to memory management. Though there have been vast improvements to what was the norm just a few years back, memory management remains a major point of performance degradation.
Games must always be aware of the issues of memory management. Many common pattern used in JavaScript are not suitable for games.

Platform variance. JavaScript games will run a vast range of platforms, from low end hand held devices, to power hungry overclocked water cooled desktop towers. The average consumer's device is generally of lower spec than the average developer's device.
The success of a browser based game is highly dependent on social networking, a game that does not have a strong focus on performance will not be as successful. Even minor performance problems can make the game unplayable on many more devices than would be  expected on a linear curve as the majority of devices are to the lower end of capability.
Bad reviews are worse than good in a market dominated by word of mouth (social networking) Poor performance is a major driver of bad reviews.

To get the best performance you must get a good understanding of what is slow and what is fast. This is true right down to the most trivial operations need to consider performance.
A look at performance.
Arrays are slow.
Creating and populating arrays are slow due to many factors.

Allocation on heap
Iteration to fill
De-allocation at end of execution (is scoped to execution content) or as a GC deferred slowdown if part of scope that is not released at execution idle.

The following snippet shows 3 examples, two from your question and a 3rd I created,
To ensure that the optimizer does not remove code that has no side effects the enemy shoot function returns a random value that is added to a global soak. All 3 methods use the same enemy, enemies and soak.
This test concentrates only on the shooting ignoring the time test.

    const enemyCount = 60;
    const enemy = { shootProjectile(){ return Math.random() }  }
    const enemies = $setOf(enemyCount,() => ({...enemy}));

    var soak = 0;
    function testA() {
        enemies.sort(() => 0.5 - Math.random()).slice(0, 2).forEach(e => {
          soak += e.shootProjectile();
    }

    function testB() {
        const enemiesCopy = [...enemies];
        const enemiesToShoot = [];

        while (enemiesToShoot.length < 2 && enemiesCopy.length) {
            const [enemy] = enemiesCopy.splice(Math.floor(Math.random() * enemiesCopy.length), 1);
            enemiesToShoot.push(enemy);
        }
        for (const enemy of enemiesToShoot) {
            soak += enemy.shootProjectile();
        }
    }

    function testC() {
        const shooterIdx = Math.random() * enemies.length | 0;
        var shooterIdx1 = Math.random() * enemies.length | 0;
        if (shooterIdx1 === shooterIdx) { shooterIdx1 = (shooterIdx1 + 1) % enemies.length }
        soak += enemies[shooterIdx].shootProjectile();
        soak += enemies[shooterIdx1].shootProjectile();
    }

Shooters: 60. Shots per call: 2

Test Function
Mean time
Max diff
OPS*
Relative Performance *1

TestA
31.929µs
±17.298µs
31,319
1%

TestB
0.609µs
±0.604µs
1,642,819
27%

TestC
0.166µs
±0.226µs
6,025,389
100%

µs millisecond. 1 millionth of second.
(*) OPS is calculated operations per second, where the function call is considered the operation
(*1) Percentage of best

As higher enemy counts will negatively effect the outcome of testA and testB and lower enemy counts will negatively effect the outcome of testC the following table is with an enemy count of 6
Shooters: 6. Shots per call: 2

Test Function
Mean time
Max diff
OPS
Relative Performance

TestA
1.208µs
±0.284µs
828,136
14%

TestB
0.490µs
±0.123µs
2,039,537
34%

TestC
0.168µs
±0.266µs
5,959,047
100%

Game compromises
I have been in the games industry for a long time and one thing I have learnt is that pushing for ideal implementations will hurt performance, while compromising in favor of performance goes completely unnoticed.
Selecting many from many
There is another factor that effects the performance of the code and that is the number of shooters. As function textC can only handle 2 shooters at a time we must rewrite it to work with any number of shooters.
At this point we make a sacrifice. Finding shooters randomly means that we need to test against shooter firing at the same time. This overhead should be ignored, rather we flag shooters that get to shoot so that we do not shoot twice.
The compromise
The function TestC will shoot about 7% less than the others giving it a slight advantage, but that advantage pales when compared to the 3* faster than testB and a huge 30* faster than testA
The updated code

const enemyCount = 60;
const enemyShoot = 10;
const enemy = {
    shoot: 0,
    shootProjectile(){ return Math.random() }
}
const enemies = $setOf(enemyCount,() => ({...enemy}));

var soak = 0;
var time = 0;
function testA() {
    enemies.sort(() => 0.5 - Math.random()).slice(0, enemyShoot).forEach(e => {
      soak += e.shootProjectile();
    });
    time ++;
}

function testB() {
    const enemiesCopy = [...enemies];
    const enemiesToShoot = [];
    while (enemiesToShoot.length < enemyShoot && enemiesCopy.length) {
        const [enemy] = enemiesCopy.splice(Math.floor(Math.random() * enemiesCopy.length), 1);
        enemiesToShoot.push(enemy);
    }
    for (const enemy of enemiesToShoot) {
        soak += enemy.shootProjectile();
    }
    time ++;
}

function testC() {
    var count = enemyShoot + 1;
    while (count--) {
        const shooter = enemies[Math.random() * enemies.length | 0];
        soak += shooter.shoot !== time ? (shooter.shoot = time, shooter.shootProjectile()) : 0;
    }
    time ++;
}

Shooters: 60. Shots per call: 10

Test Function
Mean time
Max diff
OPS
Relative Performance

TestA
26.669µs
±8.919µs
37,497
3%

TestB
2.293µs
±1.023µs
436,149
33%

TestC
0.762µs
±0.834µs
1,313,125
100%

Arrays the outcome
As you can see the results show that using arrays in this case to select items to perform and action is much slower than avoiding the need to hold shooters.
With that said arrays are not bad if used correctly.
Part of the performance penalty of arrays is the allocation and de allocation process.
As memory is currently very cheap compared to CPU cycles you can leave arrays populated and keep a separate counter to track how many active items it holds. This eliminates the need to allocate and de-allocate arrays each frame.
The overhead of iteration
Each time you iterate an array you add the overhead of the loop logic. A general rule is iterate twice only, once for update, once for display. Actions that you would normally do in a separate loop should be done in the update loop.
In this case as you would already be iterating each enemy to move them, this is where the logic to select a shooter should be.
I would not try for 2 shooters every 1 seconds, I would give all shooters odds to shoot that are equivalent. So if there are 60 enemy at 2 shoots total every 1 second the odds for any shooter shooting per frame is 2 / (60 * 60) = 5.556e-4
Thus in the main enemy loop you add Math.random() < 5.556e-4 && enemy.shootProjectile(); complete eliminating the extra code finding shooters, and in my view creating a far more realistic AI.
 All tests on Chrome 87. 64Bit i9 windows laptop, cooling set to active.


VBA - create separate spreadsheets from a filtered table

I think Power Query (aka Get & Transform) could do this much more straightforwardly. Two queries one filtering for one thing another for the other they could live in the same or two different workbooks - refresh and save as, done. You could VBA the bit that saves them into separate books and names them in various ways I guess.


Count pairs in list of integers such that their addition is equal to the input value

The solution has a quadratic time complexity. If it solves the 50000-strong list in 18 seconds, I'd expect about 1800 seconds (aka 30 minutes) for a 500000 one. Notice that the problem is aggravated by the way you are looking for duplicates (and IsPairUnique doesn't look correct; it is prone to false positives).

There are few standard ways to bring the complexity down.

Sort the list. Arrange two iterators, one at the beginning, another at the end.

Now add the pointed elements. If the sum is less than the target, advance the left one. If it is greater, move the right one toward the beginning. If it is a target, record it, and move both. In any case, when moving an iterator, skip duplicates. Rinse and repeat until they met.
If you have enough extra memory, put them in a set. For each element in a set check if its complement is also there.


Extract version string from text file with Powershell

I haven't found a terser approach using only built-ins, but having a little more confidence now in Powershell, I think I'd simply refactor out the group matching code:

filter Select-MatchingGroupValue($groupNum) {
    if (! $groupNum) {
        $groupNum = 0
    }
    select -InputObject $_ -ExpandProperty Matches |
        select -ExpandProperty Groups |
        select -Index $groupNum |
        select -ExpandProperty Value
}

Then you could use it like:

Get-Content .\somescript.vim -ErrorAction SilentlyContinue |
    Select-String '^" Version: (.*)' |
    select -First 1 |
    Select-MatchingGroupValue 1

In the end, you haven't saved that many lines, but refactoring out the tedious expansions of Matches, Groups, and Value makes the resulting code much clearer IMO.


A netty Channel can be open and not connected so your NettyConnection.isConnected is not correct. See this.
and 3.

It's pointless to write such code in scala. What you need is just a scala lazy val. Try this:

class NettyConnectionManager(val config: NettyConfig) extends ConnectionManager {
  lazy val connection = {
    val newConnection = new NettyConnection(config)
    newConnection.connect()
    newConnection
  }

  def close = connection.close
  def connected = connection.isConnected
}

scala lazy vals already use double check locking to initial the val only once, you don't have to do all the primitive stuff yourself as in NettyConnectionManager or NettyConnection. Next time you think about using var of Option, use lazy val instead. See SIP-20 to know more about how scala community is trying to improving this strategy.

And, wrapping a Channel in two classes like NettyConnection and NettyConnectionManager is also bad design decision. You gain little and add much unnecessary complexity.


Some quicky remarks:

a well-behaved API should return specific HTTP codes depending on the outcome, that is:
200 for success, or 201 for resource created. 204 is a possibility for an empty but successful response too but I would not advise using the full panoply available. Just be aware of what codes exist and when to use them.
likewise, use 401/403 for permission issues or authentication errors but here you have the @login_required that should take care of that
accordingly, an error should return a meaningful status code to the client - 400 would be a good candidate for an invalid request
the bottom line, always return an appropriate status code, never return HTTP/200 if the request failed. API calls are routinely automated, and the client will rely on the status code returned by the server to determine if the call was successful or not.
useless variable: u = current_user.id  # 2458017363. You could just write: author_id=current_user.id, instead of author_id=u. u is not an intuitive variable name anyway
I don't understand the logic of generating a random ID in your code, the database backend should generate an incremented record ID for you (simply update your data model). I don't see why you need a random value here...
When you decide to handle certain exceptions like except IntegrityError, you can indeed decide to ignore them or hide them to the client but you should still log them for later review. IntegrityError suggests there is something wrong with your handling of incoming data. It should not happen if data is inspected and sanitized properly.
except Exception is too broad when all you're doing is json.loads. The error that you can expect here should be ValueError. Try submitting empty JSON and malformed JSON to verify.
to sum I don't think you should have resp['error'] and resp['success'], just use the same name in all cases eg: 'response'. It is the status code that will make the difference between success and failure. Whatever you do, the API should respond in a way that is consistent and predictable.


Choosing a Color based on an int for a 2048 clone in Java

Something is wrong with your design. Your method is technically correct, but the problem is that it relies on a given magic int i to determine which color to return.

This can be seen by

int[] Num = {2,4,8,16,32,64,128,256,512,1024,2048};

This declares an array of fixed magic values. The issue is that, somewhere in your code, you're determining which i to give to this method and you're testing it against known fixed values only in the method.

This highly couples parts of your application. You should refactor this code so that the logic of "which number corresponds to which color" is centralized in a single place. One of comment says that you're doing a 2048 clone, as such, the centralized place could be a class called Block. You could even make it an enumeration of all the possible blocks, each with its respective value and color.

As such, don't use use Strings to represent blocks, use proper objects with attributes; this is what Object-Oriented Programming is about. An example could be the following (with perhaps a better name for the constants):

public enum Block {

    SQUARE_2(2, new Color(231, 223, 134)),
    SQUARE_4(4, new Color(151, 206, 104));

    private final int value;
    private final Color color;

    private Block(int value, Color color) {
        this.value = value;
        this.color = color;
    }

    // add getters

}

That said, you can improve a little bit the current code. You are currently doing:

for(int j = 0 ; j < Num.length ; j++){
    if(i == Num[j]){
        return RECT_COLORS[j];
    } else if ( j == Num.length - 1 ){
        return RECT_COLORS[Num.length-1];
    }
}
return RECT_COLORS[Num.length-1];

In the case where the Num array doesn't have the given value, you have a special else if to handle the last case. You actually don't need this: you can safely let your code exit the for loop normally and return the last value in this case:

for (int j = 0 ; j < Num.length ; j++) {
    if (i == Num[j]) {
        return RECT_COLORS[j];
    }
}
return RECT_COLORS[Num.length-1];

A second point concerns the variable names: you should try to respect Java naming conventions. The local variables should start with a lowercase letter (num instead of Num, which could arguably have a better name also; emerald instead of Emerald...).


Finding the average, the five smallest, and the five largest numbers in an array

There are a number of built-in functions in PHP that would make your code shorter and more direct.

The first is implode. implode takes and optional glue string and an array of values, and joins them together into a single string. So for implode(", ", array(1, "a", 3)), it would return "1, a, 3". This avoids the need to loop over the elements of an array to print them with a separator, and to catch the last case where there should be no separator.

The second is array_sum. This, as its name suggests, takes an array and sums the values. This also avoids an explicit loop.

The third is array_slice. This function will take an array, and return a portion of it based on the given parameters. It can even be used to index in reverse with a negative offset.

Putting it all together, we get the following:

<?php
    echo "
";

    $temperatures = array(78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68, 62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73);

    echo "Recorded temperatures : ";
    echo implode(", ", $temperatures);
    echo "
";

    echo "Average Temperature is : ";
    echo number_format(array_sum($temperatures) / count($temperatures), 1);
    echo "
";

    //sort the temperatures in ascending order for both of the following lists.
    sort($temperatures);

    //print the first 5 values
    echo "List of five lowest temperatures : ";
    echo implode(", ", array_slice($temperatures, 0, 5));
    echo "
";

    //print the last 5 values
    echo "List of five highest temperatures : ";
    echo implode(", ", array_slice($temperatures, -5, 5));
    echo "
";

    echo "
";
?>


Rock, Paper, Scissors, Lizard and Spock - Relational Paradigm

Validate actions

The Action table could use some validation logic:
WinsId and LosesId should be unique together.
You could enforce this with a unique constraint.

But there's more for the game to make sense:

WinsId should not be equal to LosesId
Each WinsId and LosesId should have the same count.
That is, each action should beat and be beaten by the same number of other actions.

Although these conditions are not possible to enforce with constraints,
it would be good to add a helper function that can be used to perform a sanity check easily.

Handling ties

Instead of this:

INSERT INTO @Result
SELECT 'Player 1 Wins!', ...
UNION
SELECT 'Player 2 Wins!', ...

IF NOT EXISTS(SELECT * FROM @Result)
INSERT INTO @Result VALUES ('Tie!','')

I don't have an SQL Server with me to test,
but I think this simpler alternative or similar should work:

INSERT INTO @Result
SELECT 'Player 1 Wins!', ...
UNION
SELECT 'Player 2 Wins!', ...
UNION
SELECT 'Tie', '' WHERE @Player1 = @Player2

Highlight SQL keywords

The common practice is to capitalize SQL keywords, like this:

CREATE TABLE [Hand]
(
     Id INT PRIMARY KEY NOT NULL
    ,Name VARCHAR(20) NOT NULL
)

Use indentation effectively

Good indentation goes a long way to helping readers understand the code.
A block of code like this, overindented and practically flat at the same,
is not really helpful:

insert into @Result
         select 'Player 1 Wins!' as Result, w.Name + ' ' + a.ActionText + ' ' + l.Name as [Text]
         from [Action] a
         join [Hand] w on w.Id = a.WinsId
         join [Hand] l on l.Id = a.LosesId
         where w.Id = @Player1
         and l.Id = @Player2
         UNION
         select 'Player 2 Wins!' as Result, w.Name + ' ' + a.ActionText + ' ' + l.Name as [Text]
         from [Action] a
         join [Hand] w on w.Id = a.WinsId
         join [Hand] l on l.Id = a.LosesId
         where w.Id = @Player2
         and l.Id = @Player1

It would be better this way:

INSERT INTO @Result
SELECT 'Player 1 Wins!' AS Result, w.Name + ' ' + a.ActionText + ' ' + l.Name AS [Text]
    FROM [Action] a
        JOIN [Hand] w ON w.Id = a.WinsId
        JOIN [Hand] l ON l.Id = a.LosesId
    WHERE w.Id = @Player1 AND l.Id = @Player2
UNION
SELECT 'Player 2 Wins!' AS Result, w.Name + ' ' + a.ActionText + ' ' + l.Name AS [Text]
    FROM [Action] a
        JOIN [Hand] w ON w.Id = a.WinsId
        JOIN [Hand] l ON l.Id = a.LosesId
    WHERE w.Id = @Player2 AND l.Id = @Player1

Naming

Single letter table aliases like w, l, a are not very helpful.
It would help understanding this code if you spelled out winner, loser, action.


First, Python has an official style-guide, PEP8, which programmers are encouraged to follow. This makes it easier for other Python programmers to read your code. PEP8 recommends using lower_case both for variable and function names, which I have used in the code below.

In your output function you use string formatting (good). However note that if you just want to paste the values in order, there is no need to explicitly mention the indices. So you could write "The player won {} of {} games ({:0.2%})".format(wins, total, winrate). But there is an even easier way in Python 3.6+: f-strings. I also think this is not enough to put it into a function, I would just leave it as a single line in main:

print(f"The player won {wins} of {total} games ({wins/total:0.2%})")

Your rolldies function could be made more general if it accepted a parameter telling it how many dice to roll. You can also use a list comprehension here, or random.choices:

def roll_dice(n=2):
    return sum(random.randint(1, 6) for _ in range(n))

DIE = [1, 2, 3, 4, 5, 6]
def roll_dice(n=2):
    return sum(random.choices(DIE, k=n))

Note that the singular is "die" and the plural is "dice", not "dies".

In your simOneGame function, instead of chaining a lot of comparisons with or, just use in:

def sim_game():
    initial_roll = roll_dice()
    if initial_roll in {2, 3, 12}:
        return True     # won
    elif initial_roll in {7, 11}:
        return False    # lost

Your rolling in the else branch can also be a bit shortened:

    else:
        #Roll until roll is 7 or initial roll
        roll = roll_dice()
        while roll not in {7, initial_roll}:
            roll = roll_dice()
        return roll == 7    # 7 wins

You could theoretically replace the while loop with a single random.choices call, but you would have to manually set the probabilities to the right values.

The simNGames function can be shortened a lot by using the fact that False == 0 and True == 1:

def sim_n_games(n):
    return sum(sim_game() for _ in range(n))


A method to log and display text in a console screen simultaneously.

Is it necessary?

I don't see what this achieves that can't be done by piping the output of your program through tee or similar; it just removes flexibility (you can no longer not save the logs).

Naming

All identifiers containing double underscore are reserved for the implementation for any purpose - including as macros.  So you'll need to remove those from the relevant names.

Allow moving rvalues

In the constructor, it's better to accept the file name by value, and std::move() it into the member:

FileLogger(std::string pfileName, bool appendToFile = true)
    : fileName(std::move(pfileName)),
      linkWithFile(fileName!="<null>"),
      linkWithCout(true),
      appendToFile(appendToFile)
{}

Omit what can be defaulted

There's no need for a copy constructor that's identical to the compiler-provided one, so just omit that - and then you won't inhibit the generation of a move constructor.

Extensibility

How about a more composable, general-purpose tee_stream class?  Then you can output to as many locations as you like, chosen on the fly at runtime.

Don't surprise your users

Given FileLogger logCout ("log.text", false);, then  logCout << "Hello " << "World"; opens the file, writes Hello to it, closes it, then opens it again, truncating and replacing the contents with World.  Most users would expect both Hello and World to be present after that line.

You should document somewhere that users can't write to a file called <null> - or change the magic name to a better value, such as the empty string (then the test becomes !fileName.empty()).


A function that checks if a string subnet mask is valid

Missing includes

#include <stdbool.h>
#include <string.h>

Other test may be needed

@Wingblade

Non-standard function

is_numeric() is not standard C library nor did I find it in Linux.

Questionable signature

I'd expect a function that checks a string's validity to cope with a const char * subNetMask.  So using strtok() on the supplied subNetMask is not possible.  Code needs to make a copy or otherwise assess the string.

// isValidSubnetMask(IN char *subNetMask)
isValidSubnetMask(IN const char *subNetMask)

Weak functionality

Below are 7 test cases that failed OP's code.  Sample working code provided.  sscanf() is a bit ponderous, yet useful as a test competitor.

bool is_numeric() {  // Added undefined Op's missing function.
  return true;
}

static bool isValidSubnetMask2(const char *subNetMask) {
  int n = 0;
  sscanf(subNetMask, "%*3[0-9].%*3[0-9].%*3[0-9].%*3[0-9]%n", &n);
  if (n == 0 || subNetMask[n]) {
    return false;
  }
  int i[4];
  sscanf(subNetMask, "%d.%d.%d.%d", &i[0], &i[1], &i[2], &i[3]);
  return i[0] <= 255 && i[1] <= 255 && i[2] <= 255 && i[3] <= 255;
}

void test(bool expect, const char *s) {
  char buff[99];
  strcpy(buff, s);
  bool y = isValidSubnetMask(buff);
  if (y != expect) {
    printf("Failed %d <%s>\n", expect, s);
  }
  y = isValidSubnetMask2(s);
  if (y != expect) {
    printf("Oops %d <%s>\n", expect, s);
  }
}

int main() {
  test(1, "255.255.255.0");
  test(1, "255.255.255.123");
  test(1, "0.0.0.0");
  test(0, "455.255.255.0");
  test(0, "255.255.255.-0");
  test(0, "255.255.255. 0");
  test(0, "2.2.5.2.3");
  test(0, "2.2.3");
  test(0, "+2.5.2.3");
  test(0, "A.5.2.3");
  test(0, "2.2.5.2.");
  test(0, "2..2.5.2");
  return 0;
}

Output

Failed 0 <255.255.255.-0>
Failed 0 <255.255.255. 0>
Failed 0 <2.2.5.2.3>
Failed 0 <2.2.3>
Failed 0 <+2.5.2.3>
Failed 0 <2.2.5.2.>
Failed 0 <2..2.5.2>


Implementing a singly linked list in C++

Unnecessary member variables

You have a member variable curr that has no purpose as a member variable, because it is only used as a temporary pointer to iterate through your list.  You should make curr simply be a local variable in the functions it is used in.

The member variable temp is never used and should be deleted.

\$O(n)\$ add

Your addNode function takes linear time because it has to find the end of the list.  You should either add to the beginning of the list, or keep a tail pointer so that you can quickly add to the tail.


Three ways to sum the values of letters in words

how's example 3 the least readable? I would write it a little better but you've got it right already:

def count_word3(word):
    return sum(ord(c) - 64 for c in word)


honestly: this code should be replaced completely.

you dont give any informations about how your MyCell and MyTextField look like, so I can just give you a general advice: Let MyTextField have a delegate it can call if a certain operation is triggered on it.

ie it could call  textField:(MyTextField *)textField didTriggerOperation:(APOperation)op and the implementation would be similar to:

-(void)textField:(MyTextField *)textField didTriggerOperation:(APOperation)op
{
    if(textField == self.descriptionTextField){
        if(op){
            switch ( op )
            {
              case APOperationClear:
                // something with "txt"
                break;
              case APOperationEnableSearch:
                // something with "valid"
                break;
              case APOperationGetText:
                // something with "txt"
                break;
              case APOperationPos: {
                // something with "txt"
                break;
              }
            }
        }

    }
}

your textField would call is when the operation was triggered like

[self.delegate textField:self didTriggerOperation:operation];


Can I further secure this blog post loading script?

secure?

not entirely: you emit a debug message to the user when something goes wrong when connecting to the database which may leak information about the server (consider a dumb PDO implementation that emits the $dsn, $options and $username in the error message).

Replace the echo with a forward to a 502 page and log the error message internally.
you also include a file from a text file repository and assume it doesn't contain any php code that may do Bad Things™ (while the $dbh is still in scope) or any XSS shenanigans.

You can use readFile to avoid the php code but not the XSS.

usable?

Is is that just emits a fixed number of titles in a fixed way. to do anything else you need to write a new function most of it will be copy and paste.

Instead just return an array with date-title pairs and let the calling code figure out how it should be displayed.

also add a parameter to allow the calling code to pass in a parameter for the number of records requested and at what point it should start to allow paging?

Besides that you store a date as a string in the database, let dates be a dates.

In fact the function itself is not necessary with how the code is used.

Make OOP? well you could create a querryable object that will return the aforementioned array and keeps the object handle private.


It's good to validate HTML code on https://validator.w3.org/,
it can spot interesting bugs, for example that  noon 	 is outside of a

 here:

     11am

     noon

     1:30pm
        LE EECS 1012

     FA VISA 2065

And that \ is not allowed as path separator in the src attribute of img tags, as it is here:

The other warnings are interesting too,
about the inconsistent number of columns in table rows.


Select random IDs from a table, using MySQLi

In the comments section, we talked about options around the DB queries.  It sounds like ORDER BY rand() may not be suitable for your use case in dealing with those execution times (which still seem odd to me given size of dataset).

So let's assume rather than look at optimizing that randomized query (again there are many good examples of this out there), or caching query results locally in some manner that you find appropriate, we are just going to look at simplifying your code, but sticking with the approach of randomizing the id's in the application.

I would suggest that you test through both sides of your if-else conditional to understand the relative completion speed of the "download all ids and shuffle" vs. the "random row retrieval" side of the conditional.  Ask yourself things like:

Do you really need both sides of this conditional?
What are the actual use cases of your application?
Are you primarily going to be grabbing one or a few rows at a time vs. grabbing entire set of id's?

This may influence your way of thinking about this section of code.  It might even, for example, prompt you to split this function with one function being called to get full result set and another function being called to get partial result set.

You may want to look at randomization approach in the data seek side of the conditional.  If you were trying to retrieve a substantial portion of (but not full) result set, you could waste a lot of time in the while loop trying to find an offset that has not already been set in the result array.

A better approach to randomization might be:

// generate array of offsets to search by getting
// $length number of random offset keys
// assume $length has already been verified to be <= $count
// not shown - you might check whether sorting $target_offsets helps with access time at all
$target_offsets = array_rand(range(0, $count - 1), $length);

for ($i = 0; $i < $length; i++) {
    // seek record and read into $ids array
    mysqli_data_seek($ids_r, $target_offsets[$i]);
    $id = mysqli_fetch_assoc($ids_r);
    $ids[] = $id['id'];
}

Regardless of approach here, you need to understand if at some percentage of full result set, it might be faster to retrieve full array, shuffle and slice to get the desired result vs. random row retrieval.

A few other thoughts in looking at your code:

Always strive to use meaningful variables names.

Consider these examples:

$ids_r => $id_results
$link => $mysqli_link
$length => $record_limit

These immediately give code reader exact understanding of what is stored in the variable.

You are doing nothing to validate the input to your function.  You shoudd consider validating, for example that a valid mysqli resource, non-zero length string for table name and where clause, and integer value for record limit are passed. Throw exception of fail out quickly if these conditions are not met.
Your code has no comments. You should always consider appropriate comments to make your code more readable.
Speaking of more readable code. You should strive to keep your code < 80 chraracters per line.  You only have one questionable example in your code:

Here:

$ids_r = mysqli_query($link, 'select id from `' . $table . '`' .
($where ? ' where ' . $where : ''));

which could be made more readable like:

$where = $where ? ' WHERE ' . $where : '';
$sql = 'SELECT id FROM `' . $table . '`' . $where;
$id_results = mysqli_query($link, $sql);


Finding median from unsorted array with duplicate elements without sorting it

If we never modify the elements of array, then it should be passed as a pointer to const: int const *array.

The frequency counts can be unsigned, and ought to be able to represent any size of input array (that suggests that count should be a size_t).

We absolutely must test that the return value of malloc() (and family) is not null before trying to dereference it (including passing it to memset()).  Additionally, it's not necessary or desirable to cast it to the target type:

size_t *freq = calloc(sizeof *freq, range + 1);
if (!freq) {
    fputs("Memory allocation failed!\n", stderr);
    exit(EXIT_FAILURE);
}

The algorithm has undefined behaviour if any element in the array is less than zero.  We need to find the minimum as well as maximum value, or perhaps change the input to be an unsigned type.

The counting is strange, with the nested loop.  Normally, we'd loop just once, incrementing the index for each element we look at - something like this:

for (int i = 0;  i < count;  ++i) {
     ++freq[array[i]];
}

To avoid excessive temporary memory use for the count array, we could use a multi-pass approach.

Divide the range [min,max] into into (say) 256 buckets.
Count the inputs into those buckets.
Identify the median bucket.  Call that M.
Now divide the range represented by M into buckets.
Make another pass over the inputs, counting values within M into these new buckets (discarding values not in M).
Repeat until the bucket size is 1.


Maybe you can use dict instead of str to store the driver-load values. If the driver is the key, you can search easily.

#!/usr/bin/env py

s = {'5.9':'1', '7':'1.5', '10':'2', '18':'4', '40':'8'}
load_value = raw_input("Enter a load value\n")
driver = s.get(load_value)
if driver is None:
    print "Could not find driver value"
else:
    print driver


Your program provides a good example for seeing how one can increase code readability through some common techniques: (1) convenience variables to avoid verbose repetition; (2) code organized as small commented "paragraphs" or blocks; and (3) the use of shorter variables names to lighten the visual weight of the code, thus enhancing ease of reading and visual scanning. Note that short names must be used judiciously: because they can be cryptic, short vars typically
derive their meaning either from a consistently used convention in the program
or from other contextual clues (eg, from nearby functions or collections having more explicit names and from well-placed comments). Here's a heavily edited version of floyd_warshall() along those lines. Because I'm lazy, I will assume that you implemented Floyd-Warshall correctly.
def floyd_warshall(graph):
    # Collect all vertices.
    vertices = set(
        col[i]
        for col in graph
        for i in (0, 1)
    )
    n = len(vertices)
    rng = range(n)

    # Initialize the distance and next-vertex matrix.
    dists = [
        [0 if i == j else INF for j in rng]
        for i in rng
    ]
    next_vertices = [
        [0 for j in rng]
        for i in rng
    ]

    # Populate the matrixes.
    for src, dst, weight in graph:
        i = src - 1
        j = dst - 1
        dists[i][j] = weight
        next_vertices[i][j] = j

    # Do that Floyd-Warshall thing.
    for k in rng:
        for i in rng:
            for j in rng:
                ikj = dists[i][k] + dists[k][j]
                if dists[i][j] > ikj:
                    dists[i][j] = ikj
                    next_vertices[i][j]  = next_vertices[i][k]

    return path_reconstruction(dists, next_vertices)

A bigger issue is that your floyd_warshall() function should not be calling a
function that prints. Rather it should return some kind of meaningful data.
That approach makes your function more readily testable. For example,
path_reconstruction() could return a list of declarative dicts.
def path_reconstruction(dists, next_vertices):
    # Same ideas here: return data, don't print; use convenience
    # vars where they help with readability.
    rng = range(len(dists))
    paths = []
    for i in rng:
        for j in rng:
            if i != j:
                path = [i]
                while path[-1] != j:
                    path.append(next_vertices[path[-1]][j])
                paths.append(dict(
                    i = i,
                    j = j,
                    dist = dists[i][j],
                    path = path,
                ))
    return paths

Then do your printing outside of the algorithmic code.
def main():
    edge_lists = [
        [
            [1, 3, -2],
            [2, 1, 4],
            [2, 3, 3],
            [3, 4, 2],
            [4, 2, -1],
        ],
        [
            [1, 2, 10],
            [1, 3, 20],
            [1, 4, 30],
            [2, 6, 7],
            [3, 6, 5],
            [4, 5, 10],
            [5, 1, 2],
            [5, 6, 4],
            [6, 2, 5],
            [6, 3, 7],
            [6, 5, 6],
        ],
    ]
    for el in edge_lists:
        paths = floyd_warshall(el)
        for p in paths:
            print(p)


Print sum of numbers 1 to 200 except mults of 4 or 7 in Python

I think your use of % is fine, but that could be simplified to:

def main():
    print sum([i for i in range(201) if i % 4 and i % 7])

if __name__ == '__main__':
    main()

Edit: Since I had a bug in there, that's a pretty clear indication that the % is a tripwire. Instead, I'd probably do:

def divisible(numerator, denominator):
    return numerator % denominator == 0

def main():
    print sum(i for i in range(201) if not(divisible(i, 4) or divisible(i, 7)))


Rewriting clumsy code that gets the value of a nested property in JS object

If you're certain the token exists in either of the objects you can do:

First check for the existence of the value in data.

var value = data.d || data.value;

then access the value to get the token

var token = value && value.GetContextWebInformation.FormDigestValue;

var value = data.d || data.value;

var token = value && value.GetContextWebInformation.FormDigestValue;

if (token) {
  this.options.token = token;
}

Otherwise, you can use getIn function:

function getIn(pathArray, obj) {
  var tmp = obj;
  for (var i = 0; i < pathArray.length; i++) {
    if (tmp.hasOwnProperty(pathArray[i])) {
      tmp = tmp[pathArray[i]];
      continue;
    }
    return undefined;
  }
  return tmp;
}

var token = getIn(['d', 'GetContextWebInformation', 'FormDigestValue'], data) ||
            getIn(['value', 'GetContextWebInformation', 'FormDigestValue'], data);

if (token) {
  this.options.token = token;
}


It depends on what you mean by "better".  I'd use a Thread since the job is constantly running.

A Thread object will be a foreground thread, which will prevent the application from terminating as long as it is running.

Task.Run will queue the job up to run on a thread pool thread.  It may not start running immediately, and it will be a background thread, so it will not prevent the application from terminating if all other foreground threads have terminated.

The number of threads that a thread pool can run is limited, so if your job is always using one of them that increases the possibility that some other task will run late.  Or possibly your job will be delayed while some other task that is part of the thread pool runs.


Sorted vs Unsorted

Your QVector sequence contains an unsorted sequence of values.  Your median calculation has a precondition that your sequence is sorted.  Consider the sequence 1, 0, 1, what is the median?

Small, Focused, and Testable Functions

Prefer writing functions that employ the single responsibility principle.  Splitting out median and testing it with different sequence types would have pointed out a problem. How about calculating the mean of an empty container? Is division by zero a problem?

Standard Algorithms

Being able to understand when you should use standard algorithms and applying them is very important.  Mean can be written using std::accumulate().  Median can be written in terms of std::nth_element().  Mode can be written using boost::bimap (or utilize std::unordered_map+std::multimap) and std::upper_bound() with std::transform() to return the modes of a sequence.  Not all sequences are uni-modal.


Finding matching PDF files in different folders and merging the two files into one

I cannot do full test as I do not have that PDF software of yours. But the idea is that process all file names in that folder 1, store them in a collection, also if the file name ends with " SomeWord.pdf" then add to another collection.

When done, process the other collection and see if a matched " AnotherWord 2014.pdf" found in first collection. Merge if found.

Reworked after Trial is downloaded.

Option Explicit

Private oFullList As Object, oMyList As Object, oFSO As Object

Private Const FDR1 = "C:\Test\"
Private Const FDR2 = "C:\Test\Merged\"

Private Const sAppend1 = " SomeWord.pdf"
Private Const sAppend2 = " AnotherWord 2014.pdf"

Private oPDF As New PDF_reDirect_v25002.Batch_RC_AXD
Private lFiles As Long

Sub Main()
    lFiles = 0
    Debug.Print Now & vbTab & "Program Started"
    '===[ Create Collection Objects ]===
    ' FullList stores all the filenames in the directory
    If oFullList Is Nothing Then
        Set oFullList = CreateObject("System.Collections.ArrayList") ' Create if not created
    Else
        oFullList.Clear ' Remove all old entries
    End If
    ' MyList only stores filenames that will be checked for merge
    If oMyList Is Nothing Then
        Set oMyList = CreateObject("System.Collections.ArrayList") ' Create if not created
    Else
        oMyList.Clear
    End If
    '===[ Check FileSystemObject ]===
    If oFSO Is Nothing Then
        Set oFSO = CreateObject("Scripting.FileSystemObject")
    End If
    '===[ Main procedures ]===
    CheckFiles
    'ListFiles ' Skipped, debug only
    ProcessMergeFiles
    '===[ Clean Up ]===
    Set oFullList = Nothing
    Set oMyList = Nothing
    Set oFSO = Nothing
    Set oPDF = Nothing
    '===[ Print Summary ]===
    Debug.Print Now & vbTab & "Program Finished. " & lFiles & " merged PDFs has been created"
End Sub

Private Sub CheckFiles()
    Dim oFDR As Object, oFile As Object, sTmp As String, n As Long
    '===[ Process all filenames of FDR1 ]===
    For Each oFile In oFSO.GetFolder(FDR1).Files
        sTmp = oFile.Name
        ' Add to FullList collection
        oFullList.Add sTmp
        ' Only add to MyList collection if it ends with sAppend1
        n = InStr(1, sTmp, sAppend1, vbTextCompare)
        If n > 0 Then
            oMyList.Add Left(sTmp, n - 1) ' Stores only the prefix
        End If
    Next
End Sub

Private Sub ListFiles()
    Dim i As Long
    Debug.Print "=== Listing " & oMyList.Count & " item(s) in oMyList ==="
    For i = 0 To oMyList.Count - 1
        Debug.Print i + 1 & vbTab & oMyList(i)
    Next
End Sub

Private Sub ProcessMergeFiles()
    Dim i As Long, sTmp As String
    For i = 0 To oMyList.Count - 1
        sTmp = oMyList(i)
        If oFullList.Contains(sTmp & sAppend2) Then
            'Debug.Print "Merge file pair found: """ & sTmp & """"
            MergeFiles sTmp
        End If
    Next
End Sub

Private Sub MergeFiles(sFilePrefix As String)
    Dim bSuccess As Boolean
    Dim aFiles() As String ' <- Required datatype

    If oPDF Is Nothing Then
        Set oPDF = New PDF_reDirect_v25002.Batch_RC_AXD
    End If

    ReDim aFiles(1)
    aFiles(0) = FDR1 & sFilePrefix & sAppend1
    aFiles(1) = FDR1 & sFilePrefix & sAppend2

    With oPDF
        bSuccess = .Utility_Merge_PDF_Files(FDR2 & "\" & sFilePrefix & sAppend2, aFiles)
        If bSuccess Then
            Debug.Print "Merged pdf files with prefix """ & sFilePrefix & """"
            lFiles = lFiles + 1
        Else
            Debug.Print "Failed to merge pdf files with prefix " & sFilePrefix
            Debug.Print "ERR(" & .LastErrorNumber & "):" & .LastErrorDescription
            .Reset_Errors
        End If
    End With
End Sub


You could use a bidirectional map. In Java syntax this would be:

BidiMap<Type, Type> superior = new BidiMap<>();
superior.put(EARTH, WIND);
superior.put(WIND, WATER);
superior.put(WATER, FIRE);
superior.put(FIRE, EARTH);

That's it. This greatly reduced the redundancy of your code, as well as the verbosity. Since it is a BidiMap, you can query it in both directions.

An alternative approach is to define an array ComparisonResult[typeCount][typeCount] cmp and initialize that using similar calls as above, again avoiding redundancy. Then your compare method can just return cmp[this.ordinal ()][other.ordinal()].


comparing each with each means the quadratic time complexity, and skipping the ones with different length does not improve the bottomline.

Sort the set of (sorted) substrings, and the anagrams will form contiguous runs. The run of length \$k\$ produces \$\dfrac{k(k-1)}{2}\$ pairs.

Example:

An original array:

ab
cde
xy
dec
ba
ced

After each string has been sorted, it becomes

ab
cde
xy
cde
ab
cde

Now, after the entire array is sorted lexicographically, it becomes

ab
ab
cde
cde
cde
xy

The ab, ab and cde, cde, cde form the contiguous (that is, uninterrupted) runs, of length 2 and 3 respectively.


Improving your solution

private Stack <Integer> oddStack;
private Stack <Integer> evenStack;

I'd replace these with an array.

private Stack<Integer>[] stacks = (Stack<Integer>[])new Stack[2];

Then you don't have to keep converting from numbers to names when you use them.

private int counter;// count added element

You don't need this, as Stack has a size method.

private int shift;//count internal movement from one stack to another.

You never use this outside of a single method.  Rather than creating an object field, just use a local variable.

public twoStacksInOneQueue()
{
    counter = 1;
    shift = 0;
    oddStack = new Stack<Integer>();
    evenStack = new Stack <Integer>();
}

This gets simpler.

public twoStacksInOneQueue()
{
    stacks[0] = new Stack<Integer>();
    stacks[1] = new Stack<Integer>();
}

No need for the other two here.

public void addToQueue(int num)
{
    if(counter % 2 == 0)
    {
        evenStack.push(num);
        System.out.println("evenStack: " +  num);
    }
    else
    {
        oddStack.push(num);
        System.out.println("oddStack: " +  num);
    }
    counter++;
}

And this becomes just

public void addToQueue(int num)
{
    int index = ((stacks[0].size() + stacks[1].size()) % 2;
    stacks[index].push(num);
    System.out.println(((index == 0) ? "evenStack: " : "oddStack: ") +  num);
}

Note that this would only be one line if it weren't for printing the stack information.

    int temp;
    int result = 0;

    if(counter == 0)//empty queue
    {
        System.out.println("The Queue is empty!");
    }

I wouldn't declare temp until later, and I would return from the empty case (or throw an exception).

    if (stacks[0].empty() && stacks[1].empty())
    {
        System.out.println("The Queue is empty!");
        return 0;
    }

I'll put result back later.

        while (shift-1  > 0)//move the moved stack back. -1 because of the popped element above

You are doing an extra math operation on every iteration of the loop.  But you don't have to do so.  Either

        while (shift > 1)//move the moved stack back. 1 because of the popped element above

Or

        shift--; //move the moved stack back. -1 because of the popped element above
        while (shift > 0)

The latter might be more efficient on some platforms, since comparisons are often implemented as subtractions and comparisons to 0.

    else if (counter % 2 == 0) //if there are even elements
    {
        while(!evenStack.empty())//loop while not empty
        {
            //move the entire stack to another to get the bottom of the stack
            temp = evenStack.pop();
            oddStack.push(temp);
            shift++;
        }
        result = oddStack.pop();//the previous bottom of the moved stack
        System.out.println("result From even: "+result);

        while (shift-1  > 0)//move the moved stack back. -1 because of the popped element above
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift--;
        }
        counter--;
    }
    else //if there are odd elements
    {
        while(!oddStack.empty())
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift++;
        }
        result = evenStack.pop();

        System.out.println("result from odd: "+result);
        while (shift-1 > 0)
        {
            temp = evenStack.pop();
            oddStack.push(temp);
            shift--;
        }
        counter--;
    }
    shift = 0;//reset internal moved counter.

This seems longer than it needs to be.

    int index = ((stacks[0].size() + stacks[1].size()) % 2;
    int result = removeLast(stacks[index], stacks[1 - index]);

    System.out.println(((index == 0) ? "result From even: " : "result from odd: ") + result);

    return result;

Again, if it weren't for the output requirement, we could have returned directly.

And then just define a method for removeLast:

public static int removeLast(Stack<Integer> stack, Stack<Integer> temp)
{
    int snapshot = temp.size();

    while (!stack.empty())
    {
        temp.push(stack.pop());
    }

    int result = temp.pop();

    while (temp.size() > snapshot)
    {
        stack.push(temp.pop());
    }

    return result;
}

Rather than explicitly counting how many elements we shift, now we just reduce temp back to its original size.

Because we defined a method for this, we only have to write this logic once.  We call the method with different arguments rather than duplicating the logic.

The thing is though that this method has you moving half the elements twice on every removal.  We can do better.  On average, we only need to move one element per removal.

An alternative solution

class StackQueue {

    private Stack<Integer> backward = new Stack<>();
    private Stack<Integer> forward = new Stack<>();

    public void enqueue(int item) {
        backward.add(item);
    }

    public int dequeue() {
        if (forward.empty()) {
            if (backward.empty()) {
                // throwing an exception would likely be better
                return 0;
            }

            do {
                forward.push(backward.pop());
            } while (!backward.empty());
        }

        return forward.pop();
    }

}

This gives constant time enqueue operations and on average gives constant time dequeue operations.  When I say "on average", I mean that it moves each element from backward to forward once per removal.  However, on a particular operation, it moves either 0 or all of them.


Find Element in Tree Given a List of Directions

It's not that safe.

*Main> maybeElemAt [] Empty
*** Exception: tree.hs:(7,1)-(11,54): Non-exhaustive patterns in function maybeElemAt

So let's add a pattern

maybeElemAt :: Directions -> Tree a -> Maybe a
maybeElemAt []     (Node x _ _)     = Just x
maybeElemAt (R:ds) (Node _ _ Empty) = Nothing
maybeElemAt (R:ds) (Node _ _ r)     = maybeElemAt ds r
maybeElemAt (L:ds) (Node _ Empty _) = Nothing
maybeElemAt (L:ds) (Node _ l _)     = maybeElemAt ds l
maybeElemAt _ Empty = Nothing

And now we can see that two of the patterns can be removed:

maybeElemAt []     (Node x _ _) = Just x
maybeElemAt (R:ds) (Node _ _ r) = maybeElemAt ds r
maybeElemAt (L:ds) (Node _ l _) = maybeElemAt ds l
maybeElemAt _ Empty = Nothing

GHC has an option -fwarn-incomplete-patterns, or you can use -W to get that plus other warnings. See Warnings and sanity-checking in the GHC User's Guide.


Very nice overall.
Don't see anything technically wrong.
I agree with @ratchet freak that your variable naming (and declaring multiple objects in one line) is a not great. I would prefer better names and one variable per line.
Things I would change for efficiency:
// You know how big this vector is going to get.
std::vector<typename It::value_type> v;

// So reserve the appropriate space:
v.reserve(std::distance(begin, end));

Also this is not what you want:
return std::move(v);

// jsut return the object
return v;

Otherwise you will screw up RVO done by the compiler and it will generate a copy rather than a move.
At the call site the value returned by a function is already an rvalue reference. So adding the move here does not change anything (it will still be moved).
But this is not going to move the values:
buffer.push_back((*left <= *right) ? *left++ : *right++);

Here you are only getting lvalues passed to push_back so you are copying the underlying elements. Why not try and get a move out of it?
buffer.push_back(std::move((*left <= *right) ? *left++ : *right++));


How to (and should I) avoid repetition while assigning values from different sources?

1.I assume if type(step) is dict: should be elif type(step) is dict:.

2.isinstance is preferable than type because isinstance caters for inheritance, while checking for equality of type does not (it demands identity of types and rejects instances of subtypes).

3.You also can apply duck-typing.

try:
    number = step.number
except AttributeError:
    try:
        number = step['number']
    except KeyError:
        number = 1

And these ways are quite pythonic.

4.I suggest you can inherit your Step class from dict then you don't need to check types. Yo will just do

number = step.get('number', 1)
time_value = step.get('time_value', '')


How to optimize my telegram bot written in Python?

From my point of view you can use a visitor pattern for this with a simple dictionary, specially for your operations, here is a small example:
Insead of this
@bot.callback_query_handler(func=lambda call: True)
def tempo(call):

    # here a handle the queries launched both by main buttons and the inline keyboard

    if call.data == "demo_yes":

        keyboard = types.InlineKeyboardMarkup()
        ......

Use the following
tempo_operations = {"demo_yes" : demo_yes_function,
                    "demo_no" : demo_no_function,
                    ....}

@bot.callback_query_handler(func=lambda call: True)
def tempo(call):

    if call.data in tempo_operations:
        tempo_operations[call.data]()
    else:
        print("Operation not supported")

Hope you can get the idea :)


Simple implementation of a generic stack

Ownership

Yes raw pointers are fine if you are not transferring ownership (Is the class responsibility to delete them).

Pop function

Also I am not sure if this will compile for any data other than pointers and types convertible to 0 since you return NULL. (Also is better to use nullptr consistently).

 T pop() {
    if (head == nullptr) {
        std::cout<<"Error stack is empty"<<std::endl;
        return NULL;
    } else {
        Node *temp = head;
        T result = temp->data;
        head = head->next;
        delete temp;
        return result;
    }
}

IMO it will be better to throw a underflow exception since is the client responsibility to check that is not empty before. Also avoid returning the data since we will be throwing an exception (For more info on this check out this article http://ptgmedia.pearsoncmg.com/images/020163371x/supplements/Exception_Handling_Article.html)

 void pop() {
    if (head == nullptr)
        throw std::underflow_error("underflow");

    Node *temp = head;
    head = head->next;
    delete temp;
 }

So the client will have to call peek before pop to get the same effect.

Parameters:

In most parameter like this (T type) you should change it to (const T& type)
to avoid copying. Even better would be to provide an overload for rvalue references like this (T&&)

peekAll function

This function seams kind of weird. Why are you deleting temp? . It seams that after the while loop temp should always be nullptr.  And aren't you just writing the stack on the stream.  I would just omit this function and move it to the << operator overload.

Also you should implement an empty function.


Can it be shorter?: DNA Sequence Analyzer from CS50 written in Python

I would group the code in functions and call them from a central main. With how you have it now, simply loading the file into an interactive console will cause all the code to run, which, if the code is long running or causes side-effects, may be less than ideal. Say I wrote a port-scanner, and it takes 2-3 minutes to run. I may not want it to start simply because I loaded the file into a REPL in Pycharm. Not only would that waste a few minutes each time, port-scanning can get you in trouble if done on a network that you don't have permission to scan.
Code wrapped in functions is simply easier to control the execution of, because it will only run when the function is called.
Grouping code into functions also allows you to easily test each chunk in isolation from the rest of the code. It's difficult to test code when you're dependent on the first half of the code to supply test data to the latter-half. It's much easier however to simply load the script into a REPL, and throw test data at the function (or use proper unit-tests). Then you can test one piece of code in isolation without touching the rest of the code.

I personally believe that STRs and STR should be lower-case. According to PEP8, Python's style and convention guide, regular variables should be lower case, with words separated by underscores. Variables that are considered to be constants however should be upper-case, separated by underscores.
Local variables that remain unchanged have never clicked as "constants" in my head, so it depends on what you decide.
Regardless though, STRs should either be all upper-case, or all lower-case; in which case the STR counterpart will need to be renamed so it doesn't clash with the str built-in. A name like str_ could be used, or you could use a more descriptive name.

compare = {}

. . .

for key, value in row.items():
    compare[key] = int(value)

This can make use of a dictionary comprehension. Whenever you have the pattern of creating a set/list/dictionary before a loop, then populating the structure within the loop, you should consider a comprehension:
compare = {key: int(value) for key, value in row.items()}

Similarly, to ensure that a condition holds for an entire collection (or two in this case), you can combine all with a generator expression (the part passed to all):
if all(compare[STR] == str_counts[STR] for STR in STRs):
    matched = True
    print(match_name)

"If all corresponding values in the two dictionaries match, set the matched flag". It reads quite nicely.
That gets rid of the need for match_count, and the second last loop.

You're looping more than you need to. You appear to only care about if at least one match is found; yet you keep looping even after one is.
I'd break once one is found. If you combine that with for's else clause, you can prevent unnecessary looping and still detect failure:
for row in db:
    . . .
    if all(compare[STR] == str_counts[STR] for STR in STRs):
        print(match_name)
        break

else:
    print("No Match")


Don't know if you wanted a full review or not so I supplied one since I was going over it anyways. Not really much wrong, mostly aesthetics. I could find no errors in your code, but maybe one of these fixes will ninja your problem away. You never know, the all-powerful PHP god's might be feeling better today :)

POST Data

Not sure if better, but if I'm looking for $_POST variables, I usually just do the following. Up to you though, nothing wrong with what you've got.

if($_POST) { etc... }

You should have some sort of sanitizer for those user inputs though. This is the only real issue I see with your code. Take a look at filter_input if you have PHP 5.2 or greater, otherwise you'll have to take a look around at what others are doing. It is never a good idea to take raw user input and run it in your program. That can lead to all sorts of nasty things.

Ignoring Keys

If you have a list of keys, or other items that you want to exclude, make them into an array and then check against it. Its cleaner than having a bunch of if statements and allows for extension later.

$exceptions = array(
    'hiddenField',
    'button2',
    'cloneAdmin',
);

if ($value !== "" && ! in_array($key, $exceptions)) { etc... }

Also, please use curly braces everywhere and not just on outter or large if statements. Yes PHP can work without them, but debugging your code will become very difficult later. Many might argue this point, but it truly is easier to read.

Since you are already checking if the value is blank, you might as well move that to the beginning and place all other checks inside it. What's the use of running all that code if the value is blank or a key you don't want to process? Better yet, just add the following to the top of the foreach loop and it will skip those records entirely.

if($value === '' || in_array($key, $exceptions)) { continue; }

Multiple If Statements

Don't use if statements for checking variables that you know a range of values for. Switch statements are faster and easier to read.

//Don't do this
if($key === 'DESCRIPTION_OF_ITEMS') { etc... }
if($key === 'EMAIL') { etc... }

//Do this
switch($key) {
    case 'DESCRIPTION_OF_ITEMS':
        //etc...
    break;
    case ''EMAIL':
        //etc...
    break;
}

Long Variables

Heredoc will make your long variables easier to read.

$content .= <<HTML

Thank you for submitting your registration form... we'll get back to you shortly.

You can expect to receive an email with the following registration information:

$emailMessage
HTML;

Long Strings as Arguments

If you are going to use long strings in functions you should replace them with variables, even if you aren't going to use those variables again. It makes it cleaner and easier to read.

$recipients = array();//You'll see why I used an array soon
$recipients[] = "foobar@bazbat.com";
$recipients[] = "$sendTo";
$recipients = implode(', ', $recipients);//See :)

$subject = "Foobar Registration Form";

$headers = array();//Same as recipients
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/html;";//This line didn't originally have "\r\n" so maybe this was your problem?
$headers[] = "charset=iso-8859-1";
$headers[] = "From: $FROM_EMAIL";
$headers[] = "Reply-to: $email";
$headers = implode("\r\n", $headers);

mail($recipients, $subject, $emailMessage, $headers);//See much cleaner

Sorry I couldn't be of more use in finding your error. Since you are indeed receiving a success string, I would say that your send to line is just wrong somehow. Try dumping its contents before sending the message to manually check if anything is wrong. Only other thing I can think of is that maybe your server doesn't have the mail() function installed. Though, since you said it succeeded at some point, I don't know what to tell you. Check php_info() anyways to see if its enabled. As for if this is the wrong stackoverflow subsite? Not really. It could have gone on stackoverflow and no one would have complained. Here you just get the added benefit that I reviewed your code too :)


Python 3 - simple temperature program version 1.3

You're not following PEP8 and you still have a spaghetti mind-set. Each function should have a single responsibility.

value_input however is in charge of:

Asking and validating user input.
Handling how to convert the input.
Convert and display the input.

This should instead only perform the first task I've said above. After this you should have the calling code perform 2 and 3.

convert_c2f also is responsible for two things converting and displaying the input.

It can be seen in main that you were originally doing something better than you have now, so it's unclear why you changed this.

def read_selection():
    return input('''Welcome to the temperature conversion program!

Please make a selection:

    c to convert from Celcius to Fahrenheit;
    f to convert from Fahrenheit to Celsius; or
    q to quit the program.

Enter your selection: ''')

def float_input():
    value = input('''\nPlease enter the temperature you
want to convert: ''')
    try:
        return float(value)
    except ValueError:
        print('That is not a number!\n')

def convert_c2f(value):
    return (value * (9 / 5)) + 32

def convert_f2c(value):
    return (value - 32) * (5 / 9)

def main():
    while True:
        selection = read_selection().lower()
        if selection == 'q':
            return
        elif selection == 'c' or selection == 'f':
            value = float_input(selection)
            if selection == 'c':
                converted = convert_c2f(value)
                print(f'The answer is: {converted}°F\n')
            else:
                converted = convert_f2c(value)
                print(f'The answer is: {converted}°C\n')
        else:
            print('Invalid selction. Try again.\n')