Personally, here is how I would do it. I think this is pretty straight-forward. I think it is also no less efficient than the other (longer, more complex) answer. The method Subarray is something I wrote before, I didn’t write it just for this.

/// <summary>Similar to <see cref="string.Substring(int,int)"/>, only for arrays. Returns a new
/// array containing <paramref name="length"/> items from the specified
/// <paramref name="startIndex"/> onwards.</summary>
public static T[] Subarray<T>(this T[] array, int startIndex, int length)
{
    if (array == null)
        throw new ArgumentNullException("array");
    if (startIndex < 0)
        throw new ArgumentOutOfRangeException("startIndex", "startIndex cannot be negative.");
    if (length < 0 || startIndex + length > array.Length)
        throw new ArgumentOutOfRangeException("length", "length cannot be negative or extend beyond the end of the array.");
    T[] result = new T[length];
    Array.Copy(array, startIndex, result, 0, length);
    return result;
}

public static IEnumerable<T[]> SearchPattern<T>(this IEnumerable<T> seq, params Func<T[], T, bool>[] matches)
{
    Contract.Requires(seq != null);
    Contract.Requires(matches != null);
    Contract.Requires(matches.Length > 0);

    // No need to create a new array if seq is already one
    var seqArray = seq as T[] ?? seq.ToArray();

    // Check every applicable position for the matching pattern
    for (int j = 0; j <= seqArray.Length - matches.Length; j++)
    {
        // If this position matches...
        if (Enumerable.Range(0, matches.Length).All(i =>
            matches[i](seqArray.Subarray(j, i), seqArray[i + j])))
        {
            // ... yield it
            yield return seqArray.Subarray(j, matches.Length);

            // and jump to the item after the match so we don’t get overlapping matches
            j += matches.Length - 1;
        }
    }
}


2 methods to parse the same pattern of line in a file

The first part could be merged, for sure.

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = line.split("=");
    splitLigneDeuxiemePartie = splitLigneDeuxiemePartie[1].split(",");

Wrap it in a method

public String[] extractSplitLigneDeuxiemePartieFromLine(String line){
    String[] splitLigneDeuxiemePartie = line.split("=");
    return splitLigneDeuxiemePartie[1].split(",");
}

and use it like so:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);
    Partition partTemp;
    List<Partition> partitionsBuild = new ArrayList<Partition>();

    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partTemp = new Partition();
        partTemp.setHostname(partStringTemp);
        partitionsBuild.add(partTemp);
    }
    topologie.setPartitions(partitionsBuild);
}

public void insertToplogieNatures(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);
    List<String> naturesBuild = new ArrayList<String>();

    for (String natureTemp : splitLigneDeuxiemePartie) {
        naturesBuild.add(natureTemp);
    }
    topologie.setNatures(naturesBuild);
}

For the rest, it's better to take a separate approach because these functions do different things.

Try Arrays.asList for the natures.

public void insertToplogieNatures(String line, Topologie topologie) {
    topologie.setNatures(
        Arrays.asList(extractSplitLigneDeuxiemePartieFromLine(line))
    );
}

For the partitions, you could perhaps simplify by making a new constructor for Partition that takes hostName as parameter:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);
    Partition partTemp;
    List<Partition> partitionsBuild = new ArrayList<Partition>();

    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partTemp = new Partition(partStringTemp);
        partitionsBuild.add(partTemp);
    }
    topologie.setPartitions(partitionsBuild);
}

Allowing you to remove storing to temporary local variable:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = extractSplitLigneDeuxiemePartieFromLine(line);

    List<Partition> partitionsBuild = new ArrayList<Partition>();
    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partitionsBuild.add(new Partition(partStringTemp));
    }
    topologie.setPartitions(partitionsBuild);
}

But now that you have only a single use of splitLigneDeuxiemePartie, you don't need to store that in a local variable either:

public void insertToplogiePartitions(String line, Topologie topologie) {
    List<Partition> partitionsBuild = new ArrayList<Partition>();
    for (String partStringTemp : extractSplitLigneDeuxiemePartieFromLine(line)) {
        partitionsBuild.add(new Partition(partStringTemp));
    }
    topologie.setPartitions(partitionsBuild);
}

Sometimes local stores help with clarification, and sometimes they don't. In this case, you have french variable names which I don't understand, and the local variable names don't help me understand your code, so I prefer the shortened form.

...

Although, if we're going to use a constructor which takes a hostName, you might as well label your temporary variable as such.

public void insertToplogiePartitions(String line, Topologie topologie) {
    List<Partition> partitionsBuild = new ArrayList<Partition>();
    for (String hostName : extractSplitLigneDeuxiemePartieFromLine(line)) {
        partitionsBuild.add(new Partition(hostName));
    }
    topologie.setPartitions(partitionsBuild);
}


I know you've found a solution you like for the final line of your code, but I'm a bit concerned with the overall performance and characteristics.of your code.

Oh, I do have an alternative to your compactness solution but I will keep that for a different, shorter answer.

Confusion of metaphors

filterEmptyLines filters the lines from dict.  filterComments does not.  It transforms them from possibly-commented lines into lines with no comments.  This may seem like a minor or pedantic point, but calling two different things by the same name can cause errors.  stripComments would be a better name, I think.

Overengineered and unsafe functions

None of your three functions are stack safe. Each one of them is recursive but none of them is tail-recursive.  This means that processing a large file could blow the stack.

Each one of them can be rewritten safely using combinator functions, which are usually more efficient than pattern matching and explicit recursion (and gives an extra bonus that I'll explain later).

filterComments

This is not tail recursive because it prepends the transformed x to the beginning of the list returned by xs.filterComments.  It could be rewritten with a tail-recursive inner helper function, but this function can be done much more simply as a map...

def filterComments(m: List[String]): List[String] =
  m map (_.takeWhile(c => c != '#').trim)

filterEmptyLines

Unsafe for the same reason as filterComments.  Can be written safely as

def filterEmptyLines(m: List[String]): List[String] =
  m filter (! _.isEmpty)

splitParameters

Same as the other two, but multiple recursive applications of ++ is even more expensive.  This can be rewritten safely as

def splitParameters(m: List[String]): List[String] =
  m flatMap (_.split("\\s*(=>|,|\\s)\\s*").map(_.trim))

Oh, what happened to .toList?  Why does that work without it?  The answer is that Scala's flatMap does an implicit conversion of the array to a list.  Google canBuildFrom if you want to learn something about Scala collection internals.

Over-specific types

Once those three functions are rewritten to use combinators rather than pattern matching, they don't need to take or return List[String].  They could take and return Seq[String].  This gives you more freedom abut what you pass in (could be List[String], could be some other Seq-based collection).  No performance penalty (the appropriate filter/map/flatmap of the actual type will be called) and much more flexibility.  OK, at the end you would have to convert the sequence back into a list (or whatever you want the final form to be), but this allows you delay that decision till it is important.  This is that extra bonus I mentioned before.

And I'm about to explain why using Seq - or possibly Iterator could give a big performance boost.

Multiple traversals and intermediate collections

getLines returns an iterator (a lazy, one-pass collection which only processes each element on demand).  But you immediately convert it to a list, reading the whole (potentially large) file into memory.  Then each transformation in turn creates an entirely new collection.  So you actually create 4 collections in a row, traversing the entire contents of the file 3 times (possibly 4 if there are no empty or comment-only lines).  But I'm pretty sure you only care about the final one.

Even if you always want to process the entire file, that's expensive (the bigger the file, the worse it gets).  And what if you only want to process the first n lines or process the file in chunks, not wasting memory on processed and not-yet-processed chunks?

There's a pretty simple solution which will give you all those options (but which doesn't force you to overcomplicate things just because you might want those options later).

Be lazy (use views, iterators or streams)
Don't keep a reference to any of the intermediate transformations.

Being Lazy

Option 1: List View

If you're sure you always want to read the whole file into a list, turn that list into a view.  When you apply map, filter' orflatMap` to a view, it doesn't process the whole collection yet.  It returns the original collection wrapped in a delayed transformation and only applies the transformation when you ask for the elements and only to the elements you ask for.  If you just apply another transformation to the new view, again, no processing is done, you just get a new view.  So if you apply all three functions to the view and only then ask for the results as a list, the original collection will only be traversed once, applying all three transformations to one element before proceeding to the next.

If you only take the first 10 lines from the final view, it will only process lines until it has 10 non-empty, non-comment-only lines.  The rest of the collection inside the view will remain untouched till you ask for it.

And none of the functions needs to know that laziness is happening, if they take and return Seq[String#, because a view is a Seq.  Bonus.

The drawback, compared to iterators, is that the entire original collection stays in memory until there is no reference to it and it can safely be garbage-collected.

Option 2: Iterators

getLines returns an iterator.  Why not stick with it.  map, filter and flatMap work the same with with iterators as with views.  So if your three functions take and return Iterator[String], it just works.

The bonus that 1) the whole file isn't even read until you ask for it all to be processed and 2) the original, pre-processed lines are definitely thrown away and garbage collected.

The danger is that you have to be very careful to only traverse each intermediate iterator once.  So don't keep any references around.

Option 3: Stream

You could convert the getLines iterator into a stream.  This has the lazy file-reading advantage of the iterator and doesn't have the touch-only-once limitation of iterators.  However, it's actually a touch trickier than with iterators to make sure you don't keep the whole file in memory.  Oh, and Stream is a Seq.

Whichever of the 3 options you choose, you can still have filterEmptyLines and friends take/return either Seq[String] or Iterator[String], because all Seq descendants have a toIterator method and vice versa.  So you can write them not to care about laziness or how you actually implement it.

Don't keep references (till you really need one)

For different reasons, you lose some of the benefits of laziness if you keep references to any of the intermediate collections (including the output of toDict).  With iterators, it's dangerous.  So

"test.txt".toDict().filterComments.filterEmptyLines.splitParameters

is batter than

val dict = "test.txt".toDict()
dict.filterComments.filterEmptyLines.splitParameters

(assuming the implicit class added)


C++ sum and averaging functions for arrays and argument sets

Different approach:

I'd use iterators and standard library. Using them it becomes really simple:

template <typename ForwardIt, typename T = typename std::iterator_traits<ForwardIt>::value_type>
T average(ForwardIt first, ForwardIt last, T initvalue = {}) //will be 0 for builtins
{
    auto distance = std::distance(first, last);
    auto result = std::accumulate(first, last, initvalue);

    return result / distance;
}

It is also possible to have a distance argument that will be defaulted to what std::distance() produces, but since my use cases are mostly bound to RandomAccessIterators, I don't care, since distance is constant time on random access iterators.

It can be noticed that iterators abstract container type, so they become really easy to use.

The code actually is part of my library. It is so ancient that I forgot it even exists.

As for sum, it is simply using std::accumulate().

Some more tips:

Standard library has type traits. They help to debug templates. The toolbox should try to provide them as well.

template <typename T>
struct is_floating_point_array :
                public std::false_type
{};

template <typename T, std::size_t size>
struct is_floating_point_array<T[size]> :
                public std::bool_constant<std::is_floating_point_v<T>>
{};

//one for std::array

Ironically, std::is_array<> won't work on instantiations of std::array, so I recommend writing your own. The above will not only provide easier debugging experience, but will also allow tagged dispatch or if constexpr opportunities. Even more, it will provide concept support, which will make metaprogramming even easier. I didn't directly inherit from std::bool_constant on the first phase since I favored readability to less code height, maybe I was wrong.

Iterators are essential part of standard library. I recommend using them at least in obvious cases. Currently using the code one needs to use std::size() or write one themselves. Pretty much everyone I know doesn't know about std::size(). std::begin() and std::end() (or their member counterparts) destroy opportunity for making the mistakes.


The arithmetic solution to this is relatively simple as we're talking modulo here:

return i % N;

This should produce the same results for your adjusted index.

When I ran a few calculations on the modulo operator through WolframAlpha, I got the following results:

for \$F(x) = x \mod 3\$

\$ 5 \mapsto 2 \$
\$ 4 \mapsto 1 \$
\$ 3 \mapsto 0 \$
\$ 2 \mapsto 2 \$
\$ 1 \mapsto 1 \$
\$ 0 \mapsto 0 \$
\$-1 \mapsto 2 \$
\$-2 \mapsto 1 \$
\$-3 \mapsto 0 \$

The pattern we see here is exactly what you describe.

@Schism pointed out that this behavior is only that of "mathematical modulo". It seems that some implementations are unfriendly in that regard. We can thus assume that we need to actually do the switching of negative numbers ourselves.

This leads to the following implementation:

if (i < 0) {
   //assuming the behavior described by Schism (-1 % 3 = -1)
   i = N + (i % N);
} else {
   i = i % n;
}

Unfortunately this is still implementation-dependent, so now we need to eliminate the sign in our modulo calculations to have the same behavior, regardless of implementation:

bool wasNegative = false;
if (i < 0) {
    wasNegative = true;
    i = -i; //there's definitely a bithack for this.
}
int offset = i % N;
return (wasNegative) ? (N - offset) : (offset);


Send message and wait for receive while using async/await and promises the proper way

The while (true) { await sleep(1); ... is potentially very computationally expensive. Yes, it'd be good to refactor it out if possible.
Response bug Your current implementation looks like it has a bug, or what could very easily become a bug. The inbox array is global, but each portInfo array item will push separate, undistinguished items to the inbox array. That is, each forEach iteration will create a port and open it immediately, and then whichever iteration whose sendAndReceive happens to run its timeout first after the data callback has pushed an item to the array will get the response. Here:
const response = await sendAndReceive(m, port);

Unless you have only a single portInfo, the response received is likely to correspond to a different iteration's m and port.
The easy way to fix this would be to declare a separate inbox array inside each iteration - but the whole approach there deserves some reworking, as you noticed.
Inside the innermost loop that calls sendAndReceive, you might construct Promises for each message being iterated over, and push their resolve function to an array. When the parser responds, if the array has a resolver function, shift it out and call it with the data:
portInfos.filter(pinfo => pinfo.manufacturer === 'FTDI')
    .forEach(portInfo => {
        const port = new SerialPort(portInfo.path).setEncoding('ascii');
        const parser = port.pipe(new ReadLine({
            delimiter: '\r\n',
            encoding: 'ascii',
        }));

        const resolves = [];
        parser.on('data', data => {
            if (resolves.length) {
                resolves.shift()(data);
            }
        });

        port.open();

        const serialMessage = api.createReadMessage(SERIAL);
        const batteryMessage = api.createReadMessage(BATTERY);
        for (const message of [serialMessage, batteryMessage]) {
            new Promise((resolve) => {
                port.write(message);
                resolves.push(resolve)
            })
                .then((response) => {
                    console.log(m.trim());
                    console.log(response);
                });
        }
    });

The promises are currently dangling, which is usually weird, but in this case, the promises will never reject. If parser might not be able to get a data for a given message, and it exposes an API for that (an error event, maybe?), it would be good to listen for that, so errors can be properly handled instead of ignored.
Note that the above approach calls port.write twice at once in a given iteration *once for each method), instead of waiting for the prior message Promise to resolve first - this will speed up your program a bit, since you're now waiting in parallel, not in serial. If you wanted to do something when both messages are received, you'd use Promise.all and pass into it an array of the Promises instead of using for..of. (If you have to wait in serial, you can await the resolution of each Promise inside the loop)

Other things I noticed:
for..await is only for async iterators While you're technically allowed to do
for await (const m of [serialMessage, batteryMessage]) {

it doesn't make sense to use for await, since the array there is just a plain array - it's not something that implements the async iterator interface. It'd be more appropriate to use just for (const m ...
Variable names m isn't so great as a variable name. message is significantly more informative.
Only use async when you need to return a Promise You do:
SerialPort.list()
  .then(async portInfos => {
    portInfos.filter(pinfo => pinfo.manufacturer === 'FTDI')
      .forEach(async portInfo => {

The .then's callback does not use await directly inside of it, nor does it need to return a Promise, so there's no need for the async keyword - it's just potentially confusing noise.


Compare / Join two object collections LINQ

This code seems to suffer from poor readability and maintainability. What does splitSmallLine[2] mean, and why do I care if it matches splitBigLine[1] (ponders the next developer to run into this code)? It's very easy to make mistakes in this code, so I think bringing some clarity into what you are actually selecting/comparing against will help.

Since I don't actually know what your files look like, or what the fields represent, let's just start here:

string[] small = new string[] {
    "Joe,Smith,22",
    "Sally,Jones,32"
};

string[] big = new string[] {
    "Smith,22,Joe",
    "Jones,34,Sally",
    "Doe,15,Jane"
};

We have two "files" that store people, but the fields aren't in the same place. The first thing you could do is bring meaning to your parsed rows, like so:

var smallFilePeople = from personLine in small
                      let personFields = personLine.Split(',')
                      select new
                      {
                          FirstName = personFields[0],
                          LastName = personFields[1],
                          Age = personFields[2]
                      };

var bigFilePeople = from personLine in big
                    let personFields = personLine.Split(',')
                    select new
                    {
                        FirstName = personFields[2],
                        LastName = personFields[0],
                        Age = personFields[1]
                    };

Now I know that I'm selecting people, and I have a single place to show what I'm actually pulling out of each indexed location. This makes writing a join query based on this very simple and easy to understand:

var joined = from smallFilePerson in smallFilePeople
             join bigFilePerson in bigFilePeople
                on new { smallFilePerson.FirstName, smallFilePerson.LastName } equals
                   new { bigFilePerson.FirstName, bigFilePerson.LastName }
             select new
             {
                 FirstName = smallFilePerson.FirstName,
                 LastName = smallFilePerson.LastName,
                 AgeInSmallFile = smallFilePerson.Age,
                 AgeInBigFile = bigFilePerson.Age
             };

This example is a bit more contrived than yours, but I'm sure you can see where this may help. I would also take this a step further and split out the query/parsing logic/joining into distinct functions. It's a good separation of concerns, and you may end up reusing the parsing for each file in other new ways.


Checking two text field for match and checking for null

Your indentation is a bit wonky.  Why is the first line indented?  Why isn't the stuff in the inner-else indented correctly?

There's no reason to println() our passcodes.  At the very least, we should be certain to wrap these in #if DEBUG so that they're taken out of the release build of our project.

I don't understand why we're dispatch_async-ing to the main thread.  Is this code not already being executed on the main thread?  If this isn't on the main thread, then okay... but now I have to ask how come the presentViewController calls aren't also being dispatched to the main thread?  Seems like dispatching to the main thread is unnecessary.

As for efficiency, I'm not sure there's a way to make your code execute any faster, however, there are some improvements we can make.

First of all, rather than checking if our string is equal to "", we should check its length.  If a text field has never had its text property set or become first responder, it's text property can actually be nil.  "" and nil are different.

But perhaps more importantly, our conditions are structure in such a way that it makes it difficult for the programmer to sort through everything that's going on.

Let's start by handling all of our failure conditions.

var errorDescription: String?

if !(count(self.passcodeText1.text) > 0) {
    errorDescription = "Pass code can not be blank."
} else if self.passcodeText1.text != self.passcodeText2.text {
    errorDescription = "Pass codes do not match."
}

if let message = errorDescription {
    // handle error condition
} else {
    // proceed
}

Now we've simplified things a bit, eh?

Finally, let's wait until the user dismisses the alert controller away before we change anything on the current controller.  This will make it more clear to the user what area is wrong.  And instead of just resigning first responder, let's make the first text field the first responder so it's ready for the user to start fixing the error.  Ready?

So, filling in the comments from the above snippet:

if let message = errorDescription {
    let action = UIAlertAction(title:"OK", stlye:.Default) {
        _ in
        passCodetext1.text = ""
        passCodetext2.text = ""
        passCodetext1.becomeFirstResponder()
    }

    let alertView = UIAlertController(title:"ALERT!!", message:message, preferredStyle:.Alert)
    alertView.addAction(UIAlertAction(title:"OK", style:.Default, handler: action))

    self.presentViewController(alertView, animated:true, completion:nil)
} else {
    self.performSegueWithIdentifier("setupTouchID", sender: self)
}

And as a final note, I'd recommend declaring all of your strings as constants in some file somewhere in your app where you store all of these.  Or perhaps better yet, make a .plist file in your project to store all these in.


Here are my notes that I would bring to the code review.

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "strings"
)

func AuthCodeReview(req *http.Request) bool { // why bool? why not error
    sHeader := strings.SplitN(req.Header.Get("authorization"), " ", 3) // 3 for fields after 0 & 1?
    if len(sHeader) == 0 || sHeader[0] == "" {                         // check index in range
        log.Print("Missing Authorization Header") // never Fatal!
        return false
    }
    if len(sHeader) > 1 { // why 1? why ignore 0? check index in range
        fmt.Printf("sHeader: ", sHeader[1])  // debug?
        devEnv := os.Getenv("authorization") // LookupEnv?
        if devEnv == sHeader[1] {
            fmt.Println("valid") // debug?
            return true
        }
    }
    fmt.Println("Not valid: " + sHeader[1]) // debug?
    return false
}

func Auth(req *http.Request) bool {
    sHeader := strings.SplitN(req.Header.Get("authorization"), " ", 2)
    if sHeader[0] != "" {
        fmt.Printf("sHeader: ", sHeader[1])
        devEnv := os.Getenv("authorization")
        if devEnv == sHeader[1] {
            fmt.Println("valid")
            return true
        } else {
            fmt.Println("Not valid: " + sHeader[1])
            return false
        }
    } else {
        log.Fatal("Missing Authorization Header")
        return false
    }
}

func main() {}

Playground: https://play.golang.org/p/_MwBV80vWx

  log.Fatal is equivalent to log.Print() followed by a call to
  os.Exit(1).

  os.Exit causes the current program to exit with the given status code.
  The program terminates immediately; deferred functions are not run.

Your program is running 100,000 client connections using goroutines. One connection has a problem, so you crash the program. We have 100,000 very upset customers. Handle errors and fail gracefully; return errors; don't panic or Exit.

See Errors.

fmt.Println("valid") // debug?

Your sysout is a massive clutter of messages. That may make sense for debugging, but it doesn't make sense for production. What is the purpose of this and similar statements.

fmt.Println("Not valid: " + sHeader[1]) // debug?

If this message is not for debugging, it should be logged (log not fmt).

  strings.SplitN The count determines the number of substrings to
  return: n > 0: at most n substrings; the last substring will be the
  unsplit remainder.

// 3 for fields after 0 & 1?
sHeader := strings.SplitN(req.Header.Get("authorization"), " ", 3)

If you are expecting two fields SplitN(2) will return the first field in index 0 and any remainder in index 1. SplitN(3) will return the first field in index 0, the second field in index 1 and any remainder in index 2. Having a remainder may or may not be valid.

Playground: https://play.golang.org/p/IQA8iqIdN5

sHeader[1] // why 1? why ignore 0?

You don't say what the format of req.Header.Get("authorization") is. What does sHeader[1] represent. Add a comment to define sHeader and sHeader[1].

I reorganized your code.

Don't write code as a heavily indented stream of consciousness. First, write the normal flow. The first step in a code review is to read and verify the normal flow, it should be obvious. Second, add exception handling. Third, add error handling. Sensibly minimize indentation.

See Indent Error Flow.

For example, a simple first draft,

func AuthFirstDraft(req *http.Request) error {
    // TODO: improve error detection and handling
    sHeader := strings.SplitN(req.Header.Get("authorization"), " ", 3)
    devEnv := os.Getenv("authorization")
    if len(sHeader) > 1 && devEnv == sHeader[1] {
        return nil
    }
    return fmt.Errorf("error")
}

Code review is an iterative process. If there are significant changes, open a new question with the revised code.


Efficiency

You currently perform three queries:

check if a user with that name exists
get salt for that username
check if user with that username and password exist

You can perform all these actions with one query:

SELECT salt, password FROM users WHERE username = :username LIMIT 1;

Then just hash the supplied password with the salt from the db, and compare the result to the password from the db. It might look something like this:

if (hash_equals($grabUser->fetch()['password'], $this->core->blueHash($password, $grabUser->fetch()['salt'])) {
    echo 'valid password';
}

Return Early

If you negate your if clauses, you can safe one level of nesting, which I think results in more readable code, because nesting decreases readability, and because it's clearer to what if clause the else clause belongs. Eg:

if(!($grabUser = $this->db->prepare($prefix.$type.$suffix)))
{
    return array(0,0);
}

$grabUser->bindParam(":username", $username, PDO::PARAM_STR);
$grabUser->execute();
if(count($grabUser->fetchColumn()) <= 0)
{
    return array(0,0);
}

Misc

it's unclear why you are returning an array. It seems to always contain [1, $userPassword]. Why do you need to return the password? And wouldn't it be easier to just return true or false instead of 1 or 0 inside an array? At least I would add a PHPDoc style comment explaining what is returned.
I would extract some of the code to its own function to increase readability and avoid duplication. eg you could have fetchFromUser($columnName, $username).
I don't know what password hashing you currently use, but I would think about switching to bcrypt. It's easier to use (you don't have to manage salts, etc), and is currently considered secure.


This is a highly readable style, and simple. You might be able to make a loop and run through the list in some fashion, but it's unlikely to actually lower complexity, just shift it around a bit.


First, note that this review is of general good coding practices for production code, and not all suggestions will be appropriate for the sphere of "competitive programming", in which I have no significant experience.

Some thoughts:

For readability, use whitespace consistently and more frequently. There should be whitespace (0) after control statements (if, while, for), around operators (+, %, ..), and before curly braces ({).

In Java, the convention is that open curly braces go on the same line, not on a newline.

Use final aggressively when variable declarations will not change to reduce cognitive load on readers.

AutoCloseable resources such as Scanner should be used in a try-with-resources block to ensure they get closed.

a and b are poor choices for variable names because they're meaningless. Variable names should describe the value they hold. You probably don't even need the intermediate variables.

Methods not intended for use outside their class should be private. Always prefer the most restrictive access you can reasonably apply.

In a real application, it would be highly preferable to having the reversed sum pushed back to the main() method to handle printing. This gives you flexibility, rather than pushing your output choice through your code - if you want to change later, it changes in fewer, higher-level places.

It might be nice to use the number of cases they provide you with.

Don't throw Exception ever - throw the most specific checked exception possible. Don't declare thrown checked exceptions if you don't actually throw them.

Your algorithm is much more complex than it needs to be. Lists are extraneous. The problem can be solved with math.

If you were to apply all the changes I suggested, your code might look more like:

import java.util.Scanner;

class Main {

    public static void main(final String[] args) {
        try (final Scanner sc = new Scanner(System.in)) {
            final int numberOfCases = sc.nextInt();
            for (int i = 0; i < numberOfCases; i++) {
                final int firstNumber = sc.nextInt();
                final int secondNumber = sc.nextInt();
                System.out.println(addReversedNumbers(firstNumber, secondNumber));
            }
        }
    }

    private static int addReversedNumbers(final int firstNumber, final int secondNumber) {
        return reverseNumber(reverseNumber(firstNumber) + reverseNumber(secondNumber));
    }

    private static int reverseNumber(final int number) {
        int numberToReverse = number;
        int reversedNumber = 0;

        while (numberToReverse > 0) {
            final int digit = numberToReverse % 10;
            numberToReverse /= 10;
            reversedNumber = 10 * reversedNumber + digit;
        }
        return reversedNumber;

    }

}


Reading in a file and performing string manipulation

This code looks a little wild. I'd tame it like this:

#include <algorithm> // for std::remove
#include <fstream>   // for std::ifstream
#include <string>    // for std::string and std::getline
#include <utility>   // for std::move
#include <vector>    // for std::vector

std::ifstream infile("thefile.txt");    // we don't really care where you got the name from

std::vector<std::string> names;

for (std::string line; std::getline(infile, line, ','); )
{
    line.erase(std::remove(line.begin(), line.end(), '"'), line.end());
    names.push_back(std::move(line));
}

// done

A few points to note:

Keep it simple. Don't overthink.
Use ready-made algorithms, don't reinvent wheels (std::remove removes values).
Include what you use (std::string, std::getline).
Use algorithms, don't hand-roll your own loops. (erase/remove)
Understand what algorithms can do for you (don't hand-write your own "erase"). Get familiar with the standard library.
Don't leak scopes. The line string is only needed within the loop, and no further.
Efficiency tip: You can move from the line string that you no longer need and save yourself a copy. Also, we process everything in one step; no need to loop repeatedly.

Furthermore, I suggest factoring this logic into a file:

std::vector<std::string> tokenize_file(std::string const & filename, char delimiter)
{
    std::vector<std::string> result;

    // ...

    return result;
}

Usage:

std::vector<std::string> names = tokenize_file("thefile.txt", ',');


Shopping cart program in Java with a text menu

Naming
I can't begin with another topic.
You use 2 different approaches to name your variables:

someName -> it's a camelCase
some_name -> it's a snake_case

Read this article to understand the difference
Java has own code style and you should use only camelCase for your variable name, class name, method name
I'll provide more examples about naming in Java.
Let's start with simple variable (not final, because final variable has own name convention)

someName - for variable (not final variable) name
someMethod - for method name
SomeClass - for class name

You may have final variable, it's commonly use in case when you need the property that will be general for all objects of the class and this property will not change.
private static int SOME_IMMUTABLE_VARIABLE = 10;

You need to fix names for your variables and methods:
remove_keychains -> removeKeyChains() // in the same manner for others


Performance of speech enhancement code for Android app

Performance

I cannot offer any mayor improvements, just some small things:

You should save results of a calculation or action instead of doing them over and over.

For example:

2*FastMath.PI: this is not dependent on the loop variables, just save it in a variable (same goes for 2*sigmaSqr.get(j).get(k) which you are doing three times for every loop; and NoisySignal[k] - mue.get(j).get(k) which you are doing twice). These duplicate calculations are quite hard to catch in your code. If you write the equations on paper, it becomes easier to spot.
mue.get(j).get(k): you are doing this three times. I don't know what mue is, but depending on the kind of list, it may be expensive (same goes for sigmaSqr.get(j).get(k))

You could also move the calculation of X_estimate inside the previous j loop:

for(int j = 0; j < Consts.NUM_OF_CLUSTERS; j++)
{
    Log_q[j]=FastMath.log(c.get(j)) + Log_h_second[j] - Log_h_final;
    q[j]=(FastMath.exp(Log_q[j]));// equation (10)

    Double temp_X_estimate = 0.0;
    for(int k = 0; k < Consts.SIZE_OF_SEMPELS_IN_CHUNCK; k++)
    {
        temp_X_estimate += (X_hat[j][k]*q[j]);
    }
    X_estimate[k]=temp_X_estimate;// equation (9)
}

It will save you running through the loop once, you can profile it to see if it is worth the loss in readability.

Readability

Code Structure

I would probably pull out the j==0 case in front of the loop. Keeping it in the loop is confusing and seems unnecessary.

Function calls do cause an overhead, but I would still consider extracting some of the code to separate functions (this would make profiling the code easier).

Additional variables also cause a slight overhead, but some of your expressions are quite long and hard to grasp. You might consider adding intermediate variables with an expressive name saving a temporary state of the calculation. An alternative would be to use newlines to present the expressions in a better way.

Variable Names

I don't think that your variable names are very expressive. I'm not that deep into the topic, but I would guess that at least some of them can be improved upon.

Also, just using case to differentiate names is quite confusing (f_X vs F_X).

Comments

I'm guessing that you have some kind of documentation to which your current comments refer. But without it, they are not that useful. It might be helpful to add this documentation (or a short excerpt) to the top.

Style

Please follow general style guidelines.

variable names start with a lowercase letter (this lets a reader easily see that it is a variable, not a class)
declare variables where they are used (tmp_log_h for example is declared outside the loop, even though it is not needed there)
use more spaces (for example, before and after ==, =, /, *, etc)
in Java, camelCase is usually used instead of underscores (you do this sometimes (eg maxVi or sumExp, but mostly you use underscores)

Misc

get rid of unnecessary brackets (for example (X_hat[j][k]*q[j]), tmp_R_samples = (f_X/F_X), or f_X = (...); especially in the last example, the expression already has enough parentheses without the extra once :) )


Search a unique list and search a larger list to set dictionary with keys of binary values

== with broadcasting is the most straightforward solution:

array_to_search = np.array(np.random.randint(0,5,(1,10))).ravel()
array_of_unique_values = np.unique(array_to_search)

# Creates the binary vectors
matches = array_of_unique_values[:, None] == array_to_search

# Converts to dict
output = dict(zip(array_of_unique_values, matches))

You can also set return_indices flag to True in np.unique and use these to create the table:

array_to_search = np.array(np.random.randint(0,5,(1,10))).ravel()
array_of_unique_values, indices = np.unique(array_to_search, return_inverse=True)
matches = np.zeros((array_of_unique_values.size, array_to_search.size), dtype=bool)
matches[indices, np.arange(array_to_search.size)] = True
output = dict(zip(array_of_unique_values, matches))


Value flipping is traditionally just done with a negation:
this.showAllOnlineFriends = !this.showAllOnlineFriends

That is a common, good practice way to do it. It is highly recognizable and easy to understand


Things that I would like to point out in your code:

Use of Strings

I see that you used Strings in defining the names of the parts for your burger like bread, and meat types. I suggest you use enums so as to regulate the possible types of bread, meat, and others that can be added to a meal, like so:

BreadType Enum

public enum BreadType {
    WHITE_BREAD("white bread");

    private String type;

    BreadType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return type;
    }
}

MeatType Enum

public enum MeatType {
    BEEF("beef"), VEAL("veal");

    private final String type;

    MeatType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return type;
    }
}

You can also use enums to store other properties too. This can be done for items like Supplements which have prices attached to them, drinks, and sides like so:

Supplement Enum

public enum Supplement implements FoodItem {
    TOMATOES("tomato", 0.99), BACON("bacon", 0.59), ONIONS("onion", 0.49),
    KETCHUP("ketchup", 0.29), COCKTAIL("cocktail", 0.29), CUCUMBERS("cucumbers", 0.29);

    private BigDecimal price;
    private String type;

    Supplement(String type, double price) {
        this.type = type;
        this.price = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }

    @Override
    public String toString() {
        return type;
    }

    public BigDecimal getPrice() {
        return price;
    }
}

Drink Enum

public enum Drink implements FoodItem{
    APPLE_JUICE("apple juice", 3.49);

    private final BigDecimal price;
    private final String name;

    Drink(String name, double price) {
        this.name = name;
        this.price = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }

    public BigDecimal getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return name;
    }
}

Side Enum

public enum Side implements FoodItem {
    FRIES("fries", 3.99);

    private final BigDecimal price;
    private final String name;

    Side(String name, double price) {
        this.name = name;
        this.price = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }

    public BigDecimal getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return name;
    }
}

You may have noticed the use of BigDecimals in prices part instead of double. The reason for this is that BigDecimal gives us a way to exactly represent numbers. More on this reason over here.

The Hamburger Meals

I take it you want to create different hamburger meals -- each meal having different items compared to that of the other meals. Here's what I did:

FoodItem interface

public interface FoodItem {
    BigDecimal getPrice();
}

You mentioned four "food items" in the problem: Hamburger, Fries, Supplement, and Drink. Assuming that each "food item" has a price, these classes should implement FoodItem. The reason for this is to ease the computation of the price in a hamburger meal. Speaking of hamburger meal, I also created a HamburgerMeal class:

HamburgerMeal class

public class HamburgerMeal {
    private final List<FoodItem> foodItems;
    private final List<Supplement> supplements;
    private final HamburgerMealType hamburgerMealType;

    public HamburgerMeal(HamburgerMealType hamburgerMealType) {
        this.foodItems = new ArrayList<FoodItem>();
        this.supplements = new ArrayList<Supplement>();
        this.hamburgerMealType = hamburgerMealType;
    }

    public BigDecimal getPrice(){
        BigDecimal resultingPrice = BigDecimal.ZERO;
        for(FoodItem foodItem : foodItems){
            resultingPrice = resultingPrice.add(foodItem.getPrice());
        }
        for(Supplement supplement : supplements){
            resultingPrice = resultingPrice.add(supplement.getPrice());
        }
        return resultingPrice;
    }

    public void addItem(FoodItem foodItem){
        foodItems.add(foodItem);
    }

    public void addSupplement(Supplement supplement) {
        checkIfAddingSupplementsIsStillAllowed();
        supplements.add(supplement);
    }

    private void checkIfAddingSupplementsIsStillAllowed() {
        if(supplements.size() == hamburgerMealType.getMaxNumberOfSupplements())
            throw new AdditionOfItemNotAllowedException("No more supplements can be added to " + hamburgerMealType);
    }

    @Override
    public String toString() {
        return hamburgerMealType + " burger meal";
    }
}

You may have noticed the variable HamburgerMealType having a property called maxNumberOfSupplements. That's because, it's also an Enum!

HamburgerMealType Enum

public enum HamburgerMealType {
    BASIC("basic", 4), BIO("bio", 6), DELUXE("deluxe", 0);

    private final String name;
    private final int maxNumberOfSupplements;

    HamburgerMealType(String name, int maxNumberOfSupplements) {
        this.name = name;
        this.maxNumberOfSupplements = maxNumberOfSupplements;
    }

    @Override
    public String toString() {
        return name;
    }

    public int getMaxNumberOfSupplements() {
        return maxNumberOfSupplements;
    }
}

This helps us keep track the main property of a MealType which is the maximum number of Supplements it can have.

You may have also noticed the use of AdditionOfItemNotAllowedException. Whenever you think something "illegal" can happen (which is adding a supplement into a meal that can't have supplements), it is best to catch them with Exceptions instead of just saying that it's "illegal". Here's the code for the said exception:

public class AdditionOfItemNotAllowedException extends IllegalArgumentException {
    public AdditionOfItemNotAllowedException(String message) {
        super(message);
    }
}

Lastly, we have the Hamburger class.

Hamburger class

public class Hamburger implements FoodItem {
    private final BigDecimal price;
    private final BreadType breadType;
    private final MeatType meatType;

    private Hamburger(Builder builder){
        this.price = builder.price;
        this.breadType = builder.breadType;
        this.meatType = builder.meatType;
    }

    public static class Builder{
        private final BigDecimal price;

        private BreadType breadType = BreadType.WHITE_BREAD;
        private MeatType meatType = MeatType.BEEF;

        public Builder(double price){
            this.price = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        }

        public Builder breadType(BreadType breadType){
            this.breadType = breadType;
            return this;
        }

        public Builder meatType(MeatType meatType){
            this.meatType = meatType;
            return this;
        }

        public Hamburger build(){
            return new Hamburger(this);
        }
    }

    public BigDecimal getPrice(){
        return price;
    }

    public BreadType getBreadType() {
        return breadType;
    }

    public MeatType getMeatType() {
        return meatType;
    }
}

I used the static builder pattern for this one since the Hamburger specs you mentioned have defaults for BreadType and MeatType. This is also to avoid passing three parameters into the constructor which may get confusing when you don't know which parameter comes first.

I end this answer with the main code I wrote:

Main class

public class Main {
    public static void main(String[] args){
        HamburgerMeal standardBurgerMeal = new HamburgerMeal(HamburgerMealType.BASIC);
        Hamburger hamburger = new Hamburger.Builder(5.99).build();
        standardBurgerMeal.addItem(hamburger);
        standardBurgerMeal.addSupplement(Supplement.TOMATOES);
        standardBurgerMeal.addSupplement(Supplement.BACON);
        standardBurgerMeal.addSupplement(Supplement.ONIONS);
        standardBurgerMeal.addSupplement(Supplement.KETCHUP);
        System.out.println(standardBurgerMeal + " price: " + standardBurgerMeal.getPrice());

        HamburgerMeal bioBurgerMeal = new HamburgerMeal(HamburgerMealType.BIO);
        Hamburger bioBurger = new Hamburger.Builder(6.99).meatType(MeatType.VEAL).build();
        bioBurgerMeal.addItem(bioBurger);
        bioBurgerMeal.addSupplement(Supplement.TOMATOES);
        bioBurgerMeal.addSupplement(Supplement.BACON);
        bioBurgerMeal.addSupplement(Supplement.ONIONS);
        bioBurgerMeal.addSupplement(Supplement.KETCHUP);
        bioBurgerMeal.addSupplement(Supplement.COCKTAIL);
        bioBurgerMeal.addSupplement(Supplement.CUCUMBERS);
        System.out.println(bioBurgerMeal + " price: " + bioBurgerMeal.getPrice());

        HamburgerMeal deluxeBurgerMeal = new HamburgerMeal(HamburgerMealType.DELUXE);
        Hamburger deluxeBurger = new Hamburger.Builder(7.99).build();
        deluxeBurgerMeal.addItem(deluxeBurger);
        deluxeBurgerMeal.addItem(Drink.APPLE_JUICE);
        deluxeBurgerMeal.addItem(Side.FRIES);
        System.out.println(deluxeBurgerMeal + " price: " + deluxeBurgerMeal.getPrice());
    }
}

I apologize if my explanation is confusing. This is pretty much the first long answer I posted ever lol.


Class Object to create objects of type Object, in a dynamic way, with magic methods

As pointed out before, in a comment, non-magic methods in a class shouldn't be prefixed with __.

Since they are private, they are prefixed with _.

Closures are a really nice feature that came with PHP5.3, and they weren't being used to their full potential.

Closures have the method bindTo, which generates a new Closure binded to that object.
This allows to use the variable $this inside the Closure.
It helps the fellow programmers that decide to use this to write in a more natural way.
The best part is that there are no kludges needed!

The method _run_magic_method() will look like this:

    private function _run_magic_method( $method, $args=null )
    {
        $obj = (object)$this->props;

        if( is_a( $this->methods[$method], 'Closure' ) )
        {
            $return = call_user_func_array( $this->methods[$method]->bindTo( $obj ), (array)$args );
        }
        else
        {
            $return = call_user_func_array( $this->methods[$method], array_merge( array(&$obj), (array)$args ) );
        }
        $this->props = (array)$obj;
        return $return;
    }

Since objects are passed as references in PHP5, all changes are reflected on the properties.

The final code:

<?php

    class Object {
        private $props = array();
        private $methods = array(
            '__construct'=>null,
            '__get'=>null,
            '__set'=>null,
            '__isset'=>null,
            '__unset'=>null,
            '__toString'=>null
        );
        private function _run_magic_method( $method, $args=null )
        {
            $obj = (object)$this->props;

            if( is_a( $this->methods[$method], 'Closure' ) )
            {
                //Inside the closure, the $this will be changing the parent $this->props
                $return = call_user_func_array( $this->methods[$method]->bindTo( $obj ), (array)$args );
            }
            else
            {
                $return = call_user_func_array( $this->methods[$method], array_merge( array( &$obj ), (array)$args ) );
            }

            $this->props = (array)$obj;
            return $return;
        }
        private function _has_magic_method( $method )
        {
            return isset( $this->methods[$method] ) && is_callable( $this->methods[$method] );
        }
        function __construct( array $props )
        {
            foreach( array_keys( $this->methods ) as $method )
            {
                if( isset( $props[$method] ) )
                {
                    $this->methods[$method] = $props[$method];
                    unset( $props[$method] );
                }
            }
            $this->props = $props;
            if( $this->_has_magic_method( '__construct' ) )
            {
                $this->_run_magic_method( '__construct' );
            }
        }
        function __get( $key )
        {
            if($this->_has_magic_method('__get' ) )
            {
                return $this->_run_magic_method( '__get', array($key) );
            }
            else
            {
                return $this->props[$key];
            }
        }
        function __set( $key, $value )
        {
            if( $this->_has_magic_method( '__set' ) )
            {
                $this->_run_magic_method( '__set', array( $key, $value ) );
            }
            else
            {
                $this->props[$key] = $value;
            }
        }
        function __isset( $key )
        {
            if( $this->_has_magic_method( '__isset' ) )
            {
                return $this->_run_magic_method( '__isset', array($key) );
            }
            else
            {
                return isset( $this->props[$key] );
            }
        }
        function __unset( $key )
        {
            if( $this->_has_magic_method( '__unset' ) )
            {
                return $this->_run_magic_method( '__unset', array($key) );
            }
            else
            {
                unset( $this->props[$key] );
            }
        }
        function __call( $key, $args )
        {
            if( isset( $this->props[$key] ) && is_callable( $this->props[$key] ) )
            {
                return call_user_func_array( $this->props[$key], $args );
            }
            else
            {
                trigger_error( 'The key "'.addslashes($key).'" is not a callable', E_USER_ERROR );
            }
        }
        function __toString( )
        {
            if( $this->_has_magic_method( '__toString' ) )
            {
                return $this->_run_magic_method( '__toString' ) . '';
            }
            else
            {
                trigger_error( 'There is no defined __toString method', E_USER_ERROR );
            }
        }
        private function _keys()
        {
            return array_keys( $this->props );
        }
        static function keys( Object $obj=null )
        {
            if( $obj === null )
            {
                return array();
            }
            else
            {
                return $obj->_keys();
            }
        }
    }

Example of execution:

$obj = new Object(array(
    'a'=>5,
    '__get'=>function($k){
        echo 'Getting the value from the key \'',$k,'\'', PHP_EOL;
        return $this->{$k};
    },
    '__set'=>function($k,$v){
        echo 'Setting a value on the key \'',$k,'\'', PHP_EOL;
        $this->{$k}=$v;
    }
));

/*
 *Should output:
 *
 * Getting the value from the key 'a'
 * 5
 * Setting a value on the key 'b'
 * Getting the value from the key 'b'
 * 6
 *
 */


Can I make my render method more efficient?

Sometimes, the correct answer really is "Nope; it's all good."  It makes for a boring answer, but there it is.  It doesn't look like you can make this much faster, based on what you've provided.

One thing you might consider is checking the variables to see if the image manipulations are actually needed before calling the respective methods.  So, for example, something like...

graphics.setTransform((AffineTransform) defaultTransform.clone());
if(rotation != 0.0) {
    graphics.rotate(rotation, center.x, center.y);
}
if(scale.x != img.getWidth() || scale.y != img.getHeight()) {
    graphics.scale(scale.x, scale.y);
}
//...

This might give you a bit of performance where you don't need to bother going down into the rotate() and scale() methods.

Also, is there any way you can get rid of that (AffineTransform) cast?  Probably not, but that would speed you up ever so slightly.


Small BM25+ implementation for probibalistic result ranking

You should use built-ins to simplify the code:

def containing_term(term)
  total = 0
  @docs.each do |doc|
    total += 1 if doc.include?(term)
   end
 total
end

Becomes:

def containing_term(term)
  @docs.count {|doc| doc.include?(term) }
end

And

def avg_dl
  doc_lengths = 0
  @docs.each do |doc|
    doc_lengths += doc.length
  end
  doc_lengths / total_docs
end

Becomes:

def avg_dl
  @docs.map(&:length).inject(:+) / total_docs
end

You are close to immutable,  make the last step

In Collection you use sort!, disallowing method chaining, sort and returning a new object would be more expected.

Use a Hash for an easy but massive optimization

The method:

def term_freq(term)
   # Will need something better here to clean out the document.
   # This is temporary ;)
  @body.gsub(/[^\s\p{Alnum}\p{Han}\p{Katakana}\p{Hiragana}\p{Hangul}]/,'')
   .downcase
   .split
   .count(term)
end

Should be a Hash lookup, where the Hash is created at init time, time complexity would become O(1) with an Hash instead of O(n).


Are you getting the correct output with the recommended complexity? It's been a long time since I've written my own sort but start by confirming that before any of my recommendations below.

I suspect str.split(" ") is causing problems for you because you're creating lots of strings which you're about to parse and then throw away. How about parsing the integers directly from str in a single pass instead?

Try changing sb.append(currentMinValue + " ") to sb.append(currentMinValue).append(" "). It might be a small optimization but it's easy to do.

How about splitting your main into two methods? The first for everything that uses reader, the second for everything that uses sb. Besides improving the structure of the program this provides a natural point for garbage collection.

What command-line args are you giving to the JVM? Since you know your memory limit try allocating it all at the start to save time allocating more memory later. You might also play with different garbage collection strategies. As you're discovering, forcing garbage collection isn't a good idea. If you're correctly setting the maximum in the JVM it should automatically garbage collect as needed to prevent running out of memory.

Hope at least one of these suggestions helps. I'm curious what gives the biggest improvement.


Regular expression to get a string between two strings where the last string can also be 'end of string'

URLSearchParams would make things significantly easier:

const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';
const query2 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue&someMoreParam=dummy_value2';

const params1 = new URLSearchParams(query1);
const params2 = new URLSearchParams(query2);

console.log(`For Query1: result = ${params1.get('requiredParam')}`);
console.log(`For Query2: result = ${params2.get('requiredParam')}`);

It's supported natively in the vast majority of browsers, but not all. For the rest, here's a polyfill. It's better not to re-invent the wheel when you don't need to, and it's good when you're able to use a standard API (with examples and documentation and Stack Overflow answers about it, etc).
As a side note - when using regular expressions, I'd recommend using capture groups only when necessary. If all you need to do is group some tokens together logically (like for a | alternation), non-capturing groups should be preferred. That is, if URLSearchParams didn't exist, better to do (?:&|$) than (&|$). Reserve capturing groups for when you need to save and use the captured result somewhere - otherwise, non-capturing groups are more appropriate, less expensive, and require less cognitive overhead.
If you had to go the regex route, another slight improvement would be to use a negative character class instead of lazy repetition. In the pattern, you have:
(.*?)(&|$)

Lazy repetition is slow; it forces the engine to advance one character at a time, then check the rest of the pattern for a match, and repeat until the match is found. Since you know that the capture group will not contain any &s, better to match anything but &s:
([^&]*)

Once you do that, you don't even need the final (&|$) or (?:&|$) due to the greedy repetition.


Using atom to reference state in Clojure

No, you probably don't want to store an atom in the record.  You probably want:

(defn get-current-frame [frame]
  (nth (:frames frame) (:id frame)))

(defn update-current-frame [frame active]
  (assoc frame :id active))

(def f (Frames. [:a :b :c :d :e :f :g] 0))

Then

> (get-current-frame f)
:a
> (get-current-frame (update-current-frame f 4))
:e

If you feel the need to have an atom:

brain.core> (def f (atom (Frames. [:a :b :c :d :e :f :g] 0)))
#'brain.core/f
brain.core> (get-current-frame @f)
:a
brain.core> (swap! f update-current-frame 4)
#brain.core.Frames{:frames [:a :b :c :d :e :f :g], :id 4}
brain.core> (get-current-frame @f)
:e


There was no way I could get the bitmap to the class where I need to upload it to the server so for the sake of organization and code cleanliness I created this

This is pretty concerning to me as it implies that your object model and dependency graph might be a little wonky, but as that's likely a lot more complicated than the question immediately at hand, I'd like to make the same suggestion as Eric Stein: use an existing cache library. Guava would likely be a good place to start. It has crazy flexible cache capabilities.

Even if you don't use a preexisting cache, a proper caching class that gets instantiated and injected would ease testing concerns, make thread safety easier to reason about, loosen coupling, and just all around be better.

Here are the current (obvious) limitations you have:

What if you want to store more than 1 bitmap?
What if you want to have more than 1 cache?
Have you considered the thread safety aspect of this? References are atomic on the JVM, but I'm not actually sure if this is threadsafe in the sense of up to date observation. It's possible that a thread could get a coherent, but out of date read.
Unit testing this could get a bit nasty.

Luckily since the class is so simple, it wouldn't be too bad, but it would be strange that your tests for a consumer of this class would essentially have to rely on the implementation of ImageCacheUtils.
If you had concurrent unit tests, thread safety is once again a concern.

Given all this though, I think you've already mentioned your main limitation: you have no control at all over the life time of the object in your cache. You're basically subjected to the whims of the garbage collector, and to me, that would be a little scary. Getting null may be an almost unthinkable edge case now, but what happens when you change Java versions? What happens if you run it on a server that's running low on memory?

In short, the little cache-like-thing that you've made is a clean, simple enough implementation of what little it does, but I'm afraid that a proper cache might do a lot more than as appears on the surface.

Caching is crazy complicated, and if you continue down this path, you'll likely realize that this isn't sufficient for your true requirements (though I'm still skeptical that this is the most proper solution).


Async Check for Domain Fullname With WPF and Caliburn.Micro

I'll start off by saying I don't have Caliburn.Micro experience but do have other MVVM experience.

I'm going to assume the ShellView is the shell for your entire application.  I don't know what other code that is running but I can tell you as a user I would not want to fire off your application and wait for over 10 seconds, because we are waiting for 10 seconds plus the time it takes for the other calls to come back, to be able to use the application.  Worst yet is even if the screen hasn't shown.  Then I'm likely to fire it off multiple times thinking it stuck or I didn't double click it.

In general it's not best practice to do async void, so I would question why Task.Delay instead of Thread.Sleep since the delay is the only async code.

If we are leaving it as async it should be wrapped in a try/catch otherwise if there is an exception you will need to handle it in Application.DispatcherUnhandledException or AppDomain.UnhandledException.  Which brings up a point if there is an exception I assume you want just Failed as the user name?

Now to a different idea.  You could remove this from startup, or try once to get it in startup,  Then setup a timer to recheck if it failed.  The application state could be based on if it has a name yet or not.  For Example:  The user can start entering data but can't save it until we retrieved the AD user.

If just want to wait until there is user name or not it still better to give the user an idea what's going on so they can see the application isn't just hung and that's it's checking network activity.  Create an initial view of just gather application information and part of that is gathering network user information.


Multi-threaded concepts are complicated at times. If you really want to learn multi-threading, it is important to get it right. Some things can be extremely difficult to get right. I can highly recommend reading Java Concurrency in Practice.

Overall

It is not that often I see "multi-threaded code" without a single synchronized keyword, or a single use of an atomic variable or concurrent data structure. I suggest you read up on all three of those to better understand what you will have to deal with sooner or later.

I think that you are adding a lot of overhead with the way you are constructing your tasks, that it will remove any benefits you get by running it multi-threaded. Creating all the lists that you use simply takes more time than actually running the code.

It is also important to consider that you are using System.out.println, this is a synchronized call, which means that only a single thread can only run it a time. This tends to be a big concurrency bottle-neck in a lot of multi-threaded code. As your task(s) seems to only be to use System.out.println, I think your code would be better of as single-threaded.

Oops, missed some!

In your current code, it does not run the print method for the last x items in the list. There already, it is broken.

If you have 1024 items and use a "block" value of 100, 24 items will be missed. (Hint: What is the value of your cursor variable after your for-loop to start the tasks is finished?)

Singleton mindset

This code:

public static HashSet<Task> tasks = new HashSet<Task>();

By making it public static it seems like you are in the "singleton mindset". Avoid this. This has no business being either public or static. Imagine if some code somewhere at some point would call tasks.clear(); - That could break a lot.

This field is also a big memory leak. You are only adding tasks to it, you are not removing any tasks.

Extending for no reason

You are extending the MultiThreaded class, but all methods and fields in that class are static. Extending it has no real effect besides giving you quick-access to the methods and variables, by not having to write MultiThreaded. each time. This is a bad reason for extending a class.

getTask

Your public static Task getTask(int id) method, although it is not used, suggests that you are using the wrong data-structure. You could use a Map<Integer, Task> which will make the getTask lookup much more efficient (from \$O(n)\$ to \$O(1)\$).  As you are dealing with multi-threading, better make it a ConcurrentMap as well. You should however ask yourself if you really need this in the first place.

Are we working? Are we working? Are we, are we, are we?

This code:

while(MultiThreaded.processing()) { continue; }

Is a busy-loop. This code will run as quickly as possible and waste CPU power for you. Running this will essentially remove any benefits you get by using multi-threading in the first place. You should check into the wait-notify construct. This can be compared to three kids in the backseat of your car constantly asking you "Are we there yet? Are we there yet? Are we, are we, are we?", I bet you can drive better without such a distraction. (No offense intended against kids)

This busy-loop does not get better by the fact that your processing() method is an inefficient way to check if any task is still working. Use Atomic variables to keep track of the number of running tasks.

The wheel...

Java 8 provides the concept of parallel streams which significantly makes this easier.

Your main method can be replaced with this:

List<TestObject> values = new ArrayList<TestObject>();
for (int i = 1; i < COUNT; i++)
    values.add(new TestObject(String.valueOf(i)));
values.parallelStream().forEach(o -> o.print());
System.out.println("move on");


VLookup simulation: copying data from one sheet to another

This was an interesting challenge - improve performance of arrays

But first, to cover the basics:

Option Explicit is missing - this statement fixes the most basic syntax issues
The range references are good overall, but lengthy and repetitive

The only one missing is on the 6th line Rows(... which deletes rows from active sheet

Indentation is inconsistent, and missing at the first level (Sub - End Sub)
The first loop doesn't work properly, and every execution it deletes the last row with data

For 10 rows i=11, but the .End(xlUp).Row is 10, and becomes Rows("11:10").Delete

'Delete Rows with no content
 Dim i As Integer
 i = 0
 Do
   i = i + 1
 Loop While Range("A" & i) <> ""
 Rows(i & ":" & Worksheets("All Time SMS Dump").Range("A" & Rows.Count).End(xlUp).Row).Delete (xlShiftUp)

In all For loops you have For i = 2 To... & For j = 2 To... then compare i - 1 = j - 1

Assigning .Range("D2:D" & LastRowSF) to array, first item in the array is D2 (index 1)

The main Sub defaults to public, but the Public keyword should be explicit

Most subs and functions should be made Private to modules unless they are utilities

On to Performance

I'm providing 3 versions for comparison (v1 - is your version with three For loops)

v2 - Code cleanup and optimization (three For loops)
v3 - Improve performance - change algorithm (one For loop)
v4 - Arrays and a dictionary (one For loop)

v2 - Code cleanup and optimization (three For loops)

Public Sub VinLookUpArr1()
    Dim wsAT As Worksheet, wsSF As Worksheet, valAT As Variant, valSF As Variant
    Dim lrAT As Long, lrSF As Long, vinAT As Variant, vinSF As Variant, t As Double

    t = Timer
    Set wsAT = ThisWorkbook.Worksheets("All Time SMS Dump")
    Set wsSF = ThisWorkbook.Worksheets("Salesforce Dump")

    lrAT = wsAT.Range("A" & Rows.Count).End(xlUp).Row
    lrSF = wsSF.Range("A" & Rows.Count).End(xlUp).Row

    vinAT = wsAT.Range("A2:A" & lrAT)
    vinSF = wsSF.Range("C2:C" & lrSF)

    wsAT.Rows(wsAT.Rows(1).End(xlDown).Row + 1 & ":" & lrAT + 1).Delete xlShiftUp
    wsSF.Rows(wsSF.Rows(1).End(xlDown).Row + 1 & ":" & lrSF + 1).Delete xlShiftUp
    wsAT.Columns("G:H").NumberFormat = "General"

    valAT = wsAT.Range("G2:G" & lrAT)
    valSF = wsSF.Range("D2:D" & lrSF)
    wsAT.Range("G2:G" & lrAT) = DoLookUpArr1(vinAT, vinSF, valAT, valSF)
    valAT = wsAT.Range("H2:H" & lrAT)
    valSF = wsSF.Range("E2:E" & lrSF)
    wsAT.Range("H2:H" & lrAT) = DoLookUpArr1(vinAT, vinSF, valAT, valSF)
    valAT = wsAT.Range("I2:I" & lrAT)
    valSF = wsSF.Range("F2:F" & lrSF)
    wsAT.Range("I2:I" & lrAT) = DoLookUpArr1(vinAT, vinSF, valAT, valSF)
    Debug.Print "lrAT: " & lrAT & "; lrSF: " & lrSF & "; Time: " & Format(Timer - t, "0.000")
End Sub

Private Function DoLookUpArr1(ByVal vinAT As Variant, ByVal vinSF As Variant, _
                              ByVal valAT As Variant, ByVal valSF As Variant) As Variant

    Dim rAT As Long, rSF As Long, lrSF As Long

    lrSF = UBound(valSF)
    For rAT = 1 To UBound(valAT)
        For rSF = 1 To lrSF
            If vinAT(rAT, 1) = vinSF(rSF, 1) Then
                valAT(rAT, 1) = valSF(rSF, 1)
                Exit For
            End If
        Next rSF
    Next rAT
    DoLookUpArr1 = valAT
End Function

v3 - Improve performance - change algorithm (one For loop)

This loops only once for all vLookups:

Public Sub VinLookUpArr2()
    Dim wsAT As Worksheet, wsSF As Worksheet, urAT As Variant, urSF As Variant
    Dim lrAT As Long, lrSF As Long, lcAT As Long, lcSF As Long, t As Double
    Dim rAT As Long, rSF As Long, map(1 To 2, 1 To 4) As Byte, i As Long

    t = Timer
    Set wsAT = ThisWorkbook.Worksheets("All Time SMS Dump")
    Set wsSF = ThisWorkbook.Worksheets("Salesforce Dump")

    map(1, 1) = 1:    map(2, 1) = 3        'A to C (VINs)
    map(1, 2) = 7:    map(2, 2) = 4        'G to D
    map(1, 3) = 8:    map(2, 3) = 5        'H to E
    map(1, 4) = 9:    map(2, 4) = 6        'I to F

    lrAT = wsAT.Cells(Rows.Count, 1).End(xlUp).Row              'lr = last row
    lrSF = wsSF.Cells(Rows.Count, 1).End(xlUp).Row
    lcAT = wsAT.Cells(1, Columns.Count).End(xlToLeft).Column    'lc = last col
    lcSF = wsSF.Cells(1, Columns.Count).End(xlToLeft).Column

    urAT = wsAT.Range(wsAT.Cells(1), wsAT.Cells(lrAT, lcAT))    'ur = used range
    urSF = wsSF.Range(wsSF.Cells(1), wsSF.Cells(lrSF, lcSF))

    For rAT = 2 To lrAT
        For rSF = 2 To lrSF
            If urAT(rAT, map(1, 1)) = urSF(rSF, map(2, 1)) Then
                For i = 2 To 4
                    urAT(rAT, map(1, i)) = urSF(rSF, map(2, i))
                Next
                Exit For
            End If
        Next
    Next
    wsAT.Range(wsAT.Cells(1), wsAT.Cells(lrAT, lcAT)) = urAT
    Debug.Print "lrAT: " & lrAT & "; lrSF: " & lrSF & "; Time: " & Format(Timer - t, "0.000")
End Sub

v4 - Arrays and a dictionary (one For loop)

The most important improvement is gained by the .Exists() method of the dictionary

Public Sub VinLookUpDictionary()
    Dim wsAT As Worksheet, wsSF As Worksheet, urAT As Variant, urSF As Variant
    Dim lrAT As Long, lrSF As Long, lcAT As Long, lcSF As Long, t As Double
    Dim rAT As Long, rSF As Long, map(1 To 2, 1 To 4) As Byte, i As Long, d As Dictionary
    t = Timer
    Set d = New Dictionary
    Set wsAT = ThisWorkbook.Worksheets("All Time SMS Dump")
    Set wsSF = ThisWorkbook.Worksheets("Salesforce Dump")
    map(1, 1) = 1:    map(2, 1) = 3        'A to C (VINs)
    map(1, 2) = 7:    map(2, 2) = 4        'G to D
    map(1, 3) = 8:    map(2, 3) = 5        'H to E
    map(1, 4) = 9:    map(2, 4) = 6        'I to F
    lrAT = wsAT.Cells(Rows.Count, 1).End(xlUp).Row              'lr = last row
    lrSF = wsSF.Cells(Rows.Count, 1).End(xlUp).Row
    lcAT = wsAT.Cells(1, Columns.Count).End(xlToLeft).Column    'lc = last col
    lcSF = wsSF.Cells(1, Columns.Count).End(xlToLeft).Column
    urAT = wsAT.Range(wsAT.Cells(1), wsAT.Cells(lrAT, lcAT))    'ur = used range
    urSF = wsSF.Range(wsSF.Cells(1), wsSF.Cells(lrSF, lcSF))
    For rSF = 2 To lrSF
        d(urSF(rSF, map(2, 1))) = vbNullString
    Next
    For rAT = 2 To lrAT
        For rSF = 2 To lrSF
            If d.Exists(urAT(rAT, map(1, 1))) Then
                For i = 2 To 4
                    urAT(rAT, map(1, i)) = urSF(rSF, map(2, i))
                Next
                Exit For
            End If
        Next
    Next
    wsAT.Range(wsAT.Cells(1), wsAT.Cells(lrAT, lcAT)) = urAT
    Debug.Print "lrAT: " & lrAT & "; lrSF: " & lrSF & "; Time: " & Format(Timer - t, "0.000")
End Sub

Results

Total Rows on sheet "All Time SMS Dump": 20,001
Total Rows on sheet "Salesforce Dump":   20,001

v1 = Time: 53.469 sec (arrays - 3 loops)
v2 = Time: 54.676 sec (arrays - 3 loops)
v3 = Time: 20.637 sec (arrays - 1 loop)
v4 = Time:  0.484 sec (arrays & dictionary - 1 loop)


I would nest HashEntry inside of HashMap as just Entry since it's not very likely to ever stand on its own.

The _ prefix is a bit dangerous as the standard reserves the underscore prefix in a few situations (though not this situation). Still though, it's a bit awkward for it to be there not only in case of bad habits, but also because it serves no purpose. And, map.get(3)._k reads a little oddly.

I would call them key and value. It's just a few more characters to type, and it makes the code read a lot clearer (map.get(3).key).

hashFunc is a bit of an odd name. I would just call it hash instead since it's clearly a function.

std::invalid_argument fits a bit better in getBucket than runtime_error does. The more the type of an exception can tell you, the better (in general -- don't take it to an extreme).

for (HashEntry entry : bucket) {

It probably doesn't matter in practice since HashEntry's are fairly cheap, but this creates a copy of each bucket entry. If HashEntry weren't guaranteed to be such a trivial type, this could be devastating to performance. It should be for (const HashEntry& entry : bucket) {.

Any method that doesn't permute that map should be const (keyExists, get, getBucket). Const correctness is an important part of C++, and it should always be kept in mind when designing/implementing classes.

Why does main return 1? It seems the flow that reaches main is a successful execution, which means that the return value should be 0 (or EXIT_SUCCESS).

You do a lot of the same "loop over and find the correct bucket slot" logic. That should be pulled into a function. That can be done by either making a Bucket type that has the concept searching built in, or, more simply, just write a function that loops over a vector<HashEntry> and returns an iterator to the HashEntry (or end()).

When possible, constants in the form of macros should typically be avoided in favor of const constants. const int SIZE = 10 -- or, since it's being used an array size/index, you might find const std::size_t SIZE = 10; more fitting (I would just stick with an int).

Macros do not have a type, and their names are typically lost as debugging symbols. A const variable has either of those drawbacks, and it also doesn't sacrifice anything.

Since getBucket is a very straightforward constant time operation, it doesn't really matter, but containers activate my super picky mode with regards to performance :).

Try to avoid doing the same work twice. For example, consider your implementation of put. It calls getBucket and it calls keyExists, which behind the scenes calls getBucket. This implies that it might be good to have an additional method behind the scenes and leverage that for checking if keys exists:

bool HashMap::keyExists(const std::vector<HashEntry>& bucket, int k) const {
    for (const HashEntry& entry : bucket) {
        if (entry.key == k) {
            return true;
        }
    }
    return false;
}

bool HashMap::keyExists(int k) const {
    return keyExists(getBucket(k), k);
}

bool HashMap::put(int k, int v) {
    std::vector<HashEntry>& bucket = getBucket(k);
    if (keyExists(bucket, k)) return false;
    bucket.push_back(HashEntry(k, v));
    return true;
}

While I'm being a bit performance paranoid, it would also be better to call getBucket after keyExists in your current implementation. That way, for the case when keys don't exist, you don't bother doing the work of getting the bucket.

HashEntry entry = static_cast<HashEntry>(*itr);

Is this cast necessary? I can't imagine that it is. Also, HashEntry entry = static_cast<HashEntry>(*itr) should be const HashEntry& entry = ... (and really it should be const HashEntry& entry = *itr; or const auto& entry = *itr;).

I also wouldn't bother deferencing the iterator:

if (itr->key == k) {
    bucket.erase(itr);
    return true;
}

A break; immediately following a return is just noise. Since the function has already been exited, the loop will have been too.

In the spirit of more performance paranoia, it would be nice to allow a single operation for both checking the existence of a key and retrieving the value of it if it does exist. This allows you to avoid the same loop over the bucket twice.

Something like bool find(int key, int& value); or std::pair<bool, int> find(int key) would do the trick (provided it was implemented to take advantage of the ability to do only a single pass).

If you had the concept of an iterator, you could also do this in the form of having a find() that returns an iterator either to the element or to the end(). It's actually a bit icky to do this without iterators since you don't really have anything meaningful to return if you want to avoid a reference parameter. You would have to have either a std::pair<bool, int*> will a null value, or you'd have to have a junk value in the int component of a std::pair<bool, int>. With an int, the junk value approach works pretty well since you can just throw a 0 in it, but if this were to become generic, it becomes more of a concern.

The key in HashEntry should be const since it should never change after construction. Currently this doesn't matter, but if you were ever to return a reference to the HashEntry so that the value could be changed, it would be necessary to maintain the contract of the map. This is why the value_type of std::map<K, V> and std::unordered_map<K, V> is std::pair<const K, V> instead of std::pair<K, V>.

You probably realize this already, but this HashMap is not really a hash map in the strict sense. In particular, it does not honor the expected O(1) lookup and insertion run times. Instead, all of the meaningful operations are all O(n). The unbounded linear scans over the vectors kill it.

There are essentially three main components to a hash table: look up, insertion, and deletion.

The run time of insertion is of course T(lookup) + T(insertion), and with deletion, it's T(lookup) + T(deletion). This means that lookup, insertion, and deletion all have to be constant time operations for insertion and deletion to be constant time.

This means that hashing must be constant time, and it means that whatever is done in the case of a collision must be constant time. In your case, the buckets grow indefinitely, so the lookup across them is linear time. Provided randomly distributed data (which is likely to happen, but bear with me), if you have n keys and S buckets, each bucket will have n/S items in it. A linear scan over that is O(n/S) = O(1) time for constant S.

The easiest solution to this is to make S non-constant. How you do this actually turns out to be relatively important since pathological cases can exploit most approaches. For example, ensuring S >= N/c for some constant c gives you a decent average case, but if keys are not distributed well across buckets, you're essentially back to linear scans.

Another approach might be to decide that whenever a bucket goes over a certain size, double the size of buckets. This would work well at first glance since it would mean resizing and rehashing the map rarely, but once again, pathological cases could purposely target the same bucket so a relatively small amount of keys could cause a hugely sparse map. (Provided the bucket size case was constant, a linear number of keys could cause quadratic growth in the number of buckets).

So, where am I going with this? Go find a well known, well understood, commonly used approach to implementing a hash map, and implement it. I might do linear probing since it's pretty easy to implement and it's relatively drawback free. Other viable approaches can be found on Wikipedia, in a well known implementation (e.g. clang or gcc's unordered_map, or Oracle Java's java.util.HashMap), or in an algorithms text book.


Project Euler Problem 1 - Functional approach?

Some changes:

You don't need #light any more.  I would also use |> more (this is more useful in more complex examples where it helps type inference.

open System
[for n in 1..1000 do if n % 3 = 0 || n % 5 = 0 then yield n]
|> List.sum
|> printfn "The sum of all multiples are: %d"
Console.ReadKey () |> ignore


DB2 statement to update a header file if no corresponding record exists

Not really but you can simplify your query like this (variable are not replaced 2x)

Exec SQL UPDATE  TC400F f1
         SET  (f1.T40STS, f1.T40OFL) = ('05', '1')
         WHERE  (f1.T40SID, f1.T40PID) = (:K#T41SID, :K#T41PID) AND
         NOT EXISTS
         (SELECT * FROM TC401F f2 WHERE (f1.T40SID, f1.T40PID)=(f2.T41SID, f2.T41PID));


Any comments about my code being (or not) pythonic?

It's 100% not pythonic code. If we go to PEP8 -- Descriptive: Naming Styles we'll see:

  __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces.
  E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Yes never create these.
I can give you one example for why this is in place.

Say a novice to Python comes across this magic attribute and method that you have created.
They don't know what it does, they've not come across a magic method that has not been documented in the Python docs.
But they have yours.
They laboriously search the Python docs, but just can't find it.
They then don't use your code, as they don't know what it does.

Now, I maybe being a foolish hobgoblin, and so sure your new 'init' could possible be a magic method.
But I'd still argue that __has_init_class__ should defiantly not be.
Instead that could be _has_init_class.

I'd argue that _has_init_class is somewhat pointless and you should just use hasattr(cls, '__init_class__').
You also don't test this, and so it seems to me that you don't use it.
In short it may be some nice sugar, but you probably don't need or use it.

I don't think __init_class__ is a good name.
It makes me think you'll be running it near __init__,
which from your tests in definitely not the case.
You may say, you'll use __new_class__ instead.
No, __new__ works together with __init__ to construct objects, and so would shift confusion.
I would name it more closely to how you are using it.
From what I know I'd call it _nonabstract_meta_constructor.
That's a bit long for my liking so I'd just use _meta_const.

And so I'd use:

class MyType(abc.ABCMeta):
    """
        Metaclass.

        It adds extra functionality of an optional class constructor, which might by added
        to the class by adding a class method __init_class__(cls) to the class definition.

        Class constructor takes no arguments.
    """

    def __init__(cls, name, bases, nmspc):
        super().__init__(name, bases, nmspc)
        if hasattr(cls, '_meta_const') and not inspect.isabstract(cls):
            cls._meta_const()

Ok it's not "100% not pythonic code". If you remove the magic methods, your code has no glairing PEP8 errors.
You probably don't need all the docstrings on the tests, and your MyType docstring should be changed to follow PEP257.
You should have a summery line, and then your multi-line docstring as you have it.

But it's good. Apart from the magic I'd have no, non-petty, reason to complain.


Feynmann lifeguard riddle graphical representation

Don't use wildcard imports

Change from tkinter import * to import tkinter as tk, and then prefix all tk classes and variables with tk. (eg: tk.Frame(...)).

One reason is that PEP8 discourages wildcard imports. Also, by using the prefix your code becomes more self-documenting.

One problem I see people make is that they import * from both tkinter and ttk. Since both of them have many classes with the same name (Button, Entry, etc), it becomes impossible to know which is being used without remembering which the order of the imports. If you change the order of the imports you could break many lines of your code.

You don't use ttk here, but if you get in the habit of using wildcard imports, eventually it will cause you problems.

Name your main function main

This is largely personal preference, but I think it helps to name your main function main, and place it at the top of the file. When I was scanning your code, it wasn't until I got down to literally the last line in the file that I knew which function was called first.

Use an object-oriented architecture

Python objects are easy to use, and make writing GUI code much easier. I recommend writing all tkinter programs with classes and objects. There's a stackoverflow question that covers this: Best way to structure a tkinter application

Separate widget creation from widget layout

I personally find it easier to write, maintain, and understand code when the widget creation is separate from widget layout. That is, instead of doing "create widget; layout widget; create widget; layout widget", do "create widget; create widget; layout widget; layout widget". I usually do the grouping by parent (eg: create all children of a parent widget, then layout those children, then go to the next, and so on)

When all of your widgets are in the root it's not quite as important as when you have multiple areas in your GUI that are independent, but even with everything sharing the same parent, grouping them together makes that more apparent.

For example:

l = Label(master, text="Lifeguard Y")
lifeguard_y_w = Scale(master, from_=0, to=HEIGHT, orient=HORIZONTAL)
l = Label(master, text="Child Y")
child_y_w = Scale(master, from_=0, to=HEIGHT, orient=HORIZONTAL)
l = Label(master, text="Sand Speed / Sea Speed ratio")
sand_speed_w = Scale(master, from_=1, to=3, resolution=0.1, orient=HORIZONTAL)

l.pack()
lifeguard_y_w.pack()
l.pack()
child_y_w.pack()
l.pack()
sand_speed_w.pack()

Use explicit options to pack

You are relying on default values for all of your pack statements. While those defaults likely won't ever change, it makes your code a bit easier to read and your intent more obvious if you're explicit about where you expect the widgets to go.

l.pack(side="top")
lifeguard_y_w.pack(side="top")
l.pack(side="top")
child_y_w.pack(side="top")
l.pack(side="top")
sand_speed_w.pack(side="top")

Consider the effect of resizing the window on your design

Your program doesn't handle resizing very well. It's not terrible, but it could be better. For example, as a user I would expect the yellow/blue area to expand to fill the top part of the window when I make the window larger, but it doesn't. I also don't expect to have the buttons chopped off if I make the window smaller; instead, I expect the yellow/blue area to shrink. It's also fairly common for an "OK" button to stick to the bottom, which it doesn't.

You can use options to the geometry managers (pack, place, and grid) to control this. There's no single solution to making it work, it all depends on what you want to have happen when the window is resized. However, the first step usually involves designating a "hero" widget that will grow and shrink with the window. Most GUIs have such a thing, typically it's a text or canvas widget.


Return boolean for navigation (nav) links before and after clicking them

You don't have to construct XPath expressions via string formatting at all. You can locate the element and then find an inner child element by calling the find_element_by_*() methods on a parent element, making the search "context-specific".

And, there is a better locator to find the links by text - "by link text".

Also, to check if the nav listbox is expanded or not, you can use .get_attribute() method to extract and check the value of the aria-expand attribute.

Improved code:

def func(locator, name):
    navigation_box = self.driver.find_element_by_xpath(locator)

    # expand the listbox if not expanded
    is_expanded = navigation_box.get_attribute("aria-expand") == 'true'
    if not is_expanded:
       navigation_box.click()
       is_expanded = True

    link_exists = len(navigation_box.find_elements_by_link_text(name)) > 0

    # collapse the listbox if expanded
    if is_expanded:
        navigation_box.click()

    return link_exists

You should additionally think of a better name for the function and add a docstring explaining what the function does.


Creating linked list data with iterator pattern

You define the copy constructor in terms of the assignment operator

Linkedlist( const Linkedlist & rhs )
{
    init( );
    *this = rhs;
}

It is more traditional to do it the other way around. Normally you define the assignment in terms of the copy constructor. The idiom is called "Copy and Swap"

Linkedlist(Linkedlist const& rhs)
{
    // Create a copy
}

Linkedlist& operator=(Linkedlist rhs) // pass by value to get copy
{
    rhs.swap(*this);   // swap the copy with this.
    return *this;      // As rhs leaves scope with the old values
}                      // it is automatically deleted.

There are a couple of problems with doing it the other way around.

You do not provide the strong exception guarantee. On an assignment you destroy the content of you list. Then start to populate it with new values. If at any point copying fails you are left with a half complete object and no way to roll back to the original object.

Assignment should fall into three distinct phases.

A = B;

Create a copy of the object being assigned from B into a temporary object. This will be the new value that A holds once everything works. If this copy fails then the value of A should not be changed.
Swap the internal state of A with the temporary object. Since a swap should never fail this has no danger. A will now hold a copy of B and the temporary object will hold the old value of A.
Destroy the old object. If this fails it does not matter. As the state of A is now consistent.

const Linkedlist & operator= ( const Linkedlist & rhs )
{
    if( this == &rhs )
        return *this;
    clear( );

At this point A has been cleared. Thus if the folloping loop fails you have no way to recover the original value of A. This will leave your program in a funny state. You have provided The Basic Exception Guarantee in that the object is not invalid. But this is not usually acceptable.

    for( const_iterator itr = rhs.begin( ); itr != rhs.end( ); ++itr )
        push_back( *itr );

    return *this;
}

This seems a bit over-elaborate!

Object & front( )
  { return *begin( ); }

You are creating an iterator just to de-reference it! Why not just

Object & front( )
  { return head->next.data; }

You should also put a comment that it is undefined behavior when the list is empty. Best to document these things up front.x

Not to sure you need to define two different classes for iterator and const_iterator. Seems like a lot of duplicated code.

Also you iterator does not meet even the requirements to trivial iterator as you are missing operator ->. See http://www.sgi.com/tech/stl/table_of_contents.html specifically look at the iterator section. I presume you are actually trying to implement the concept of Bi-Directional iterator the definition can be found here http://www.sgi.com/tech/stl/BidirectionalIterator.html

In addition your container object is supposed to provide some specific types that allow the user of your class to obtain information about the content type. Requirements can be found here: http://www.sgi.com/tech/stl/Container.html

See here for an example of an iterator:   https://codereview.stackexchange.com/a/9399/507 (though I did not make the container as well as I could because I did not specify the types I should have).

See here for an example of a linked list using a single sentinel.
https://codereview.stackexchange.com/a/126007/507


Creating a definition text from 3 string arguments

Code Style

Logic section

Use blank lines to separate your code into logical sections

Instead of:

var sb = new StringBuilder();
sb.Append(mainId);
if (sb.Length > 0 && !string.IsNullOrEmpty(secondaryId))
{
   sb.Append("_");
}
sb.Append(secondaryId);
sb.Append(extraText);

You can write:

var sb = new StringBuilder();   // section of object creation

sb.Append(mainId); // section of appending mainID

// section of checking for mainID and secondaryID
if (sb.Length > 0 && !string.IsNullOrEmpty(secondaryId))
{
   sb.Append("_");
}

sb.Append(secondaryId);
sb.Append(extraText);

The same for the rest part.

Long condition in if statement

Don't use long condition in if statement. It's not readable.

Instead of:

if (sb.Length > 0 && (char.IsNumber(sb[0]) || '+'.Equals(sb[0]) || '-'.Equals(sb[0])))

You can use:

isNum = char.IsNumber(sb[0]);
isPlus = sb[0].Equals('+');
isMinus = sb[0].Equals('-');

if (sb.Length > 0 && (isNum || isPlus || isMinus)
{
   sb.Insert(0, "N");
}

We can move deeply and I want to get rid of this long if statement:

if (sb.Length > 0)
{
   isNum = char.IsNumber(sb[0]);
   isPlus = sb[0].Equals('+');
   isMinus = sb[0].Equals('-');

   if (isNum || isPlus || isMinus)
   {
      sb.Insert(0, "N");
   }
}

I still don't like this if construction, I'll extract this code into separate method. Before this I'll create an array of legal symbols

if (sb.Length > 0)
{
   isNum = char.IsNumber(sb[0]);
   isLegalSymb = isLegalSymb(sb[0]);

   if (isNum || isLegalSymb)
   {
    sb.Insert(0, "N");
   }
}

Separate method for checking if character is legal.

private static bool isLegalSymb(char symb) {
   string[] legalSymb = { "+", "-" };

   for (int i = 0; i < legalSymb.Length; i++) {
     if (symb.Equals(legalSymb[i])) {
       return true;
     }
   }

   return false;
}

Comments

Your code is not always obvious and other developers may don't understand anything without a context of this code.

In such situations you can provide more comments to make our life more easy.

It relates to your code:

foreach(var illegalChar in IllegalCharacters) {
  sb.Replace(illegalChar.ToString(CultureInfo.InvariantCulture), string.Empty);
}

I'm also confused with:

private const string IllegalCharacters = "\\" + "\"" + "'#,.[]{}" + " ";

I'll again extract this code into separate method:

replaceAllBannedCharacters(sb);

Separate method for replacing all banned symbols:

private static void replaceAllBannedCharacters(StringBuilder sb) {
  string[] bannedSymb = { "#", "'", ".", "[", "]", "{", "}", "," };

  for (int i = 0; i < bannedSymb.Length; i++) {
    sb.Replace(bannedSymb[i], string.Empty);
  }
}

Naming

mainId can be replaced with firstID

secondaryId can be replaced with secondID


You shouldn't use os.system to run commands. You should use subprocess instead, for example:

from sys import argv
import subprocess

cmd = 's.py'
args = [cmd] + argv[2:]
subprocess.call(args)

This is a lot cleaner. In your version you added quotes around the command line arguments that contained spaces. (Which btw would break spectacularly if the command line arg also contained quote character...) Using subprocess, you don't need such dirty hacks.