Two try blocks in a method is a smell IMO: your method is trying to do two things, which implies it's not doing one and only one thing.

Let's see:

We open a stream from a given url and if all goes well we have an inputStream to work with.

Or things go bad, and we log an error, and then try to send an error response before we return null - if returning the error response failed, we log and still return null.

We use the stream to create a new file, and return a hard-coded string on success, or null on failure.

That alone looks like a bit of reusable functionality that should be extracted into its own method: one whose responsibility would be to send an error response:

void sendErrorResponse(HttpServletResponse response, string message) {
    try {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
    } catch(IOException e) {
        LOG.error("An error occurred while sending error response: " + e.toString());
    }
}

Next, you need a function that takes a url and gives you an inputStream.

InputStream openStreamFromUrl(string url, HttpServletResponse response) {
    InputStream result;
    try {
        result = new URL(url).openStream();
    }
    catch(IOException e) {
        string message = "Cannot open stream for url=" + url;
        LOG.error(message);
        sendErrorResponse(response, message);
    }
    return result;
}

So calling this openStreamFromUrl function either returns a valid and opened InputStream, or a null reference. This means we can now do this:

public String handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes, HttpServletResponse response) {
    InputStream inputStream = openStreamFromUrl(url, response);
    if (inputStream == null) {
        return null;
    }

    // handle file upload
}


Naming

The elephant in the room: names like var1 and var2 really hinder the readibility. var1 probably means has_packet_loss, var2 -> latency. Naming is hard, but it also is a fundamental property of readable code.

Ternary

You got repetition in

if var1 == 0: # has_packet_loss
    Status.configure(background="Green")
else:
    Status.configure(background="Red")

Becomes:

  status_color = "Red" if has_packet_loss else "Green"
  Status.configure(background=status_color)

Comments

You are commenting weird things: # Start & End Button is a thing I clearly see from the code, but the general purpose of the script is not immediately obvious. I suggest avoiding line-by-line comments and instead go for a docstring explaining the general purpose.

Logic extraction

StatusPing.configure is repeated 3 times:

if var2 <= 35:
    StatusPing.configure(background="Green")
if 35 < var2 < 70:
    StatusPing.configure(background="Yellow")
if var2 >= 70:
    StatusPing.configure(background="Red")

Write a function to determine background color and use it to avoid this repetition (Or a list of tuples)

Named constants

Define parameters at the start and use them later, this makes the code easier to re-use and makes it funnier to tinker (pun intended) with it. For example the ID to ping, the size of the widget, the colours, the messages...


It depends really on how you will use those models.
For example if you always, always get question object then find the answers that belong to it. there is no point adding profile relation with answers models and keep it to questions only.

If in rare cases (not in loops) you might deal with an answer without getting its question object first, its still ok to do answer.question.profile


It looks almost correct. But it can be improved.

Bug

What will happen if the input array is empty? Stack overflow.

Boolean values

Why return 1 for true and 0 for false instead of using boolean values?

if array[0] == item:
    return 1
return 0

In fact you could return the result of the boolean expression directly:

return array[0] == item

Similarly, what's happening here?

found = []

found.append(search(x, item))
found.append(search(y, item))

for elm in found:
    if elm ==  1:
        return True

return False

You append 0-1 values into found. If found contains a 1, return True,
otherwise return False. All this could be written on a single line:

return search(left, item) or search(right, item)

I also renamed the meaningless x and y to left and right.

Use doctests

Doctests are awesome. They are easy to write and execute and can greatly increase your confidence in your code and make it possible to refactor the code safely. For example:

def search(array, item):
    """
    >>> search([], 1)
    False

    >>> search([1,2,3,4], 8)
    False

    >>> search([1,2,3,4], 0)
    False

    >>> search([1,2,3,5], 4)
    False

    >>> search([1,2,3,5], 3)
    True

    >>> search([1,2,3,5], 5)
    True

    >>> search([1,2,3,5], 1)
    True

    """

    if not array:
        return False

    if len(array) == 1:
        return array[0] == item

    mid = len(array) // 2
    left = array[:mid]
    right = array[mid:]

    return search(left, item) or search(right, item)

You can run this with python -m doctest script.py.
If any of the test cases fails, you'll get a nice report (otherwise no output).


Faster generation of list with multiple sublists

aa = np.random.random((5, N1))
idxs = np.random.choice(N1, N2, replace=False)
bb = np.random.random((10, N2))

# I need to improve the performance of this line.
cc = [func(m[idxs], bb[i]) for (i, m) in enumerate(aa)]

Unless I'm misunderstanding something, half of bb is never used. Shouldn't the 5 in the instantiation of aa and the 10 in the instantiation of bb be the same value?

def func(m1, m2):
    return -2.5 * np.log10(10 ** (-0.4 * m1) + 10 ** (-0.4 * m2))

Algebraically, $$\log_{10}(10^x + 10^y) = \log_{10}(10^x (1 + 10^{y - x})) = x + \log_{10}(1 + 10^{y - x})$$ Since in this scenario \$-1 \le y - x \le 1\$ there doesn't seem to be any numerical-analytic reason not to simplify like this.

Depending on your error requirements, it may be possible to speed up the logarithm further by approximating it with a Taylor expansion $$\log_{10}(1 + 10^z) = \frac{\ln 2}{\ln 10} + \frac{z}{2} + \frac{\ln 10}{8} z^2 - \frac{\ln^3 10}{192} z^4 + \frac{\ln^5 10}{2880}z^6 - \ldots$$
or with a Padé approximant.


I would recommend you to actually strictly match the http.Get signature using a struct:

type Getter func(url string) (*http.Response, error)

type RetryingClient struct {
    Getter Getter
    MaxAttempts int
}

func (rc RetryingClient) Get(url string) (*http.Response, error) {
    ...
}

And instead of directly calling http.Get, the embedded Getter interface gives you much more flexibility:

for testing
for using a proxy

Why do you defer the response.Body.Close() ? Since it won't be use, you can close it immediately.

Using the interface, you could make a function embedded in the struct to compute a default delay instead of hard-coded time.Duration(attempts) * time.Second.
For instance: defaultDelay(attempt int) time.Duration


Overall I'd say this code is very easy to read. I can see quickly how everything works. Here are a few suggestions:
Only Make Public What's Necessary
There are 3 update() functions. Looking at them, it's not clear what the purpose of them is. The first one doesn't look like it should be public at all. It changes the internal state of the object, but doesn't update the string it comes from, which is confusing. It means that a caller could repeatedly call it with the same character from a string and it would count incorrectly. I'd make that version private.
I'd also make the argument to void update(char) be const since it's not modified.
Naming
Name Your Method Arguments!
What do the method arguments represent? Presumably for the 2 update() methods that take a pointer to a character, they represent a string to be parsed. They should have a name like parseString or something similar.
Improve Your Method Names
The method name update() doesn't tell me anything about what the function does. Any method that modifies the state of an object updates it in some way. A better name might be parse() or advanceLineAndColumn() or something that says what it actually does.
The getStr() method is very deceptive because it looks like it gets a pointer to the string this object is parsing. But it doesn't! Since this is C++, you'd be better served by making an operator<<() method or free function to print out your object.
Even reset() could be a little more descriptive. Perhaps something like resetParsing() or resetLineAndColumn(). Consequently, why would I want to use reset() instead of just creating a new instance? They seem fairly lightweight, so what's the advantage? If there is one, maybe that would be helpful in renaming the method.
Fix This Bug
In updated(str, size); you have a potential memory stomper. If size is greater than the actual length of str, you'll call update(str); and str might point to memory you don't have permission to read, causing a crash. Alternatively it might point to other data in your app and cause other problems such as incorrect line and column values.
All of this could be avoided if you...
Use std::string
Since you're using C++, you should be using C++'s string class to handle strings. It eliminates the possibility of running off the end of the string because you can access it using the at() method, which will throw an exception if you try to access a character outside the length of the string.


I would like to hear some feedback about style on my program,

The vertical spacing is excessive.

Odd separation example: blank lines between case code printf("so far you got %d bottles in your basket\n", bottle2); and break; misleads code blocks.  Consider instead;

        case 2:
            printf("how many bottles of Whiskey would you like\n");
            scanf("%d", &bottle2);
            printf("so far you got %d bottles in your basket\n", bottle2);
            break;

        case 3:

{ at line end or next line:  Stay consistent

do{
...
    switch(choice)
    {                  // why here vs above line

I'd expect following to be less indented.

       return 0;

It is apparent code is not written using an auto formatter and that is the biggest style problem.  Any style worth using will match an auto formatter.  Manually formatting is not productive and too inconsistent.

  and which one is better "do while" or "while loop" to run my program.

Use of do() is OK here as the loop should always execute at least once.  Some style guides eschew do().  As will such styles issues, follow your group's coding rules.

Style aside, code not checking the result of an input function like scanf("%d", &choice); is weak.

// better
if (scanf("%d", &choice) != 1)  {
  break;
}


IRestClient looks over-engineered. All of those helper members merge down to one common Call which can make the interface much simpler to define.

public interface IRestClient {
    IRestHeadersCollection DefaultRequestHeaders { get; }
    string DefaultContentType { get; set; }
    TimeSpan Timeout { get; set; }
    Task<RestResponse<TReturn>> SendAsync<TReturn>(RestRequest request, CancellationToken cancellationToken = default(CancellationToken));
}

The client now simplified to its core features.

The commonly used parameters can be aggregated into a class

public class RestRequest {

    public RestRequest() {
    }

    public RestRequest(IRestClient client) : this() {
        var contentType = client.DefaultContentType;
        if (!string.IsNullOrEmpty(contentType)) {
            ContentType = contentType;
        }
        var headers = client.DefaultRequestHeaders;
        if (headers != null) {
            foreach (var header in headers) {
                Headers.Add(header.Key, header.Value);
            }
        }
    }

    public IRestHeadersCollection Headers { get; } = new RestRequestHeaders();

    public Uri Resource { get; set; }
    public HttpVerb HttpVerb { get; set; } = HttpVerb.Get;
    public string ContentType { get; set; } = "application/json";
    public object Body { get; set; }

    class RestRequestHeaders : HttpHeaders, IRestHeadersCollection {
        public RestRequestHeaders() : base() { }
        public IEnumerable<string> this[string name] => GetValues(name) ?? Array.Empty<string>();
    }
}

Naming is important here. Change the name to resource from queryString, which means something different to how it was originally being used with regards to HTTP requests.

Parameter order should also be changed to be more consistent.

Your original call would have looked something like

...await client.PostAsync<ReturnObject, BodyObject>(body, "...");

with the URI parameter second. When making the request, the first argument should be the resource being called. Everything else can be built up from there

...await client.PostAsync<ReturnObject, BodyObject>("...", body);
...await client.PostAsync<ReturnObject, BodyObject>("...", body, token);
//...etc

The following extensions allow for the same functionality as before on the IRestClient abstraction

public static class RestClientExtensions {
    #region Delete
    public static Task DeleteAsync(this IRestClient client, string resource) {
        return client.DeleteAsync(new Uri(resource, UriKind.Relative));
    }

    public static Task DeleteAsync(this IRestClient client, Uri resource) {
        return client.DeleteAsync(resource, CancellationToken.None);
    }

    public static Task DeleteAsync(this IRestClient client, Uri resource, CancellationToken cancellationToken) {
        var request = new RestRequest(client) {
            Resource = resource,
            HttpVerb = HttpVerb.Delete
        };
        return client.SendAsync<object>(request, cancellationToken);
    }
    #endregion

    #region Get
    public static Task<RestResponse<TReturn>> GetAsync<TReturn>(this IRestClient client) {
        var request = new RestRequest(client) {
            HttpVerb = HttpVerb.Get
        };
        return client.SendAsync<TReturn>(request, CancellationToken.None);
    }

    public static Task<RestResponse<TResult>> GetAsync<TResult>(this IRestClient client, string resource) {
        try {
            return client.GetAsync<TResult>(new Uri(resource, UriKind.Relative));
        } catch (UriFormatException ufe) {
            if (ufe.Message == "A relative URI cannot be created because the 'uriString' parameter represents an absolute URI.") {
                throw new UriFormatException(Messages.ErrorMessageAbsoluteUriAsString, ufe);
            }
            throw;
        }
    }

    public static Task<RestResponse<TReturn>> GetAsync<TReturn>(this IRestClient client, Uri resource) {
        return client.GetAsync<TReturn>(resource, CancellationToken.None);
    }

    public static Task<RestResponse<TReturn>> GetAsync<TReturn>(this IRestClient client, Uri resource, CancellationToken cancellationToken) {
        var request = new RestRequest(client) {
            Resource = resource
        };
        return client.SendAsync<TReturn>(request, cancellationToken);
    }
    #endregion

    #region Patch
    public static Task<RestResponse<TReturn>> PatchAsync<TReturn, TBody>(this IRestClient client, Uri resource, TBody body) {
        return client.PatchAsync<TReturn, TBody>(resource, body, CancellationToken.None);
    }

    public static Task<RestResponse<TReturn>> PatchAsync<TReturn, TBody>(this IRestClient client, Uri resource, TBody body, CancellationToken cancellationToken) {
        var request = new RestRequest(client) {
            Resource = resource,
            HttpVerb = HttpVerb.Patch,
            Body = body,
        };
        return client.SendAsync<TReturn>(request, cancellationToken);
    }
    #endregion

    #region Post
    public static Task<RestResponse<TReturn>> PostAsync<TReturn, TBody>(this IRestClient client, TBody body, Uri querresourceString) {
        return client.PostAsync<TReturn, TBody>(body, querresourceString, CancellationToken.None);
    }

    public static Task<RestResponse<TReturn>> PostAsync<TReturn, TBody>(this IRestClient client, TBody body, Uri resource, CancellationToken cancellationToken) {
        var request = new RestRequest(client) {
            Resource = resource,
            HttpVerb = HttpVerb.Post,
            Body = body,
        };
        return client.SendAsync<TReturn>(request, cancellationToken);
    }
    #endregion

    #region Put
    public static Task<RestResponse<TReturn>> PutAsync<TReturn, TBody>(this IRestClient client, TBody body, Uri resource) {
        return client.PutAsync<TReturn, TBody>(body, resource, CancellationToken.None);
    }

    public static Task<RestResponse<TReturn>> PutAsync<TReturn, TBody>(this IRestClient client, TBody body, Uri resource, CancellationToken cancellationToken) {
        var request = new RestRequest(client) {
            Resource = resource,
            HttpVerb = HttpVerb.Put,
            Body = body,
        };
        return client.SendAsync<TReturn>(request, cancellationToken);
    }
    #endregion
}


Note: Minor change to the algorithm after I found a scenario it didn't cover

This is more of a mathematical problem than a programming one. After some thinking and experimentation, I've come up with an algorithm that can solve this in O(n), where n is the number of digits in the starting number. The basic principle is that we first break down the number into an array of digits, then start at the two ends and work our way inward to the middle, trying to set each pair of digits to the lower one, or as close to the lower one, in as many places as possible.

When examining a pair of digits, we always override the lower-order digit with the higher-order one. If the lower-order digit is greater than the higher-order one, it means the value of our number has reduced as a result of the override, so we set a carry flag. This carry flag will cause the next digit we measured from the lower end of the number (i.e. the lower-order one if we're less than halfway through the number, and the higher-order one if we're more than halfway through) to increment by one before the override is made. If this incrementation causes the digit to "overflow" into 10, we immediately set the digit to 0, set the carry flag to true, and proceed to the next digit.

function nextPalindrome(n) {
    let digits = [];
    let m = n;
    while (m > 0) {
        digits.unshift(m % 10);
        m = Math.trunc(m / 10);
    }

    let carryFlag = false;
    let midPoint = Math.floor(digits.length / 2);

    for (let i = 0; i < digits.length; i++) {
        let copyFrom = digits[i];
        let copyTo = digits[digits.length - 1 - i] + carryFlag;
        if (copyTo === 10) {
            digits[digits.length - 1 - i] = 0;
            carryFlag = true;
        }
        else {
            let digit = (i < midPoint) ? copyFrom : copyTo;
            carryFlag = copyTo > digit;
            digits[i] = digits[digits.length - 1 - i] = digit;
        }
    }

    return digits.reduce((acc, next) => 10 * acc + next, 0);
}

I don't have a pure mathematical proof detailed, but it seems to work. Please feel free to test it (especially with edge cases) and comment if something's wrong.


Proper way to log progress and resume in Python

You may want to consider using the standard Python logging module to log in the information, and just keep the parser.

import logging

logger = logging.getLogger('repeatingApp')
hdlr = logging.FileHandler('/path/to/logfile')
hdlr.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)

class RepeatingTask(object):
    def page(self):
        self.process_request()
        self.increment()
        logger.info(json.dumps([["current","key-xyz"],
                                [self.current,self.val_abc]]))


Do not do use bare except

Your execpt catches all exceptions including KeyboardInterrupt. Once the program is launched, there is no way (as far as I can see) to stop it.

If you are interested in failed conversions, you should catch ValueError.

Bug (solutions)

Using these values :

        a = int("0") # int(input("\nEnter a : "))
        b = int("2") # int(input("Enter b : "))
        c = int("3") # int(input("Enter c : "))

I got

Your equation is 2x+3 = 0
X = -3/2 or -2.000000

Another bug (pretty-printing)

With :

        a = int("0") # int(input("\nEnter a : "))
        b = int("-1") # int(input("Enter b : "))
        c = int("-1") # int(input("Enter c : "))

I get :

Your equation is 1x-1 = 0
X = -1

Yet another bug (no solutions)

With :

        a = int("1") # int(input("\nEnter a : "))
        b = int("0") # int(input("Enter b : "))
        c = int("0") # int(input("Enter c : "))

No solution is printed.

Organisation

If you want to make things easier to read/maintain/fix, you should split the logic into multiple independant entities like functions for instance. Once could handle the logic to get the input from the user, one to generate the pretty-printed equations, one to look for solution, etc.

Also, you should try to write automatic tests. I'll let you find online how to write unit tests in Python.

Finally, it is a good habit to define functions/classes in your file but to write code that actually calls it behind a if __name__ == "__main__": test so that it does what you want when you use your file as a script but you can also import it to enjoy the functions and stuff without having any side-effects.

Useless conversions

chr returns a string, there is no need to convert it to string afterward.

Do not repeat yourself

You have :

            if b > 0:
                sgn_b = "+"
            else:
                sgn_b = "-"
            if c > 0:
                sgn_c = "+"
            else:
                sgn_c = "-"

in two different places. There is no need for this, just do this away from the if a > 0: test.

Keep it simple

When looking for a solution, you are trying to handle all scenarios in a pretty akward way. The best place to start with is to answer the simple question : "is a different from 0 ?". If a is 0, next question is "is b different from 0?".

Trying to group the different cases makes things easier to read. Also, it is easier to ensure you've handled all interesting cases.

Suggestion

When you pretty print the equations, 1 is a special case, -1 should probably be considered just as special.

My final version of the code is below. I have mostly moved code from one place to another and I haven't fixed any issue because it is more interesting for your to do it. Also, I have a few ideas to make the pretty-printing function much more concise but it is a bit more advanced and I feel like you should learn one step at a time.

from math import sqrt

def get_input():
    while True:
        try:
            a = int("1") # int(input("\nEnter a : "))
            b = int("0") # int(input("Enter b : "))
            c = int("0") # int(input("Enter c : "))
            return a, b, c
        except ValueError:
                print("You can only enter integers")

def get_pretty_eq(a, b, c):
    if a > 0:
        sgn_a = ""
    else:
        sgn_a = "-"
    if a == 0:
        part_a = ""
    elif a == 1:
        part_a = sgn_a+"x"+chr(0x00B2)
    else:
        part_a = sgn_a+str(abs(a))+"x"+chr(0x00B2)

    if b > 0:
        sgn_b = "+"
    else:
        sgn_b = "-"
    if b == 0:
        part_b = ""
    elif b == 1:
        if a != 0:
            part_b = sgn_b+"x"
        else:
            part_b = "x"
    else:
        if a != 0:
            part_b = sgn_b+str(abs(b))+"x"
        else:
            part_b = str(abs(b))+"x"

    if c > 0:
        sgn_c = "+"
    else:
        sgn_c = "-"
    if c == 0:
        if a == 0 and b == 0:
            part_c = "0"
        else:
            part_c = ""
    elif a == 0 and b == 0:
        part_c = str(abs(c))
    else:
        part_c = sgn_c+str(abs(c))
    return part_a + part_b + part_c + " = 0"

def get_solution_as_string(a, b, c):
    if a != 0:
        if b != 0:
            if c != 0:
                D = b**2-(4*a*c)
                if D > 0:
                        x_1 = ((-b+sqrt(D))/2*a)
                        x_2 = ((-b-sqrt(D))/2*a)
                        return "X1 = %f\nX2 = %f" %(x_1,x_2)
                elif D == 0:
                        x = -b/(2*a)
                        return "X1 = X2 = %d" %x
                elif D < 0:
                        x_1 = ((-b+sqrt(-D))/2*a)
                        x_2 = ((-b-sqrt(-D))/2*a)
                        return "X1 = %f%s\nX2 = %f%s" %(x_1,"i",x_2,"i")
            else:
                x_2 = -b/a
                if b % a != 0:
                        return "X1 = 0\nX2 = %d/%d or %f" %(-b,a,x_2)
                else:
                        return "X1 = 0\nX2 = %d" %x_2
        else:
            if c != 0:
                if -c > 0:
                        x_1 = sqrt(-c/a)
                        x_2 = -x_1
                        return "X1 = %f\nX2 = %f" %(x_1,x_2)
                else:
                        x_1 = sqrt(c/a)
                        x_2 = -x_1
                        return "X1 = %f%s\nX2 = %f%s" %(x_1,"i",x_2,"i")
            # this lack of "else" case is very suspicious
    else:
        if b != 0:
            if c != 0:
                x = -c/b
                if c % b != 0:
                    return "X = %d/%d or %f" %(-c,b,x)
                else:
                    return "X = %d" %x
            else:
                return "X = 0"
        else:
            if c != 0:
                return c,"!= 0"
            else:
                return "0 = 0. DUH!"

if __name__ == "__main__":
    a, b, c = get_input()
    print("\nYour equation is %s\n" % get_pretty_eq(a, b, c))
    print(get_solution_as_string(a, b, c))


Autoloading Class files and instantiating a class - Admin backend

Using spl_autoload_register() is a well known and recommended way of auto-loading classes.

And of course you can't call objects without having them instantiated first.


Keep reading user keyboard input if available, while echoing back the latest available

With a bit of suggestion/help on Haskell's IRC channels, I came up with this, which doesn't forkIO at every recursion.
{-# language LambdaCase #-}

import Control.Concurrent
import Data.Maybe
import System.IO

main :: IO ()
main = do
  hSetBuffering stdin NoBuffering
  future_input <- newEmptyMVar
  forkIO $ pollInput future_input
  processInput future_input 'l'

pollInput :: MVar Char -> IO ()
pollInput future_input = (putMVar future_input =<< getChar) >> pollInput future_input

processInput :: MVar Char -> Char -> IO ()
processInput future_input latest_input = tryTakeMVar future_input >>=
    \case Just input -> putStrLn ("direction change " ++ return input)
                        >> processInput future_input input
          Nothing    -> putStrLn ("keep direction " ++ return latest_input)
                        >> threadDelay 100000
                        >> processInput future_input latest_input


Find optimum teams given calendar availabilities

Review
Imports
import operator is being done twice, which is unnecessary.
from itertools import combinations, chain: chain is never used, and can be removed.
N Choose R
As of Python 3.8, the "n choose r" function is built-in and can simply be imported:
from math import comb.
The function is never used, so may be deleted.
Constants
time_slots = 24*4*7
That is ... the number of hours in a 4-week month?  No?  Perhaps you should name some of those numbers, and use UPPER_CASE to indicate the result is a constant:
SLOTS_PER_HR = 4
HRS_PER_DAY = 24
DAYS_PER_WEEK = 7
TIME_SLOTS = SLOTS_PER_HR * HRS_PER_DAY * DAYS_PER_WEEK

Code Organization
You've got imports, function definition, constants, code, another function definition, more code.  Organize your code, please!

imports
constants
function definitions
code (ideally in a main-guard)

Use blank lines to separate sections.  Your first function immediately follows the imports without a blank line, which makes it harder to understand.  3 blank lines before the second function definition seems excessive, and no blank line after the last function makes it harder to see that the code which follows is not part of the function.
Order import ... statements before from ... import ... statements.
Use Function Parameters
def make_teams(availabilities_dict, team_size):
If I call make_teams(availabilities, 10), I'd expect the function to make teams of 10, but it will actually make teams of size TEAM_SIZE (a global constant) instead!  The team_size parameter is never used.
Similarly, if I pass in a dictionary of 200 people, it will stop making teams when NUM_PEOPLE is reached.  len(availabilities_dict) would be more intuitive.
Use a for loop instead of a manual loop counter
    i = 0
    while len(assigned) < NUM_PEOPLE:
        considering = list(sums[i][0])
        ...
        i += 1

This loop can be changed to something like the following, which has eliminated the i loop variable.  We've even moved the test for number of people assigned from every loop to only being done when the list of assigned people changes.
    for considering, team_sum in sums:
        ...
        if none_assigned:
            ...
            if not len(assigned) < NUM_PEOPLE:
                break

Large functions
make_teams() is a large function, 22 lines long, not counting blank lines or docstrings.  No comment is in sight.  Functions should be decomposed into smaller functions, which do simpler tasks, instead of a single monolithic function doing everything.  Smaller functions are easier to understand.
Type Hints
Adding type-hints can go a long way towards improving readability of the code.
Optimizations
NumPy -vs- Bitarray
numpy is a powerful, flexible, and fast library for manipulating vast quantities of data in multidimensional arrays.
Most of the power of numpy is completely unused by this code.  The part that is being done by numpy could be replaced with bitarray, a library that is optimized exclusively for dealing with arrays of bits in a fast, efficient, memory conscious way.
I haven't run timed trials of numpy using 1-dimensional bit arrays against the bitarray library, so I'm offering this as something to look into, rather than explicitly stating one is better than the other.
Lists -vs- Sets
You are maintaining a list of all assigned players, and testing that no player in a considering list is in the assigned list.  The problem is person in assigned is an \$O(N)\$ operation.  If you maintained as set of assigned players, then player in assigned becomes an \$O(1)\$ operation, significantly faster.
Moreover, with sets you can test all the players in considering at once.  If assigned.isdisjoint(considering) is true, there is no overlap; no player in considering has been assigned.
Suggested code
from bitarray import bitarray
from bitarray.util import urandom
from itertools import combinations

# Types for type-hints (using Python3.9 style)
Schedules = dict[int, bitarray]
Team = tuple[int]
Teams = list[tuple[Team, int]]

# Constants
SLOTS_PER_HR = 4
HRS_PER_DAY = 24
DAYS_PER_WEEK = 7
TIME_SLOTS = SLOTS_PER_HR * HRS_PER_DAY * DAYS_PER_WEEK

def make_teams(availability: Schedules, team_size: int) -> Teams:
    """
    A good docstring here
    """

    # Inner function for determining the common availability of a team
    def common_availability(team: tuple[int]) -> int:
        avail = bitarray(TIME_SLOTS)
        avail.setall(True)
        for player in team:
            avail &= availability[player]
        return avail.count()

    # team combinations are created and sorted in one step.
    team_combinations = sorted(combinations(availability, team_size),
                               key=common_availability, reverse=True)

    # Collect teams, while maintaining a set of assigned players
    assigned = set()
    teams = []

    for team in team_combinations:
        if assigned.isdisjoint(team):
            # I didn't store availability scores, so recalculate here if really needed.
            teams.append((team, common_availability(team)))
            assigned |= set(team)

    return teams

# Create random schedules
def test_data(num_people: int, time_slots: int) -> Schedules:
    return {i: urandom(time_slots) for i in range(num_people)}

if __name__ == '__main__':
    from time import perf_timer

    for num_people in range(TEAM_SIZE, 101, TEAM_SIZE):
        availability = test_data(num_people, TIME_SLOTS)
        start = perf_counter()
        teams = make_teams(availability, TEAM_SIZE)
        secs = perf_counter() - start
        mins = int(secs / 60)
        secs -= mins * 60

        print(f"{num_people:3d} {mins:02d}:{secs:06.3f}")

My 5 year old laptop finds teams of 5 from 100 people in 02:08.887 ... well under the 10 minutes you're experiencing on your "state of the art computer".  That isn't a really good, qualitative performance comparison, so you'll have to profile it to see how much of an improvement you see.


For the same reasons as @DJanssens, I would like to compliment you for a simple and clean algorithm making proper use of the standard library. That may seem basic, but there are too many people ignoring the standard <algorithm> in the world, so I'm glad that you decided to use it. I only want to add two more things:

First, I don't think that shrink_to_fit will do what you expect it to do. When you construct result, you allocate memory and fill it with spaces, so result's size probably grew to. shrink_to_fit will get rid of the allocated but unused memory, but it won't get rid of the extra spaces that you allocated at construction.
What you can do is default-construct your std::string and use an std::back_inserter to fill it the lazy way. The std::back_inserter will perform some magic so that the result's push_back method is called whenever an element has to be added:

std::string find_intersection(std::string & first, std::string & second)
{
    std::sort(std::begin(first),std::end(first));
    std::sort(std::begin(second), std::end(second));

    std::string result;

    std::set_intersection(
        std::begin(first), std::end(first),
        std::begin(second), std::end(second),
        std::back_inserter(result)
    );

    return result;
}


Find intersection of rectangle with itself rotated

Not a full rewrite, but some pointers:

Typically, a main function's do-block shouldn't be doing a whole lot of work. Additionally, do-blocks should try to avoid having lots of let statements, and instead "outsource" that work to helper functions. A function with type Double -> Double -> Double -> [((Double, Double), (Double, Double))] could replace most of the do block (the arguments would be w, h, and a).

Every style guide I've seen recommends putting type signatures on every top-level function. Just reading the code to try and figure out what the above mentioned type should be can be surprisingly difficult. Unfortunately, as the author of a program, it's really easy to forget that you know the types because the ideas for the program were your own.

Primes in function names are typically reserved for one of two things. It could mean a strict variant, such as foldl'. "Strict" in this case means that the function evaluates its argument, as opposed to Haskell's default of waiting to evaluate things as long as possible. The other option is that it's a minor variation on the function of the same name (many haskellers would say to avoid doing even this, and to reserve primes on function names for strict varaints alone). getints' is not a minor variation on getints, it is a helper function. A more appropriate name might be getintsHelper. On the other hand swap' is a minor variation on swap, and barring a better name like swapBoth, swap' is a reasonable name for that function.

Your function uniq looks like Data.List.nub. nub is a strange name and uniq honestly makes more sense, but it's better to use library functions that readers are familiar with. It's also fine to define synonyms, like uniq = nub, this way readers can see that in the source. Recognizing that uniq is a complete re-implementation is a bit harder. If you think a function you need is simple or common, check the standard library! Haskell's is quite extensive.

With top-level types added and no other changes, this would be a very strong starting point. I'd label that as good work!


Lattice path from Project Euler with Python solution

All of your approaches are very brute force.  The answer can be computed with a bit of mathematical reasoning.  For an m × n lattice, all paths will have m + n segments, of which m segments will go down and n segments will go right.  So, out of m + n slots, count the ways to pick m downward moves; the rest of them will be rightward moves.  The number of paths is:

$${m + n \choose m} = {m + n \choose n} = \frac{(m+n)!}{m! \, n!}$$

So, the Python solution is simply:

from math import factorial

def lattice_paths(m, n):
    return factorial(m + n) // factorial(m) // factorial(n)

Even though the calculation involves large factorials, Python supports big integers seamlessly, and arrives at the answer nearly instantaneously.


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

Avoid pow for float

The use of pow converts the argument to a double and returns a double.  If you're casting the result to a float anyway, the use of std::powf would be more appropriate.  But see the next suggestion for an even better approach.

Prefer multiplication to pow with small, fixed integral powers

The content of the pdf function could be rewritten like this instead:

 return 1.0f/((u+1)*(u+1));

Usealittlemorewhitespace

With everything crowded together on the line, it's hard to read and understand some lines like this:

float gammath = (gamma[i]/Q)*(G-Q*(K-1));

I'd write it like this instead:

float gammath{gamma[i] / Q) * (G - Q * (K - 1)};

This also uses the C++11 uniform initialization syntax, which I prefer.

Use constexpr where appropriate

Any time you can make a numerical constant or expression constexpr is one more opportunity for compiler optimization.  In this case, virtually everything in main, including du, K, gamma, G, and Q can be made constexpr simply by adding that keyword in front of the declaration.  With that, the compiler is free to evaluate expressions like this:

G - Q * (K - 1)

once at compile-time rather than at runtime.  It can save quite a bit of time if you use it.

Move invariants out of the loop

The value of the expression listed above does not change within the loop (or within the program at all, as presented).  Smart compilers can usually optimize that by themselves, but doing it manually may give you insight.  For example, we can make a constant of that expression outside the loop:

constexpr auto m{G - Q * (K - 1)};

Now the inner if boils down to if (m > 0) but since it's invariant within the loop, move it outside.  Now we have the encapsulating if outside and the for loop inside which makes a lot more sense.

Use C++11 threading features

The calculations for each value of gamma are completely independent.  For that reason, they could easily be calculated in parallel.  Here's a way to do that:

int main() {
    constexpr float du = 0.0001;
    constexpr int K = 3;
    constexpr float gamma[4] = {0.31622777, 0.79432823, 1.99526231, 5.01187234};
    constexpr int G = 50;
    constexpr int Q = 2;
    constexpr auto m{G - Q * (K - 1)};
    std::vector<std::future<float>> chunks;
    if (m > 0) {
        for (int i = 0; i < 4; i++) {
            float gammath{gamma[i] / Q * m};
            chunks.push_back(std::async(integ, gammath, K, du));
        }
    }
    std::mutex cout_mutex;
    for (int i=0; i < 4; ++i) {
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << gamma[i] << '\t' << 1 - chunks[i].get() << '\n';
    }
}

This requires <future>, <mutex>, and <vector> as #includes.

Parallelize the recursive integrals

If there are 100,000 steps in the integral, why do that with a single core?  If you have a multicore machine like I do, you could divide that work among multiple cores by using the same kind of std::async technique shown above.  This would dramatically speed the results (and can be divided among as many cores as you have).  I did not implement that, but the code above should give a hint as to how to do such a thing generically.

Use static for functions which can have file scope

If the pdf, cdf and integ functions are never used outside the file in which they're defined, the compiler can get quite clever about inlining code and other optimizations.  For that reason, I'd recommend making those functions static if at all possible.

Results

I didn't have the patience to run this at the du value in the program (0.0001) so I ran it at 50 times that at 0.005 to speed up testing.  Obviously, that's an option if you can accept the lower resolution, but I just did it to speed up timing tests.

The original (with the modified value of du) took 1.06 seconds, while the modified version took 0.723s.  At full resolution (du = 0.0001) the results took 30 minutes and 3 seconds on the same 64-bit 8-core Linux machine.


QCombobox Case selection - Pyside2 Index via Sqlite

Well you have already identified the problem: repetition.
It can be tackled fairly easily. Instead of that if/elif block you can use a (zero-indexed) list that contains the WHERE clause for the query:

    options = [ None, '%html%', '%javascript%']
    query = "SELECT url,size,content_type FROM 'google.com.au'"

    if options[index] is not None:
        query += f" WHERE content_type LIKE '{options[index]}'"

    sourceModel = QSqlQueryModel()
    sourceModel.setQuery(query, db)
    proxyModel = QSortFilterProxyModel(self)
    proxyModel.setSourceModel(sourceModel)
    self.tableView.setModel(proxyModel)
    self.tableView.setSortingEnabled(True)

Only the first option is different: there is no WHERE clause. In the other places the request is always the same, it's only the search pattern that is different.

What I am doing here is simply selective string concatenation. Note: using an F-string for the WHERE clause, requires Python >= 3.6. Usage is not mandatory but if you have a recent version of Python embrace the new features.

Instead of None you could say '' (an empty string). I chose None to signify option #0 is a special case. I am not checking that index is actually in the range 0->2. If you think this could happen, add a if to check.


Haskell network connection graceful handler

Just one remark: When handling IO resources, I'd strongly suggest using bracket for resources that are obtained at some point and later released. Not only it makes your code much safer, it clearly demarcates which resource is used in which parts. And that also prevents separating opening and closing of resources, which is often a hard-to-find error.


I don't know much about Android, so I can't answer that specific question, but there's still some things to change.

 @Override
public IBinder onBind(Intent arg0)
{
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate()
{
    // TODO Auto-generated method stub
    super.onCreate();
}

@Override
public void onDestroy()
{
    // TODO Auto-generated method stub
    super.onDestroy();
}

It looks like your IDE generated these for you, but you don't need them. Get rid of them, they're just clutter.

PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);

Ouch! In Java, we put one space after each comma in the argument list, and sometimes spaces in expressions. This line should look like

PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

Also, if you put spaces around an operator, it should be one space on each side, so Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP should be Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP

notification.setLatestEventInfo(this.getApplicationContext(), "Score Collection!", "Please enter scores at this time!", pendingNotificationIntent);

If I recall correctly, on Android all user-facing strings should be handled by the OS so that you can localize them easily.

Other than that, this code looks pretty good.


Writing a product() function analogous to sum

Since your definitions have only two cond clauses, you may replace cond with if.  Your iterative definition is a departure from the example of sum.  It should return 1 (product identity) when a is greater than b, not null.  This makes the outer cond unnecessary.

Your definition of compute-pi suffers from imprecision of float operations (it fails to produce meaningful values for n > 85).  It would be better to convert to float after computing the approximating fraction.

(define (product term a next b)
  (if (> a b)
      1
      (* (term a) (product term (next a) next b))))

(define (i-product term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (* (term a) result))))
  (iter a 1))

(define (compute-pi steps)
  (define (next n) (+ n 2))
  (* 8.0 (* steps 2) (/ (i-product square 4 next (* (- steps 1) 2))
                        (i-product square 3 next (* steps 2)))))


To save a few lines create a Style enum first:

enum Style
{
    Header,
    Hour,
    Condition,
    Temperature
}

Then assign each style a color:

static Dictionary<Style, ConsoleColor> _styles = new Dictionary<Style, ConsoleColor>
{
    [Style.Header] = ConsoleColor.Magenta,
    ...
}

Use overloading to encapsulate the styling logic like this:

private static void Print(Style style, string format, params object[] args)
{
    Console.ForegroundColor = _styles[style];
    Console.Write(format, args);
    Console.ResetColor();
}

private static void PrintLine(Style style, string format, params object[] args)
{
    Print(style, format, args);
    Console.WriteLine();
}

I think it's a good idea to stick to the Print & PrintLine convention like the console does it.

Then you can turn this:

 ChangeColor(ConsoleColor.Magenta);
 Console.WriteLine("== Day {0} ==", printDate.ToLongDateString());

into:

Print(Style.Header, "== Day {0} ==", printDate.ToLongDateString());

You can go even further and create a special method called PrintHeader and do all the magic there like so:

PrintHeader(printDate)
{
    Print(Style.Header, "== Day {0} ==", printDate.ToLongDateString());
}

This way your printing becomes even cleaner and you can manipulate the header separately.

The same applies for other cases.

 DateTime printDate = DateTime.Now.Date;
 for (int i = 0; i < days; i++)
 {
     printDate = printDate.AddDays(1);
     ...
 }

I would remove the helper above the loop and write:

 for (int i = 0; i < days; i++)
 {
     var printDate = DateTime.Now.Date.AddDays(i + 1);
     ...
 }

Magic numbers

You should replace all those 5, 6, 21 etc with constants and give them proper names. I have no idea what they mean. You in few week will wonder too why such numbers.

 if (weatherAtHour != null)    {
 }

make it

if (weatherAtHour == null) { continue; }

to reduce nesting.

for (int hour = 6; hour <= 21; hour = hour + 3)

I would encapsulate this logic in a method like this:

private static IEnumerable<int> Hours()
{
    for (int hour = 6; hour <= 21; hour = hour + 3)
    {
        yield return hour;
    }
}

Then in your weather print you can use link with ease:

var weathersAtHour =
    Hours()
    .Select(hour => timePointsDuringtDay.SingleOrDefault(weatherTimePoint => weatherTimePoint.TimePoint.Hour == hour))
    .Where(x => x != null);

foreach (var weatherAtHour in weathersAtHour)
{
   ...
}


Calculate amount of mugs StackExchange should give away so I'll receive one

Documentation

I think that what the query is doing is looking at your reputation rank, then rounding up to the nearest 50.  It would be nice to hit "edit description" and document that for the benefit of anyone else using Stack Exchange Data Explorer.

Generality

Data Explorer allows parameterization.  Use it.

Style

You shouldn't have to declare variables for such a simple query.  In SQL, try to say what you want.  Don't state the steps for calculating it.

A good way to avoid defining variables is to use Common Table Expressions (the WITH clause) instead.

Brevity

It would help to use the relevant functions RANK() and CEILING().

WITH UserRanks AS (
    SELECT DisplayName
         , RANK() OVER (ORDER BY Reputation DESC) AS RepRank
        FROM Users
)
SELECT *, 50 * CEILING((RepRank + 0.0) / 50) AS BatchedRepRank
    FROM UserRanks
    WHERE DisplayName = ##Username:string##;


Joining tables by skipping the intermediate parent table

Your changes to the query are good changes.

Just because the both adm_app and quals_data have the same child relationship to the personal_data table does not mean you have to include the personal_data table in a join if there's no relevant data on it.

You should run both of your queries with the query-plan EXPLAIN to show the difference in the queries. Avoiding the join will make for a simpler query with better performance.

Having said that, what about the rest of your query, are there improvements that can be made? Nothing big, really. I am not a big fan of snake_case for table and column names, but it is more important that you are consistent, and neat with the concept.

If I were to have any complaints, it would just be two really small things:

a spelling error.... I know, it's seriously pedantic, but in my "real job" I would point out the error soon because it is the sort of thing that is hard to correct later... convertion should be spelled conversion
abbreviations should be consistent in names. Since you have personal_data and fully named columns like convertion_marks, then it follows that you should not have abbreviations for adm_app and quals_data. Those should be full names.

As you can tell, the only issues I can see are really trivial.


My primary suggestion would be to try and make the code more intuitive.

While the current variable names are syntactically valid, they are a bit cryptic IMO. Consider using slightly longer and more descriptive names throughout the code. That will make it easier to understand when you come back to it a few months down the road.
Use date objects (not strings), when generating the quarter dates. Start by creating the initial quarter date with the CreateDate() function. (Use this formula to calculate the first quarter of the month). Then use DateAdd() to derive the remaining quarters. For comparisons, use DateCompare().
Consider using a non-ambiguous format like yyyy-mm-dd for the list value. You can still display a more user friendly format for the list text.
Be sure to explicitly scope all variables to avoid accidental scope conflicts. For example, if the variables are submitted via URL, use url.howManyOpts instead of just howManyOpts

<cfparam name="url.startDate" default="#now()#">
<cfparam name="url.howManyOpts" default="10">
<cfparam name="url.selQuarter" default="">

<!--- create starting quarter date --->
<cfset quarterMonth = Int((month(url.startDate) - 1) / 3) * 3 + 1>
<cfset currQuarter = createDate(year(url.startDate), quarterMonth, 1)>

<!--- if selected quarter was not defined, set a default --->
<cfif !len(trim(url.selQuarter))>
    <cfset url.selQuarter = currQuarter>
</cfif>

<select name="selQuarter">
   <cfoutput>
   <cfloop from="1" to="#url.howManyOpts#" index="x">
       <!--- separated for clarity --->
       <cfset optValue   = dateFormat(currQuarter, 'yyyy-mm-dd')>
       <cfset optText    = dateFormat(currQuarter, 'mm-dd-yyyy')>
       <cfset isSelected = dateCompare(currQuarter, url.selQuarter) eq 0>

       <option value="#optValue#" <cfif isSelQuarter>selected</cfif>>#optText#</option>

       <!--- move to next quarter --->
       <cfset currQuarter = dateAdd("m", 3, currQuarter)>
    </cfloop>
    </cfoutput>
</select>


Manager - Repository or Factory or both?

What is a Manager? It's usually a class that does too much. In this case it tries to be a repository and a factory a the same time. This should be separated.

Why would we do this? To make the usage more obvious and to be able to add functionality to either class without affecting or breaking the others and of course to test each module separately.

DocumentRepository

When implementing the repository consider switching from the List<T> to the HashSet<T>. This would improve not only the performance (which is probably neglectable here - with a dozen of documents no one will notice the change) but it would greaty simplify your code and both methods would be single calls:

public bool Add(IDocument document)
{
    return ActiveDocuments.Add(document);
}

public bool Remove(IDocument document)
{
    remove ActiveDocuments.Remove(document);
}

What about the naming? You call your methods Create and Close but I don't see anything but adding and removing documents to/from a collection. I suggest naming them simply Add and Remove respectively.

If you store the documents in a database then you may add other methods to it. However even better would be to implement two repositories. The first one only knows how to talk to the database and if you need to cache the documents then the decorator repository can do the rest.

Example:

interface IDocumentRepository
{
    IDocument Get(int id);
    bool Add(IDocument document);
}

class DocumentRepository : IDocumentRepository
{
    public IDocument Get(int id)
    {
        // get from database
    }
    bool Add(IDocument document)
    {
        // add to database
    }
}

class CachedDocumentRepository : IDocumentRepository
{
    private readonly DocumentRepository _documentRepository;

    private readonly HashSet<IDocument> _cache = new HashSet<IDocument>();

    public CachedDocumentRepository(DocumentRepository documentRepository)
    {
        _documentRepository = documentRepository;
    }

    public IDocument Get(int id)
    {
        // check the cache and get a document from there or
        // get it from _documentRepository.Get(id);
        // and add to the cache
    }

    bool Add(IDocument document)
    {
        // add to the cache and
        // add to database
    }
}

IEnumerable

With your current implemetation you could remove the Get method and further simplify the repository by implementing the IEnumerable<IDocument> interface for this class.

DocumentFactory

This class should only know how to create documents. It can have methods for creating many different types but nothing else.


Std lib-like C++ function to find nearest elements in a container

I think all you need is std::nth_element:

template<typename Q, typename I, typename Distance>
void find_n_nearest(const Q& q, I first, I nth, I last, Distance dist)
{
    using T = decltype(*first);
    auto compare = [&q, &dist] (T i, T j) { return dist(i, q) < dist(j, q); };
    std::nth_element(first, nth, last, compare);
    std::sort(first, last, compare);
}

int main()
{
    auto distance = [] (int i, int j) { return std::abs(i-j); };
    std::vector<int> v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};
    auto res = {0, 10, 23, -20, 36};

    find_n_nearest(4, v.begin(), v.begin() + 5, v.end(), distance);
    assert(std::equal(v.begin(), v.begin() + 5, res.begin()));
}

If you just need the n nearest elements but not necessarily sorted, you can skip std::sort. Then complexity is linear in n.

I have skipped the initial copy part, because it's not always needed. Feel free to add it if you like.


Is it OK to use while ((line = r.readLine()) != null) construct?

Assignment inside a condition is ok in this case, as the assignment is surrounded by an extra pair of parentheses – the comparison is obviously != null, there is no chance that we wanted to type line == reader.readLine().

However, a for loop might actually be more elegant here:

for (String line = reader.readLine(); line != null; line = reader.readLine()) {
    doSomething(line);
}

Alternatively, we could do this which also restricts the scope of line as with the for-loop, and additionally eliminates unnecessary repetition:

while (true) {
    final String line = reader.readLine();
    if (line == null) break;

    doSomething(line);
}

I like this solution most because it doesn't mutate any variables.


My one comment is add a comment on exactly what it is doing.

Even after studying I am not 100% sure what it does (I would need some unit tests to feel I understood it).

What I think you are trying to achieve:

Convert \" into "
Convert \\\" into \"


You can remove the size parameter as arrays know their own size in Swift, and use the zip, map and reduce functions to perform the computation rather than the C-style for loop, which is now unavailable in the latest versions of Swift (as is i++):

func mac(a: [Float], b: [Float]) -> Float {
    return zip(a, b).map(*).reduce(0, +)
}

The zip function takes two arrays and makes a single array of tuples, with each tuple containing the nth element from each array.
The map function changes each element of the array with a user-supplied function. In this case, the multiplication operator is passed in, which multiplies each pair.
The reduce function performs the task of summing each result (starting at 0).


For the moment, I did not dive into the details of your implementation, but one thing is obvious:

When you find search, you return an integer value corresponding to its position.
When you do not find it, you return a string .

This adds a little complication as how to call (and test) your function. But if you replace the returned string by None, it will be easier to call your function:

# Let us use your working example
if jump_search_2(arr, 16):
   # print("Found !")
else:
   # print("Not Found")
   # This is more pythonic than:
   # elif (jump_search_2(arr, 16) == "Not Found")


The main optimization I can think of is precomputing the sets. If array1 has shape [m,n] and array2 is [q,p], the original code is creating a set 2*m*q times. You can get this down to m+q.

In addition, you could follow the Python style guide in terms of naming conventions and whitespace, which will help working together with other Python programmers. Also it's nice to loop over the data structure itself instead of over a range of indices.

This would result in for example:

import numpy as np

def intersection(array1, array2):
    intersection = np.empty([array1.shape[0], array2.shape[0]], dtype=np.int8)
    array2_sets = map(set, array2)
    for i,row1 in enumerate(array1):
        set1 = set(row1)
        for j, set2 in enumerate(array2_sets):
            intersection[i,j] = len(set1.intersection(set2))
    return intersection

If you can forget about "keeping it simple to understand" you could also convert your data to sparse matrices and take the matrix product, e.g.:

from scipy.sparse import csr_matrix

def intersection2(A, B, sparse=True):
    """The rows of A and B must contain unique, relatively
    small integers
    """
    assert min(A.shape[1], B.shape[1]) < 256  # to fit inside uint8
    z = max(A.max(), B.max()) + 1

    def sparsify(A):
        m, n = A.shape
        indptr = np.arange(0, m*n+1, n)
        data = np.ones(m*n, dtype=np.uint8)
        return csr_matrix((data, A.ravel(), indptr), shape=(m,z))

    intersection = sparsify(A) * sparsify(B).T
    return intersection if sparse else intersection.todense()


How to speed up drawing process of output from .tflite model

TL;DR
Introduce coroutines in your code.
Analysis
It is difficult to optimize a code, where multiple parts are missing, like:

what does getIndexOfMax do? Maybe this is the bottleneck
How do results look like? Arrays? Maps? HashMaps?

I found also some strange code parts, like:

Why results?.let {? This can be removed completely.
var pos: Int should be moved inside the inner loop and made a val

Suggestion
I have too little context and I'm not familiar with Android, so the only thing I can suggest is using coroutines. My Example:
suspend fun draw(canvas: Canvas) = coroutineScope {
    val rotated = sensorOrientation % 180 == 90
    var rotatedW = frameWidth;
    var rotatedH = frameHeight;
    if (rotated) {
        rotatedW = frameHeight
        rotatedH = frameWidth
    }

    val multiplier =
        min(
            canvas.height.toFloat() / rotatedH.toFloat(),
            canvas.width.toFloat() / rotatedW.toFloat()
        )
    val w = (rotatedW * multiplier).toInt()
    val h = (rotatedH * multiplier).toInt()

    val xw = w / 256f
    val xh = h / 256f
    val rectF = RectF()
    for (y in 0 until 256) {
        for (x in 0 until 256) {
            launch {   // <-----
                val pos = getIndexOfMax(results!![0][y][x])
                if (pos > 0) {
                    val vertical = y / 256f * h
                    val horizontal = x / 256f * w
                    rectF.left = horizontal - xw
                    rectF.top = vertical - xh
                    rectF.right = horizontal + xw
                    rectF.bottom = vertical + xh
                    canvas.drawRect(rectF, boxPaint)
                }
            }
        }
    }
}


Am I correct in saying this solution is O(nlog(n))?

Proof

Whenever there are nested loops,the complexity is measured by number of times inner most loop get executed.
Example

for (i = 1; i <=n; i ++) {
   for (j = 1; j <=i; j ++) {
      // some O(1) expressions
}

inner loop executed=1+2+3+4+...n=(n*(n+1))/2≈ n2.
Hence time complexity is O(n2).

In your case the inner loop is executed 2+3+4+..+n times≈n2.

Hence time complexity of your solution is  O(n2)

Your first approach in Java 7 can be improved by eliminating the inner loop.
Here is an approach which uses only one loop.

    array[1]=array[0]+array[1];
    int sum=array[0];
    int length=array.length;
    for(int i=2;i<length;i++)
    {
        array[i]+=array[i-1]+sum;
        sum+=array[i-1];//storing the sum up to i-1;
    }

Improvement

Eliminated the inner loop.
Added a new variable sum which keeps the summation of the numbers up to index i-2 when calculating array[i].
Time Complexity reduced from O(n2) to O(n).

Hope this helps.


Character Picture Grid (from Automate the Boring Stuff)

The question itself
It's not great. The textbook makes some decisions that haven't done the programmer any favours. First, you will notice that the input and output are mirrored about the line \$x=y\$. This is not a coincidence: it's the result of the textbook using column-major order when row-major order makes much more sense in this context.
Also, the grid presented is not only a sequence of sequences, it's a sequence of sequences of sequences since there are inner strings.
To solve both problems, ignore what the textbook tells you and instead attempt to code for this grid:
grid = (
    '..OO.OO..',
    # ...
)

and use [y][x] indexing instead of [x][y] indexing.
Such changes will reduce this to a much more trivial problem that does not require any explicit loops, and can be done via
print('\n'.join(grid))


Finding the balancing point of a subsequence

Without messing with your actual algorithm, right now it's effectively \$O(n^2)\$.

Creating the initial deque is \$O(n)\$
The while loop is essentially \$O(n)\$ (worst case)
Within the while loop you call equi with successively smaller lists \$k=(n, n-1, n-2, \dots, n-5)\$ and equi is \$O(k)\$ (worst case).

So the loop is \$O(n^2)\$ and dominates.

You can get some improvement in running time vs complexity though (maybe 20%) by fixing this line:

is_sequence = equi(list(equi_deque))

to be

is_sequence = equi(equi_deque)

The conversion to a list is unnecessary, and is an \$O(k)\$ operation.


The code looks fine to me. The only things I would personally change is the use of the live() method (which has been deprecated, and was slow anyway) todelegate() and the use of the :nth() selector, which again I believe is not very fast - although I've not specifically tested it. In place of that I'd use eq().

$('.modal-pagination').delegate('a', 'click', function(e) {
    e.preventDefault();
    var thePag = $(this).attr('id');
    $('.show-content').find('.page-me').hide().eq(thePag -1).show();
});


jQuery range slider change text based on hidden field value

First of all you can dramatically simplify your callback function body structure.
Instead of using a series of if (inputValue === ... you might define a simple array of your texts, like:

var texts = [
    'Terrible',
    'Poor',
    'Average',
    'Good',
    'Excellent'
];

Then the callback function entire body becomes as simple as:

// here the example of your first ratings() invocation
$('span#sliderOutput1').fadeOut(function() {
    $(this).text(texts[$('input#agent_score_quality').val() - 1]).fadeIn();
});

Now to avoid rewriting such a callback function for each of your rows, you can make it a named, independent function, then invoke it from your `setInterval() callback, with the needed information about involved row, so the whole JS part looks like this:

$(document).on("page:load ready", function() {

var texts = [
    'Terrible',
    'Poor',
    'Average',
    'Good',
    'Excellent'
];

  function ratings(selectorInput, selectorSlider) {
    var input = $(selectorInput);
    var slider = $(selectorSlider);
    var oldvalue = input.val();
    setInterval(function(){
      if (input.val()!= oldvalue){
        oldvalue = input.val();
        ratingsCallback(input, slider);
      }
    }, 100);
  }

  function ratingsCallback(input, slider) {
    $(slider).fadeOut(function() {
      $(this).text(texts[input.val() - 1]).fadeIn();
    });
  }

  ratings('input#agent_score_quality', 'span#sliderOutput1');
  ratings('input#agent_score_communication', 'span#sliderOutput2');
  // and so on...
});

Finally better solution

(but see also CAVEAT below)

Thanks to combined suggestions from @Chococroc comments and @Margus answer, this is a yet much more minified version of the code.

It only needs that each  element becomes .
Then the whole JS part can be reduced to:

$(document).on("page:load ready", function() {

  var texts = [
      'Terrible',
      'Poor',
      'Average',
      'Good',
      'Excellent'
  ];

  $('.row input').on('change', function() {
    var slider = $(this).closest('.row').find('.slider-output');
    slider.fadeOut(function() {
      slider.text(texts[input.val() - 1]).fadeIn();
    });
  }
});

Note that this solution only focuses on the initial question main issue. Beyond that, as noticed by @Chococroc, it could be enhanced in several ways, like:

allow strict independency between logics and presentation, by using
dedicated class names like js-slider-output, so CSS needs don't mix
with JS needs
ensure to avoid any potential conflict with other
class="row" elements in the whole context, by affecting a
supplemental class to each row, e.g.
,
so the change-event binding becomes $('.js-slider input')...

CAVEAT

Still focused on the main issue (how to reduce JS code) I didn't pay attention to a particular point in the given HTML example: here the source data for the range values resides in hidden elements.

So as pointed out by the OP author, in this case the change event will not fire when value changes.

So what?

from the fact that these elements are hidden, we can assert that the changes don't come from user action
then we can assume that some other JS part is involved to make this change to happen
so we should have the availability to add <this element>.change(); somewhere in this JS part

Hopefully not forgetting some other blocking point...


Here are some notes I made while reading your code.

For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.

Writing code is a process of stepwise refinement.

Start by looking at two similar methods.

go-angular/server/app.go:

func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    err := json.NewDecoder(r.Body).Decode(&s)
    s.ID = uuid.New().String()
    if err != nil {
        sendErr(w, http.StatusBadRequest, err.Error())
    } else {
        err = a.db.Save(&s).Error
        if err != nil {
            sendErr(w, http.StatusInternalServerError, err.Error())
        } else {
            w.WriteHeader(http.StatusCreated)
        }
    }
}

func (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, http.StatusBadRequest, err.Error())
    } else {
        s.ID = mux.Vars(r)["id"]
        err = a.db.Save(&s).Error
        if err != nil {
            sendErr(w, http.StatusInternalServerError, err.Error())
        }
    }
}

Write them in more readable form.

func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var s student
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, http.StatusBadRequest, err.Error())
        return
    }
    s.ID = uuid.New().String()
    err = a.db.Save(&s).Error
    if err != nil {
        sendErr(w, http.StatusInternalServerError, err.Error())
        return
    }
    w.WriteHeader(http.StatusCreated)
}

func (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var s student
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, http.StatusBadRequest, err.Error())
        return
    }
    s.ID = mux.Vars(r)["id"]
    err = a.db.Save(&s).Error
    if err != nil {
        sendErr(w, http.StatusInternalServerError, err.Error())
        return
    }
    w.WriteHeader(http.StatusOK)
}

Write more readable code.

  Go Code Review Comments: Indent Error
  Flow.

  Try to keep the normal code path at a minimal indentation, and indent
  the error handling, dealing with it first. This improves the
  readability of the code by permitting visually scanning the normal
  path quickly.

Use var to declare variables that are decoding targets. They have zero value(s).

var s student

Don't do things before they are necessary.

s.ID = uuid.New().String()

The s.ID value is discarded in addStudent if there is an error in decoding. Wait until it is needed, as you did in updateStudent.

In addStudent you returned a status.

w.WriteHeader(http.StatusCreated)

Return a status in updateStudent.

w.WriteHeader(http.StatusOK)

And so on.

Make sure that your app.go code is good before worrying about testing.


I think this class is largely fine as a display/view generation helper class, but worry about its broader utility.  Let me ask, if the PHP script in your usage example already owns the logic for the specific filename that it wants to include, shouldn't it also know the specific for the path to the file at this point already?  This HTML-rendering logic already knows know the most specific information about the asset that is to be included (the asset filename) but defers the more general information about the asset (its directory location) to the class.  That seems like an odd division of responsibility.  Additionally, your approach seems limited to only using asset files which are hosted on the same domain as the page being rendered, as I don't see how your solution supports full URL references.

Since you are going down the path of trying to dynamically inject what are basically config-driven values into this HTML template, I would suggest you truly decouple the configuration of included assets from the HTML template, perhaps striving more towards a solution like:

<html>
<head>
    <!-- Other HTML HEAD contents -->
<?php
// You could obviously use templating library as well,
// but raw PHP "spaghetti code" shown here for demonstration
foreach(Assets::getCssIncludes() as $url) {
?>
    <link rel="stylesheet" href="<?php echo $url; ?>">
<?php
}

foreach(Assets::getJsHeadIncludes() as $url) {
?>
    <script type="application/javascript" src="<?php echo $url; ?>"></script>
<?php
}
?>
</head>
<body>
    <!-- BODY content -->
<?php
foreach(Assets::getJsEndOfBodyIncludes() as $url) {
?>
    <script type="application/javascript" src="<?php echo $url; ?>"></script>
<?php
}
?>
</body>
</html>

With this sort of approach you can totally decouple your template from needing to have any hard-coded references to it's asset dependencies.  You could derive these from configuration and expose via "Assets" (or similar class).

This is advantageous as you begin to want to deploy different configurations of a page into different environments (i.e. dev, staging, production).  You could have production configured to inject the current stable production assets, while pre-prod environments can injects other assets versions or new assets that are not suitable or not yet deployed to production.


Comment by @T.C.:

Don't merge them; sort them separately and then use std::set_difference:

#include <algorithm>
#include <vector>
#include <iostream>
template <typename T>
void print(T& c)
{
 for(auto & element : c)
  std::cout << element << " ";

 std::cout << "\n";
}

int main()
{
 std::vector<int> vec {1,2,3,4,6,7,8};
 std::vector<int> vec4 {3,4,5,6};
 std::sort(vec.begin(), vec.end());
 std::sort(vec4.begin(), vec4.end());
std::set_difference(vec.begin(), vec.end(), vec4.begin(), vec4.end(), std::inserter(vec5, vec5.begin()));
 print(vec5);
}

Input: {1,2,3,4,6,7,8} and {3,4,5,6}
Output wanted: 1,2,5,7,8
Output real: 1,2,7,8

You cannot use std::set_difference because of the hashes used as comparison criteria. The Hash Distribution of new hashes is not sortable in a way that new items will be the last ones, which is a requirement for std::set_difference.


Optimization fo code snippet including multiple np.multipy statements

First a quick non-performance related mode: np.multiply could simply be replaced by * in your case since it's basically scalar x array. That would make the code less verbose.

xh = K_Rinv[0, 0] * x
xh += K_Rinv[0, 1] * y
xh += K_Rinv[0, 2] * h

My first intuition on your problem was that it lends itself to be rewritten as scalar product. See the following example:

import numpy as np

K_Rinv = np.random.rand(3, 3)

x = np.random.rand(4206, 5749)
y = np.random.rand(4206, 5749)
h = np.random.rand(4206, 5749)
xyh = np.stack((x, y, h))

xh_dot = np.dot(xyh, K_Rinv[0, :])

But it turns out, that this is 4x slower than what you have.

The "vectorized" version below still turns is about 1.5x slower than what you have for my toy dataset.

xh_vec = (xyh * K_Rinv[0, :]).sum(axis=2)

A quick check with np.allclose(...) does however confirm, that the results are indeed (numerically) equivalent.

You might see some improvement by putting your code into a separate function and apply the @jit(nopython=True) decorator from numba if that's an option. numba is a Just-in-Time compiler for Python code, and is also aware of some, but not all, numpy functions. For the simple test above, the time was a bit more than half than that without using numba. When measuring, take care to exclude the first run, since that's when the compilation takes place.

Unfortunately, I'm a little bit short on time at the moment to look into this further.


Haskell program with basic CLI parsing, file reading, and decoding file contents into specified types

First things first: great work on adding a type signature on every function. Now, let's see how we can improve the code.

Use interesting case first, others later
When we pattern match in a binding or in a case expression, it's often easier to start with the interesting case first and then handle the Error cases:
decodeTeacher :: PersonDecoder
decodeTeacher encoded =
  case lines of (name:dept:_) -> Just (Teacher name dept)
                _             -> Nothing
  where lines = splitOn "\n" encoded

decodeStudent :: PersonDecoder
decodeStudent encoded =
  case lines of (name:age:_) -> decodeStudentLines name age
                _            -> Nothing
  where lines = splitOn "\n" encoded

Check the standard library for already existing functionality
We stay at those functions. The name lines is very unfortunate, as there is already a lines in the Prelude. It's a function with the following signature:
lines :: String -> [String]

With that function, we can get rid of splitOn:
decodeTeacher :: PersonDecoder
decodeTeacher encoded =
  case lines encoded of
    (name:dept:_) -> Just (Teacher name dept)
    _             -> Nothing

decodeStudent :: PersonDecoder
decodeStudent encoded =
  case lines encoded of
    (name:age:_) -> decodeStudentLines name age
    _            -> Nothing

Prefer simpler logic where possible
Next, we have a look at parseArgsSuffix:
parseArgsSuffix :: CLIParser
parseArgsSuffix [] = Nothing
parseArgsSuffix (fname:_) =
  if hasSuffix fname "student" then Just (decodeStudent, openFile fname ReadMode)
  else if hasSuffix fname "teacher" then Just (decodeTeacher, openFile fname ReadMode)
  else Nothing

That's a rather long if expression. A guard may be easier to read and handle:
parseArgsSuffix :: CLIParser
parseArgsSuffix [] = Nothing
parseArgsSuffix (fname:_)
  | fname `hasSuffix` "student" = Just (decodeStudent, openFile fname ReadMode)
  | fname `hasSuffix` "teacher" = Just (decodeTeacher, openFile fname ReadMode)
  | otherwise                   = Nothing

Note that we should keep the uninteresting case here first, as it improves readability. However, we're repeating ourselves. Something along
parseArgsSuffix :: CLIParser
parseArgsSuffix [] = Nothing
parseArgsSuffix (fname:_)
  | fname `hasSuffix` "student" = decodeVia decodeStudent
  | fname `hasSuffix` "teacher" = decodeVia decodeTeacher
  | otherwise                   = Nothing
  where
    decodeVia f = Just (f, openFile fname ReadMode)

might reduce the duplication. Now, let's have a look at hasSuffix:
hasSuffix :: String -> String -> Bool
hasSuffix filename suffix = if length components == 0 || length components == 1
  then False
  else last components == suffix
  where
    components = splitOn "." filename

Again, splitOn is an overkill here. We only want to know if our filename ends with the given extension. The function isSuffixOf from Data.List handles that fine:
hasSuffix :: String -> String -> Bool
hasSuffix filename suffix = ('.' : suffix) `isSuffixOf` filename

We could probably even remove hasSuffix completely that way.

Make sure that functions are total
parseArgsFlag is partial. If we use parseArgsFlags on ["whoops!", "-t"], then none of the patterns match:
parseArgsFlag :: CLIParser
parseArgsFlag [] = Nothing
parseArgsFlag ("-t":_) = Just (decodeTeacher, wrapStdIn)
parseArgsFlag ("-s":_) = Just (decodeStudent, wrapStdIn)
parseArgsFlag ("--teacher":_) = parseArgsFlag ["-t"]
parseArgsFlag ("--student":_) = parseArgsFlag ["-s"]

If that is intended, then everything is fine. However, if you want to handle those cases, then add a match all pattern:
parseArgsFlag _               = Nothing

I would prefer something like this, by the way:
parseArgsFlag :: CLIParser
parseArgsFlag args
  | any (`elem` args) ["-t", "--teacher"] = Just (decodeTeacher, wrapStdIn)
  | any (`elem` args) ["-s", "--student"] = Just (decodeStudent, wrapStdIn)
  | otherwise                             = Nothing


"Multiplying" 2 lists of Strings together in Java 8

Method name

I agree with you, multiply() does sound a bit odd for lists of non-numbers... perhaps combine() or cartesianProduct() are arguably better names?

Lambdas

'Single-shot' lambda definitions does not require the use of { return ...; }:

.map( s1 -> list2.stream().map( s2 -> s1 + s2 ).collect( Collectors.toList() ) )

Actually, when you are mapping an element to a Collection, only to flatMap() it immediately afterwards, you can probably do without the inner collect():

return list1.stream()
            .flatMap( s1 -> list2.stream().map( s2 -> s1 + s2 ) )
            .collect( Collectors.toList() );


Subclassing Profile.Profile to use it as a context manager

An __exit__ method should analyze the exc_type parameter. If there really was an exception, the collected profile is most likely not representative, and should not be accumulated. At least provide an option for such behaviour.

Otherwise looks pretty good.


From the SendAsync docs:

  After calling SendAsync, you must wait for the e-mail transmission to
  complete before attempting to send another e-mail message using Send
  or SendAsync.

So no, this may not work properly. You need to register an event handler on the SmtpClient.SendCompleted event so that you know the message has sent successfully.

I'm going to be frank about this, the SmtpClient has an awful API. Your confusion is not your fault.

Your best bet would be to create a dictionary of recipients to use as a queue.

Send the first message and pass the dictionary key in as the token.
When the message completed event occurs, use the token to remove the recipient from the dictionary and send the next message.
Repeat until the queue is empty.

This is going to be a slow, fairly synchronous process, so you may want to spin up a background thread or task to run this on, if your program has other work to do while this is going on.

I really encourage you to thoroughly read through the documentation I linked to. It's an old part of the framework and not very user (or async) friendly.

Or forget all that and just use the newer SendMailAsync(MailMessage) method.

Just be sure to await the result.

    try
    {
        await client.SendMailAsync(mm);
    }

Which means that you'll need to modify the signature of your method to be compatible with async/await.


Project Euler problem 92 (sequences formed by the sum of squares of digits) in Haskell

Overall, your solution looks like a reasonable Haskell implementation of the question. Well done. I found some tiny bits to comment about anyway.

Separate algorithm from IO

Part of your algorithm is specified in the main function. To make it easier to play with it, it is better to do all computations in some other function, and only handle input/output in main. In your case:

solve :: Int -> Int
solve n = length $ filter chainTo89 $ [1..n - 1]

main = print (solve 1000000)

This allows us, for example, to call solve on various numbers in ghci, in tests, or in benchmarks.

benchmarks

Since you asked about algorithmic improvements, benchmarks are actually a good idea. To use the criterion benchmarking library, we add an import and replace the main function:

import Criterion.Main

-- code to benchmark

main = defaultMain
  [ bgroup "chain89"
    [ bench ("solve " ++ show n) $ whnf solve n
    | n <- [100000, 200000 .. 1000000]
    ]
  ]

This benchmarks the solve function on values below 1 million, in 100k steps. The question asks for 10 million, but i decided to run my benchmarks on the smaller inputs to get more rapid feedback. If you compile this to an executable (say, chain89), run it as chain89 --output chain89.html to produce a nich benchmark report in chain89.html. For your code as given, I get these numbers (in ms):

Looks more or less linear to me. Did you expect it to look linear? Maybe think about it a moment before reading on.

Linear?!

I didn't expect it to be linear, because we're duplicating the work in the recursive calls. You mentioned that caching the recursive results helped a lot, so I expected the complexity without caching to be clearly worse than linear, and to regain linear complexity by caching, as you would expect from a dynamic programming solution.

After seeing the benchmark results, I realized that for large numbers n, the result of sumSquareDigits n is always much smaller than n. To approximate the result after one step, consider this: if the input is n, it has k = log n / log 10 digits. In the worst case, these digits are all 9. Then the result is k * 9 * 9. For example, sumSquareDigits 999999 is only 486. So even if we multiply an already large input by 10, the result after the first step is not more than 81 bigger, which doesn't translate into too many additional recursive calls. There are additional recursive calls, so this is still slower than linear, but only very little, so we don't see it in the benchmark results.

Memoization for small inputs

We can memoize the result on small values, where small means that the values can occur after the first step. In other words, if we want to support inputs to n, we want to memoize the results for 1 to 81 * log n / log 10, because that's the biggest number we can see after the first step, see above.

Haskell supports an unusual approach to memoization: We can set up a lazy data structure which maps inputs to outputs, and in the initialization of each entry in the data structure, we access other entries. As long as we're never (directly or indirectly) accessing an entry from itself, the entries will be computed in an appropriate order.

Which data structure do we want here? We're going to use the consecutive numbers from 1 to (81 * log n / log 10) as inputs, so we probably want to use an array. We need to add an import, change chainTo89 to add the memoization and adapt solve to the new variant of chainTo89.

import Data.Array.IArray

-- other code here

makeChainTo89 :: Int -> (Int -> Bool)
makeChainTo89 n = compute where
  size = 81 * ceiling (log (fromIntegral n) / log 10)

  cache :: Array Int Bool
  cache = array (1, size) [(i, compute i) | i <- [1 .. size]]

  fetch x = cache ! x

  compute 89 = True
  compute 1 = False
  compute x = fetch (sumSquareDigits x)

solve :: Int -> Int
solve n = length $ filter chainTo89 $ [1 .. n - 1] where
  chainTo89 = makeChainTo89 n

I renamed chainTo89 to makeChainTo89 because makeChainTo89 n returns a function that computes the same values as the old chainTo89 when called with values that are less than or equal to n. The variable size holds the size of the memoization table and is computed as explained above. The cache is the memoization table itself. It contains an entry for all i between 1 and size, mapping i to compute i. The fetch function retrieves an entry from the memoization table, and the compute function does the actual work of computing the next element in the chain. Note that compute looks almost like the old chainTo89 except that it calls fetch instead of the calling itself recursively. But fetch will force a cache entry which contains a  call to compute in its thunk, so that the recursion structure is actually the same. Just when the same cache entry is forced again, the result is already there.

This only works if n is big enough (so we never move out of the table after moving into it) and if there are really no other cycles than the cycles involving 1 and 89. Here's how the benchmark results look like for this version of the code:

That's almost 60% faster.

Avoiding right-associative (++)

Your digits function appends an element to the right of an immutable linked list, which requires copying the whole list. Since the order of the digits is irrelevant for the reset of the algorithm, it would be better to prepend the found digit to the list. (Even if the order is relevant, it is better to first produce the reversed list of digits, and then reverse once).

This is the new digits function:

digits :: Int -> [Int]
digits 0 = []
digits x = x `mod` 10 : digits (x `div` 10)

It is another 35% faster:

More ideas

Some other low-level ideas for speeding this up further:

explore divMod or quotRem as an alternative to div and mod.
explore alternatives to (^ 2).

And one high-level idea:

avoid looping over all permutations of the same selection of digits.

Further improvements

Also check out Max Taldykin's answer for (impressive) additional improvements on top of what I propose in my answer.


I would highlight the following areas of possible improvements:

argument parsing: even though you have only 2 arguments to handle, using argparse would simplify the code and improve readability. It would also might make sense to have "url or studio ID" defined in a custom type, raising ArgumentTypeError if validation fails
HTML parsing: in general, parsing HTML with regexes or using str.count(), str.find() is considered a bad practice. Consider switching to an HTML parser like lxml or BeautifulSoup instead
HTTP requests: instead of using requests.get() every single time, initialize session = requests.Session() and re-use it using session.get(). This would make a positive and noticable impact on performance.

  if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase

And, see if you can improve on detecting 404 - would issuing .head() requests instead of .get() and checking .status_code work instead of downloading the whole page and checking for <!D in the HTML code.


It is customary to use lowercase names for variables and Capitalized names for classes, so I would rename Genders -> genders, and likewise the Models and Brands arrays too.

The if blocks are a bit tediously written. They would be better this way:

var genderFilter = $(this).attr('data-Gender');
if (genderFilter) {
    if (jQuery.inArray(genderFilter, genders) == -1) {
         // Element was not found, add it.
         genders.push(genderFilter);
    }
}

Btw, note that when you retrieve data-Gender="0" using .attr('data-Gender'), it's treated as the string "0", and in if ("0") { ... } it evaluates to true, so the genders array will have the values 0, 2, 1. Perhaps you might want to use .data('genders') instead, in which case the genders array will have the values 2, 1.

For models and brands, using .data('model') instead of .attr('data-Model') will give the same result, so I suggest using the simpler.

For genders, models, brands, you do essentially the same thing.
This calls for a helper function:

function addToArrayIfNew(arr, item) {
    if (item && jQuery.inArray(item, arr) == -1) {
        arr.push(item);
    }
}

With this, you could simplify the entire code like this:

$( ".mix" ).each(function() {
    addToArrayIfNew(genders, $(this).attr('data-Gender'));
    addToArrayIfNew(models, $(this).data('model'));
    addToArrayIfNew(brands, $(this).data('brand'));
});


So, based on your update it looks like you've switched to reading from Stream - good decision.

A bit simplified/cleaner approach for reading int is:

public static class ASN1Int
{
    public static int Read(Stream inputStream)
    {
        const int sizeMarker = 0x80; //TODO: name appropriately

        int size = inputStream.ReadByte();

        if (size < sizeMarker)
            return inputStream.ReadByte();

        size -= sizeMarker;
        //TODO: add assertion to make sure size<=4 if needed

        var result = inputStream.ReadByte();

        while (--size > 0)
            result = (result << 8) + inputStream.ReadByte();

        return result;
    }
}


A script that uses placeholder attribute to show a typing effect

Performance Considerations

As the code stands now, every time the type function is invoked (that is, every 80 milliseconds) the code will parse the DOM looking for any elements with the searchBox class.

You can improve the code's efficiency by moving that expensive operation outside the function.

var i = 0, ct = 0, searchBox = $(".searchBox"); obj.typeIt;

function type(){
    // ...
    searchBox.attr("placeholder", obj.typeIt);
    // ...
};

If you know there'll only be one element with the searchBox class, you could improve its efficiency a step further by using the native document.querySelector method.

var i = 0, ct = 0, searchBox = document.querySelector(".searchBox"); obj.typeIt;

function type(){
    // ...
    searchBox.setAttribute("placeholder", obj.typeIt);
    // ...
};

Timeout/Interval Overlap

This one's not a biggie, but it's good to be aware of when working with setTimeout and setInterval.

Your interval function is running every 10 seconds to invoke type, while within the type function a timeout is running every 80 milliseconds to invoke type again (until the end of the search text short circuits that behavior).

If the code happens to be in the middle of writing out some search text when the 10-interval kicks in, you'll see some unusual behavior: multiple characters will be written within 80 milliseconds.

For something like this, that's probably not a major issue (you'll only see it happen when the search text is abnormally long or the interval time is abnormally short), but if you want to account for it, you can eliminate setInterval altogether. Instead, you can put a 10-second timeout in the "dead end" branch of the type function (the if block that short-circuits the 80-ms timeout upon reaching the end of the search text), just before the return statement.

function type(){
    obj.typeIt = obj.searchTxt[ct].slice(0, ++i);
    if(obj.typeIt === obj.searchTxt[ct]){
        i = 0;
        if(ct === obj.searchTxt.length-1){
            ct = 0;
        }else{
            ++ct;
            /* This replaces the setInterval call later in your code: */
            setTimeout(function(){
                if(obj.hasFocus){
                    type();
                }
            },10000);
        }
        return;
    };
    $(".searchBox").attr("placeholder", obj.typeIt);
    setTimeout(type, 80);
};

This ensures that type is invoked every 80 milliseconds while typing out the search text, and then every 10-seconds between search texts.

Another option is to use the clearTimeout method to make sure you don't have duplicate timeouts for the same function call running in parallel.

// define a timeout variable
var i = 0, ct = 0, timeout; obj.typeIt;

function type(){
    // ...
     if(timeout){clearTimeout(timeout);} // eliminate duplicate timeouts
     timeout = setTimeout(type, 80);
}

This is useful if there are multiple entry points for the type function, such as if you were to invoke it from the window's onFocus event.


There are a bunch of things in here that @nanny has not yet covered, so let's go through some of those:

Java class names should be CamelCase. Your class scramble should be Scramble.
use whitespace in lines consistently, especially around keywords and operators. Lines like:

... wordList= new ....

should be:

... wordList = new ....

You have done this correctly in most places, so the places you have it wrong stand out....
There is no need, and it is now discouraged, for you to add the generic type to instance constructor calls. The generic type can be inferred from the target. i.e. your line:

ArrayList<String> scramblesList= new ArrayList<String>();

should be:

ArrayList<String> scramblesList = new ArrayList<>();

When possible, you should use the interface type for your variables, not the concrete type. For example, the line above should actually be:

List<String> scramblesList = new ArrayList<>();

No need to "type" variable names ... (hungarian notation). We know that scramblesList is a list, so there's no need for the List suffix on scramblesList, it should just be scrambles (good thing we renamed the class to Scramble to avoid confusion...).
1-liners are a maintenance problem. Sure, they look smart, and take less space, but the person maintaining your code in the furture will dislike you. This:

if (args.length < 2 ) die( "Must pass name of input files on cmd line." );

should be:

if (args.length < 2 ) {
    die( "Must pass name of input files on cmd line." );
}

while we are on it, you have successfully turned your Java semantics in to Perl... was that the intention? If so, there's better ways to handle problems like this... an IllegalArgumentException is the better/right solution.
try-with-resources is your friend, learn to use it: try-with-resources
Know your standard libraries... Java can do a lot of what you are doing in it's native libraries. Learn them....
use printf:

long endTime = System.currentTimeMillis();  // like clicking STOP on your stopwatch
long ms = endTime-startTime;
System.out.println("Elapsed time in seconds: " + ms/1000.0 + "\n");

can be:

long ms = System.currentTimeMillis() - startTime;
System.out.printf("Elapsed time in seconds: %.3f\n", ms / 1000.0);

Oh, and you have added a \n to a println which seems redundant.

Let Java work for you:

This code throws lots of potential exceptions which you don't handle... and there's a lot simpler ways to do things....:

   BufferedReader scrambles = new BufferedReader( new FileReader( args[1] ) );
    BufferedReader words = new BufferedReader ( new FileReader( args[0] ) );
    ArrayList<String> scramblesList= new ArrayList<String>();  // default initial capacity is 10
    ArrayList<String> wordList= new ArrayList<String>();

    long startTime = System.currentTimeMillis();  // like clicking START on your stopwatch

    while (scrambles.ready())
    {
         String scramble = scrambles.readLine();
         scramblesList.add( scramble );
     }

    Collections.sort( scramblesList );
    while (words.ready())
    {
        String word = words.readLine();
        dictionaryList.add( word );
    }
    Collections.sort( wordList );

The above code, excluding the sorts, and stopwatch, can be replaced with:

List<String> words = Files.readAllLines(Paths.get(args[0]));
List<String> scrambles = Files.readAllLines(Paths.get(args[1]));

As @nanny pointed out, the sorting is unnecessary.

Performance

Once you have your two word lists, the fastest way to match these things is to use a map...., a map of Lists....

Convert the words in to a Map<String,List<String>>:

    Map<String, List<String>> canonWords = new HashMap<>();

    for (String word : words) {
        String canon = toCanonical(word);
        if (!canonWords.containsKey(canon)) {
            canonWords.put(canon, new ArrayList<>());
        }
        canonWords.get(canon).add(word);
    }

Then, with canonWords, search for matches with scrambled words:

    for (String scram : scrambles) {
        String canon = toCanonical(scram);
        List<String> match = canonWords.get(canon);
        if (match != null) {
            System.out.printf("Scramble %s Matches words %s\n", scram, match.toString());
        }
    }