First, you can easily throw away semicolons ";".

Second, if you want shorter code, you can do like this:

function arabicToRoman(num) {
  var roman = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1}
  var result = ''

  for (var i in roman) {
    while (num >= roman[i]) {
      result += i
      num -= roman[i]
    }
  }
  return result
}

But, it's also almost ten times slower, so it's up to you - do you need compact code, or performance?


Comparing two strings to see if string 2 is inside string 1

The problem with your approach is that you're traversing the second String as many times as there are elements in the first String with the replaceFirst call (which also involves a regular expression).

Also, this has nothing to do with performance, but you could just use

return count == str2.length();

instead of the long, and so more difficult to read,

boolean result = true;
if (count == str2.length()){
    result = true;
} else {
    result = false;
}
return result;

You can tackle this problem a lot more effectively by taking advantage of the fact that only lower case letters will be used (a-z). Consider the following approach:

We know that there are 26 lower case characters. Let us create an array of 26 values int[] array = new int[26];.
For each character c of the second String, we increment the value stored in the array at the position c - 'a': this corresponds to the alphabetical position of the character (based from 0: 'a' -> 0, 'b' -> 1, ..., 'z' -> 25).
Then for each character c of the first String, we decrement the value stored at the alphabetical position.
Finally, if at the end of this process, we end up with at least one value that is strictly positive, we know that the second String wasn't contained in the first one. This is because it means that we encountered a character in str2 more times than it was in str1 (it was incremented more times than it was decremented).

A sample implementation of this approach would be:

public static boolean scramble(String str1, String str2) {
    int[] array = new int[26];
    for (char c : str2.toCharArray()) {
        array[c - 'a']++;
    }
    for (char c : str1.toCharArray()) {
        array[c - 'a']--;
    }
    for (int value : array) {
        if (value > 0) {
            return false;
        }
    }
    return true;
}

You can test it with

public static void main(String[] args) {
    System.out.println(scramble("rkqodlw", "world")); // prints "true"
    System.out.println(scramble("cedewaraaossoqqyt", "codewars")); // prints "true"
    System.out.println(scramble("katas", "steak")); // prints "false"
}


Solution to Chef and Squares challenge, timing out in Java but not in C++

My first observation was the same as @EmilyL.'s: that you're performing unneeded string concatenations.  Upon investigation, however, it turned out to be a loser to substitute two invocations of System.out.print() methods for a string concatenation plus one method invocation -- the result ran about 70% slower than the original code for me.

It took a while for the lightbulb to turn on, but that slowdown is a key symptom of the underlying problem: System.out is unbuffered, at least when it's not connected to a terminal.  In a comment you described addressing the problem by building the output in a StringBuilder and then printing it all at once.  That's a viable mechanism for buffering manually, but cleaner and easier to integrate into your original solution would have been to wrap a buffered stream around System.out and print to that.  In other words, at the top of main() add ...

PrintStream out = new PrintStream(new BufferedOutputStream(System.out));

... and everywhere else print to out instead of to System.out().  Doing that cut my run time by more than 50% relative to the original code, for a maximal-size test set.


Controller with abstract methods for a delete method

Three part answer here: a quick answer, a more detailed answer with alternatives, and some specifics to your code.

Quick Answer

There isn't anything wrong with having abstract controller methods, anymore than there is to having abstract methods in general.  That being said, the example you gave isn't an abstract method: it is simply a  parent method.  An abstract method is a method without a definition that must be defined by the child class.  That would be a bad idea in your use case, because there might be cases when you don't need to delete entries but would have to provide a definition anyway.  You are simply looking to implement some commonly used functionality in your parent class for easy-reuse, which is perfectly reasonable.  The fact that this is a controller doesn't change the overall picture at all, although there are a few caveats to keep in mind.

Finally, having the behavior of the parent method change based on definitions in the child method is perfectly reasonable to.  I use that pattern myself frequently (I'm referring to the definition of $default_model in the child class).  That could be considered an abstract property, except that PHP doesn't have such a thing.  As a result the only issue to watch out for there is the possibility that the developer that uses this system forgets to define the necessary properties.  There are two good ways to avoid that:

Instead of using a property, use an actual abstract method, which is supposed to return a string with the same value
Inside the parent method, check for a correctly defined $default_model and throw a detailed exception if it is missing: 'Cannot execute delete method for class ' . get_class($this) . ' because $default_model is not defined'  This way if you try to use this later and forget to declare all the properties, you get a clear and immediate warning telling you exactly what you did wrong.

Long Answer

Let's consider your goal: you have lots of controllers to implement lots of CRUD operations.  (for example) You need to CRUD users, you need to CRUD Customers, more CRUDs for Orders, products, categories, and so forth.  After putting together your second controller filled with repetitive CRUD methods, you really should be wondering "what can I do to avoid repeating myself so much" which is what you are really asking here.  You are trying to fix this problem by putting some basic CRUD functionality into the parent.  As I said, that is a reasonable approach and can avoid a lot of repetition.  It's worth mentioning the potential downsides:

This is a non-starter if your framework automatically routes to public controller methods.  This isn't the norm, but I've seen frameworks that do it.  If your public controller methods are automatically valid routes in your system, then putting any public methods in a base class means that every controller that extends that base has all those routes by default.  This is a very easy way to introduce accidental security vulnerabilities.
Your current implementation will also cause you trouble if you ever need flexibility in how the delete method is called.  I like the old adage "The only thing worse than no abstraction is the wrong abstraction".  For instance, what if you have a public-facing user's page and the user should only be able to delete themselves?  You won't be able to use this guy.  The validation rules are fixed, the calling sequence is fixed, etc...  Baking in a little more flexibility may be good, once you know what areas you need flexibility for.
Although less of a problem, this can result in unnecessary code "living" in your controllers if you put it in the base but don't actually need it all the time.

I consider that first one to be a show-stopper, but the second one is one you can plan for, and the third one is not a big deal, so (again), what you are doing isn't crazy.  There are a couple other ways to do this though, just because:

You can use traits, and have a trait for each CRUD method.  This way you only have to throw in the ones that you want.
You could put the CRUD functionality in separate classes that get generated and called as needed.  You could imagine having a deleteManager class which is passed in a model name (default_model) and the $_POST input, and which then does everything you have in your example.  This will again give you more flexibility.  Your controller only contains the functionality it needs, and you can have as many variations as you need without cluttering up your base class.  Maybe you have one deleteManager that does exactly what you have here, another that extends it and adds some authentication checks, etc... Maybe not the best examples but you should get the idea.

A review of your code

This is code review, and while I certainly want to answer your immediate question, a big goal of this site is to review everything.  So if you don't mind me making some other comments:

Your indentation is off.  You indent 8 spaces after the first line, and four spaces elsewhere.  I'm sure it was just a mistake, and it is best to try to fix those things before posting here, but it is more important to fix it in your code.  Following code formatting best practices makes reading code much easier, which makes debugging code much easier, which makes coding much easier.  You'd be surprised how often the little things matter.
You have a lot of inconsistencies in how you stylize your variable names and method names.  Choose snake_case, camelCase, or TitleCase and stick to it.  You use all three: Validator, validation_rules, toJson.  If uncertain just use PSR.
Your code doesn't properly addressing all possible branches.  No action is taken if the data validates but the delete fails.  This may cause problems for whatever client is calling this API endpoint.
You aren't using dependency injection.  That isn't exactly something that you fix overnight, but maintaining any size code base without automated tests (i.e. unit and integration testing) is a gigantic pain, and doing that requires dependency injection.  It makes for better code anyway.  Now is the time to start learning it.
I think there is some real code smell here: helperModel::toJson.  What is this helperModel and why does it have the job of converting to JSON?  Sounds suspiciously like a God Class.
I think some of your variables could be named better.  Granted, naming variables is hard, but it is worth the effort.  For instance, $default_model.  That doesn't give much hint as to what it is, and presumably the variable itself doesn't contain the model but rather the name of the model.  model_name might be better.  Similarly delete_contact is probably better off as a simple contact.  It is going to be deleted but it is still just a contact.  That one might be a nitpick though.
Finally, return early (aka guards).

I've loosely pulled together most of these suggestions for a counter-example:

public function delete(){
    if ($_SERVER['REQUEST_METHOD'] != 'POST'){
        echo 'error';
        return;
    }

    if(empty($_POST)){
        echo 'error';
        return;
    }

    // since the validator can't do anything without validation rules,
    // I would just pass them in to the constructor rather than
    // calling a separate method.
    $validator = new validator(array(
        'id'    => 'required|numeric',
    ));

    $validated = $validator->validate($_POST, true);
    if($validated === false){
        echo 'error';
        return;
    }

    $modeClass = $this->modeClass;
    $model = new $modelClass;
    if (!$model->delete($validated['id'])){
        echo 'error';
        return;
    }

    echo 'success';
}


Authenticating to Amazon EC2 Container Registry

Syntax errors

$aws_region = "--region $aws_region"

This is not how you set a variable in Bash. The correct syntax is

aws_region="--region $aws_region"

Likewise for the later statements. Note that there are no spaces before and after the =, and you drop the sigil before the variable name when you're assigning to it.

Use the appropriate shell parameter expansion

If you consult the Shell Parameter Expansion section of the Bash  manual, you'll see that

declare registry_id="${REGISTRY_ID:?''}"
if ! [[ -z $registry_id ]]; then
    $registry_id = "--registy-id $registry_id"
fi

can be expressed more succinctly as

declare registry_id=${REGISTRY_ID:+--registy-id "${REGISTRY_ID}"}

and similarly for aws_region.

Use debugging prints

If you don't like the way the $query variable works, you can just execute the command without assigning it to a variable and still have Bash print the executed command (to stderr) with set -x in a subshell environment.

(set -x; aws ecr get-login "$aws_region" "$registry_id" "$options")

Redirect error messages to stderr

It is customary to print error messages to stderr for easy filtering, so write the last echo as

>&2 echo "---ERROR! Please login to AWS with myob-auth or ADFS."

Other notes

I personally prefer writing typeset over declare because the latter is a bashism whereas the former would also work in ksh, and it is the same amount of typing.
Looking at the Docker Engine API, it seems that the Docker version follows the common major.minor.build-patch format, so I would choose the more light-weight and simpler in syntax cut over sed and move the self-evident version-getting command into the test conditional.

if [[ $(docker version -f {{.Client.Version}} | cut -d'-' -f1) < 17.06 ]]
then
    options="--no-include_email"
fi

Don't write if ! [[ $? == 0 ]] and if ! [[ -z $aws_region ]]. Write if [[ $? != 0 ]] and if [[ -n $aws_region ]]. Okay, more leeway to the second one because I believe fewer people know about test -n than test -z, but at least it is not an inferior option.


Is there a better way to convert to a specific type with reflection?

You could use an extension method (if this is common), or a regular generic method with a "IConvertible" constraint on the desired value then call "Convert.ChangeType" in your SetValue call.
static class ObjectExtensions
{
    public static void SetPropertyValue<T>(this object obj, string propertyName, T propertyValue)
        where T : IConvertible
    {
        PropertyInfo pi = obj.GetType().GetProperty( propertyName );

        if( pi != null && pi.CanWrite )
        {
            pi.SetValue
            (
                obj,
                Convert.ChangeType(propertyValue, pi.PropertyType),
                null
            );
        }
    }
}

class TestObject
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

void Main()
{
    TestObject o = new TestObject();

    // Propery1 == null, Property2 == 0
    o.SetPropertyValue( "Property1", 1 );
    o.SetPropertyValue( "Property2", "123" );
    // Propery1 == 1, Property2 == 123
}

Obviously no error handling and this is assuming you want it available on all types, so I just threw it in an "ObjectExtensions" class so it'll be visible on all types.
Just adjust the constraints to fit your exact needs, or just throw it in a regular class if you don't want to use extensions.


Calculating a specific entry in a Pascal’s triangle recursively

Since this question is marked as beginner, let me compliment the neat structure and consistent style I see throughout. It's well done.

Variable, method, and class names are all meaningful, and useful.

The validation and error handling systems are uncommonly comprehensive, and again, well done.

Validation

The validation should provide more feedback to the user. Saying 'not enough arguments' is fine, but then you should also say how many are expected. Does the user have to engage on a guessing game, bouncing between too many arguments, and not enough arguments before discovering how many they need?

Pre-initializing variables

There is no need to preinitialize variables. The following:

    int row = 0;
    row = parseInteger(args[0]);

    int column = 0;
    column = parseInteger(args[1]);

can just be:

    int row = parseInteger(args[0]);
    int column = parseInteger(args[1]);

Algorithm

THis is where I see the biggest problem, and it's not because you've made a mess, but because I think you've missed the point. If the problem is: "... to calculate the entry of a Pascal’s triangle with a given row and column recursively" then that is not what you have done.

You have calculated all entries and stored them in an array, then indexed the values you need. Sure, some parts are recursive, but I expect that the point is to not have the arrays at all.

Consider the triangle:

1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
.....

The 'simple' solution is to have a method like:

public int getPascalValue(int row, int column) {
    if (column == 0 || column == row) {
        return 1;
    }
    return getPascalValue(row - 1, column - 1) + getPascalValue(row - 1, column);
}

That is a system for recursively calculating the value at a given row/column (assuming valid input).

It does a fair number or recalculations, but the point is that it solves the problem as stated.


Find duplicated text for tasks in MS Project

If I understand correctly, you are testing to see if there are any duplicate entries in Text30 and if you find a duplicate setting flag 5 to 1.

In this case you are duplicating at least half of the tests that you are conducting because Task(1).Text(30) = Task(2).Text30 is the same comparison as Tasks(2).Text30 = Task(1).Text30.

So you can cut down on the number of tests that you do by eliminating tests that you have already performed.  This is done by starting the inner loop at the current value of the outer loop.

e.g.

For Temp2 = 1 To ActiveProject.Tasks.Count

should be revised to

For Temp2 = Temp To ActiveProject.Tasks.Count

However an even quicker way would be to use a Scripting.Dictionary. I don't have project installed on my PC but even so if the code below doesn't work it should at least point you in the right direction

Sub Lacunza()

    Dim myUniqueText30 As Scripting.Dictionary
    Set myUniqueText30 = New Scripting.Dictionary

    Dim myTask As Long
    For myTask = 1 To ActiveProject.Tasks.Count

        With ActiveDocument.Tasks(myTask)

            If myUniqueText30.Exists(.Text30) Then

                .Flag5 = 1

            Else

                myUniqueText30.Add Key:=.Text30, Item:=myTask

            End If

    Next

    ' As this point you have a scripting dictionary which will return the task id
    ' where the first occurence of a particular Text30 value was found.

End Sub


You already reached two of your goals. The interpreter is very readable and very concise. It is pretty fast but could easily be made faster, but then the code would become longer and more complicated.

If you want the interpreter to stay readable, leave it as-is. Maybe document the wrap-around semantics in the Javadoc.

One thing you could change is for the , command to just be memory[memoryPointer] = stdin.read() & 0xFF;. This is more common than % 256, since this is about bit msnipulation, not about arithmetics.


Loading either all shops or a specifically named shop from a DataTable

You don't need any lambda expressions at all.

You can write

if (cmbShop.Text == "All Shops")
    Program.con.GET_Table_From_DataBase("sh", "select * from shops ");
else
    Program.con.GET_Table_From_DataBase("sh", "select * from shops where shopname='" +  cmbShop.Text + "' ");

DataTable shops = Program.con.dst.Tables["sh"];


Function for iterating out an unordered list of custom taxonomy terms

As pointed out, there is a lot of code repetition and this is a big problem when any changes get made.  It's so easy to quickly make a change to one piece of code and miss the 3 other versions of it which do the same thing.

Rather than factor out these parts of code into functions though, you can re-factor the code into a recursive function.  The idea being that you just use the same code to do each layer of the process rather than loops within loops calling helper functions to do the more common tasks.

One other thing I have changed is to build the output into a string rather than echo it out directly.  I would normally then return this string to the calling code and let that do whatever it wants with it.  This allows more control over the output generated, also allows the output to be re-used (although not sure how that would be necessary in this case) rather than having to re-generate the output each time.  But as I'm not sure how this is called, I just echo the combined string at the end.

function taxonomy_nav( string $category = null, array $settings = null  ) : string {
    if ( $category == null )    {
        $settings = [
            'taxonomy'     => 'kernal_category',
            'parent'        => 0,
            'number'        => 0,
            'hide_empty'    => false
        ];
        $parent_terms = get_terms( $settings );
    }
    else    {
        $parent_terms = get_terms( $category, $settings );
    }

    foreach ( $parent_terms as $parent_term ) {
        $list =  '
'. $parent_term->name.'';

        $childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );

        if ( ! is_wp_error( $childrenCheck ) && ! empty ( $childrenCheck ) ) {
            $list .= '
'
                . taxonomy_nav ( 'kernal_category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id )  )
                . '
';
        }

        $list .= '
';
    }

    echo $list;
}

As you can see, in the if ( ! is_wp_error( $childrenCheck ) block, it just starts the sub list and then calls itself to do the processing for any child nodes.

This also shows how the list item itself is only ever generated by the one line of code, not repetition and any changes are easily identified.


Scraping table contents from a webpage using vba with selenium

Good job once again!

I would eliminate one loop depth level - there is only a single table that you are interested it - iterate over its rows directly. And, I would switch to more concise CSS selectors to locate table rows and cells.

Also, I would rename post to a row and t_data to cell to correspond to what these variables represent:

For Each row In driver.FindElementsByCss("table#ctl00_body_MedicineSummaryControl_grdSummary tr")
    For Each cell In row.FindElementsByCss("td")
        y = y + 1
        Cells(x, y) = cell.Text
    Next cell

    x = x + 1
    y = 0
Next row


Before reviewing micro-design we may focus on overall architecture. You already know that in future you will also need to read an Excel file, it may be a good moment to introduce an abstract base class (or an interface) to abstract this detail from the client:

public abstract class Convertor
{
    public abstract IEnumerable<Company> ToCompanyModel(string path);
}

Note few changes:

I'm using Convertor as base class name then you will have, for example, CsvConvertor, no need to repeat any of those information in the method name.
I'm returning IEnumerable<Company> instead of List<Company>. The effective type you're using to store the result is an implementation detail, here I picked the most generic one but you may return IList<Company> as well (what if, for example, you will decide to store Company as an hash-table to detect duplicates?)

How to create the right Convertor instance? I assume you have DI in-place then you may have a factory class which will create the right instance according to file extension (assuming you're sure you will need Excel files). Something similar to:

public interface IConvertorFactory
{
    Convertor Create(string path);
}

If not then simply use DI to get the converter instance without any factory. You now have another problem: testing. Do you want to unit test your converter using physical files? Of course you need to but it's also handy to work with in-memory representations then you may add an overload with StreamReader:

public abstract class Convertor
{
    public abstract IEnumerable<Company> ToCompanyModel(string path);
    public abstract IEnumerable<Company> ToCompanyModel(StreamReader stream);
}

Default implementation may simply open the stream reading line-by-line and you won't need to worry about file size because it won't read everything in memory. Another benefit is that you can check for reader logic without mixing with I/O logic (and this is good to write extensive testing).

ICompanyRepository companyRepository has no reason to be static, you just make your class not thread-safe without any other benefit.

You're not doing any error handling. Things may go wrong and caller will get unknown exception. You'd better handle possible errors and return a single well-known exception (let's say InvalidDataException) with all the required details. Do not forget to document exceptions you may throw. You may even decide to ignore errors in one row and continue processing.

You're splitting each line with row.Split() multiple times, it's a waste: do it once.

To reduce nesting you can use continue and filters (example, again, without error handling):

foreach (string row in csvLines.Where(x => !String.IsNullOrEmpty(x))
{
    var fields = row.Split(',');

    var externalId = fields[0];

    if (companyRepository.CompanyExist(externalId))
        continue;

    // ...
}

However the truth is that you do not need to do CSV parsing by hand. In Microsoft.VisualBasic assembly (if you do not want to use an external library) you already have a well-tested and complete implementation:

using (var parser = new TextFieldParser(new StringReader(stream)))
{
    parser.SetDelimiters(new string[] { "," });

    // Skip header
    parser.ReadLine();

    while (!parser.EndOfData)
    {
        var fields = parser.ReadFields();

        // Same as before
    }

Note that you can catch MalformedLineException to handle errors and you can specify exactly the expected type of each field (if you want to). Also text fields may be enclosed in quotes, use TextFieldParser.HasFieldsEnclosedInQuotes property to instruct the parser. Blank lines are, by default, skipped and you may even use comments (see TextFieldParser.CommentTokens property).

Very last note: if CSV file is generated by Excel then be aware that it won't always use the comma as delimiter but the current list separator character (see CultureInfo.TextInfo.ListSeparator).


Truth table generator for an arbitrary function

The main flaw that can be observed in your function is the presence of code duplication: expressions such as 2^numArguments and arguments <- rev(as.logical(intToBits(i-1)))[-(1:(32-numArguments))] appear multiple times. Code duplication is generally bad, you could refactor so that each of them appears only one time.

Other little things:

R.utils and stringr are loaded but never used.
It's better to use FALSE instead of F.

Here is an alternative solution using expand.grid:

truthTable2 <- function(func, valuesOnly = FALSE) {
  args <- formals(func)
  L <- setNames(rep(list(c(TRUE, FALSE)), length(args)), names(args))
  df <- expand.grid(L)
  result <- sapply(1:nrow(df), function(i) do.call(func, lapply(df, `[`, i)))
  # or result <- do.call(func, df) if func is vectorized
  if (valuesOnly) {
    unname(result)
  } else {
    df[[substitute(func)]] <- result
    as.matrix(df)
  }
}

truthTable(majority)
#          a     b     c majority
# [1,]  TRUE  TRUE  TRUE     TRUE
# [2,] FALSE  TRUE  TRUE     TRUE
# [3,]  TRUE FALSE  TRUE     TRUE
# [4,] FALSE FALSE  TRUE    FALSE
# [5,]  TRUE  TRUE FALSE     TRUE
# [6,] FALSE  TRUE FALSE    FALSE
# [7,]  TRUE FALSE FALSE    FALSE
# [8,] FALSE FALSE FALSE    FALSE

Benchmark:

bench::mark(
  truthTable(majority),
  truthTable2(majority),
  check = FALSE
)
# # A tibble: 2 x 13
# expression                min  median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory time
# <bch:expr>            <bch:t> <bch:t>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list> <list> <lis>
# 1 truthTable(majority)   89.5us  97.4us     9634.    1.44KB     6.22  4650     3      483ms <lgl[~ <df[,~ <bch~
# 2 truthTable2(majority) 189.6us 204.7us     4292.        0B     4.07  2110     2      492ms <lgl[~ <df[,~ <bch~
# # ... with 1 more variable: gc <list>

bigf <- function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q) TRUE

bench::mark(
  truthTable(bigf),
  truthTable2(bigf),
  check = FALSE
)
# # A tibble: 2 x 13
#   expression             min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result               memory            time    gc
#   <bch:expr>        <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list>               <list>            <list>  <list>
# 1 truthTable(bigf)     2.13s    2.13s     0.469      64MB     5.63     1    12      2.13s <lgl[,18] [131,072 ~ <df[,3] [262,351~ <bch:t~ <tibble [1 x~
# 2 truthTable2(bigf)    2.43s    2.43s     0.412    76.5MB     5.77     1    14      2.43s <lgl[,18] [131,072 ~ <df[,3] [262,218~ <bch:t~ <tibble [1 x~
# Warning message:
# Some expressions had a GC in every iteration; so filtering is disabled.


Tkinter program that displays 28 numbers on the screen

For most of your question you will need to ask stack overflow specific question on each thing you want to do.

For example: You could ask a question about how to change the display of a button when said button is clicked. This kind of question is best suited for stack overflow.

However I can help you with making your existing code a bit better.

Lets take everything in your program and place it into a class. This will serve to make working with the code a much less painful process as we can work with class attributes and we do not need to worry about global variables. (Globals are bad Mmm Kaaa!)

Here is your code reworked into a class. For the rest you should ask a series of question on stack overflow :)

A few notes: Try to be more consistent with naming conventions. ClassName, functionName, variable_name. This will make the code easier to read and maintain. You might also want to change self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y)) to use the .format() method instead as it is the correct method going forward and % is being fazed out.

from Tkinter import *
import random

class Game(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")

        self.parent = parent
        self.parent.title("Centered window")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()

        self.tile_frame_column = {}
        self.tiles_make_number = {}
        self.tile_frame_column_counter=0
        self.tiles_make_number_counter=0
        self.xpos=35
        self.ypos=50

        self.tile_numbers = ['1', '2', '3', '4', '5', '6', '1', '2', '1', '2', '1', 'l', '1', '3', '4', '2', '1', '2', '1', '1', '2', '1', '1', '6', '4', '3', '2', '2']

        self.addNumbers()

    def centerWindow(self):
        w = 850
        h = 530
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.parent.geometry('%dx%d+%d+%d'%(w, h, x, y))

    def addNumbers(self):
        if not self.tile_numbers:
            return
        rand = random.choice(self.tile_numbers)
        self.tile_frame_column[self.tile_frame_column_counter] = Button(root, text=rand, font="Helvetica 16 bold")

        self.tile_frame_column[self.tile_frame_column_counter].place(x=self.xpos, y=self.ypos)
        self.tile_numbers.remove(rand)  # remove that tile from list of tiles
        self.xpos += 80
        if (len(self.tiles_make_number) % 7 == 0) & (len(self.tiles_make_number) > 0):
            self.xpos = 35
            self.ypos += 80
            self.tile_frame_column[self.tile_frame_column_counter].place(x=self.xpos, y=self.ypos)
            self.xpos += 80
        self.tiles_make_number[self.tiles_make_number_counter] = rand
        self.tile_frame_column_counter += 1
        self.tiles_make_number_counter += 1
        root.after(10, self.addNumbers)

if __name__ == '__main__':
    root = Tk()
    ex = Game(root)
    root.mainloop()


Keep your code styling uniform everywhere

Line 3 with your function declaration after $carousel.each( doesn't follow the same styling as used later on in line 50 when declaring the callback function for the click event listener here $this.on('click', '.carousel_prev', function (e) {.
Your if's/else if's/else's don't use the same format. You go from if () { to if (){.

Simplify your if statements
You should change:

if (outer_width > 1145) {
    container_width = 1170;
}
if (outer_width > 960 && outer_width < 1145) {
    container_width = 960;
}
if (outer_width < 960) {
    container_width = parseInt((9/10)*outer_width,10);
}

to use a combination of if(), else if(), and else():

if (outer_width > 1145) {
    container_width = 1170;
} else if (outer_width > 960) {
    container_width = 960;
} else {
    container_width = parseInt((9/10)*outer_width,10);
}

Another example of this is here:

if (outer_width < 760){
    $li.css('width', container_width);
    $li.eq(1).addClass('active');
    if ($li.eq(2).hasClass('active')) {
        $li.eq(2).removeClass('active');
    }
} else if (outer_width > 760){
    $li.eq(1).addClass('active');
    $li.eq(2).addClass('active');
}

It can easily be written as:

if (outer_width < 760) {
    $li.css('width', container_width);
    $li.eq(1).addClass('active');
    if ($li.eq(2).hasClass('active')) {
        $li.eq(2).removeClass('active');
    }
} else {
    $li.eq(1).addClass('active');
    $li.eq(2).addClass('active');
}

This also fixes a problem with a dead spot that happens if outer_width is equal to 760. Unless this is unwanted behavior, which I see no reason why it should be, then the second option is the better way to go. This is an implementation of the TF-Statement or binary condition, where if it's not one, it always has to be the other. Sorry, I've been in math theory recently. :-)

Use simpler and more concise code
Where you define var not_active_no = $this.find('li').not('.first').not('.last').not('.active').length;, you could have easily written a single cleaner and concise $.not(); like so: var not_active_no = $this.find('li').not('.first, .last, .active').length; or you could've just settled with a single CSS call like so: var not_active_no = $this.find('li:not(.first, .last, .active)').length;.


Unfortunately the exercise is a bit abstract to me, because I cannot visualize the data you are manipulating. A data sample would have been welcome to better comprehend your purpose.

A few comments anyway

I don't see the code for FindLastRow
You have multiple references to C17, so it should be defined as a constant variable. It could be named START_CELL or something. Using uppercase is common practice.
999: another magic number that also appears multiple times. It should be made a constant too, MAX_ITERATIONS or something. Or it could be passed as a parameter to CheckOccurance (you already have 3). The aim is to avoid repetition, and leave room for flexibility (because you might want to change that value at some point).
Warning: CheckOccurance is a typo
You also have more 'arbitrary' values like 3, 4... I suppose they are offsets. Again it would better to use variables instead because they are more descriptive, this will make your code more readable, easier to understand and will reduce the risk of errors, especially if you shift rows/columns later. And here, doing a search & replace on 3 or 4 is not an option.
This line has 3 hardcoded values: ws.Range(Cells(lastUsedRow, 3), Cells((occur * 999) + 16, 3)).value = key & "-" & x. And x is not the most meaningful name for a variable.
Rather than using ranges like "C17:C" & LRow with hardcoded references it would be better to use named ranges. They are more descriptive and more flexible. Like variables, you define them once, and reuse them multiple times. Why You Should Be Using Named Ranges in Excel
Using ActiveSheet is tricky, because the context could change, for example your macro could switch to another sheet or workbook, and ruin your assumptions. It would be safer to retrieve a named reference (from ActiveSheet.Name) to a variable and then use that variable. If you have no sheet selected, this property returns Nothing.
If you are concatenating just two cells maybe using an array and JOINing is a bit overblown: strCell = Join(Array(wsSource(i, 1), wsSource(i, 3)), "|"). But the best is to run a benchmark and test performance using different approaches. Don't be afraid to experiment. Good code is code that is efficient while remaining intelligible.
I don't understand why you declare your variable like this: Dim wsSource As Worksheet and then use it like this: wsSource = .Range("C17:U" & LRow).value. Did you mean Range ?
The choice of data type for your variables is not always optimal: several variables are of type Double. From the doc: "Double (double-precision floating-point) variables are stored as IEEE 64-bit (8-byte) floating-point numbers ranging in value from: -1.79769313486231E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values". Performance matters when you are doing arithmetic operations in loops.
Even Long is more than enough: "Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647."
FYI: Total number of rows and columns on a worksheet: 1,048,576 rows by 16,384 columns (source: Excel specifications and limits). So when working with columns, Integer is sufficient: "Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767".
But but but surprise: "In recent versions, however, VBA converts all integer values to type Long, even if they're declared as type Integer. So there's no longer a performance advantage to using Integer variables; in fact, Long variables may be slightly faster because VBA does not have to convert them." (Source: The Integer Data Types).

Code structure

Overall, tabulation is OK except UniqueListWithSumQty
Usage of With where appropriate
Some line spacing would be desirable, calls to external methods eg. Call CheckOccurance should be highlighted and not drowned with the rest of the code because it is important to be able to follow the processing stream.
One problem: lack of comments. There are important for you too, because in a few weeks or months, you will have lost your train of thought and you will have to re-analyze your own code. It is also very helpful to put some data sample in comments when you extract or compute data, to have an idea of what the values look like. For example, when you extract rows from a range, copy-paste a row or a small portion of your range and add it to comment.
It is important not just to document the individual steps, but also the general logic of your code, for this you add a few lines of comments at the top of your module.

The code is quite short, but unfortunately it's not as easy to understand as it should be, because there are too many hardcoded values, and the underlying data is not known.

Strategy

Obviously this is what you are interested in and this is where I am going to be the least helpful, because I lack some insight.

First of all, you did not give a clear definition of what qualifies as duplicate data. You've mentioned order numbers but that's the only thing we know. So I am assuming that you are really looking for duplicate order numbers but maybe that's not the whole story. You mention 'concatenating 2 fields' but what are they ?

Maybe all of this was not even necessary, because Excel now has built-in tools to find duplicate data: How to Find Duplicates in Excel. But then, it this was not sufficient for your purpose it should have been made clear and maybe we could propose a better approach.

A COUNTIF might suffice. You even use it in your code. Maybe there is a reason but what was it, I am wondering.
Dictionaries are certainly useful, but in the present case ?


Removing everything after a certain character

You're using the same variable for two different purpose. It would be readable with separate variables:

$urlWithoutParameters = strstr($url, "?", true);
if ($urlWithoutParameters !== FALSE) {
    // if you need additional processing
}

It might be safer to use PHP's built-in parse_url function which could help handling invalid inputs too:

  On seriously malformed URLs, parse_url() may return FALSE.

From Effective Java, 2nd edition, Item 47: Know and use the libraries:

  By using a standard library,
  you take advantage of the knowledge of the experts who wrote it and the
  experience of those who used it before you.

(It's mostly a Java book but it applies here.)


Simple Linux upgrade script in Bash revision 2

Don't use non-portable terminal escape codes
The tput program exists for exactly this purpose:
red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)

(I've downcased your variable names, to avoid surprising conflicts with environment variables)
Inline the single use functions
show_success and show_error_and_exit are laudable, and do help readability, but they are only used once each, and may be clearer if written directly into error_handler.  Either way, their output really ought to go to the error stream: >&2.
Reduce duplication
Look at this pattern:
echo -e "\n${GREEN}Step 1: configure packages${NOCOLOR}"
echo -e "${YELLOW}dpkg --configure -a${NOCOLOR}"

sudo dpkg --configure -a

error_handler $?  1

This structure is repeated throughout the program, but it can be refactored.  Let's write the variable parts using variables:
echo "${green}Step ${step}: ${description}${nocolor}"
echo "${yellow}${command}${nocolor}"

$command

error_handler $?  $step

There's three things we need: a step number, description, and the command to run.  The command needs to be an array; that's easy to arrange by passing it as all the arguments after description.  We can also inline the error_handler:
do_action()
{
    step=$1; shift
    description=$1; shift
    printf "${green}Step %s: %s\n" "$step" "$description"
    printf "${yellow}"
    printf '%q ' "$@"
    printf "${nocolor}\n"

    if "$@"
    then
        printf "${green}Step %s: SUCCESS${nocolor}\n" "$step"
    else
        err=$?
        printf "${red}Step %s: FAILED${nocolor}\n" "$step" >&2
        exit $err
    fi
}

This function is then used as:
i=0
do_action $((++i)) "configure packages" dpkg --configure -a
do_action $((++i)) "fix broken dependencies" apt-get install --fix-broken
do_action $((++i)) "update cache" apt-get update
do_action $((++i)) "upgrade packages" apt-get upgrade
do_action $((++i)) "upgrade distribution" apt-get dist-upgrade
do_action $((++i)) "remove unused packages" apt-get --purge autoremove
do_action $((++i)) "clean up" apt-get autoclean

You might choose to make the step number a global variable and increment it inside the function; I haven't done that, because global variables tend to proliferate and make the program hard to reason about.
Don't sudo in a script
Many calls to sudo is a sign that the entire script needs superuser capabilities, so it's better if the user runs the script as root.  You could automate this (though I would personally just error out):
test $EUID = 0 || exec sudo $0 "$@"

Full program
#!/bin/bash
set -e -u

red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)

do_action()
{
    step=$1; shift
    description=$1; shift
    printf "${green}Step %s: %s\n" "$step" "$description"
    printf "${yellow}"
    printf '%q ' "$@"
    printf "${nocolor}\n"

    if "$@"
    then
        printf "${green}Step %s: SUCCESS${nocolor}\n" "$step"
    else
        err=$?
        printf "${red}Step %s: FAILED${nocolor}\n" "$step" >&2
        exit $err
    fi
}

i=0
do_action $((++i)) "configure packages" dpkg --configure -a
do_action $((++i)) "fix broken dependencies" apt-get install --fix-broken
do_action $((++i)) "update cache" apt-get update
do_action $((++i)) "upgrade packages" apt-get upgrade
do_action $((++i)) "upgrade distribution" apt-get dist-upgrade
do_action $((++i)) "remove unused packages" apt-get --purge autoremove
do_action $((++i)) "clean up" apt-get autoclean


Create a strategy to find the mapped implementation of the interface provided:

IDictionary<Type, Type> mappings; //Populated with all interface to implementation types

private DalServiceBaseClient CreateHttpClient<T>(string baseAddress) {
    var httpClient = new HttpClient {
        BaseAddress = new Uri(baseAddress)
    };
    var implementationType = mappings[typeof(T)];
    if (implementationType == null)
        throw new ArgumentException("No type exists for the provided interface");

    return (DalServiceBaseClient)Activator.CreateInstance(implementationType, httpClient);
}

Note how reflection is used to create an instance of the implementation.

The mappings would be pre-populated and can look like...

mappings = new Dictionary<Type, Type>();
mappings[typeof(IMasterService)] = typeof(MasterServiceClient);
mappings[typeof(ISlaveService)] = typeof(SlaveServiceClient);

//...other types;

Another option if not too keen on using reflection, is to use a factory delegate which would allow a more strongly typed mapping.

IDictionary<Type, Func<HttpClient, DalServiceBaseClient>> mappings; //Populated with all interface to implementation types

private DalServiceBaseClient CreateHttpClient<T>(string baseAddress) {
    var httpClient = new HttpClient {
        BaseAddress = new Uri(baseAddress)
    };
    var implementationFactory = mappings[typeof(T)];
    if (implementationFactory == null)
        throw new ArgumentException("No type exists for the provided interface");

    return implementationFactory(httpClient);
}

Which would be populated like

mappings = new Dictionary<Type, Func<HttpClient, DalServiceBaseClient>>();
mappings[typeof(IMasterService)] = (httpClient) => new MasterServiceClient(httpClient);
mappings[typeof(ISlaveService)] = (httpClient) => new SlaveServiceClient(httpClient);

//...other types;


Wrapping fetch(), preserve promise-based API for outer function

but am not sure if that applies here. And, is it necessary to return
  the result wrapped in a new promise, at all?

Yes, that applies here.

No, returning Promise.resolve() is not necessary. .then() returns a new Promise object. Use

return result

within the function passed to .then().

Note, a value returned from .catch() results in a resolved Promise. Depending on how errors are handled an error could be thrown (withing {} of a function).

this.fetchCalendarData(0, 6).then((fetched_calendar_data) => {
    this.calendar_data = fetched_calendar_data;
});

should include the second parameter to .then() to handle potential error

.then((fetched_calendar_data)=>{}, err=>{/* handle error */})

given then Promise.reject() is returned from .catch(), or .catch() should be chained to .then()

.then((fetched_calendar_data)=>{}
.catch(err=>{/* handle error */})

fetchCalendarData(offset, length) {
  return fetch(this.props.Uri + '?offset=' + offset + '&length=' + length)
  .then(response => response.json())
  .then(result => {
    if (result.hasOwnProperty('redirect_to_login')
       && result.redirect_to_login == true) {
         window.location.reload(window.globalAppState.base_url + "/login");
    }
    return result;
  })
  .catch(() => {
    throw new Error('FAILURE');
  });
}

this.fetchCalendarData(0, 6)
.then(fetched_calendar_data => {
  this.calendar_data = fetched_calendar_data;
})
.catch(err => console.error(err));


Rounding ints division result to certain "granularity"

Let me start with the usual:

Naming

myDecimal: Usually, the prefix "my" does not bear any sensible information. You should think about the information you want to pass by the types name. (For example Decimal is often the name for decimal fractions and the way in which numbers are stored in it!)
rest: in the context of a modulus this is called remainder
candidat: this is a candidat but where is the other one and which one is it? You should call this something like: flooredValue

Reusability

Everytime that you use this function you have to use the exact type or must cast, which is slow. You should think about making it a template function.

Performance

Most of this is micro optimizations but you seem to be interested in every last bit of time. I don't know how much of this is automatically done by your optimizing compiler:

go to assembler: This is very easy code that can be written in assembler. Especially the division and modulus are two functions that are slow (compared to others) and (at least) on x86 architectures the assembler instruction for division gives you the modulus at the same time. (likely optimized by the compiler)
multiplication by 2: this can be replaced by a left shift by one (very likely optimized by the compiler)
multiplication in return: instead of using a multiplication you can use an addition to return the results (return val - remainder; and return val + granularity - remainder;) (maybe not optimized by the compiler)

Note that all of those "optimizations" could be done automatically by the compiler and even more important might not be optimizations on modern architectures anymore. When it comes to performance you should compare on the assembler level and do extensive profiling.


As mentioned in the comments, you should go for more readable code:

1) Split by responsibility:

One method for user input:

ulong GetPrimeIndex() { // TODO: Get User input from Console }

The algorithm itself:

ulong FindNthPrime(ulong n) { // TODO: the algorithm }

print the result...

public static void Main(string[] args)
{
  ulong primeIndex = GetPrimeIndex();

  Stopwatch watch = Stopwatch.StartNew();
  ulong nthPrime = FindNthPrime(primeIndex);
  watch.Stop();

  Console.WriteLine($"{primeIndex} prime is: {nthPrime}");
  Console.WriteLine($"Elapsed time: {watch.ElapsedMilliseconds}");
}

2) Naming:

In C# local variable names use camelCase: largestprime should be largestPrime

Because primes are always  positive, you should use ulong instead of long. It will give you a broader range to operate in.

I think you're missing a couple of breaks in these tests:

                if (primearray[x] * primearray[x] > potentialprime)
                     break;
                if (prime > 3 && (potentialprime % primearray[x] == 0 || potentialprime % primearray[x+1] == 0 || potentialprime % primearray[x+2] == 0))
                     isprime = false;
                if (prime <= 3 && potentialprime % primearray[x] == 0)
                     isprime = false;

It should be:

  if (primearray[x] * primearray[x] > potentialprime)
    break;
  if (prime > 3 && (potentialprime % primearray[x] == 0 || potentialprime % primearray[x + 1] == 0 || potentialprime % primearray[x + 2] == 0))
  {
    isprime = false;
    break;
  }
  if (prime <= 3 && potentialprime % primearray[x] == 0)
  {
    isprime = false;
    break;
  }

Be aware that

  primearray[x] * primearray[x]

may overflow the domain range. You should maybe make the check by sqrt instead?


SVG class with boilerplate prologue and epilogue from files

Is it correct to put code that does something more complex than just assigning constant values in the class definition?

In general, I try to avoid it. Any code in the class definition will be run as soon as the class definition is executed – that is, as soon as somebody imports your code. So putting complex code in the class definition causes problems for importers:

If the code is slow, you slow down the rest of the program
If the code has side effects, you’re breaking the rule of least surprise – it’s quite unusual for importing a module to have side effects
If the code can throw exceptions (e.g. if you try to read svg_start.txt and it’s not there), same thing. When I import a library, the only exception I expect it might throw would be an ImportError. Throwing an OSError is generally quite unusual.

So I’d try to avoid it if you can. Only run that code when you need it – i.e., when somebody starts making instances of the class.

In this case, I’d think of maybe defining a descriptor, which caches the file contents, and then apply that to the class, like so:

class CachedFile:

    def __init__(self, path):
        self.path = path
        self.contents = None

    def __get__(self, instance, type):
        if self.contents is None:
            self.contents = open(self.path).read()
        return self.contents

class SVGDrawing:

    svg_start = CachedFile(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_start.txt'))
    svg_end = CachedFile(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'svg_end.txt'))

    def __init__(self, *args, **kwargs):
        pass

Note that in this case, the file reads are deferred right up to the point where we need them – much more efficient than doing a read at import time. The flipside is that this code is a bit more complicated – you should decide if the performance gain is worth it.


Adding punctuation to US and European patent numbers

Here is a solution using a generator, which gives you linear time. Your current solution is not linear, because list.insert is already \$\mathcal{O}(n)\$.

def interweave(x, y):
    """
    Given an iterable `x` and an iterable `y` of indices and items,
    yield from `x`, but interweave the items from `y` at the given indices.
    """
    y = iter(y)
    next_i, next_y = next(y, (-1, ""))
    for i, next_x in enumerate(x):
        if i == next_i:
            yield next_y
            next_i, next_y = next(y, (-1, ""))  # default value for when y is exhausted
        yield next_x

def punctuate(text, punctuations):
    return "".join(interweave(text, punctuations))

It passes all the given testcases:

In [98]: punctuate('US 8012999 B2', [(4, ','), (7, ',')])
Out[98]: 'US 8,012,999 B2'

In [99]: punctuate('US 20170107206 A1', [(7, '/')])
Out[99]: 'US 2017/0107206 A1'

In [100]: punctuate('US 09700674', [(5, '/'), (8, ',')])
Out[100]: 'US 09/700,674'

In [101]: punctuate('EP 2795605 B1', [(4, ' '), (7, ' ')])
Out[101]: 'EP 2 795 605 B1'


Determine if element is a select, if so fill it with data from another object

I tried to decipher your code, and express it in pseudo-code:

for each view:
    request view data from server
    for each view:
        for each <select> element with dataParent in view:
            find view where view.name == dataParent
            if found and has data:
                load <select> with data from that view

So you load data for each view, but then you also go through all other views to pass this data to them when they happen to need it. However you don't only pass the data from currently loaded view, but you try to cover all the views (some of which have not been loaded yet).

So the first optimization to make is to eliminate this third loop through all the views. Just passing the data from currently loaded view to the views that need it:

for each view (loadedView):
    request view data from server
    for each view:
        for each <select> element where dataParent == loadedView.name:
            load <select> with data from that loadedView

That's better, but we still need to loop through all the views to find out which ones need our data. Perhaps there are hundreds of views and only three need the data.

A better approach would be to use a publish-subscribe model. Instead of having to loop through all the views, each view that needs data would subscribe itself on the view who's data it needs. When the data for that view is loaded, it would publish this data to all its subscribers

For example:

viewA = new View();
viewB = new View();
viewC = new View();
viewA.addListener(viewB);
viewA.addListener(viewC);
// load view A, which will also push data to views B & C
viewA.loadData();

Each view would have an array of its subscribers. .addListener() method would add a new item to this array. And in loadData(), after the data has been fetched from server, we'd loop through this subscribers array and call a method like addData() on each view.


First things first: any time you find yourself using letfn, you should strongly consider simply breaking those functions out into their own defns. In this case, node-matches is large enough and decoupled enough to make that clearly the right choice.

One way you can make your code more concise is to take advantage of the fact that you can do destructuring directly in function arguments:

(defn node-matches [[tag attrs] [node-tag node-attrs]]
  (and (= node-tag tag)
       (every? (fn [[key val]]
                 (= (key node-attrs) val))
               (seq attrs))))

If you want to make clear what it is that you're destructuring, you could add :as prototype and :as node to your parameters.

When you think about it, though, that every? expression is really just trying to determine if attrs is a subset of node-attrs. In Clojure, you can use the subset? function to do that. So, assuming that you've already required [clojure.set :as set]:

(set/subset? (set attrs) (set node-attrs))

A lot of the complexity in the rest of find-nodes comes from the fact that you're complecting the logic that traverses the HTML tree and the logic that uses node-matches to do the matching and assemble the final result.

The best way to improve find-nodes, then, is to break it apart. Actually, traversing a Hiccup-style HTML tree is incredibly easy in Clojure using the tree-seq function:

(tree-seq vector? tagsoup/children (tagsoup/parse "test.html"))

This will give you a sequence of all the nodes in the HTML tree:

([:html {}
  [:head {}
   [:title {} "This is a test page"]]
  [:body {}
   [:div {:id "something-important"}
    [:p {:class "alert"}
     "\n        ...\n      "]]
   [:div {:id "something-else"}
    [:p {:class "message"}
     "\n        Hello World.\n      "]]]]
 [:head {}
  [:title {} "This is a test page"]]
 [:title {} "This is a test page"]
 "This is a test page"
 [:body {}
  [:div {:id "something-important"}
   [:p {:class "alert"}
    "\n        ...\n      "]]
  [:div {:id "something-else"}
   [:p {:class "message"}
    "\n        Hello World.\n      "]]]
 [:div {:id "something-important"}
  [:p {:class "alert"}
   "\n        ...\n      "]]
 [:p {:class "alert"}
  "\n        ...\n      "]
 "\n        ...\n      "
 [:div {:id "something-else"}
  [:p {:class "message"}
   "\n        Hello World.\n      "]]
 [:p {:class "message"}
  "\n        Hello World.\n      "]
 "\n        Hello World.\n      ")

And at this point, you're pretty much done. You just need to filter this sequence using the shortened version of node-matches that we wrote above:

(defn find-nodes [[tag attrs] root]
  (filter (fn [[node-tag node-attrs]]
            (and (= tag node-tag) (set/subset? (set attrs) (set node-attrs))))
          (tree-seq vector? tagsoup/children root)))


Basic input system for a few form fields

Handling the Problem

To make this scalable you need to generate the HTML to fit however many items you want to include. To Render it this way you need a data structure to hold what you want to render.

First Think of the data structure then what functions you need to render this data.

My Solution

I picked the following data structure.

[{
  title: String
  value: Number
}]

Here is the list of render functions I picked.

renderForm -> Render just the form
renderResults -> Render just the results
render -> Render the entire screen

And finally, we will need to capture the data changes from the form to update the data structure and then call renderResults so I created the onFormChange function.

Code

// Code goes here

const data = [{
  title: 'E',
  value: 0
}, {
  title: 'M',
  value: 0
}, {
  title: 'C',
  value: 0
}, {
  title: 'F',
  value: 0
}]

function onFormChange (value, i) {
  data[i].value = value;
  renderResults();
}

function renderForm () {
  const elForm = document.getElementById('form');
  let html = '';
  elForm.innerHTML = '';
  data.forEach((d, i) => {
    html += `
      How many ${d.title}'s
      <input type='text' value=${d.value} onchange="onFormChange( this.value, ${i})">

    `;
  })
  elForm.innerHTML = html;
}
function  renderResults () {
  const elResults = document.getElementById('results');
  let html = '';
  elResults.innerHTML = '';
  // Render Each Element
  data.forEach((d, i) => {
    html += `
      ${d.title}: ${d.value}

    `;
  })
  // Render Total
  let sum = 0;
  data.forEach((d) => {
   sum += Number(d.value) || 0
  })
  html += `

Total is ${sum}

  `
  elResults.innerHTML = html;
}

function render () {
  renderForm()
  renderResults()
}

window.onload = render;

<!DOCTYPE html>

    <form id="form">
    </form>

Final Thoughts

I did add a total div at the end of the results to show how you can also do some calculations on the entire data set when any of the values change.

Go ahead and add any additional data to the data array and have fun with it.


Yes it is, it takes 0.372798 seconds to run on my computer for a 50 MB file, for a 46KB file this runs in the blink of an eye.

Anyway as this is Codereview I suggest an equally fast but higher level version of your code:

def get_names(filename)
    File.read(filename).tr('"', '').split(',')
end


SPOJ - POWFIB (Fibo and non fibo) Time Limit Exceeds

Here, you are using modular exponentiation and modular multiplication, which are fast enough.
Your nonfibo function is also taking only O(lg(n)) time.
But your method for computing nth fibonacci number is not much efficient. Try using this Linear Recurrence Solving Method.


Checking whether given array is sorted by divide-and-conquer

It looks like your are doing it mostly right.   You have problems with length zero and length 1 arrays, but you should be able to fix those pretty quick.

You may be doing more work than necessary.  If an array is not sorted, you might find leftPart is false, but you unconditionally go on to determine the value of rightPart anyway, despite it not mattering.  The simplest way to avoid that is to combine that recursive calls and the && operation.  Ie:

return isSorted(arr, start, middle) && isSorted(arr, middle, end);

Lastly, if the array contains duplicates, can it still be considered sorted?  You return false for [1, 2, 2, 3].


Generally it looks like your know what your doing, maybe you could be more efficient by removing the blur event since you wouldn't need to save/validate if the input is already populated or left empty, this will also save you calling onInputChange twice when an input is changed.

Backbone will automatically create this.$el from the el property so you can just do.

el: 'form' and then this.$el would be created for you.

Finally i would use listenTo rather than on for example.

this.model.on('invalid', this.onModelInvalid, this);

would be done like this using listenTo.

this.listenTo(this.model, 'invalid', this.onModelInvalid);

This allows you to keep track of events on the object and then remove them all at once later on.


The layout of your code is consistent and easy to read.  I don't see any functional problems.
One consideration for all digital logic is whether you can tolerate glitches on your outputs.  If your PWM output is directly driving a load such as a power inverter, you likely want to avoid glitches.  To avoid glitches, change your combinational output to a registered output:
always_ff @ (posedge clk_i) begin
    if (1'h0 == s_rst_n_i) begin
        channel_o <= 1'h0;
    end
    else begin
        channel_o <= (req_value_i != counter);
    end
end

I also simplified the expression by removing the ternary code ? 1'h1 : 1'h0.  But, this is just a matter of coding style preference.
Another consideration is whether to use a synchronous reset (as you have) or an asynchronous reset.  The advantage of asynchronous is that you don't need to have the clock toggling in order to reset your logic.  For asynchronous, you would use:
always_ff @ (posedge clk_i or negedge s_rst_n_i) begin


Dynamic Fibonacci algorithm in x86 (MASM)

I'm wondering how this is normally done

Yours is as good a solution as anyone else's.
That said, a solution that pushes the elements would not need to address these elements relative to EBP at all.

; new f[] of size n + 2
lea     edi, [ebx + 2]             ; save size of array in edi
shl     edi, 2                     ; mul by 4, size of DWORD int

You can calculate the required stackspace in a single LEA instruction:

; new f[] of size n + 2
lea     edi, [ebx * 4 + 8]

; f[0] = 0 and f[1] = 1
mov     DWORD PTR[esp], 0
mov     DWORD PTR[esp + 1 * 4], 1
; for (i = 2; i <=n; i++)
mov     ecx, 2                     ; loop count i set to 2

All of these assignments require a 32-bit immediate value. That's a lot of bytes! Because later we need ECX=2, we can start with clearing ECX and incrementing twice towards 2, storing the intermediate results in memory:

; f[0] = 0 and f[1] = 1
xor     ecx, ecx
mov     [esp + 0 * 4], ecx         ; f[0] = 0
inc     ecx
mov     [esp + 1 * 4], ecx         ; f[1] = 1
inc     ecx                        ; loop count i set to 2

But wait, there still room for improvement!

The address [esp + 0 * 4] requires a modR/M-byte, sib-byte and an 8-bit displacement.
The address [esp + ecx * 4] requires a modR/M-byte and a sib-byte.

Final draft:

; f[0] = 0 and f[1] = 1
xor     ecx, ecx
mov     [esp + ecx * 4], ecx       ; f[0] = 0
inc     ecx
mov     [esp + ecx * 4], ecx       ; f[1] = 1
inc     ecx                        ; loop count i set to 2

; f[i] = f[i - 1] + f[i - 2]
lea     eax, [ecx - 1]
mov     esi, DWORD PTR[esp + eax * 4]
dec     eax
add     esi, DWORD PTR[esp + eax * 4]
mov     [esp + ecx * 4], esi

You can easily address the 2 previous array elements by adding offsets -4 and -8.
This liberates the ESI register that also no longer needs to be preserved.

; f[i] = f[i - 1] + f[i - 2]
mov     eax, [esp + ecx * 4 - 8]   ; f[i - 2]
add     eax, [esp + ecx * 4 - 4]   ; f[i - 1]
mov     [esp + ecx * 4], eax       ; f[i]

        mov     ecx, 2
L1:     cmp     ecx, ebx
        jg      endL1
        ...
        inc     ecx        ; inc i
        jmp     L1
endL1:

A loop like this is wasteful because of the uncondional jump that gets executed on every iteration, on top of the conditional jump that needs to be  processed anyway. You can make the conditional jump the only jump that gets executed repeatedly.

        mov     ecx, 2
        jmps    L2         ; once
L1:     ...
        inc     ecx        ; inc i
L2:     cmp     ecx, ebx
        jbe     L1         ; repeatedly


Mitch, you have a nice program there.  As I pointed out above, current_search_start is not updated which means 9 of 10 threads are searching the same space and the last searches the whole space.  Minor error though.

Your use of condition variables and mutexes is nicely done.  Overall, nothing significant to comment on.

Some minor comments:

The precedence of -> is higher than that of * so this:

if (!(*(pUnitOfWork->shouldStop))) {

can be written:

if (!(*pUnitOfWork->shouldStop)) {

or some might prefer:

if (*pUnitOfWork->shouldStop == false) {

And

*(pUnitOfWork->shouldStop) = true;

can omit the parenthesis and be neater.
I would change some variable names.  cValue seems meaningless. pUnitOfWork would be just work.  The p (and vp) prefixes you used look like Hungarian.  I would never use such things unless forced to by an outdated coding convention.
find_value should strictly be static
The loop in find_value would be more normal as a for:

for (int c = work->start; c < work->end; ++c) {
    if (*work->shouldStop) { ... }
    if (c == work->search) { ... }
}

Also I would add a thread number and some debug to see which thread number is successful (especially with the current_search_start bug, as the thread is not always the same :-)


Bug

This might be a typo, but when I ran your program it infinitely looped.  The problem was in your constructor:

  public HeapItem(int[] arr, int index) {
       array = arr;
       index = 0;
  }

Here, you are setting index to 0 when you should be setting it to the input argument, like this:

  public HeapItem(int[] arr, int index) {
       array = arr;
       this.index = index;
  }

Reuse HeapItem

Your code all seemed very reasonable to me.  There is just one small improvement I would make here:

      if (current.index < current.array.length-1) {
         pq.add(new HeapItem(current.array, current.index+1));
      }

I would just reuse current instead of creating a new HeapItem, like this:

      if (current.index < current.array.length-1) {
         current.index++;
         pq.add(current);
      }

Create result list with exact size

One other small thing you could do is compute the output list size, when you are iterating through the arrays.  That way, you could create result with the correct size instead of having it autoexpand as you add elements to it.

  int outputSize = 0;
  for (int i = 0; i < arrays.length; i++) {
      pq.add(new HeapItem(arrays[i], 0));
      outputSize += arrays[i].length;
  }
  List<Integer> result = new ArrayList<Integer> (outputSize);


Echoing back input in uppercase over a socket with Hy, a Python Lisp dialect

I wouldn't use the threading macro here. That's most useful when you want to see the data flow, but you're using c two times in this expression, there's no clear flow that -> could make easier to untangle. It makes it more complicated in this case...

If you'd decouple the receive and the send part, then it'd be different, but then the expression becomes so simple you don't even need the macro:

(let [[received (.recv c 10000)]]
  (.send c (.upper received)))

With the threading macro, the inner part would become (-> received (.upper) (.send c)) - doesn't make it much clearer, either.

What you could do, however, is abstract away the accept -> do something -> close thing into a macro:

(defmacro with-accepted-connection [listening-socket & rest]
  (quasiquote (let [[*sock* (get (.accept (unquote listening-socket)) 0)]]
                (unquote-splice rest)
                (.close *sock*))))

(with-accepted-connection s (.send *sock* (upper (.recv *sock* 10000))))

The above may or may not work out of the box, I just conjured it up. But something similar may make the code lispier and easier to understand the intent later.


Combined looping and recursion when implementing Quicksort, using proper Clojure style

We are far from from beta-reduction here. The "reduction" can only be
  understood using explicit instruction flow semantics.

No. You have chosen to interpret loop and recur in this way, but that is not how Clojure understands them.

recur is simply a flag for a tail-recursive call, functional as you like.
loop is a gloss on defining and applying a function.

We could define loop as a macro in terms of fn:

(defmacro loop [bindings & expressions]
  (let [[bindees values] (->> bindings
                              (partition 2)
                              (apply map vector))]
    `((fn ~bindees ~@expressions) ~@values)))

The real loop macro checks the syntax of bindings. I've not bothered. And it handles destructuring explicitly. I've left it for fn to do.


Other than the style (yeah, you mentioned it) I think that you can:

First a small change: replace this

    int firstSpace = fullName.indexOf(" ");
    firstName = fullName.substring(0, firstSpace);
    int lastSpace = fullName.lastIndexOf(" ");
    middleName = fullName.substring(firstSpace + 1 , lastSpace);
    lastName = fullName.substring(lastSpace + 1, fullName.length());

with this:

String[] parts = fullName.split(" ");

But the main change I would suggest is a design one: remove the need for instance variables, by making each function return the input for the next.

public static void start()
{
    greet();
    String fullName = askInput();
    String[] nameParts = seperateFullName(fullName);
    String[] initials = getInitials(nameParts);
    showResult(initials);
}

(and of course modifying each function to return the value they compute)

Why?

It decouples each different part of the program, keeping them independent, specific, and therefore less prone to errors introduced somewhere else in the code.
It helps also with testing, as you can easily test each function separately.
It also helps with reusability as you could re-use each different part in other places.

Other than that, check the spelling in functions' names (For example: in seperateFullName separate is misspelt)


I'd start by avoiding directly encoding ASCII character codes into the logic. For example, instead of:

if ord char > 64 && ord char < 91

I'd probably use:

if char >= 'A' && char <= 'Z'

I think this shows the intent enough more clearly to be worthwhile.
Given that you also do this a couple of different places, I'd probably write a small isUpper function to return a Bool indicating whether a character is an upper-case letter:

isUpper :: Char -> Bool
isUpper char = char >= 'A' && char <= 'Z'

Then the rest of the code can use that:

encryptChar char shift = if isUpper char     -- ...

decryptChar char shift = if isUpper char     -- ...

[Note: the standard library already has an isUpper, but it may not fit your needs, since it's Unicode-aware, and here you apparently only want to deal with English letters.]


Possible memory-leak on a self-removable event handler

The code that you have will not result in holding onto a reference to any variables that the anonymous handler closes over once that handler is fired and the handler variable leaves scope or is set to something else (i.e. null), even if the A instance is kept alive.

So in short, it's fine.

Note that this is only ever a problem in the first place if the anonymous even handler closes over a variable that is a) expensive to keep alive, i.e. a very large collection of data and b) has a much shorter lifetime than the object that has the event being subscribed to.  If the object holding the event goes out of scope before, or very soon after, whatever is being closed over, then the object is not held in memory any longer than if the event handler is unsubscribed.  That specific case isn't actually all that common.


The algorithm can be simplified quite a bit. No need for switch-case. Just create an array (faceCount) with six slots and increment the appropriate slot. In other words:

roll = generator.nextInt(6);
faceCount[roll]++;

Then to print, iterate over faceCount and display the appropriate values (increment by one to adjust for array indexing).


No need to copy first array

Right now, you have this code that copies the first array into mergeArray, and then you start the merging loop:

    int[] mergeArray = new int[arrays[0].length];
    System.arraycopy(arrays[0], 0, mergeArray, 0, arrays[0].length);

    for(int i = 1; i < arrays.length; i++) {
        mergeArray = merge(mergeArray, arrays[i]);
    }

You don't actually need to do this copy.  Instead, you can just do this:

    int[] mergeArray = arrays[0];

    for(int i = 1; i < arrays.length; i++) {
        mergeArray = merge(mergeArray, arrays[i]);
    }

Reduce bounds checking

Your merging function is correct, but it checks both the left and right bounds on each iteration:

    while(index != mergeArr.length){
        if(left == arr1.length) {
            while(right != arr2.length) {
                mergeArr[index++] = arr2[right++];
            }
        } else if(right == arr2.length) {
            while(left != arr1.length) {
                mergeArr[index++] = arr1[left++];
            }
        } else {
            if(arr1[left] < arr2[right]) {
                mergeArr[index++] = arr1[left++];
            } else {
                mergeArr[index++] = arr2[right++];
            }
        }
    }

It would be slightly faster to only checking the bound that was moved:

    while (true) {
        if (arr1[left] < arr2[right]) {
            mergeArr[index++] = arr1[left++];
            if (left == arr1.length) {
                while (right != arr2.length) {
                    mergeArr[index++] = arr2[right++];
                }
                break;
            }
        } else {
            mergeArr[index++] = arr2[right++];
            if (right == arr2.length) {
                while (left != arr1.length) {
                    mergeArr[index++] = arr1[left++];
                }
                break;
            }
        }
    }

If you make this change, you also need to add a check before the loop that handles the case where one or both of the arrays had length 0.


Mergesort, instrumented for counting reads and writes

A minor "bug"

One of the main advantages of mergesort is that it is a stable sorting algorithm.  That is, it guarantees that two elements will not be swapped unnecessarily if they have the same value.

For that reason, the comparison in merge() should be implemented with:

if (leftArray[lIndex] <= rightArray[rIndex])

… so that it prefers taking from leftArray first if there is a tie.

For ints, it makes no practical difference whether the sort is stable, because two ints that are equal are indistinguishable.  But it's still a good idea to use <= rather than < for the comparison, to stay true to the mergesort algorithm.

Bounds convention

In Java, a common convention is to specify a range using inclusive lower indexes and exclusive upper indexes.  Examples of this convention can be seen in Arrays.copyOfRange(original, from, to) and string.substring(beginIndex, endIndex).  A main advantage of this convention is that endIndex - beginIndex is the number of elements in that range, which often leads to fewer ± 1 adjustments in the code.

For example, with that convention, you would get rid of the awkward array.length - 1 in doMergeSort(), and the couple instances of (middle + 1) in merge().  Also, populateArray() would have j < end as the loop condition, which is more idiomatic.  (To be fair, you would have to change the test in doMergeSort() to if (low + 1 < high).)

Copying array elements

populateArray() should be replaced by Arrays.copyOfRange() (or perhaps a wrapper around Arrays.copyOfRange() if you need the instrumentation to count reads and writes).  Similarly, the loops to copy the leftover leftArray and rightArray elements could be replaced by System.arraycopy().  Both techniques would not only save a few lines of code, but might also be slightly faster than a hand-written loop.

The post-increment operator is handy for updating index counters with less verbosity:

if (leftArray[lIndex] <= rightArray[rIndex]) {
    parentArray[pIndex++] = leftArray[lIndex++];
} else {
    parentArray[pIndex++] = rightArray[rIndex++];
}

In summary, I don't see anything that can be done about the number of reads and writes, because that's just how the mergesort algorithm works.  But you might be able to shorten the code a bit, and squeeze out a tiny (likely imperceptible) performance gain.


The optimized way to find the top k leading candidates from a unsorted hash map in python

So, you want to count something and afterwards get the top k? That sounds like a job for collections.Counter!

from collections import Counter

def leading_candidates(votes, timestamp, k):
    vote_counts = Counter(vote['candidate']
                          for vote in votes
                          if vote['timestamp'] <= timestamp)
    return [candidate[0] for candidate in vote_counts.most_common(k)]

if __name__ == "__main__":
    print(leading_candidates(votes, timestamp, 2))

This way you don't need to special case a candidate not yet having received a vote (something you could have also done with a collections.defaultdict(int)). And it is \$\mathcal{O}(n)\$.

Also note that if k is large, the line if candidates[candidate] in sorted_votes will become slow, as it is a linear scan. At the same time, you can iterate over the keys and values of a dictionary at the same time with candidates.items(), so you don't need to do candidates[candidate].

Python has an official style-guide, PEP8, which recommends using spaces after commas, which you forgot to do before k in the function signature.

You should always guard your code with an if __name__ == "__main__": guard to allow importing from the script without running it.


I'm not familiar with Android, so just some generic Java notes:

PrDatabaseAdapter should be prDatabaseAdapter (with lowercase first letter). See Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions and The Java Language Specification, Java SE 7 Edition, 6.1 Declarations:

  Names of fields that are not final should be in mixed
  case with a lowercase first letter and the first letters of subsequent words capitalized.

Javadoc comments like @param context aren't too useful, they say nothing more than the source code alone. I'd remove them.
Does it make sense to create a DatabaseAdapter with null context? I'd check this in the constructor and throw and NullPointerException if it's null. See Effective Java, 2nd edition, Item 38: Check parameters for validity


In general it looks good to me; only small nits:

You want to move from asserts to throwing proper, informative exceptions - for instance, showing both expected and actual values.

At the end of if name != ":CURVE":, you can just issue a continue instead of an else block - helps with the indentation.

Instead of making chunk a list and then doing a join at the end, you can make it a string and do string appending.


React.FunctionComponent probably isn't necessary - it's boilerplate for every single component you have, and arguably makes typings a bit worse, not better. See this article. For example, you could accidentally do:
<Scoreboard selectedOption={selectedOption}>{'The Scoreboard'}</Scoreboard>

without an error being thrown because every React.FunctionComponent is typed as taking children, even if they're not used.
To make the types more accurate, and to reduce the amount of boilerplate, consider using completely plain functions instead.
Declare variables close to where they'll be used The ButtonContainerProps is declared at the top of the script, but it isn't used until you scroll past 2 intermediate components - so if you see
const ButtonContainer: React.FunctionComponent<ButtonContainerProps> = ({

and you don't remember what ButtonContainerProps is, you'll have to scroll all the way back up to the top to see what it is. Or, even better:
If something is only going to be used once, consider whether it can be reasonably defined inline. For example:
const ButtonContainer: ({ options }: { options: string[] }) => {

I think that's plenty clear.
Let TS automatically infer return types when possible - unless explicitly typing a value is necessary to make the TS compile, or to make it easier for a reader to understand, you consider just leaving it off, like with the above ButtonContainer, since the boilerplate doesn't accomplish much. The capitalization of a component should make it clear that the function is a component that returns JSX.
Possible duplicate key It's probably pretty unlikely, but if the caller of ButtonContainer passes an array of strings that contains a duplicate, the <Button key={option} will result in a duplicate key, which is a problem. If the buttons are completely static in the DOM, I'd make the key be the index of the element in the options:
{options.map((option, i) => (
  <Button
    key={i}

Or filter out duplicates from the options before rendering.
value name? One might normally expect a variable named value to contain something from the user that might change, like something in an input box, or a count of something. Here, the value being passed to Button is actually a name or label connected to the button (and the use of value alongside a stateful count variable might seem odd). Consider renaming it to name or buttonLabel or something of the sort. (Probably not option, since it's not related to <option>)
useCallback is useful when optimizing performance and reducing unnecessary re-renders when passing the callback as a prop to a child component. But here, there's just a <button> (not a child component) which'll only change on click (won't update frequently enough for the overhead of a function call to matter at all). The useCallback is introducing complication without accomplishing anything useful here; I'd consider removing it.


MySQL Prepared Statement - Combinging 3 seperate statements in to 1 statement

Thanks for the comments. I understand what your webpage does now.

Suggestion #1 - Descriptions Of What Your Code Does - You might want to create some functions (or add some comments) just to make it more clear what each segment of code does. The OOP people like to make tons of functions that describe chunks of code, and the non-OOP people like comments. You can go either way, in my opinion. In my example here, I will use functions.

Suggestion #2 - More Whitespace - I would also add some spaces after your commas and maybe some enters after your commas in your bind_param() functions so that everything wraps nicely and is easy to read. You can do the same thing with your prepare() functions. It isn't a big deal for single line SQL statements like "SELECT * FROM table WHERE field = 'value'", but it starts becoming very helpful when you're doing long, complex INNER JOINS and other complicated SQL statements.

<?php

// control panel for multiple websies

$website = define it up here;
$item = define it up here;

function add_page($website_id, $item, $mysql)
{
    $next_page_count = increment_and_return_next_page_count($website_id, $mysql);

    create_new_page($item, $next_page_count, $mysql);
}

function increment_and_return_next_page_count($website_id, $mysql)
{
    $mysql['stmt'] = $mysql['conn']->prepare("
        SELECT website_pagecount
        FROM websites
        WHERE website_domain = ?
    ");
    $mysql['stmt']->bind_param(
        "s",
        $website_id
    );
    $result = $mysql['stmt']->execute();
    $result = $mysql['stmt']->get_result();
    $pagecount = $result->fetch_assoc();
    $mysql['stmt']->close();

    $pagecount++;

    $mysql['stmt'] = $mysql['conn']->prepare("
        UPDATE websites
        SET website_pagecount=?
        WHERE website_domain=?
    ");
    $mysql['stmt']->bind_param(
        "is",
        $pagecount,
        $website_id
    );
    $result = $mysql['stmt']->execute();
    $mysql['stmt']->close();

    return($pagecount);
}

function create_new_page($item, $next_page_count, $mysql)
{
    $mysql['stmt'] = $mysql['conn']->prepare("
        INSERT INTO pages (page_id,page_parent, page_title, page_description,page_keywords, website_id, page_layout)
        VALUES (?,?,?,?,?,?,?)
    ");
    $mysql['stmt']->bind_param(
        "issssss",
        $next_page_count,
        $item['parentpage'],
        $item['pagetitle'],
        $item['pagedescription'],
        $item['pagekeywords'],
        $website['website_id'],
        $item['pagelayout']
    );
    $result = $mysql['stmt']->execute();
    $mysql['stmt']->close();
}

add_page($website['website_id'], $item, $mysql);

?>

Other than those tips, I will defer to more experienced PHP coders. I hope my ideas help you out a little bit though. Good luck!

P.S. As for your original idea of combining the statements: I don't think they can be combined because they are doing different things. One is SELECT, another is UPDATE, and the third is INSERT. If they were all doing the same thing, then you could combine them using various types of JOINS probably. But since they are performing different actions I don't think that is an option.


Generally the code is well written, there are only a few items that need commenting on.
Avoid Using Namespace std
If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier cout you may override within your own classes. This stack overflow question discusses this in more detail.
Use Braces Around Single Statements in Program Flow
Primarily for maintenance reasons it is a good habit to create code blocks within if statements, else clauses and within loops. Many bugs have been created during maintenance when one or more statements was added to an if statement or a loop.
From this code:
    for (const auto& a: averages) cout << a << " ";

Would be better as
    for (const auto& a: averages) {
        std::cout << a << " ";
    }

Then if someone needs to add a statement to the for loop at some point it is quite simple.
This Code Could Be Simplified
    vector<double> res (nums.size() - k + 1);
        ...

    size_t res_index = 0;
    res.at(res_index) = curr_sum / k;

    while (right_it != nums.end()) {
        ...
        res.at(++res_index) = curr_sum / k;
        ...
    }

It's not clear why it was necessary to initialize the res vector to the proper size in the previous code. Since vectors are variable sized they don't need to be initialized with a size.
    std::vector<double> res;
        ...

    res.push_back(curr_sum / k);

    while (right_it != nums.end()) {
        ...
        res.push_back(curr_sum / k);
        ...
    }

removes one variable and achieves the same result.


Displaying a person's personal information with formatting

In designing classes we should try and confirm to the Single Responsibility Principle. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your Person class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your Person class: what if you wanted to create a Person from a database, or a file or a web request? You would be better splitting this into a PersonQuestionnaire class which is responsible for creating a Person from a console input.

You should never have any significant logic in your constructor like you have here. Design your constructors to simply save any parameters and set up any default values. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed.

You should consider using the int.TryParse() method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level Exception type other than where you can do something meaningful: doing a lot of this will make your applications very difficult to debug.


Error-checking macro to jump to specified label given a failing statement

NULL dereference

If allocate_empty_db() returns NULL, it will jump to the error handling code, which will cause a NULL dereference when it tries to free(db->metadatas).  You will need to guard that line like this:

if (db)
    free(db->metadatas);

The macro

I'm not exactly a fan of the macro.  First, calling it try makes me think your code is java, and then when I realize it isn't, I'm more confused.  Second, if your label is always going to be the same in every function, then you can omit the second argument of the macro and just hardcode it to goto error.  That way the macro can look smaller and the reader doesn't have to parse the extra comma and argument (which look like part of the body you are try-ing).

Also, the macro should be a do while instead of an if.  You could get in trouble with code like this:

if (condition)
    try(foo(), error);
else
    bar();

Here, your macro will cause the above to expand to:

if (condition)
    if (!foo()) { goto error; };
else
    bar();

Which is actually a syntax error because of the extra semicolon but is also close to making the else pair with the wrong if.  The macro should look like this instead:

#define try( stmt , error_label )              \
        do {                                   \
            if (!(stmt)) { goto error_label; } \
        } while(0)

This do while(0) construction is a common trick when writing C macros.  It allows a multi-statement macro to be used in an if statement like the one in my example.  See this Stackoverflow question for more info.


Is this an ok implementation of an UnorderedPair?

One thing: I would make the struct immutable since mutable structs have really bad unintended effects. Otherwise, this is a good, solid implementation.
public struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
    private readonly T a;

    private readonly T b;

    public UnorderedPair(T a, T b)
    {
        this.a = a;
        this.b = b;
    }

    public T A
    {
        get
        {
            return this.a;
        }
    }

    public T B
    {
        get
        {
            return this.b;
        }
    }

    public override int GetHashCode()
    {
        return this.a.GetHashCode() ^ this.b.GetHashCode();
    }

    public bool Equals(UnorderedPair<T> other)
    {
        return (other.A.Equals(this.a) && other.B.Equals(this.b)) ||
               (other.A.Equals(this.b) && other.B.Equals(this.a));
    }

    public override bool Equals(object obj)
    {
        return this.Equals((UnorderedPair<T>)obj);
    }

    public static bool operator ==(UnorderedPair<T> a, UnorderedPair<T> b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(UnorderedPair<T> a, UnorderedPair<T> b)
    {
        return !(a == b);
    }
}

and because time marches on, here's a more compact and performant C# 7.2 version:
public readonly struct UnorderedPair<T> : IEquatable<UnorderedPair<T>>
{
    public UnorderedPair(in T a, in T b) => (this.A, this.B) = (a, b);

    public T A { get; }

    public T B { get; }

    public override int GetHashCode() => this.A.GetHashCode() ^ this.B.GetHashCode();

    public bool Equals(UnorderedPair<T> other) => (other.A.Equals(this.A) && other.B.Equals(this.B))
        || (other.A.Equals(this.B) && other.B.Equals(this.A));

    public override bool Equals(object obj) => this.Equals((UnorderedPair<T>)obj);

    public static bool operator ==(in UnorderedPair<T> a, in UnorderedPair<T> b) => a.Equals(b);

    public static bool operator !=(in UnorderedPair<T> a, in UnorderedPair<T> b) => !(a == b);
}


Codility binary gap solution using regex

The Regex is computationally heavy.  I would consider simply iterating through the bits, keeping track of both the highest binary gap and the current binary gap. You could add optimizations such as that proposed by @konijn to bail out of iteration when you reach a point that you can no longer logically find a larger binary gap than your current max value.

That could be as simple as:

The following is updated per comments:

function binaryGap(number) {
    var binary = (number >>> 0).toString(2);
    var maxGap = 0;
    var currentGap = 0;
    var inGap = false;
    var length = binary.length;
    /*
    Fast return if binary string length is less than 3
    and no gap is possible
    */
    if(length < 3) {
        return 0;
    }
    /*
    Start iterating bits.  We start with second character.
    */
    for(var i = 1; i < length; i++) {
        /*
        See if we should continue evaluation based on whether
        we can actually exceed current maxGap number
        */
        if (maxGap >= currentGap + length - i) {
            break;
        }
        if (inGap === false) {
           // we need to check to see if a new gap is started
           if (binary[i-1] === '1' && binary[i] === '0') {
               // we are in a new gap
               currentGap = 1;
               inGap = true;
           }
        } else {
           // we need to see if gap has ended
           if (binary[i] === '1') {
               // gap has ended
               if (currentGap > maxGap) {
                   maxGap = currentGap;
               }
               inGap = false;
           } else {
               // gap has continued
               currentGap++;
           }
        }
    }
    return maxGap;
}

Here is a simple performance test I set up comparing the approaches.  Typically, I am seeing the bit iteration method working in about 20-25% of the time that the regex works.


Optimising multiple streams to single loop

Specifying a downstream Collector for Collectors.groupingBy

There is an alternative Collectors.groupingBy(Function, Collector) method that lets you specify further steps that you want to do with the intermediary List<SimpleRatifiableAction> values after the grouping.

Then, with a bit of renaming, some help from method references, plus some convenience methods like having a SimpleRatifiableAction.getKey():

public String getKey() {
    return getOrderNumber() + getActionType();
}

You can have a method that reads:

// dropping method visibility modifier for brevity
List<GroupedOrderActionUpdateEntity> process(List<SimpleRatifiableAction> actions) {
    return new ArrayList<>(actions.stream()
            .collect(Collectors.groupingBy(SimpleRatifiableAction::getKey,
                    Collectors.collectingAndThen(Collectors.toList(),
                                                  this::createUpdateEntity)))
            .values());
}

Looping once, aggregating multiple values

Inside convertToUpdateGroup(List), now renamed as createUpdateEntity(List), you are streaming twice on the List argument. While this shouldn't be an issue for most cases, there is still an option to just loop once should it be one of the remaining places to optimize (hopefully with some runtime analysis/micro-benchmarking to prove it).

This is achieved by creating the StringJoiner instance yourself (instead of relying on Collectors.joining()). To avoid similar List.get(0) calls, you can also get a reference to it once.

Putting it altogether:

// dropping method visibility modifier for brevity
GroupedOrderActionUpdateEntity createUpdateEntity(List<SimpleRatifiableAction> actions) {
    SimpleRatifiableAction first = actions.get(0);
    StringJoiner joiner = new StringJoiner(", ", "Group Order Note: ", ".");
    List<OrderActionUpdateEntity> updateEntities = new ArrayList<>();
    actions.forEach(v -> {
        joiner.add(v.getNote());
        updateEntities.add(v.createUpdateEntity());
    });
    return new GroupedOrderActionUpdateEntity(
            first.getOrderNumber(),
            OrderActionType.valueOf(first.getActionType()),
            first.getSource(),
            12345,
            joiner.toString(),
            updateEntities);
}

SimpleRatifiableAction.createUpdateEntity() is also another convenience method that you can consider:

public OrderActionUpdateEntity createUpdateEntity() {
    return new OrderActionUpdateEntity(getId(), OrderActionState.valueOf(getState()));
}