I'm interested to hear other approaches and any suggestions to mine. Here are two that I came up with:

Without a Helper Class

thanktag_queries = [
    ("div", {"class":"section ack"}, 0),
    ("li", {"class":"fn-con"}, 0),
    ("li", {"class":"fn"}, 1)
]

thanktag = None
for i in xrange(len(thanktag_queries)):
    thanktag_query = thanktag_queries[i]
    soup_result = soup.find_all(thanktag_query[0], thanktag_query[1])
    if len(soup_result) > thanktag_query[2]:
        thanktag = soup_result[0]

        if i == len(thanktag_queries)-1:
            if not contains_carriage_return(thanktag.text):
                thanktag = soup_result[-2]

        break
if thanktag != None and not contains_carriage_return(thanktag.text):
    do_something()

def contains_carriage_return(text):
    return "↵" in clean_string(text)

With a Helper Class

class ThanktagQuery:
    soup_result = None

    def __init__(self, tag, soup_options, threshold):
        self.tag = tag
        self.soup_options = soup_options
        self.threshold = threshold

    def execute_query():
        self.soup_result = soup.find_all(self.tag, self.soup_options)

    def contains_thanktag():
        try:
            return len(self.soup_result) > self.threshold
        except TypeError as exc:
            raise RuntimeError("Query has not been run yet for this instance.")

thanktag_queries = [
    ThanktagQuery("div", {"class":"section ack"}, 0),
    ThanktagQuery("li", {"class":"fn-con"}, 0),
    ThanktagQuery("li", {"class":"fn"}, 1))
]

thanktag = None
for i in xrange(len(thanktag_queries)):
    thanktag_query = thanktag_queries[i]
    thanktag_query.execute_query()
    if thanktag_query.contains_thanktag():
        thanktag = thanktag_query.soup_result[0]

        if i == len(thanktag_queries)-1:
            if not contains_carriage_return(thanktag.text):
                thanktag = thanktag_query.soup_result[-2]

        break
if thanktag != None and not contains_carriage_return(thanktag.text):
    do_something()

Both pieces of code, which attempt to be logically synonymous, address OP's initial concern with keeping the "soup finds" DRY. That is, the parameters of each soup find should only be hardcoded once instead of twice as in the original code.

The pieces of code accomplish keeping DRY by specifying the find parameters in a list called thanktag_queries. The list is composed of elements that each correspond to hardcoded information of the first four if-statements in the OP's code. This hardcoded information contains three elements (hence the 3-tuples in the case of the Without Helper Class): the target tag, the soup options (in this case the target class), and the threshold that the length of the executed soup query needs to exceed to deem that the thanktag exists in those DOM elements.

So far I've talked about the structure of the outside of the for-loop. What about within the for-loop? The structure within the for-loop differs in two ways from a direct translation of the structure from the OP's if statements. First, find_all(...)[0] is used in place of find(...) because the find_all(...) needs to be executed anyway. Second, the special case from the original fourth if-statement is handled in reverse (i.e. it uses find_all(...)[0] as default instead of find_all(...)[-2]). This choice was made because using find_all(...)[0] matches the pattern of the other if statements. This makes the code more brief, and in this case makes it more understandable.

At the end of the code, I use thanktag == None instead of thanktag in globals() in case of an unintended use of the thanktag variable in that namespace.

I wrote the "With a Helper Class" so that the code is written in a style that is more human readable and self-documenting.


Implementing a Steepest Descent Algorithm

You biggest time waster appears to be this loop:

    while f(x_k + alpha * p_k) > f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]:
        alpha = ratio * alpha

f(x_k), c, gradTrans, and p_k are all constant in the loop, so you can compute f(x_k) and c * (gradTrans @ p_k) before the loop and use these computed values in the test expression, instead of recomputing the same values over and over.

    fxk = f(x_k)
    offset = c * (gradTrans @ p_k)
    while f(x_k + alpha * p_k) > fxk + (alpha * offset)[0, 0]:
        alpha = ratio * alpha

Doing so cuts the time roughly in half.

Similarly, gradient(x_k) is computed 3 times here:

while abs((gradient(x_k)[0, 0])) > 0.1 or abs((gradient(x_k))[0, 1]) > 0.1:
    ...
    p_k = - gradient(x_k)

Again, compute once and store the result.

You should probably use vectors instead of matrices:

    x_k = np.array([10., 5.])

Which can be unpacked using tuple assignment:

def f(x_k):
    x, y = x_k
    return 100 * (y - x**2)**2 + (1 - x)**2

And using 10. and 5. in the above x_k initialization makes the arrays float64 instead of int32, which allows you to use in-place addition operators:

        x_k += alpha * p_k

instead of:

        x_k = x_k + alpha * p_k


Filter for logging http request parameters

The redirect doesn't seem to be part of the logging. Maybe put it in a separate filter that runs before this one?

The logged string could be built using String.format() or MessageFormat which would be more readable. Most logging frameworks have such formatting built into their logging methods anyway.

Do you really need to convert the post parameters into JSON? Isn't the standard toString representation of the Map good enough for logging? Apart from that most JSON libraries have a built-in mechanism to convert a Map into a JSON object so you don't need to do it yourself.


File manager project (creates and prints file)

Nice first question. It can definitely be expanded on for additional learning in the future.

Improve Error Handling

Both the functions createFile() and getFile() could be changed to return int. This would allow the program to exit with the correct status.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int createFile();                 // return EXIT_SUCCESS or EXIT_FAILURE
int getFile();                    // return EXIT_SUCCESS or EXIT_FAILURE

int main()
{
    int status = EXIT_SUCCESS;    // EXIT_SUCCESS and EXIT_FAILURE are defined in stdlib.h

    status = createFile();
    if (status != EXIT_SUCCESS)
    {
        return status;
    }

    status = getFile();

    return status;
}

In getFile() the variable filePointer is tested after fopen(). This is a good practice. In createFile() the variable filePointer is not tested, this is a bad practice. The C library function fopen() for write can fail for a number of reasons:

File exists and is protected.
File exists and it is a directory.
The program doesn't have sufficient privilege to write to the target directory.

There are more ways it can fail, this is a partial list. See full list of possible error codes. The C library function perror() can be used to report program error in the case of
I/O failures or the include file errno.h can be included and the global variable errno will contain
the error code for better error messages as shown in this stackoverflow question.

These same error messages can be used to improve the error reporting in getFile() as well.

The existing error message in getFile() might be improved by adding the file name to the error message.

fprintf(stderr, "File %s not found.\n", fileName);

Error messages should generally be reported using fprintf(stderr, FMT); rather than reporting the error
to stdout using printf().

Inconsistent File Name Size

In getFile() fileName can be up to 99 characters (strings must be null terminated),
in createFile() it can be 39 characters, this is inconsistent and may confuse the user.
The code also doesn't tell the user how long the file name can be and that could be a
problem for the user. In neither case is the length of the string checked prior to use,
and that could lead to a number of errors including buffer overflow.

A better way to handle the file name size might be to define a symbolic constant using #define.

#define MAX_FILE_SPEC_LENGHT 1024

    char userfilename[MAX_FILE_SPEC_LENGHT];

    char fileName[MAX_FILE_SPEC_LENGHT];

The file name variable should be large enough to handle a full path as well as the file name.

Many systems define the maximum file name size based on the file system implementation. On Linux the
include file linux/limits.h defines that maximum file name size using PATH_MAX. Most operating systems
will have some way of defining it.

Possible Bug

This line was flagged by my C compiler with a warning:

    fgets (&filecontent, 1000, stdin);

The warning is Incompatible pointer types passing char (*)[1000] to parameter of type char *.
Since file content is an array of chars it only needs the name filecontent rather than the address
of filecontent, to use the address, it should be &filecontent[0].

Inconsistent Variable Naming Conventions

In the function createFile() there are 3 variables, userfilename, filecontent and filePointer,
the variable filePointer is camelCase and is clear, userfilename and filecontent are not camelCase
and not quite as clear.


VBA userform loop to gather numbers from cells on an Excel sheet

What is your sub name? Find? That's a built in application function. And it doesn't explain at all what you're doing.
Also your indenting and spacing is way off base. Even if allowing for extra space, your function should look like this -
Option Explicit
Private Sub PopulateLabels()
    Application.ScreenUpdating = False
    Dim i As Integer, k As Integer

    k = 1
    i = 1

    For i = i To 42
        C1 = "C1_" & i
        Me.Controls(C1) = Sheet14.Range("I" & k).Value
        If Me.Controls(C1) = "0" Then
            Me.Controls(C1).ForeColor = &H8000000F
        End If
        k = k + 1
    Next

    k = 1
    i = 1

    For i = i To 42
        C2 = "C2_" & i
        Me.Controls(C2) = Sheet14.Range("J" & k).Value
        If Me.Controls(C2) = "0" Then
            Me.Controls(C2).ForeColor = &H8000000F
        End If
        k = k + 1
    Next

    k = 1
    i = 1

    For i = i To 42
        C3 = "C3_" & i
        Me.Controls(C3) = Sheet14.Range("K" & k).Value
        If Me.Controls(C3) = "0" Then
            Me.Controls(C3).ForeColor = &H8000000F
        End If
        k = k + 1
    Next

    k = 1
    i = 1

    For i = i To 42
        C4 = "CL4_" & i
        Me.Controls(C4) = Sheet14.Range("L" & k).Value
        If Me.Controls(C4) = "0" Then
            Me.Controls(C4).ForeColor = &H8000000F
        End If
        k = k + 1
    Next

    k = 1
    i = 1

    For i = i To 42
        C5 = "C5_" & i
        Me.Controls(C5) = Sheet14.Range("M" & k).Value
        If Me.Controls(C5) = "0" Then
            Me.Controls(C5).ForeColor = &H8000000F
        End If
        k = k + 1
    Next

    k = 1
    i = 1

    For i = i To 42
        C6 = "C6_" & i
        Me.Controls(C6) = Sheet14.Range("N" & k).Value
        If Me.Controls(C6) = "0" Then
            Me.Controls(C6).ForeColor = &H8000000F
        End If
        k = k + 1
    Next

    Application.ScreenUpdating = True
End Sub

I renamed it and added indents. Now lets move on to the code.

Variables
&H8000000F is a constant for vbButtonFace. I would at least give it a constant instead of repeating it over and over
 Const FACE_COLOR as Long = vbButtonFace

Your i and k variables are telling me nothing about what they are. Give me some context. Also, you haven't declared variables
C1
C2
C3
C4
C5
C6

What are those? Also, why are they being set to different strings?
C1 = "C1_" & i
C2 = "C2_" & i
C3 = "C3_" & i
C4 = "CL4_" & i 'Where did that L come from
C5 = "C5_" & i 'Where did that L go
C6 = "C6_" & i

I can't imagine what they are, or why they need to be set 42 times. Also it looks like you iterate the k the same number of times as the i, so why do you need the k?

Refactoring
You continually set i and k to 1, then iterate i from 1 to 42, increasing k by one each time. i and k are the same and they are always the same set of numbers.
Not only that, but you're doing the same exact thing 6 times -
For i = 1 To 42
    'something is something and i
    'something is Sheet14, letter and i
    'Check if it's 0 and change color
Next i

As far as I can tell, you change the Control string and the column letter. I'm sure we can create a procedure that takes arguments for this -
Sub DoTheThing(ByVal controlNameBase As String, ByVal columnNumber As Long)
    Dim i As Long
    Dim controlName As String
    For i = 1 To 42
        controlName = controlNameBase & i
        Me.Controls(controlName) = sheet14.Cells(i, columnNumber)
        If Me.Controls(controlName) = 0 Then Me.Controls.ForeColor = vbButtonFace
    Next
End Sub

Now we have -
Option Explicit
Private Sub PopulateLabels()
    Application.ScreenUpdating = False

    Const CONTROL_STRING1 As String = "C1_"
    Const CONTROL_STRING2 As String = "C2_"
    Const CONTROL_STRING3 As String = "C3_"
    Const CONTROL_STRING4 As String = "CL4_"
    Const CONTROL_STRING5 As String = "C5_"
    Const CONTROL_STRING6 As String = "C6_"
    Const CONTROL_COLUMN1 As Long = 9
    Const CONTROL_COLUMN2 As Long = 10
    Const CONTROL_COLUMN3 As Long = 11
    Const CONTROL_COLUMN4 As Long = 12
    Const CONTROL_COLUMN5 As Long = 13
    Const CONTROL_COLUMN6 As Long = 14

    DoTheThing CONTROL_STRING1, CONTROL_COLUMN1
    DoTheThing CONTROL_STRING2, CONTROL_COLUMN2
    DoTheThing CONTROL_STRING3, CONTROL_COLUMN3
    DoTheThing CONTROL_STRING4, CONTROL_COLUMN4
    DoTheThing CONTROL_STRING5, CONTROL_COLUMN5
    DoTheThing CONTROL_STRING6, CONTROL_COLUMN6

    Application.ScreenUpdating = True
End Sub

Sub DoTheThing(ByVal controlNameBase As String, ByVal columnNumber As Long)
    Dim i As Long
    Dim controlName As String
    For i = 1 To 42
        controlName = controlNameBase & i
        Me.Controls(controlName) = sheet14.Cells(i, columnNumber)
        If Me.Controls(controlName) = 0 Then Me.Controls.ForeColor = vbButtonFace
    Next
End Sub

I bet we could refactor it some more..
Option Explicit
Private Sub PopulateLabels()
    Application.ScreenUpdating = False
    Const BASE_STRING As String = "C"
    Const ALTERNATE_STRING As String = "CL"
    Const END_STRING As String = "_"
    Dim i As Long
    Dim controlString As String
    For i = 1 To 6
        If i = 4 Then
            controlString = ALTERNATE_STRING & i & END_STRING
        Else
            controlString = BASE_STRING & i & END_STRING
        End If
        DoTheThing controlString, i + 8
    Next
    Application.ScreenUpdating = True
End Sub

Now the whole thing is 27 lines. At first it was 95.

Performance
You said your loops are taking a long time. That's because you're accessing the sheet every time you loop. Bring those values into an array instead.
Sub DoTheThing(ByVal controlNameBase As String, ByVal columnNumber As Long)
    Dim i As Long
    Dim controlName As String
    Dim lookUpValues As Variant
    lookUpValues = GetArray(columnNumber)
    For i = 1 To 42
        controlName = controlNameBase & i
        Me.Controls(controlName) = lookUpValues(i,1)
        If Me.Controls(controlName) = 0 Then Me.Controls(controlName).ForeColor = vbButtonFace
    Next
End Sub

Private Function GetArray(ByVal columnNumber As Long) As Variant
    GetArray = Sheet14.Range(Sheet14.Cells(1, columnNumber), Sheet14.Cells(42, columnNumber))
End Function

Conclusion
So now instead of looping through the sheet constantly, you just get all the values you need into an array and loop through that. It's much faster than going to the sheet. We also eliminated 5 of the 6 loops by creating a procedure. It also appears much cleaner and less unwieldy.


noexcept on the explicitly defaulted default-ctor and copy-ctor is already implied.
Copy-ctor and dtor would be implicitly declared if left out.
.allocate() (and also .deallocate(), but that doesn't matter) fails to check n * sizeof(T) for wrap-around.
Possible Solutions:

Start with a check. This has the advantage of simplicity and broadest conformity.

if (n > std::size_t(-1) / sizeof(T))
    throw std::bad_array_new_length();

Use saturating math, and rely on ::operator new being unable to allocate std::size_t(-1) bytes on (nearly?) all implementations. This is generally more efficient for the common case.

auto bytes = n > std::size_t(-1) / sizeof(T) ? std::size_t(-1) : n * sizeof(T);

Because the casts are so simple and obviously right, I would eschew the verbosity of static_cast. Guidelines may prohibit it though...
I suggest importing the following additional refinements from C++20:

Mark the templated ctor constexpr.
Mark .allocate()'s return-value [[nodiscard]].
Mark both operator== and operator!= constexpr.


Well, this code has a few problems:

Typing non-numbers twice in a row causes a ValueError.
It is not quite PEP-8 compliant (the official python style guide)
No docstrings
Final bit of code should be wrapped in a if __name__ == "__main__": block to add reusability.
It is not very reusable

Now let's fix all that:

Wrap your input section in it's own functions like this:

def get_num(prompt, errorMsg = "I'm sorry, that's not a valid number"):
    """Returns a number from the user"""
    while True:
        try:
            input = int(raw_input(prompt))
        except ValueError:
            print errorMsg
        else:
            return input

def get_yes_no(prompt, errorMsg = "I'm sorry, I didn't catch that. Could you try again?"):
    """Returns True for yes, False for no"""
    while True:
        input = raw_input(prompt)
        if input.startswith('y' or 'Y'):
            return True
        elif input.startswith('n' or 'N'):
            return False
        print errorMsg

This allows you to have more robust and more readable code

Naming: function names should be lowercase and separated by _. So wedcost(hours) becomes wed_cost(hours).

Also your function doesn't do what is advertised, since it keeps on recalculating.

Let's wrap that into a main function like this:

def main():
    wed_cost(get_num("How long will we be on location? "))
    while get_yes_no("Would you like to recalculate? ('Yes' or 'No') "):
        wed_cost(get_num("How long will we be on location? "))
    print "Have a nice day :)"

Then we can add this little bit of code to the bottom:

if __name__ == "__main__":
    main()

Which will run your code if it is directly called, but also allows you to reuse this code elsewhere with an import without causing any code to be run.

Finally let's put all your magic numbers (such as 75, 100 etc) somewhere more recyclable by defining some constants at the top of the code:

MIN_FEE = 250
HOURLY_FEE = 75
OVERTIME_HOURS = 6
OVERTIME_FEE = 100

Then the wed_cost function becomes:

def wed_cost(hours):
    """Prints a message with the cost of a wedding shoot given a number of hours"""
    totalCost = 0
    if hours >= OVERTIME_HOURS:
        totalCost = hours * OVERTIME_FEE
    totalCost = max(hours * HOURLY_FEE, MIN_FEE)
    print "The total cost of our services will be ${}.".format(totalCost)

This makes your code more understandable, and more debuggable :)


Working around 'ugly' method names

Ok, so you realized you are constrained by the getter names due to some 'configuration-by-convention' features of your application/framework. If you think this can be fixed permanently in the future, and require a short-term workaround, you can consider having wrapper methods to... remind you to have the permanent fix sooner than later?

public String getHorarioTIni() {
    return getEveningStartTime();
}

// use this instead
public String getEveningStartTime() {
    // here's hoping you get to rename the field names too
    return horarioTIni;
}

Also, you mentioned the getters only, so I guess there's no excuse for nNoE(). :) Reading it as isNotNullAndEmpty() is easier on the brains.

Avoiding code repetition

If you take a closer look at what you're doing now, it really boils down to these steps:

Define a 'duration description' (DD) as a start time, an optional separator, and an end time. The separator is required when both times are present.
Construct a DD for the AM session.
If there are DDs for both AM and PM sessions, insert the newline.
Construct a DD for the PM session.
Concatenate the DDs for both sessions with the optional newline in between.

Therefore, you can extract step 1 as a method:

// this can be made a class field
private static final String SEPARATOR = " - ";

private static String createDescription(String startTime, String endTime) {
    StringBuilder builder = new StringBuilder(Objects.toString(startTime, ""));
    if (isNotNullAndEmpty(startTime) && isNotNullAndEmpty(endTime)) {
        builder.append(SEPARATOR);
    }
    return builder.append(Objects.toString(endTime, "")).toString();
}

Objects.toString(Object, String) is used here to make the String generation slightly more expressive.

The method body is now more compact, and hopefully more readable as a result:

public String getTimetable() {
    final String NEW_LINE = "<br>";
    String morningDuration = createDescription(getMorningStartTime(), getMorningEndTime());
    String eveningDuration = createDescription(getEveningStartTime(), getEveningEndTime());
    StringBuilder builder = new StringBuilder(morningDuration);
    if (!morningDuration.isEmpty() && !eveningDuration.isEmpty()) {
        builder.append(NEW_LINE);
    }
    return builder.append(eveningDuration).toString();
}


Your priority is to reduce dependency on expensive strings  :

Change all associative syntax, animation['x'] >>> dot notation, animation.x .
Change 'undefined' >>> undefined.
Avoid passing/returning strings to/from functions. They are passed by value (a function uses its own copy).
Pass back a number from calcPropValue() and do the toFixed() back in the caller statement.

Also :

The tween setting is the same for every call in the same turn of the for loop, therefore calculate it once and pass to calcPropValue().
Simplify testing of tween and display values.

Inside the for loop, assign :

display = (animation.display && animation.display[1]) || null;
tween = (animation.tween && animation.tween[1]) || null;

Don't forget to add tween to the var declaration.

Modify calcPropValue() as follows :

calcPropValue = function (value, tween) {
    return tweenEase(relativeScrollTop, value[0], (value[1] - value[0]), keyframesConverted[currentKeyframe].duration, tween);
}

Ternery's will become, eg :

translateX = animation.translateX ? calcPropValue(animation.translateX, tween).toFixed(2) : '0.00';

Then consider sacrificing readability for performance by not assigning what the terneries return. Instead write them directly into the expressions where the resultant strings get used, eg :

'transform': 'translate3d(' +
    (animation.translateX ? calcPropValue(animation.translateX, tween).toFixed(2) : '0.00') + 'px, ' +
    (animation.translateY ? calcPropValue(animation.translateY, tween).toFixed(2) : '0.00') + 'px, 0.01px)' +
    (animation.scale ? ' scale(' + calcPropValue(animation.scale, tween).toFixed(2) + ')' : '') +
    (animation.rotate ? ' rotateX(' + calcPropValue(animation.rotate, tween).toFixed(1) + "deg)" : ''),

When you're done, pass the code through jslint or jshint to help spot any bloomers.


Rewafadhabihlgdity

(If you can't tell, that is supposed to say 'readability'). Leaves some things to be desired.

Variable names: All your variable names are three characters or less. This makes it very hard to read your code. Renaming r to playerCount is a start, and S can be called strengths. so1 and so2 should also be renamed, along with t, p and q. Make variables self-documenting by giving them a reasonable name.
Spacing: Dontyoufinditabithardtoreadtext/codethatdoesntcontainanyspacesandappropriatepunctuation? (I'm exagerating just to prove a point). Even though it is a bit easier to read lack of code spacing than lack of word-spacing in written text, I find a line like this hard to read:

S[k]=((a*S[k-1]*S[k-1])+(b*S[k-1])+c)%1000000;

For this particular line, consider rewriting it to this:

int previous = strengths[index - 1];
strengths[index] = (a * previous * previous + b * previous + c) % 1000000;

By using better variable names, adding space, extracting a variable, and removing unnecessary parenthesis that line becomes a lot more readable.

The lack of good variable names and spacing especially made this part of the code really hard for me to understand what you are doing and why:

for(int p=r-1,q=r-2;p>=0;p=p-2,q=q-2){
     if(q>=-1){
         so1=so1+S[p];
         if(q>=0){
             so2=so2+S[q];
         }
     }
}

Speed

Unable to reproduce / Unclear what the issues are. It seems to me that your code is quite fast. Even the input 10000000 5 6 7 8 calculated with reasonable speed IMO.

Extensibility

For testing purposes, to ensure both correct results and fast enough results, it would be useful to extract a method to do the actual calculations, and then your outermost loop could be:

        for (int i = 0; i < count; i++) {
            String s[] = sc.readLine().trim().split(" ");
            int playerCount = Integer.parseInt(s[0]);
            a = Integer.parseInt(s[1]);
            b = Integer.parseInt(s[2]);
            c = Integer.parseInt(s[3]);
            d = Integer.parseInt(s[4]);
            System.out.println(determineTeamDifferences(playerCount, a, b, c, d));
        }


def change_letter(original, new_message, key_number, alpha):

docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.It’s specified in source code that is used, like a comment, to document a specific segment of code.

You should include a docstring indicating what the parameters are and what the function does:

def change_letter(original, new_message, key_number, alpha):
    """
    Encode message.
    original: a string (word)
    new_message: empty string
    key_number: int
    alpha: a string containing lowercase alphabet
    """

unecessary function parameter: new_message

There is no need to bother user with entering an empty string.

string immutability::

new_message += alpha[(alpha.lower().index(letter) + key_number) % 26].lower()

A string is immutable in Python therefore each time you're adding to a string, you're creating another string instance and this is pretty inefficient, use list comprehension syntax instead.

list comprehension syntax:

You can use list comprehensions to replace this whole function in the following way:

def encode(message: str, shift: int):
   """Encode and return message."""
return ''.join([chr(ord(char) + shift) for char in message.lower()])

the use of ord and chr is very useful in this case since both do not care about whether a character is uppercase, lowercase or digit, they convert everything and they are much more efficient than alpha.lower().index(letter) + key_number) % 26 which call .lower() and .index() for each letter in the word.

def encipher(the_key, message, inp=True):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

same comments regarding docstrings.
you can use string.ascii_uppercase instead of manually writing the letters with possibility of a slip of hand and the creation of a bug in the case of a missed letter.
if inp: I did not find a single case where inp might be set to False so there is no need for this parameter.

This whole encipher() can be shortened to the following:

def encipher(message, encryption_key=input('Enter key: ')):
    """Encipher according to a user given key, return an error if key is not digit."""
    while not encryption_key.isdigit():
        encryption_key = input('Invalid input, enter a number: ')
    return encode(message, int(encryption_key))

f-strings: since you're using Python 3, in Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

print('\n{}  ::  {}'.format(type_word, encipher(key, type_word)))

expression can be written using f-strings in the following way:

print(f"\n{type_word} : {encipher(key, type_word)}")

same goes for question = input('\nWhat is {} of key {}  ・  '.format(word, key)).lower()

can be written:

question = input(f'What is the translation of {word} using {key} as key? ').lower()

Here's a refactored version of the code:

import random

def encode(message: str, shift: int):
    """Encode and return message."""
    return ''.join([chr(ord(char) + shift) for char in message.lower()])

def encipher():
    """Encode message interactively."""
    message = input('Enter word/message: ')
    encryption_key = input('Enter key: ')
    while not encryption_key.isdigit():
        key = input('Invalid input, enter a number: ')
    encoded_message = encode(message, int(encryption_key))
    print(f'{message} has been encoded to {encoded_message}')
    re_encode = input(f'Would you like to convert {encoded_message} again? y/n: ').lower()
    while re_encode.lower() not in 'yesno':
        print(f'Invalid input {re_encode}')
        re_encode = input(f'Would you like to convert another word? y/n: ').lower()
    if re_encode in 'no':
        print('Thank you for using Cesar cipher.')
        exit(0)
    if re_encode in 'yes':
        encipher()

def play():
    """Play a cipher game."""
    key = random.randint(1, 25)
    words = ('WWE', 'Javascript', 'Pythonista', 'Computer Science', 'Eighty-three', 'Event Log', '5K Freestyle')
    word = random.choice(words)
    answer = input(f'What is the translation of {word} using {key} as key? ')
    encoded_word = encode(word, key)
    if answer == encoded_word:
        print(f'Correct guess {encoded_word}')
    if answer != encoded_word:
        print(f'Oops! wrong guess {answer} the correct answer is {encoded_word}')
    replay = input('Would you like to play again? y/n: ')
    while replay not in 'yesno':
        print(f'Invalid input {replay}')
        replay = input('Would you like to play again? y/n: ')
    if replay in 'no':
        print('Thank you for using Cesar cipher.')
        exit(0)
    if replay in 'yes':
        play()

if __name__ == '__main__':
    while True:
        game_or_encode = input('Enter e to encode or p to play e/p: ').lower()
        while game_or_encode not in 'ep':
            print(f'Invalid entry {game_or_encode}')
            game_or_encode = input('Enter e to encode or p to play e/p: ').lower()
        if game_or_encode == 'e':
            encipher()
        if game_or_encode == 'p':
            play()


Best practice to upload files on server using Rest Service

The lines of code inside your UploadFile method look optimal to me.

Perhaps the problem is that your Stream contents are being fully buffered before they're being delivered.

I've no experience with this myself, but
How to: Enable Streaming suggests you may need to change your configured TransferMode, and change your API so that it has a method whose only parameter is Stream (perhaps pass the filename in one method and the Stream in the next method).


Looking at your code I don't see any glaring performance issues. What you really need to do is measure the performance of any code that accesses an outside resource, such as a file or web service. That said, I would benchmark the execution time for the following items:

All calls to logger since I assume these hit the file system or database. Also be wary of logging to a shared drive, as this is really a network service call disguised as a direct call to the hard disk.
The call to the WebClient.UploadString method. If that service gets bogged down, your middleware will run slow as well.
The last item that might be slow is deserializing the input from JSON.

The more likely culprits are calls utilizing external resources, such as web services or the file system.


Checking a DB table before doing an insert using AWS Lambda

Your code is already pretty good by common standards, IMO.

If it is possible, you can try to adopt ES7's async/await. The code will become more linear, while still asynchronous.

Watch out for browser compatibility though.

export async function main(event) {

  const data = await dynamo
    .get({ TableName: 'client', Key: { id: event.name } })
    .promise();

  if (data.Item) {
    throw new Error(`Client name '${event.name}' is already in use.`);
  }

  const timestamp = new Date().getTime();

  return await dynamo
    .put({
      TableName: 'client',
      Item: {
        id: event.name,
        created: timestamp,
        updated: timestamp,
        deleted: null
      },
      ConditionExpression: 'attribute_not_exists(id)'
    })
    .promise();

}


My 'almostIncreasingSequence(sequence)' code is too slow for lists that have 10000+ elements. [CodeSignal]

Checking if a list is strictly increasing
The inner loop checks if a list (in this case newList) is strictly increasing:
j = 0
in_order = True
while j < len(newlist) - 1:
    if newlist[j+1] <= newlist[j]:
        in_order = False
        break
    j += 1
if in_order == True:
    return True

In general variable names should use underscores, so newlist becomes new_list. PEP 8.
It can be simplified with a for-else:

for j in range(len(new_list) - 1):
    if new_list[j+1] <= new_list[j]:
        break
else:
    return True

Or using all:
if all(new_list[i] > new_list[i - 1] for i in range(1, len(new_list))):
    return True

Optimization
As you said, the solution is too slow for large input due to the inner loop that runs every time, making the overall complexity \$O(n^2)\$.
The current solution follows this approach:

For each element of the input list
Build a new list without such element and check if strictly increasing

Consider simplifying the approach like the following:

Find the first pair that is not strictly increasing
Build a new list without the first element of the pair and check if it is increasing
Build a new list without the second element of the pair and check if it is increasing

For example:
def almostIncreasingSequence(sequence):
    def is_increasing(l):
        return all(l[i] > l[i - 1] for i in range(1, len(l)))

    if is_increasing(sequence):
        return True

    # Find non-increasing pair
    left, right = 0, 0
    for i in range(len(sequence) - 1):
        if sequence[i] >= sequence[i + 1]:
            left, right = i, i + 1
            break

    # Remove left element and check if it is strictly increasing
    if is_increasing(sequence[:left] + sequence[right:]):
        return True

    # Remove right element and check if it is strictly increasing
    if is_increasing(sequence[:right] + sequence[right + 1:]):
        return True

    return False

I believe there should be an approach that doesn't build the two additional lists to reduce the space complexity, but I'll leave that to you.


What would be alternative ways to model IConvention?

First of all, the combination of a Specification and another method is not that unusual - it's called the Tester-Doer Pattern (although to be fair, I'm not sure whether it's a bona-fide pattern, as I've never seen it described outside of .NET). Even so, despite the precedence, I completely understand why you dislike the Temporal Coupling it implies. So which alternatives are available?

The first refactoring we could apply is to change the definition of IConvention to emply a Maybe monad. Assuming that we've defined a Maybe<T> class, IConvention now looks like this:

public interface IConvention
{
    Maybe<IConventionInstance> CreateInstance(Item item);
}

This would allow you to in a type-safe way to check whether or not an IConventionInstance instance could be created from the item.

However, once you realize that a Maybe monad really is nothing more than a special case of IEnumerable, you could consider refactoring IConvention once more:

public interface IConvention
{
    IEnumerable<IConventionInstance> CreateInstances(Item item);
}

In the normal implementation, an implementation would return zero or one item.

This would make the ConventionInstanceSelector and IConventionInstanceSelector types redundant (always a good thing), and you could implement the ModelReader class like this (caveat: I haven't tried to compile it):

public class ModelReader {
    IEnumerable<IConvention> _conventions;

    public ModelReader(IEnumerable<IConvention> _conventions) {
        _conventions = conventions;
    }

    public Model Read(IEnumerable<Item> items) {
        var model = new Model();

        var conventionInstances = from item in items
                                  from c in _conventions
                                  from ci in c.CreateInstances(item)
                                  select ci;
        foreach(var ci in conventionInstances) {
            ci.ApplyTo(model);
        }

        return model;
    }
}


Measuring the time for the bubble sort algorithm

Some tips:

std::vector<int> FiletoVector()
{
    std::ifstream SortFile("Number_Sort.input");

    std::vector<int> vector;
    int read;

    while(SortFile >> read)
    {
        vector.push_back(read);
    }

    return vector;
}

Perfectly good readable code. But you can simplify it a bit using iterators.

The standard contains an input iterator that reads values from a stream.

`std::istream_iterator<T>`  // can be used to iterate through a stream.

Since most C++ loops are based on iterators lets update your code to use an iterator based approach.

std::vector<int> FiletoVector()
{
    std::ifstream SortFile("Number_Sort.input");

    std::vector<int> vector;

    std::istream_iterator<int>  fileIter(SortFile)
    for(; fileIter != std::istream_iterator<int>(); ++fileIter)
    {
        vector.push_back(*fileIter);
    }

    return vector;
}

But if you look at the constructor of vector you will see that you can constructor the vector using two iterators. So we can simplify the above code too:

std::vector<int> FiletoVector()
{
    std::ifstream SortFile("Number_Sort.input");

    std::vector<int> vector(std::istream_iterator<int>(SortFile),
                            std::istream_iterator<int>());

    return vector;
}

We can take this one step further as we don't need to have a local member. Just return the value:

std::vector<int> FiletoVector()
{
    std::ifstream SortFile("Number_Sort.input");

    return std::vector<int>(std::istream_iterator<int>(SortFile),
                            std::istream_iterator<int>());
}

Lets look at the timming function next:

void PrintTime(std::string sorttype, std::vector<int> funcinput(std::vector<int>), std::vector<int> vecinput)
{
    // Note `sortType` is passed by value (so you get a copy)
    //      funcinput  has to be a function that takes a vector of int
    //                 that seems overly limiting.
    //      vecinput   Again you pass by value (so you get a copy)
    //                 This is probably on purpose so this is fine.
    //                 But be careful.
    //

    //Start Time
    float time = clock();

    funcinput(vecinput);

    //End Time
    time = (clock() - time) / CLOCKS_PER_SEC;

    std::cout << sorttype << " took " << time << " seconds!" << std::endl;
}

That all seems perfectly reasonable. But you are limiting yourself to sorting functions. I don't see the need for that. You should be able to time any function.

So just let your users pass in any function. Then you can specialize the function using a lambda later.

template<typename Action>
void PrintTime(std::string const& message, Action action)
{
    //Start Time
    float time = clock();

    action();

    //End Time
    time = (clock() - time) / CLOCKS_PER_SEC;

    std::cout << message << " took " << time << " seconds!\n";
}

Now you can call the function like this:

 PrintTime("Bubble Sort", [num](){BubbleSort(nums);});

So lets look at your sorting.

The first thing I notice is that you return a vector. This implies you are copying the vector at some point. Usually you sort in place for optimum performance.

You also pass by value. Which gets you that copy.

std::vector<int> BubbleSort(std::vector<int> vecinput)

Personally I would pass by reference to avoid a copy and then sort in place which means returning nothing.

void BubbleSort(std::vector<int>& vecinput)
^^^^                            ^

Secondly by specifying std::vector<int> you are limiting yourself to only sorting vectors of int. That are lots of things than can be sorted. So you should generalize this to sort any type.

template<typename T>
void BubbleSort(std::vector<T>& vecinput)

You can take this a step further by abstract the container type by allowing the user to pass in iterators.

template<typename I>
void BubbleSort(I begin, I end)

This is how the standard works. You have a bunch of containers and a bunch of algorithms. That glue that holds it all together are iterators. So you can perform nearly any algorithm on any container by passing iterators into the algorithm.

This allows you to sort vectors:

std::vector<int>   x = Load();
BubbleSort(std::begin(x), std::end(x));

But now you can also sort C-Arrays.

int  y[] = { 6,7,10,7,2,3,10};
BubbleSort(std::begin(y), std::end(y));

Three notes on your implementation of bubble sort

The best case version of bubble sort is O(n). You only need to do a single pass over the container if it is already sorted. So you should track if there was a swap on a given pass and exit early if no changes were made.
Secondly both loops go from [0..size). The inner loop does not need to cover the whole container. Each pass you have moved at least one item all the way to the correct location. So the next pass you don't need to check that item.
You do some manual swapping. There is a built in std::swap() in the standard that allows you to swap to object optimally.

This gives you something like this:

   bool noswap = false;
   for(int i = 0; noswap && i < vecinput.size(); i++)
   {
        noswap = true;
        for(int n = 0; n < vecinput.size() - i - 1; n++)
        {
            if(vecinput[n] > vecinput[n + 1])
            {
                std::swap(vecinput[n], vecinput[n + 1])
                noswap = false;
            }
        }
   }


A simple 3D Wrapper class around std::vector

Quick comments:

unsigned long => size_t everywhere ... it's the same, but that's the alias for this job
check for _xDim, _yDim, _xDim < 0 ... underflow is also undefined behvaiour ;-)
implement operator[] for those who are confident about their bounds, or for faster release builds. It's not trivial for multiple dims, check here.
free data is flawed. You need to look into unique_pointer or shared pointer which will do this stuff for you.
Resize? It is actually required? Can you not auto-resize during at()? unless you want that as a code check during development.
Consider a library


Concatenating two substrings to provide the largest possible palindromic string

Minor tweak

    boolean isPalindrome(String s) {
  int n = s.length();
  for (int i=0;i<(n / 2);++i) {
     if (s.charAt(i) != s.charAt(n - i - 1)) {
         return false;
     }
  }

Your indentation is all over the map.  Copy/paste error?

More importantly, you can save some math by writing this

    public static boolean isPalindrome(String s) {
        for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }

        return true;
    }

Perhaps a good compiler would optimize them out, but your original was doing four math operations per iteration where this only does two (and an extra at declaration).  Not counting the comparisons for either.

Small tweak

I'd rewrite main as

        try (Scanner in = new Scanner(System.in))
        {
            for (int n = in.nextInt(); n > 0; n--)
            {
                String string1 = in.next();
                String string2 = in.next();

                String palindrome = findLongestPalindrome(string1, string2);
                if (palindrome.isEmpty())
                {
                    System.out.println(-1);
                }
                else
                {
                    System.out.println(palindrome);
                }
            }
        }

Putting the algorithm in a separate method makes it easier to test and cleans up main by a lot.

We don't need a separate loop variable for the test cases here.  If we decrement instead of increment, we can simplify that logic.

Putting the Scanner in a try-with-resources eliminates a compiler warning about never closing the Scanner.

Major tweaks

      for( c = 0 ; c <length1 ; c++ )
      {
         for( i = length1-c ; i >0 ; i-- )
         {
            sub1 = string1.substring(c, c+i);
            for( d = 0 ; d < length2 ; d++ )
      {
         for( j = length2-d ; j >0 ; j-- )
         {
            sub2 = string2.substring(d, d+j);
            String temp=sub1+sub2;
              Solution obj= new Solution();
             if(temp.length()>=max_length && obj.isPalindrome(temp)==true)

                 {
                 if (max_length==temp.length())
                  {   if(temp.compareTo(result)<0)
                     {
                     result=temp;
                  }}
                 else {
                     max_length=temp.length();
                 result=temp;
                  }
             }
         }
      }
         }
      }

I changed to

    public static String findLongestPalindrome(String a, String b) {
        String result = "";
        for (int aStart = 0 ; aStart < a.length() ; aStart++ )
        {
            char firstLetter = a.charAt(aStart);
            for (int bEnd = b.lastIndexOf(firstLetter); bEnd >= 0 ; bEnd = b.lastIndexOf(firstLetter, bEnd - 1) )
            {
                for (int aEnd = a.length() ; aEnd > aStart ; aEnd-- )
                {
                    String aSubstr = a.substring(aStart, aEnd);
                    int requiredLength = Math.max(result.length() - aSubstr.length(), 0);
                    for (int bStart = 0 ; bStart <= bEnd - requiredLength; bStart++ )
                    {
                        String candidate = aSubstr + b.substring(bStart, bEnd + 1);

                        if (candidate.length() >= result.length() && isPalindrome(candidate))
                        {
                            if (candidate.length() == result.length() && candidate.compareTo(result) >= 0)
                            {
                                continue;
                            }

                            result = candidate;
                        }
                    }
                }
            }
        }

        return result;
    }

Changed arbitrary parameter names to match the problem statement.

Changed loop index variables to match their meaning relative to the parameters.

Using lastIndexOf to find the endpoint of the second string means that we can skip a lot of substrings that will never work.  The original code had to take the substrings, join them, and then check if the result is a palindrome on all substrings.  This reduces down to only possible substrings.

Determining the requiredLength allows us to skip joining and checking substrings that are too short to work.

I declared variables just in time to be initialized.  This makes it easier to see what's happening.

An alternative algorithm

The obvious brute force solution is to check every possible start and end points for both strings.  You optimized this by starting with the longest possible substrings, and I added tweaks to optimize that more.  But I actually think that was the wrong way to go.  Note that you still have to iterate over every letter to check if it is a palindrome.  You can save checking some of the substrings if you integrate the palindrome check with taking the substrings.  Instead of four nested loops with a linear time check in the middle, we can use just three nested loops.  Iterate up to the correct solution rather than check down to it.


defmodule Test do
  def contains?(term, elem) do
    elem in term
  end

  def test do
    elems = [1,2,3]
    terms = [[1,2], [2,3]]

    for e <- elems, reduce: %{} do
      acc ->
        key = Enum.find(terms, &contains?(&1, e))
        Map.update(acc, key, [e], &[e|&1])
    end
    #=> %{[1, 2] => [2, 1], [2, 3] => [3]}
  end
end

Found a simple and elegant solution using a reduce comprehension.
Here, we iterate over each elem in elems, find the first term which contains it, then update our map with either term => [elem] or term => [elem|previous_elems] depending on if that key exists in the map yet.

Side note:
If I needed the elems in the same as order they were originally I could use & &1 ++ [e] instead of &[e|&1], but as I don't have that requirement it is more efficient to prepend the list.


Most efficient way to check if user is allowed to update an object

Soo ... I'm not quite sure how to formulate this without it sounding brash, but... Both of these methods are less than ideal...

Let's follow the behavioural flow to see what issues this code has:

The webservice portion you provide only understands PUT requests.
Conventionally, PUT requests are used to create objects, not to update them.
Instead one would expect a POST endpoint for that.
You first create an OK response and then overwrite it in case something fails.
That's somewhat... annoying in comparison to the simpler direct return.

try {
    db.updateLocation(token, ml);
    return Response.status(Status.OK).entity("location updated").build();
} catch (Exception e) {
    return Response.status(Status.BAD_REQUEST).entity(ex.getMessage()).build();
}

All this code assumes that the user gets to see the Exception message.
This is a bad assumption. Your webservice method should be responsible for creating useful messages, not your business logic.
Considering that the webservice code does not compile (because the declaration for isUpdated is missing) I hope that you don't actually pretend that every Exception ever is the user's fault by throwing a HTTP 400 to them...

The root cause of your conundrum is that you're not using the power of widely used java sql abstractions. Instead of manually writing SQL statements and performing updates, you should really make use of JPA and Entities.

If you had these, all of this would boil down to the following simplified code:

private void updateLocation(String username, MapLocation update) {
    MapLocation stored = em.find(MapLocation.class, update.getLocationId());
    if (stored == null) {
        throw new LocationDoesNotExistException();
    }
    if (!stored.getUsername().equals(username)) {
        throw new IllegalLocationUpdateException();
    }
    em.persist(update);
}

Note that the codesample above makes some simplifying assumptions about transaction management and the class hierarchy of the Exceptions it throws.

Note that I'm suggesting to rewrite your webservice method to something like:

public Response update(String loginToken, MapLocation request) {
    final String username = getUsernameFromToken(loginToken);
    try {
        db.updateLocation(username, request);
        return Response.ok().build();
    } catch (LocationDoesNotExistException e) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } catch (IllegalLocationUpdateException e) {
        return Response.status(Response.Status.FORBIDDEN).build();
    } catch (Exception e) {
        LOGGER.warn("Unexpected exception in updateLocation", e);
        return Response.serverError().build();
    }
}


Here are a couple of Questions:

Have you tried reverse order in your joins?  I.e. start with PS=>PSH=>Item.
Have you tried inner joins versus left join?  Could see speed improvement (less data for sure)
Is there any way to recurse only on item?  In other words, can you get PS1.PST_IMA_RecordID from your Item row?  If so, then you would only recurse on one table.


Do not map to array

I appreciate that streaming strings is a little messy. However, there is no need to create an array; instead we can just transform the stream. I would remove the arrays and change getFrequencyMap to take a String.

Use Map::getOrDefault to simplify countError

In particular, if you do aMap.getOrDefault(ch, 0) then the Math.abs case always works.

Unlike @DapperDan's solution, this still requires looping through all 26 characters; however, the logic is a lot simpler. At least on my system, my approach is faster, even in you example when each map has only 3 elements. The cost of iterating through 26 characters is very low compared to map operations.

Use of longs

I notice you use Longs throughout (presumably due to Collectors.counting() returning a Long) but then cast to int at the end. Why not just return a long?

Stream rangeClosed vs for loop

Mostly a matter of style, but it is easy to replace the for loop with a stream.

Code

Applying these changes should yield something like

static long makeAnagram(String a, String b) {
    return countError(getFrequencyMap(a), getFrequencyMap(b));
}

private static long countError(Map<Character, Long> aMap, Map<Character, Long> bMap) {
    return IntStream.rangeClosed('a', 'z')
        .mapToObj(x -> Character.valueOf((char)x))
        .mapToLong(c -> Math.abs(aMap.getOrDefault(c, 0l) - bMap.getOrDefault(c, 0l)))
        .sum();
}

private static Map<Character, Long> getFrequencyMap(String s) {
    return s.chars()
        .mapToObj(x -> Character.valueOf((char)x))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}


Count number of ways to paint a fence with N posts using K colors

1. Code review

The question says, "Write an algorithm that counts the number of ways" but the program does not only do this: it also builds a list of the combinations. This means that the program is limited to values of \$N\$ and \$K\$ that are small enough that the list of combinations fits in the storage space of the computer. Whereas a program that did not have to produce this list could work for much larger values of \$N\$ and \$K\$, as we'll see in §3 below.
It's good practice to write a docstring for each function, describing what the function does, the arguments that it takes, and what it returns.
If a function returns a list, it does not also need to return the length of the list. If the caller needs that information, it can call len just as easily. So the function could just return combos_list.
In the line:

combos_list = new_combo_list[:]

it's unnecessary (and wasteful) to take a copy of new_combo_list. The new list can just be assigned to the old name, like this:

combos_list = new_combo_list

When a loop index (here i) is not used, it's conventional to name it _.
The code that's guarded by the line:

if not combos_list:

only runs once (on the first iteration of the loop), so it would be simpler to move it out of the loop, have one fewer iteration of the loop, and so avoid the if ... else .... Like this:

combos_list = []
for c in colours:
    combos_list.append([c])
for _ in range(1, n):
    new_combo_list = []
    # etc.

Instead of:

combos_list = []
for c in colours:
    combos_list.append([c])

use a list comprehension and write:

combos_list = [[c] for c in colours]

These lines:

combo_to_add = combo[:]
combo_to_add.append(c)
new_combo_list.append(combo_to_add)

could be simplified to:

new_combo_list.append(combo + [c])

This condition:

if not combo[len(combo) - 2:] == [c, c]:

could be simplified to:

if combo[-2:] != [c, c]:

(since Python allows you index a list backwards from the end using negative numbers).

2. Revised code

def find_combinations(n, colours):
    """Return a list of combinations of n items from the sequence colours,
    with the constraint that no colour appears three times in a row.

    >>> [''.join(combo) for combo in find_combinations(3, 'ab')]
    ['aab', 'aba', 'abb', 'baa', 'bab', 'bba']

    """
    combos = [[c] for c in colours]

    for _ in range(1, n):
        new_combos = []
        for combo in combos:
            for c in colours:
                # Check that last two colours aren't both c.
                if combo[-2:] != [c, c]:
                    new_combos.append(combo + [c])
        combos = new_combos

    return combos

Note the example code in the docstring. This can be run as a test case using the doctest module.

3. Let me count the ways

The question asked for "an algorithm that counts the number of ways", so here's how I'd go about that.

I'll start with some notation. Assume that \$k\$ is fixed. Then:

\$T(n)\$ is the total number of ways to paint \$n\$ fenceposts with \$k\$ colours, subject to the constraint that no three adjacent posts are the same colour.
\$D(n)\$ is the number of ways to paint \$n\$ fenceposts with \$k\$ colours such that the last two fenceposts are different colours (or \$n < 2\$).
\$S(n)\$ is the number of ways to paint \$n\$ fenceposts with \$k\$ colours such that the last two fenceposts are the same colour.

And then the following recurrence relations are clear:

\$D(n) = (k−1)(D(n−1) + S(n−1))\$ for \$n ≥ 2\$
\$S(n) = D(n−1)\$ for \$n ≥ 2\$
\$T(n) = D(n) + S(n)\$

We can use (2) to eliminate \$S\$ (being careful about the bound on \$n\$ as we do so), getting the recurrences:

\$D(n) = (k−1)(D(n−1) + D(n−2))\$ for \$n ≥ 3\$
\$T(n) = D(n) + D(n−1)\$ for \$n ≥ 2\$

And then substitute (5) into (4), getting:

\$D(n) = (k−1)(T(n−1))\$ for \$n ≥ 3\$

and so:

\$T(n) = (k−1)(T(n−1) + T(n−2))\$ for \$n ≥ 3\$

Since the recurrence depends only on the last two values of the sequence, it's easy to program:

def triple_free_combinations(n, k):
    """Return the number of ways to choose n items (with k choices for
    each item), subject to the constraint that no colour appears three
    times in a row.

    """
    if n == 0:
        return 1
    a, b = k, k * k
    for _ in range(n - 1):
        a, b = b, (k - 1) * (a + b)
    return a

(You should recognize this as a very simple example of the tabular method, aka "dynamic programming".)

The effort that went into find_combinations is not wasted, because now we can use that function as source of test cases:

>>> from itertools import product
>>> all(triple_free_combinations(n, k)
...     == len(find_combinations(n, list(range(k))))
...     for n, k in product(range(1, 8), repeat=2))
True

Another useful source of test cases is the On-Line Encyclopedia of Integer Sequences. For example, when \$k=2\$ we have sequence A128588:

>>> [triple_free_combinations(i, 2) for i in range(16)]
[1, 2, 4, 6, 10, 16, 26, 42, 68, 110, 178, 288, 466, 754, 1220, 1974]

and similarly when \$k=3,4,5,\ldots\$ we have A121907, A123620, A123871, ....

Finally, note that triple_free_combinations is capable of computing values that are far beyond the reach of the original function:

>>> triple_free_combinations(40, 40)
472189463994618801762969606024644975976973566598588071193029590400


Creating a list from combinations of the original data

The main way to do this faster is to use fewer loops and to do more in each loop. (AFAICT)

loops in there...

A (for event)
A.1 (make team pairs)
A.2 (make dgen)
A.3 (for team, result in event)
A.3.1.1 (for key in pairs)
A.3.1.2 (sum)
A.4 (for pair diff)

You have a lot more flexibility if you use the for loop instead of mostly comprehensions and permutations. And, permutations is wasteful, here, (as discussed, below) because it prevents a few optimisations.

A key change is we can do A vs B and B vs A in the same pass of the loop. So, we can change our loop from "for each team go through all teams" to "for each team go through all following teams". It's a big improvement.

For the line-up A, B, C, D, our iterations look like:

AB & BA
AC & CA
AD & DA

.

BC & CB
BD & DB

.

CD & DC
(done)

So, the algorithm might end up something like (in pseudo code):

past_score_differences = defaultDict(float)

for each event:

    team_outcomes = defaultDict(float)

    teams_len = len(teams in event)
    for i in range(teams_len - 1):
        home_team = teams[i]
        home_score = scores[i]

        for j in range(i+1, teams_len):
            away_team = teams[j]
            away_score = scores[j]

            team_outcomes[home_team] += past_score_differences[(home_team, away_team)]
            team_outcomes[away_team] += past_score_differences[(away_team, home_team)]

            past_score_differences[(home_team, away_team)] += home_score - away_score
            past_score_differences[(away_team, home_team)] += away_score - home_score

        list_zz.append(team_outcomes[home_team])

    # the last team doesn't go through the outer loop
    list_zz.append(team_outcomes[teams[-1]])

Still a lot of loops, but far fewer and with fewer iterations for the innermost loop.

If there is a lot of consistency in the team IDs, then you might consider not using a tuple as the key but instead using a dict within a dict, e.g.

example_past_differences = {
    'A': {
        'B': 10,
        'C': 11,
        'Etc...': 99
    }
}

# later, when accessing

home_team = ...
home_score = ...
home_past_differences = past_score_differences[home_team]
for ...
    away_past_differences = past_score_differences[away_team]
    ...
    team_outcomes[home_team] += home_past_differences[away_team]
    team_outcomes[away_team] += away_past_differences[home_team]

One last thing, your variable names are not easy to understand. I made mine way too long for accesibility to understand, but generally I think the guidance in these slides is very useful: https://talks.golang.org/2014/names.slide#1


First red flag; you're using Count(predicate) > 0. The Count() overload that takes a predicate must iterate over all elements of the parent enumerable to determine the correct count, and you're telling it to do so for each element of the child list. You simply want to know if at least one of those elements matches; for that, the Any() overload which accepts the same parameter will be faster, because it will quit as soon as it finds the first element that matches (unfortunately the worst-case of a match not existing will still require a full scan of the enumerable).

You're also parallelizing parallelization. While parallel is good, threads waiting on threads waiting on threads can easily result in an algorithm that is bound by the ThreadPool's ability to spin up new threads (the default is a 250ms wait for each new thread after a predetermined number of "readily-available" threads have been scheduled). So, after creating, let's say 10 threads for this algorithm, most of which will be waiting on sub-threads, the ThreadPool will only create four new threads per second. Let's say the TPL begind the PLinq library thinks that one thread per 100 elements of both collections is necessary. On a collection of 4500 elements, for each of which a comparison of 4500 more elements is necessary, the ThreadPool could schedule two thousand worker threads to execute. After 10 of them are created near-instantaneously, only four more per second will be created as long as at least 10 are running, meaning this algorithm will take up to 500 seconds just to schedule all the necessary threads. The more "instantaneous" threads you tell the ThreadPool to spin up before queueing them, the more cache-thrashing you'll do forcing the CPU to juggle all these threads.

First step to improving this: Instead of grouping, select a list of distinct child IDs from the parent list. This process will produce strings instead of groups of larger ParentItems, which should hopefully reduce the amount of "heap-thrashing" required to generate the groups only to reduce it down to a much smaller collection. You only ever need the child IDs from the parent list anyway.

// Group by childID and create List with all relevant IDs
var childrenOfParents = parentList.AsParallel()
   .Select(p => p.childId)
   .Distinct()
   .OrderBy(x=>x)
   .ToList();

Then, filter the child list based on the ID being in the derived list of child IDs:

// Filter childList on groupedParentList
var result = childList.AsParallel()
   .Where(child => childrenOfParents
      .Any(cid=>cid.Equals(child.ID, StringComparison.InvariantCultureIgnoreCase)))
   .ToList();

I do not know about the culture-specific comparison behavior, but if it's at all possible to compare the strings verbatim (even ToLower()ed), it would likely be preferable performance-wise.

Other things that may help include building custom extension methods that make certain assumptions:

Naive grouping or deduping (Distinct()) of an enumerable is an N2-complexity operation (compare each element to a list of already-processed elements and remove if it exists). This is the least efficient part of the first query. Deduping of a list sorted by the same projection that must be de-duped is linear (compare each element to the previous one and remove if equal). You will be able to dedupe the list of child IDs more efficiently than PLinq's default implementation if you know the list is sorted by the same projection (in this case the identity projection) that you must dedupe.

public IEnumerable<TObj> SortAndDedupe<TObj, TProj>(this IEnumerable<TObj> input, Func<TObj, TProj> projection)
{
    sortedInput = input.OrderBy(projection);

    TProj last;
    var init = false; //default(T) might be valid
    foreach(var element in sortedInput)
    {
       if(!init || !projection(element).Equals(last))
       {
          init = true;
          last = projection(element);
          yield return element;
       }
    }
}

...

// Your first query is now an NlogN operation
var childrenOfParents = parentList.AsParallel()
   .Select(p => p.childId)
   .SortAndDedupe(s=>s)
   .ToList();

Naive searching for elements that match a predicate is linear, which makes the second query N2-complexity. In your case, with a sorted list of childID strings being searched for a value that is equal to a passed projection, you can use a logarithmic binary search:

public bool IsInSortedList(this T toFind, List<T> collection)
    where T: IComparable<T>
{
    var max = collection.Count - 1;
    var min = 0;
    var idx = (max-min)/2;

    while(max >= min)
    {
       if(collection[idx].CompareTo(toFind) == 0) return true;
       else if(collection[idx].CompareTo(toFind) < 0) //search right
          min = idx+1;
       else if(collection[idx].CompareTo(toFind) > 0) //search left
          max = idx-1;

       idx = (max-min)/2 + min;
    }

    return false;
}

...

//This query is now an NlogN as well
var result = childList.AsParallel()
  .Where(child => child.IsInSortedList(childrenOfParents)
  .ToList();


Overlaping sections using Bootstrap and CSS

Shortly after the post I found out that also adding a background color to individual block elements and applying padding to both top & bottom will actually stretch out the background-color and allow of the use of margins to cover other elements like so

.grayBG {
    background-color: #f5f6f7;
    padding-top: 100px;
    padding-bottom: 100px;
}

and

.whiteBG {
background-color: #FFF;
padding-top: 150px;

}

then with the use of a -margin I was able to pull sections to overlap each other like so.

.second-section {
background-color: #FFF;
margin-top: -300px;
padding-bottom: 0;

}

There is probably a better and more efficient way of doing this but, this seemed to work for me just fine.


Binary Search Tree without pass by reference

General Observations
The code compiles and runs in Visual Studio 2019 on Windows 10.
The vertical spacing is inconsistent and could be improved.
The code could be reusable if the Binary Search Tree was made into a class.
The unit testing in main could be more effective if know values were used first and then a second test with random number generated. The test of removeVal() currently only tests a value that is never in the BST, the function does work because I changed the value in the test.
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 identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.
Function and Variable Naming
Generally the function names are fairly good, there is one exception, it isn't clear to me from the name what getReqNodes() is supposed to do.  In main it might be better to have a variable called bst or root rather than p.
Random Number Generation
It would be better to use C++ random number generators rather than the old C library function rand() function, see EDIT 2 in the first answer to this stack overflow question. Currently the random number generator is not random because it is never seeded with a value by calling srand().
One Statement Per Line
The code contains multiple lines where there is more than one statement such as:
    printTree(p); cout << endl; cout << endl;

This makes the code harder to read, understand and maintain, always remember that you may not be the only person that needs to edit the code.
There are 2 other issues with that line, that std::endl flushes the output which affects the performance of the program so using:
    std::cout << "\n";

might be a better option. The second is that if a string such as "\n" is used then the string "\n\n" can be used to output 2 new lines, decreasing the number of statements necessary, although this is also possible:
    std::cout << std::endl << std::endl;


when we need to add some javascript code to html, where we have to put it?

Optimally, it's loaded just before the body tag closes

    <!-- all html above here -->
    <script src="..."></script>
</body>

for the following common reasons:

The DOM elements that you are operating are safely parsed by then.
Script tags block execution. If they delay in loading and/or parsing, the things that follow it will have to wait. Thus, to prevent delay and from seeing a blank screen while scripts load, we load the page first, scripts last.

I have a similar answer, along with other answers, at StackOverflow which should explain more.


Wrapping types with alignment requirements

The class is missing a copy constructor and a move constructor. These can never be created by instantiating a template. Right now, the compiler will generate a defaulted copy constructor for you (and no move constructor, because you have a user-defined destructor). Since you obviously don't want that, you have to define the copy (and probably move as well) constructor yourself.
You're also missing a move assignment operator which you should probably add. Otherwise, your class wouldn't be fully usable with move-only types.
Your code is missing comments (there aren't any). You even had to explain an invariant in the question:

  ... once the aligned_wrapper is constructed, m_object will never change for that instance as the address of this will not change, this guarantees alignment. In other words, not assigning m_object in the assignment operator is intentional.

This type of information must go into comments. The next maintainer (which can be you in 6 moths' time) will need knowledge like this to understand the code.
You should add noexcept specifications to your functions. They affect efficiency of some operations (like storing in a std::vector), and since this is a very generic class, you should not limit its use in any way. An example for the assignment operator would be:

aligned_wrapper& operator = (const aligned_wrapper& that) noexcept(std::is_nothrow_copy_assignable<T>::value) {
    get() = that.get();
    return *this;
}

It would probably be a good idea to introduce a way to query Align out of an aligned_wrapper object, e.g.

static const std::size_t alignment = Align;

You don't need reinterpret_cast to convert an object pointer to void*, a static_cast is sufficient for that. Don't use stronger casts than necessary.
You can simplify the assignment to m_object and make it more obvious by assigning the result of the placement-new into it:

m_object = new (ptr) T(std::forward<Args>(args)...);

16 looks like a rather arbitrary number for the default template argument for Align (it's actually a magic number). There is even no guarantee that 16 is a valid alignment value. I would probably choose something less arbitrary such as sizeof(void*).
There is no reason to use std::aligned_storage for the type of m_storage. You don't actually care about alignment of m_storage at all (which is emphasised by you passing 1 to its Align parameter). All you need is a buffer of suitable size, and for this usigned char[sizeof(T) + Align -1] (or a std::array) would work just as well.

As a side note, be aware that std::aligned_storage_t was only introduced in C++14. Visual Studio 2013 supports some C++14 bits, but using it makes your code non-C++11-compliant.
You might want to swap the order of the data members, it might prevent need for padding between an oddly-sized m_storage and aligned m_object.
You might consider overloading the pointer operators * and -> for your class as syntactic sugar for get(), it simplifies usage. Other generic classes which store a single object sometimes do so as well; an example is boost::optional.


Start by setting your res list with \$ 0 \$ values. Thus:

res = [0] * len(temperatures)

You won't need the elif condition now. Nor would you need the ending res.append. All res.append inside the loop will be replaced by res[i] = counter values.

Use a more descriptive variable naming than skipped vowels (counter instead of cnt, result instead of res etc.)

You compute len(temperatures) a total of \$ n^2 \$ number of times. Keep the value inside another variable instead.

As for the complexity, your current algorithm is \$ O(n^2) \$, which might be reduced by using a more efficient algorithm. Take a look at this SO answer making use of a LIFO queue (stack) and getting the results in \$ O(n) \$.


Finding the longest sequence of increasing numbers in an array

No need for temporary lists
In your last review, it was mentioned that you could just use two integers to keep track of the sequences instead of two whole lists.  So instead of currentNumbersSequence and longestIncreasingSequence, you could track just the start and length of those two sequences.  The code then becomes:
public static List<Integer> findLongestIncreasingSequence(int[] numbersToBeProcessed) {

    if (numbersToBeProcessed.length == 0) {
        return null;
    }

    int bestStart  = 0;
    int curStart   = 0;
    int bestLength = 1;
    int curLength  = 1;

    for (int i = 1; i < numbersToBeProcessed.length; i++) {
        if (numbersToBeProcessed[i] > numbersToBeProcessed[i-1]) {
            curLength++;
            if (curLength > bestLength) {
                bestStart  = curStart;
                bestLength = curLength;
            }
        } else {
            curStart  = i;
            curLength = 1;
        }
    }
    ArrayList<Integer> ret = new ArrayList<>(bestLength);
    for (int i = 0; i < bestLength; i++) {
        ret.add(numbersToBeProcessed[bestStart+i]);
    }
    return ret;
}


Is there a more efficient way of implementing this clock in Raphael JS?

I think not, this is how it is meant to be.

That being said, you

Have a few missing semicolons
Capture c1 & c2 for no good reason
Calculate secAngle for no good reason
Have a veritable legion of hard coded mystical constants
Have a few weirdly named variables

After some thought, it appears that the biggest problem with this code is that you count on the animation to take 0 (milli)seconds and the execution/scheduling of the animations is instantaneous. Have you tried keeping this clock up for an hour or more? I would expect there to be discrepancies between the real time and the animated clock.


isRTL.coffee library to determine if a text is of right-to-left direction

Yep, it's possible to improve. You can simply do:

window.isRTL = (value) ->
    reRTL.test value

Another way to improve is the way you declare your special characters. Right now, it's confusing between the = and +=. Here is another way:

rtlChars = [
    '\u0600-\u06FF' # Arabic - Range
    '\u0750-\u077F' # Arabic Supplement - Range
    '\uFB50-\uFDFF' # Arabic Presentation Forms-A - Range
    '\uFE70-\uFEFF' # Arabic Presentation Forms-B - Range
].join("")

reRTL = new RegExp "^[#{rtlChars}]"

This way, adding a new character is simply adding a line in an array.


Uni-directional singly linked list in JavaScript

Just to be sure, this will always be slower than a plain Array() in JavaScript, no matter the optimizations we might find.

After perusing your code I came to:

I like your old school prototyping approach with prototype
You should have a function to retrieve the last element
I would call the root tail or root, as the last element tends to be the head
I would not declare null values in your constructors, it makes no difference:

function Node(val){
  this.data = val;
};

function SinglyList(){
  this._length = 0;
};

You almost never use (read) ._length, I would not keep track of it and just have a function that calculates the length, your code would be so much neater
I would let removeByVal() find the index that needs to be removed and then call removeAt()
I like reverse(), I had to scratch my head at first, it's quite clever for me
JS people would expect unshift instead of prepend
JS people would expect push instead of add
I like that you provided a chainable version of push


Efficiency and potential problems
You could use a Map but as you are counting word occurrences using an object is a little more efficient.
Efficiency
Your code can be improved as it is highly inefficient with each word needing to create a new object and fill its properties from the previous one, then add or update then next word. You need only create one object and add properties to it as you find them.
function mapMagazine (text) {
    return text.split(' ')
        .reduce((map, word) => (
            map[word] = map[word] ? map[word] + 1 : 1, map
        ), {});
}

or using forEach,
function mapMagazine (text) {
    const map = {};
    text.split(' ').forEach(w => map[w] = map[w] ? map[w] + 1 : 1);
    return map;
}

or the (slightly) more performant version using a for loop
function mapMagazine (text) {
    const map = {};
    for (const w of text.split(' ')) { map[w] = map[w] ? map[w] + 1 : 1 }
    return map;
}

Problems
I do however see that your code would suffer from problems with a sting such as "A is a, as an a at the beginning,  a capitalised A." (Note it has a double space in it) It would return with some of the following properties...
{
    A : 1,
    "a," : 1,
    a : 2,
    "A." : 1,
    "beginning," : 1,
    "" : 1,  // empty string from splitting two spaces
     .. and the rest
 }

I would imagine you would want something a little more like.
{
    a : 5,
    beginning : 1,
     .. and the rest
 }

To do this you need a slight mod to the function. The text should be converted to lowercase, split can use a RegExp to split into words on white spaces or groups of white spaces, and a check for empty string that can result if the text is ended on a white space such as a full stop.
BTW does the function really map magazines?
function mapWords(text) {
    const map = {};
    for (const word of text.toLowerCase().split(/\W+/)) {
        word !== "" && (map[word] = map[word] ? map[word] + 1 : 1);
    }
    return map;
}


using system calls to compare text files

Only for the pedantic

With non-2's complement, the below will compare +0 as matching -0.

char* addr1;
char* addr2;
...
if(addr1[i] != addr2[i]) ... // Oops. +0 == -0

Instead use unsigned char *

unsigned char* addr1;
unsigned char* addr2;
...
if (addr1[i] != addr2[i]) ... // OK.  Only one kind of 0

Better yet, use memcmp().

Return values

"... returns 2 if it's the same file and 1 otherwise." --> Not quite.

Code also returns via exit() with other values.

exit(-1);
exit(-3);
exit(-4);

+ 1??

Off by 1.  No need for + 1.  G. Sliepen.

// for(int i=0;i<fileSize1+1;i++)
for (int i=0; i<fileSize1; i++)

Matching type

.st_size is typed as off_t.  I'd expect fileSize1, fileSize2, i as the same.

off_t fileSize1;
...
for (off_t i = 0; i < fileSize1; i++)

Big files

.st_size is a off_t, some signed type.  mmap(void *addr, size_t length, ...) takes a length of size_t, some unsigned type.

To do this right, code may need to call mmap() multiple times as file size can exceed SIZE_MAX.

Something like:

#define CHUNK  (1048576 /* 1 Meg */)

off_t fileSize1;
fileSize1 = stat_p1.st_size;

....

for (off_t offset = 0; offset < fileSize1; offset += CHUNK) {
  size_t map_size1 = CHUNK;
  if (fileSize1 - offset < CHUNK) {
    map_size1 = (size_t) (fileSize1 - offset);
  }

  addr1 = mmap(NULL, map_size1, PROT_READ,MAP_PRIVATE, fd1, offset);

  // as above for map_size1, addr2

  for (size_t i = 0; i < map_size1; i++)
    ...
  // or
  if (memcmp(addr1, addr2, map_size1) ....


There is a way to increase readability.  A for-else statement can be used to replace flags that are only set on break.  Click here to learn more.  The else clause is only called if the loop completes without break being called.

def find_duplicates(user_info):
    results = list()
    seen = dict()
    for i, user in enumerate(user_info):
        for info in user:
            if info in seen:
                index = seen[info]
                results[index].append(i)
                pos = index
                break
        else:
            results.append([i])
            pos = len(results) - 1
        for info in user:
            seen[info] = pos
    return results

How I tested speeds

Your code, as it currently stands, will work exactly the same with integers. So, I just randomly generated large data sets this way (and played along with MAXVALUE and range a bit.

from random import randrange
from timeit import timeit
MAXVALUE = 1000

for a in range(5): #I wanted to make sure I checked 5 to make sure I don't get a outlier data set that effects my ability to use timeit reasonably.
    user_info = [[randrange(MAXVALUE) for i in range(3)] for _ in range(1000)]
    print(timeit(lambda: find_duplicates(user_info), number=10000))

Credit for improving code: Maarten Fabré


Fibonacci in linear time by using an extra pointer

Your function uses global variables, which is bad for several reasons:

The variables must be reset before the function can be called again.
The variables can be modified from outside of your function, causing
wrong results.
The function is not thread-safe.

In addition,

The program logic is not immediately obvious (at least it wasn't to me).
Calling the function with n <= 0 causes an integer overflow.

Global variables are often problematic, and
here they can be easily avoided, making the code not only safer,
but also simpler.

First, the global sum variable is elimitated by making
it local:

var x = 0
func myFibonacci(of n: Int, a: Int, b: Int) -> Int {
    x += 1
    if (x == n) {
        return b
    } else {
        let sum = a + b
        return myFibonacci(of: n, a: b, b: sum)
    }
}

or eliminate it completely:

var x = 0
func myFibonacci(of n: Int, a: Int, b: Int) -> Int {
    x += 1
    if (x == n) {
        return b
    } else {
        return myFibonacci(of: n, a: b, b: a + b)
    }
}

Now get rid of the global variable x by decrementing n instead
in the recursive call:

func myFibonacci(of n: Int, a: Int, b: Int) -> Int {
    if n == 1 {
        return b // Recursion terminates here
    }
    return myFibonacci(of: n - 1, a: b, b: a + b)
}

With a slight modification it works for n = 0 as well.
Negative arguments should be caught instead of recursing
repeatedly until an integer overflow occurs:

func myFibonacci(of n: Int, a: Int, b: Int) -> Int {
    precondition(n >= 0, "`n` must be non-negative")
    if n == 0 {
        return a // Recursion terminates here
    }
    return myFibonacci(of: n - 1, a: b, b: a + b)
}

This is what I would expect as a recursive implementation in a coding interview (of course you can also implement it iteratively,
or use a closed-form expression such as Binet's formula).

As a bonus, you can implement it for negative arguments as well,
compare Generalizations of Fibonacci numbers:

func myFibonacci(of n: Int, a: Int, b: Int) -> Int {
    if n == 0 {
        return a // Recursion terminates here
    } else if n > 0 {
        return myFibonacci(of: n - 1, a: b, b: a + b)
    } else {
        return myFibonacci(of: n + 1, a: b - a, b: a)
    }
}


Find the largest decrease in a sequence of numbers

This can be solved in a single pass, e.g., O(n).
For each temperature, subtract it from the highest temperature seen so far to get the drop.  Keep track of the largest drop.  Also update the highest temperature.
def biggest_drop(temperatures):
    highest = temperatures[0]
    largest_drop = 0

    for temperature in temperatures:
        drop = highest - temperature
        largest_drop = max(largest_drop, drop)

        highest = max(temperature, highest)

    return largest_drop


Producing residues of combinatorics on strings

Think about alternatives

  Let's says I have 2 strings ABCDEF and ACDEBF. Now before I call gen8string, I will first perform a \$\binom 6 4\$ deletion operation on each string. For instance, I will take ABCDEF delete any two characters in that string and I am left with substring of length 4. How many different such strings can I have (given all the letters are unique)? \$15=\binom 6 4\$. Now, I will do the same for both strings. Now I am left with 2 string arrays, each of size 15.

Why?

You want to generate 90 strings.  Why generate 255 strings and then mask out 165 of them?  Why not just generate 90 strings directly?

  ABEFCDEF 001122
  ABDFCDEF 001212
  ABDECDEF 001221
  ...
  ABCFBDEF 020112
  ...
  ABEFABCD 221100

The six numbers are which string has the letter.  So 001122 means AB in the first string, CD in the second string, and EF in both.  Iterate from 001122 to 221100 or vice versa.  Then you don't need gen8string at all, as all it does is eliminate invalid strings like 2222-- and 22210-.

Of course, this would happen outside the code that you posted.

Working with what we have here

You have

public static String[] gen8String(String[] pattern1, String[] pattern2){
    String[] combinedSubset = new String[90]; //emty array for the subset of 90 strings
    String  combinedString = ""; //string holder for each combined string
    int index = 0; //used for combinedSubset array
    int present = 0; //used to check if all 6 characters are present

    for(int i = 0; i < 15; i++){

        for(int j = 0; j < 15; j++){
            combinedString = pattern1[i] + pattern2[j]; //combine both 4 letter strings into 8 char length string
            char[] parsedString = combinedString.toCharArray(); //parse into array

            //check if all 6 characters are present
            for(int k = 1; k <= 6; k++)
            {
                if(new String(parsedString).contains(k+"")) {
                    present++;
                }
                else
                    break;
                //if all 6 are present, then add it to combined subset
                if(present == 6)
                    combinedSubset[index++] = combinedString;
            }
            present = 0;
        }
    }
    return combinedSubset;
}

Consider

public static String[] gen8String(String[] patterns1, String[] patterns2) {
    String[] results = new String[90];
    int resultCount = 0;

    for (String pattern1 : patterns1) {
        for (String pattern2 : patterns2) {
            String combined = pattern1 + pattern2;

            //check if all 6 characters are present
            for (int k = 1; combined.contains(k+""); k++) {
                //if all 6 are present, then add it to the results and end
                if (k >= 6) {
                    results[resultCount++] = combined;
                    break;
                }
            }
        }
    }

    return results;
}

This changes the names of the parameters.  They are collections of patterns, not the patterns themselves.

I changed the names of combinedSubset and index to be clearer about how they relate to the results.  This allowed me to drop the comments as obsolete.

Switching from C-style for loops to range based for loops gets rid of the unnecessary i and j variables.  It also gets rid of the magic number 15.

I renamed combinedString to combined and moved the declaration to where it was set.  Since a single value is never used across iterations of the outer two loops, the scope doesn't need to be any wider.

We don't need present, as we already have k.  If we make it to the sixth iteration, we can update the results and stop the loop.

If we gate the loop on the contains check, we can just check the iterations once inside the loop.  The original code checked twice on each iteration.

Note that your example suggested inputs like ABCD and CDEF.  The patterns here are actually like 1234 and 3456.

Generalizing

Your code only works for four element subsets of a six element set.  Consider rewriting so the results are a List.  Then you wouldn't have to give a result set size or maintain your own count of the results.

The largest value for k (6 here) should probably be a parameter.  Or pass in an array or list over which we could iterate.

I already modified the for loops to be based on the size of the input parameters, so that's already generalized.

And of course the name would need to change.

Precalculate

Because the current results are so narrow, you could just set them manually.  One ninety element array.


Enumerating RCData resources from the EXE file which has been launched

The code is mostly fine but there a couple of minor issues:

The documentation for EnumResNameProc explains that lpszType and lpszName could be IDs rather than strings. Use the helper function Is_IntResource from the Windows unit to identify such IDs and treat accordingly.
Using LoadLibrary is fine, but it will result in code in the DLL being executed. Instead you are better to use LoadLibraryEx passing the LOAD_LIBRARY_AS_DATAFILE or LOAD_LIBRARY_AS_IMAGE_RESOURCE for the flags.


This is a rare case where the comment is absolutely necessary, along the lines of

/* The sequence is Fibonacci numbers modulo 10. It is periodic with a
   period of 60. Each even digits appears for 4 times, and each odd
   digit for 8 times, per period. The sum of primes per period is 128.

           Reviewer's note: are you sure? Looks like you consider 1 as prime.

   To get the desired results, compute the number of entire periods,
   and process the last incomplete part separately. */

Rename subSequences toperiods
Collapse the switch to

kFound = ((k & 0x01)? 8: 4) * periods;

I don't see how kFound can be 1 or 2, so

if(( kFound == 1 ) || ( kFound == 2 )) kFound++;

seems to serve no purpose. Correct me if I am wrong.
Working with the incomplete part should be split into functions. Precompute the period once, and pass it to separate functions (computing sum of primes, counting occurrences, and returning number at position).


My advice is to use the caret-package in which you can easily define your own metrics. The use of CV is described here in a clear manner:

https://machinelearningmastery.com/how-to-estimate-model-accuracy-in-r-using-the-caret-package/

The ingredients to your metrics requirements should be deriveable from the output via str(model). Here's a small example that should help you to get to your results:

library(caret)
library(ModelMetrics)

# Generate some data
Xs<- matrix(rnorm(300*20), nrow = 300, ncol = 20)
Yvec<- rnorm(300)

# Define your metrics
maeSummary <- function (data,
                        lev = NULL,
                        model = NULL) {
  mae <- mae(data$obs, data$pred)
  names(mae) <- "MAE"

  mse <- rmse(data$obs,data$pred)
  names(mse) <- "RMSE"

  out = c(mae,mse)
  out
}

# Initialize
train= trainControl(method="CV", number=10, summaryFunction = maeSummary, returnResamp="all", savePredictions="all")

# Train
model = train(x= Xs, y = Yvec, trControl=train, method="lm")

# Overall results
print(model)

# Metrics per fold
model$resample

Good luck!


is hacking PHPMailer version 5.2.8 specifically even possible? How is this possible?

That's really hard to say. If you use external libraries there is always a chance that they contain vulnerabilities, but the same is true for your custom code (and nobody is going to check that for vulnerabilities).

I didn't find any public disclosures for that version, so that's good.

The last ones also seem to be quite old (input validation issues in 1.7.3, code exec in 1.7, DOS in 1.7.2, email injection in 2012).

  what can be done to secure PHPMailer in these instances?

You could look at the PHPMailer code yourself, and try to find vulnerabilities (the main class is only 3.5k lines, and a lot of it are comments).
You should only put those files in an open directory that are needed (ie don't include the test/example files).
You could also use an application firewall/intrusion detection system such as mod_security to prevent the exploitation of possible vulnerabilities.
And you should always use the latest version, which seems to be 5.2.9, not 5.2.8.

Misc

your indentation and spacing is off, which makes your code a bit harder to read.
don't shorten variable names. For example, displayMessage is easier to read than dispmsg.
you didn't include the actual echoing of $dispmsg, but if $member['bizname'] is user supplied and $dispmsg not sanitized, your code would be open to XSS.
having // end something comments is a sign of bad design. Your code should be organized in a way that it is obvious when something ends. That means extracting functionality into functions, and avoiding deep nesting.


Your code looks generally OK in my book (i.e. not being that rusty ;-))

A few pointers though:

Generally keep variable scope as low as possible. T temp and boolean swapped can be declared at the place where they are needed initially.
Though I see the idea of multiplying with 1 or -1, the expression looks too "magic" for me. As Comparators have a reversed() method these days, I recommend to use that.

Putting this advice to use:

public static <T> T[] bubbleSort(T[] data, Comparator<T> comparator, boolean ascending) {
    Objects.requireNonNull(data);
    int len = data.length;
    if (len <= 0) return data;
    Comparator<T> actualComparator = ascending ? comparator : comparator.reversed();

    for (int i = 0; i < len - 1; i++) {
        boolean swapped  = false;
        for (int j = 0; j < len - 1 - i; j++) {
            if (actualComparator.compare(data[j], data[j + 1]) > 0) {
                T temp = data[j];
                data[j] = data[j + 1];
                data[j + 1] = temp;
                swapped = true;
            }
        }
        if (!swapped) break;
    }
    return data;
}


It's hard to say much about such a short code sample, but factories simply encapsulate object creation (wiring up objects), which frees code using them from that responsibility.  In that sense, factories are relevant in ruby too.

However, note that client code would look like this, given your current code:

translator = FreeGoogle::Factory.create

which isn't as readable as it could be.  I think I'd prefer to write something like the following in my client code:

translator = FreeGoogle.new_translator


I am especially unsure about looping over the sections in a scroll event.

There doesn't seem to be much of an alternative. One could select all elements with class name is-visible:

const visible = document.getElementsByClassName('is-visible');

Note that that collection is live, meaning it will be updated dynamically as the DOM changes, so there isn't any reason to re-query the DOM for those.

In the version that attempts to debounce the DOM updates, the IIFEs seem a bit excessive. Is the goal to limit scope of variables?

The function passed to panels.forEach() could be simplified:

panel => {
    if(scrollTop >= panel.offsetTop - ( windowHeight / 2)){
        panel.classList.add("is-visible");
    } else {
        panel.classList.remove("is-visible");
    }
    if(scrollTop >= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {
        panel.classList.remove("is-visible");
    }
}

This can be simplified by calling Element.classList.toggle() with two arguments.

panel => {
    let addClass = scrollTop >= panel.offsetTop - ( windowHeight / 2);

    if(scrollTop >= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {
        addClass = false;
    }
    panel.classList.toggle("is-visible", addClass);
}

const panels = document.querySelectorAll(".panel");

In most browsers it would generally be quicker to fetch the game squares using document.getElementsByClassName(), but that would return a live collection (refer to this SO answer for an explanation).

 const panels = [...document.getElementsByClassName("panel")];

The debounced version looks a little bit un-efficient because it uses an interval so that function gets executed more than it needs to.

There are also many arguments not to use setInterval and setTimeout - e.g. blindman67's SO Post Why is requestAnimationFrame better than setInterval or setTimeout

The functionality from the setInterval callback could be put into a function called checkVisibility. Then the scroll handler could be simplified to use requestAnimationFrame()

let timeout;
window.addEventListener("scroll", _ => {
    if (timeout) {
        window.cancelAnimationFrame(timeout);
    }
    timeout = window.requestAnimationFrame(checkVisibility);
});