Aggregating recent trading data from Bitcoin derivatives exchange

We (and it sounds like you as well) do not have enough information to answer this question. But some good news first: I cannot see any region where your method is obviously wasting time (like searching with in for some item in a growing list).

Before you concern yourself more with this, consider that even if the variance is large, your maximum time is less than a tenth of a second, for two instruments. In other words, you could be monitoring more than 1500 instruments before you get close to a maximum processing time on the order of your frequency (one minute). So ask yourself if you are performing needless premature optimization. Will this code run with \$\mathcal{O}(1000)\$ instruments, for longer than two days? If not, you can stop right here. If yes, or as an academic exercise, continue on.

As far as I can see, the runtime of this code will be largely determined by two factors:

How long self.ws.get_ticks() takes. Does this method connect to the internet to get it's data? Then the variance might actually be the variance in establishing the connection and getting the data. This could be influenced by your internet connection, but also the current load on the server you are trying to connect to. In this case there is nothing you can do.
How many elements are returned. The actual function getting the data might take longer for more elements, but also the processing would, since you iterate over all elements of the list.

The only way to know is to gather more data. Individually time the call to self.ws.get_ticks(), collect the len(all_ticks) and plot everything in a time-ordered way. Maybe this will help you to discover something interesting.

Here are some possibilities of what you could discover:

The server where you get the information also has some updating frequency, so only every five minutes will there be data for you.
They have a rate limit, which makes all requests in-between fail (which is faster than transmitting a bunch of data).
The call actually returns all data every time, and you just break when you have reached the point of the last minute. In this case each successive call is more expensive, so of course this increases the standard deviation. Try to find a way to pass the start date to the call.

And here is a small class that can help you keep track of different timers I just came up with:

from time import perf_counter
from statistics import mean, median, stdev
from collections import defaultdict

class Timer:
    durations = defaultdict(list)

    def __init__(self, name=""):
        self.name = name

    def __enter__(self):
        self.start = perf_counter()

    def __exit__(self, *args):
        Timer.durations[self.name].append(perf_counter() - self.start)

    @staticmethod
    def calc_stats(x):
        return {"mean": mean(x),
                "std": stdev(x),
                "median": median(x),
                "min": min(x),
                "max": max(x)}

    @staticmethod
    def stats():
        return {name: Timer.calc_stats(x) for name, x in Timer.durations.items()}

With some example usage:

from time import sleep
import pandas as pd
import matplotlib.pyplot as plt

from timer import Timer

for n in range(10):
    with Timer("a"):
        sleep(0.5)
    with Timer("b"):
        sleep(0.1 * n)

print(pd.DataFrame(Timer.stats()))
#                a         b
# mean    0.500559  0.450504
# std     0.000021  0.303079
# median  0.500552  0.450502
# min     0.500534  0.000006
# max     0.500602  0.901003

plt.plot(Timer.durations["a"], label="a")
plt.plot(Timer.durations["b"], label="b")
plt.legend()
plt.xlabel("Iteration")
plt.ylabel("Time [s]")
plt.show()

Some other comments:

Instead of self.bars = {i: [] for i in self.symbols} you can use self.bars = defaultdict(list), like I did in the Timer class.
Try to avoid single letter variables. They are OK in a few cases, but i (and n) are usually reserved for integers. Use x, or maybe even better, tick.
Don't directly compare type, use isinstance(datetime.datetime, s) instead. This also allows subclasses.
Don't lie in your docstring. You say "Return a 1-min OHLCV dict, given a list of the previous minutes tick data.", but almost none of this is true. The method does not return anything and it also does not take any parameters as input!
If you know the exception to expect, catch only that. At least you don't have a bare except, but except KeyError and maybe some specific error from the parser would be better. This way you don't miss an unexpected error. You should also ask yourself what your code does if an error occurs. I think it will just use the previous iterations ts, which would duplicate data. Just hope that you never have a problem in the first timestamp!


Encapsulating the wrong things

insert and flatten should be methods on TreeNode. Solution doesn't particularly need to exist as a class. Those two methods can assume that self is the root.

Return types

As @Carcigenicate suggested: what do you return from flatten? Probably the return type hint should be changed to TreeNode, and you should modify your comment to describe the circumstances under which None will or won't be returned.


Sum of Absolute Differences algorithm implementation

A more generic SAD function
Currently, your SAD function is hardcoded to work on a 3x3 area.  Also, because it takes 3x3 arrays as inputs, you need to use a temporary array tempImage in order to copy a 3x3 area of the original image so that you can pass it to your function.
If you modified your function a bit, you could pass the original image into the function without making a copy.  Here is how I would rewrite your function:
/**
 * Calculates sum of absolute differences between a pattern and an image.
 * The area of the image to be matched is at (imgX, imgY).
 */
int calSad(const int *pattern, int patWidth, int patHeight,
        const int *img, int imgX, int imgY, int imgWidth)
{
    int ret = 0;
    int x   = 0;
    int y   = 0;

    // Set img to point at &img[imgY][imgX].
    img = img + (imgWidth * imgY) + imgX;
    for (y = 0; y < patHeight; y++) {
        for (x = 0; x < patWidth; x++)
            ret += abs(pattern[x] - img[x]);
        pattern += patWidth;
        img     += imgWidth;
    }
    return ret;
}

Note that I used y to indicate row and x to indicate column, which is reverse of how you named your variables.
Your loop in main() would simplify to this:
for (x = 0; x <= originalImage_row_length - tempImage_row_length; x++) {
    for (z = 0; z <= originalImage_col_length - tempImage_col_length; z++) {
        tempSad = calSad(&tem[0][0], LEN(tem), LEN(tem[0]),
                        &originalImage[0][0], z, x, LEN(originalImage[0]));
        if (tempSad < sad) {
            sad = tempSad;
            Xcoordinate = x;
            Ycoordinate = z;
        }
    }
}


Calculating and Outputting Pascal's Triangle with only Indices

This is SUPER bulky for what you actually need to be doing. I did this same project about a year ago in python3. You're thinking too hard about something that's a lot more simple than it looks.

while True:
  def num():
    n=input("Type however many rows you want (or 'info' for info about Pascal’s Triangle): ")
  if n=="quit":
    exit()
  if n.isnumeric():
    n = int(n)
    if n>1000:
      print("That's too many. Try again.")
      return
    else:
      a=[]
      for i in range(n):
        a.append([])
        a[i].append(1)
        for j in range(1,i):
          a[i].append(a[i-1][j-1]+a[i-1][j])
      if(n!=0):
        a[i].append(1)
        for i in range(n):
        print("   "*(n-i),end=" ",sep=" ")
        for j in range(0,i+1):
          print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
        print()
  else:
    return
  num()

The indentation may be wrong (copy and paste is challenging) but it is a lot shorter and more efficient than all the checks you're doing.
Hopefully this helps!


Print every character in a line if it's greater than 80 characters

A few notes (overall very good for a beginner):

Change MIN so that it's a static const because it respects scope and is type-safe.  Also, what is it the minimum for?  The variable name could be more specific.
Very nice on the int main(void)!
Always initialize your variables when you declare them.  This helps prevent unintended behavior later on in the program.
Declare i within your for loop, this should be standard by now (and has been as of C99).

for (int i = 0; ...)

You could also do this with your c variable, but I wouldn't recommend that as i is the counter that is tied directly to that for loop.
The rest of your for loop may be hard for some beginners to read, but I actually like it the way it is and don't find it too hard to read.
The way you have your if statement may be of concern to some.

if (i < MIN - 1)
    line[i] = c;

Their argument is that it could lead to potential bugs in the future if maintained incorrectly.  I'm going to say it's fine, as long as you're consistent with it AND use GCC 6's -Wmisleading-indentation flag to help catch those problems with it in the future
You don't append \0 to line when you are about to print it.

if (i == MIN - 1)
{
    line[i] = '\0';
    printf("%s", line);
}

You don't have to return 0 at the end of main(), just like you wouldn't bother putting return; at the end of a void-returning function. The C standard  knows how frequently this is used, and lets you not bother.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

Final code:

#include <stdio.h>

static const int MIN_LENGTH = 80;

int main(void)
{
    char line[MIN_LENGTH];
    int c = 0;

    for (int i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
    {
        if (i < MIN_LENGTH - 1) line[i] = c;
        else
        {
            if (i == MIN_LENGTH- 1)
            {
                line[i] = '\0';
                printf("%s", line);
            }

            printf("%c", c);
        }
    }
}


3-layer ASP.NET app - Need critique/advice

Things I would change in your code/approach:

log errors
get rid of static service methods
hide dll exceptions in ui. Catch it in BLL and log it/do something with it.
change DLL so the method in BLL instead of:

int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());

would use:

int userId = new UserDAL().Get_UserId(username);

These are first things that come to my head.


I am no C programmer but there are a few things that come to my eye:

Static size

You always read at most 1000 characters, what if the file size is much bigger?
Instead you would loop trough the file, reading/processing it chunkwise.

Magic Number

Even if you use the static size you should not enter it at multiple locations. Instead use a constant for it to have to apply changes only in one place:

#define READ_BUFFER_SIZE 1000
//...
char dna[READ_BUFFER_SIZE];
//...
fgets(dna, READ_BUFFER_SIZE, input);

Loop termination

It might be optimized by the compiler but unoptimized your loop end check is n times (for n = strlen(dna)) which itself is takes \$O(n)\$, making your loop \$O(n^2)\$.

Looping

You index through the loop which is more costly than walking a pointer through it like:

char *current;
// loop until the '\0' terminator is encountered
for(current = dna; *current; ++current)

However, note as stated in https://stackoverflow.com/a/2305783 that modern compiler will optimize the indexed version to the same efficient code as the pointer version.

Switching

To find the counter for the current base you are using cascading ifs, which is suboptimal. Instead use a switch statement:

switch(*current) {
default: assert("Invalid base name!");
case 'A':
//...

Incrementing

This is most likely optimized by the compiler but still: You are incrementing so use the (prefix) increment operator ++a instead of a += 1;.

Naming

In this short example the names are nearly okay but in a longer program you would want to expand the variable names e.g.:

dna -> dnaChunkBuffer (assuming you work in chunks)
input -> inputFile
i -> currentBaseIndex
a, c, g, t -> base*Count

Code-Reuse

As I said I am no C programmer but I could imagine that there is a standard algorithm which helps you count the different characters in a string. If so, I would go for that.

Error Handling

It is just a small example but what happens if there is no file at the location you entered? Your program does not account for that. You should at least test if the fopen function succeeded and given an error otherwise.


Perhaps a more "friendly" message would be nice and/or a way to customize it. As an example the generic catcher we're using right now reads:

echo '

Sorry but we ran into an unexpected problem.

The problem has been logged and support staff have been notified.

Please try again.

';


C: Sieve of Eratosthenes and next twin prime

Your Concerns
The use of pow(i, 2) is unnecessary; you should simply use i*i.
The goto statement is also unnecessary.  You could wrap the code in while(true) { ... }.
Other Concerns
The cast (int) i is also unnecessary, as i is already an integer.  Perhaps you meant to cast to a double?
Computing sqrt(n) in the for loop termination condition is inefficient; you should compute it once outside the loop.
The primes global should probably be declared static, so it isn’t visible outside the module.  Then the “helper” function sieve_of_eratosthenes should also be static.
Your overflow and resizing of the sieve does not preserve any previous work; perhaps you could use realloc?
No twin prime pair would ever be even, so you could optimize the sieve to skip even numbers.
This statement memset(primes.array, true, n * sizeof(bool)); is questionable.  If a bool is larger than 1 byte, then what are you storing in the array?  For instance, if each sizeof(bool) == 2, then primes.array[0] would be 0x0101, which is not the same as true.


Some hints on Unit tests.

Use dependency injection to make testing easier
Create mocks to eliminate all external dependencies in tests
Test units of code (functions, methods, classes)

Example of testable class:

class UserManager: UserManagerType {
 let database: DatabaseType
 init(database: DatabaseType) {
  self.database = database
 }

 func getUser(withId id: String) -> User? {
    return database.getItem(withPredicate: "id == \(id)")
 }

 func getAdmins() -> [User] {
    return database.getItems(withPredicate: "type == admin")
 }
}

protocol DatabaseType {
   func getItems(withPredicate predicate: String) -> [User]
   func getItem(withPredicate predicate: String) -> User?
}

Tests:

// create mock for database.
// Try to avoid any external dependencies in tests
class DatabaseMock: DatabaseType {
 var itemsToReturn: [User] = []
 var userToReturn: User?

 func getItems(withPredicate predicate: String) -> [User] {
   return itemsToReturn
 }

 func getItem(withPredicate predicate: String) -> User? {
   return userToReturn
 }
}

// actual test case
class UserManagerTests: XCTestCase {
  var database: DatabaseMock = DatabaseMock()
  var manager: UserManager!
  // setup before each test
  func setUp() {
    database = DatabaseMock()
    manager = UserManager(database: database)
  }

  func testReturnsCorrectUserForId() {
    let expectedUser = User(id: "123")
    database.userToReturn = expectedUser
    let actualUser = manager.getUser(withId: "123")
    XCTAssertNotNil(actualUser)
    XCTAsseerEqual(actualUser.id, expectedUser.id)
  }

  // other tests ...
}

This is not the best example (because UserManager is just a wrapper around database) but I hope you have got some ideas of how write unit tests


Finding customer searches and graphing their items

Regarding performance the code looks fine. Possibly you are missing useful indexes.

As far as the code itself is concerned I have the following observations.

Remove three part names.

[DB].[dbo].[SearchHistory] and [DB].[dbo].[CustomerExclusions]

It is common to want to run queries against different versions of the database. Hardcoding the database name in to SQL makes this harder.

If this SQL lives inside a stored proc in a copy of the database DB_copy on the same instance as DB you may be unaware that this is, in fact, referencing a different database for some time. Similarly if the SQL is sent by an application it is likely that most people will assume that changing the "Initial Catalogue" in the connection string will change the tables being queried.

Add table aliases and use them for all columns in the correlated sub query

/*Original Code*/
FROM [DB].[dbo].[SearchHistory]
WHERE NOT EXISTS
(
    SELECT 1 FROM [DB].[dbo].[CustomerExclusions]
    WHERE [CustomerNumber] = [SearchHistory].[CustomerNumber]
    AND [ExcludeFromSearch] = 1
)

/*Rewritten Code*/
FROM   dbo.SearchHistory sh
WHERE  NOT EXISTS (SELECT *
                   FROM   dbo.CustomerExclusions ce
                   WHERE  ce.CustomerNumber = sh.CustomerNumber
                          AND ce.ExcludeFromSearch = 1)

If the table CustomerExclusions does not have any columns called CustomerNumber or ExcludeFromSearch but these do exist in SearchHistory then the original correlated sub query will resolve them from the outer scope giving you incorrect results rather than an error message. Using two part names as in the second example would give an error in that case as well as making the code more explicitly self documenting. I have also removed the square brackets as they are not required and I find them distracting. For reasons of personal preference I have replaced the 1 with a *. It makes no difference to the execution plan.

Other changes.

I used a CTE to remove some of the repeated formulas scattered around the code.
I replaced your use of SUM()/COUNT(*) with AVG
It is only necessary to cast one of the operands to avoid integer division - not both.
I changed the column names returned by the query so they meet the rules for standard identifiers and don't need to be quoted.
I changed to the non standard column_alias = expression syntax as I find it makes the query easier to read when the select list contains long expressions.

WITH CTE
     AS (SELECT AtDateTime,
                /*Use CASE if < SQL Server 2012*/
                IIF(NumFound = 0, 1, 0)       AS NoResults,
                DATENAME(WEEKDAY, AtDateTime) AS WeekDayName,
                DATEPART(WEEKDAY, AtDateTime) AS WeekDayNumber
         FROM   dbo.SearchHistory sh
         WHERE  NOT EXISTS (SELECT *
                            FROM   dbo.CustomerExclusions ce
                            WHERE  ce.CustomerNumber = sh.CustomerNumber
                                   AND ce.ExcludeFromSearch = 1))
SELECT WeekDayName,
       NumberOfSearches
             = COUNT(*),
       AverageSearchesPerDay
             = COUNT(*) / CAST(COUNT(DISTINCT CONVERT(DATE, AtDateTime)) AS DECIMAL(10, 2)),
       NumberOfSearchesWithNoResults
             = SUM(NoResults),
       PercentOfSearchesWithNoResults
             = CAST(AVG(CAST(NoResults AS DECIMAL(10, 2))) AS DECIMAL(10, 4))
FROM   CTE
GROUP  BY WeekDayNumber,
          WeekDayName
ORDER  BY WeekDayNumber


Layout

Calling .setSize() with fixed dimensions isn't portable.  For example, this is what happens on Mac OS X:

Instead, call frame.pack() to automatically set the frame size according to its contents.

If you want the 2 × 2 layout, then use a suitable LayoutManager — for example, p.setLayout(new GridLayout(2, 0, 10, 6));

Don't Repeat Yourself

The code is awfully repetitive.  You should avoid repeating yourself, since repetition makes maintenance difficult: cut-and-paste programming leads to cut-and-paste bugs.  I recommend using an Enum to represent the four notes.

Explicitness

It's bad practice to catch (Exception x).  I have no clue what kind of exception would likely cause the flow of execution to jump to the exception handler.  You, as the author, might intend for certain exceptions to be caught, but you don't know what will actually happen.  Starting with Java 7, you can list multiple exceptions to be handled by the same catch block, and that's what I recommend that you do.

Avoid overuse of wildcard imports.  There exists a small probability that a future version of some package could add a class that clashes and breaks your program.  Mostly, using too many wildcard imports makes it hard for human maintainers to resolve identifiers — the compiler may be good at searching the classpath, but I'm not.  My suggested guidelines are:

It's OK to use wildcard imports with the standard Java packages that almost every Java programmer is familiar with (such as java.io.* or java.util.*).
It's OK to use one wildcard import per file, maybe two, but not much more.
If in doubt, import individual classes explicitly.
List your imports alphabetically.

By the way, you never used anything in java.awt.*.

Suggested implementation

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

public class ViolinTuner {
    private static enum Note {
        G, D, A, E;

        public final File file;

        Note() {
            this.file = new File("Sounds", this.name() + ".wav").getAbsoluteFile();
        }
    }

    private static JButton makeJButton(final Note note) {
        JButton button = new JButton(note.name());
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(note.file);
                    Clip clip = AudioSystem.getClip();
                    clip.open(audioInputStream);
                    clip.start();
                } catch (IOException | UnsupportedAudioFileException | LineUnavailableException x) {
                    x.printStackTrace();
                }
            }
        });
        return button;
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Violin Tuner");
        frame.setIconImage(new ImageIcon("Images/Icon.png").getImage());

        // buttons to panel
        JPanel notePanel = new JPanel(new GridLayout(2, 0, 8, 4));
        notePanel.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
        for (Note note : Note.values()) {
            notePanel.add(makeJButton(note));
        }

        // Component to impose a minimum width on the JFrame to ensure that the
        // window title is not truncated
        JPanel widener = new JPanel();
        widener.setPreferredSize(new Dimension(250, 0));

        // Panels to frame
        frame.setLayout(new BorderLayout());
        frame.add(notePanel, BorderLayout.CENTER);
        frame.add(widener, BorderLayout.SOUTH);
        frame.pack();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        }
    }
}


In the case that the error code is not 11000 I would re-throw the error in the inner try. That way you do not repeat, possibly complex error logic or possibly execute code that you do not want to. i.e. instead of

try {
  try {
    // code
  } catch(err) {
    if (err.code === 11000) {
      log({completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length})
    } else {
      log('an error occurred', {err} )
    }
  }
  //code that shouldn't execute when an error occurs
} catch(err) {
  log('an error occurred', {err} )
}

something like

try {
  try {
    // code
  } catch(err1) {
    if (err1.code !== 11000) {
      throw err1;
    }
    log({completed: err1.result.nInserted, duplicates: err1.result.result.writeErrors.length})
  }
  //code that shouldn't execute when an error occurs
} catch(err2) {
  log('an error occurred', {err2} )
}

I also suggest using different variable names in different exception handlers. Some spaces between parentheses and curly brackets would also make your code more readable.


Finding added keys, removed keys, and unchanged keys in ordereddict

A few notes about your current approach:

there is no need to call .keys(), the default iteration over a dict would go over the keys:

for key in a:
    # ...

for key in b:
    # ...

I think doing if key not in a: is a bit more readable than if not key in a:
added can be defined using a list comprehension:

added = [key for key in b if key not in a]

we can define the initial list values using unpacking:

added, removed, overlap = [], [], []

you can remove parenthesis around the return tuple value:

return added, removed, overlap

adding a docstring would really make sense here especially considering the return type and format which can be explicitly mentioned there
we can even go a bit further and return a collections.namedtuple() instead of a regular tuple:

from collections import namedtuple

Difference = namedtuple('Difference', ['added', 'removed', 'overlap'])

and we can add type hints as well

At the end we can get something along these lines:

from collections import namedtuple
from typing import MutableMapping, NamedTuple

Difference = namedtuple('Difference', ['added', 'removed', 'overlap'])

def differences(a: MutableMapping, b: MutableMapping) -> NamedTuple:
    """
    Calculates the difference between two OrderedDicts.

    :param a: OrderedDict
    :param b: OrderedDict
    :return: Difference
    """
    removed, overlap = [], []

    for key in a:
        if key in b:
            overlap.append(key)
        else:
            removed.append(key)

    added = [key for key in b if key not in a]

    return Difference(added=added, removed=removed, overlap=overlap)

Or, if we gonna apply Mathias's suggestion to loop over the a twice we can shorten that to:

from collections import namedtuple
from typing import MutableMapping, NamedTuple

Difference = namedtuple('Difference', ['added', 'removed', 'overlap'])

def differences(a: MutableMapping, b: MutableMapping) -> NamedTuple:
    """
    Calculates the difference between two OrderedDicts.

    :param a: OrderedDict
    :param b: OrderedDict
    :return: Difference
    """

    return Difference(added=[key for key in b if key not in a],
                      removed=[key for key in a if key not in b],
                      overlap=[key for key in a if key in b])


This is really nicely written code! I do have a few small tips, and then I'll try to answer some of your small questions.

I noticed from looking at your code, that you only use the random.randint function from the random module/library. Rather than importing the entire random module, you can just do from random import randint.
In your else block at the very end of your function, you have a return after you raise an exception. Raising an exception will exit the program, so this return can be removed entirely.
You also mention in a comment by the else block, that this will never happen. If it never happens, then why do you need it? It can be removed as well.
I did find something odd about this function. Underneath the comment # for each new child, add new children you have an expression that's evaluated, but you don't return the value of the expression. Preferably, this line should be changed to return [ ... ].
Finally, using len to find the new appropriate indices is really the only good option, right now. You can always do tree[len(tree) - 1].index() + 1, but that's horridly unclear. Just stick with len.


Servlet filter which detects if the authenticated user is a service account

One thing that is sure is that it will be more readable to move those tests in one method :

public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain chain)
        throws IOException, ServletException {
    if ( isAuthenticated(request) ) {
        MyUser myUser = getAuthenticatedUser(request);
        // app-specific tests
    }
}

Then it depends but most of the time your code is more readable when extracting intermediate steps in variables or methods.

private boolean isAuthenticated(ServletRequest request) {
    return (request instanceof HttpServletRequest) &&
           hasValidPrincipal((HttpServletRequest) request);
}

private boolean hasValidPrincipal(HttpServletRequest request) {
    MyUser user = getAuthenticatedUser(request);
    return user!=null && user.getUsername().length()>6;
}

private MyUser getAuthenticatedUser(HttpServletRequest request) {
    Object principal = request.getUserPrincipal();
    Authentication authentication = null;
    if ( !(principal instanceof Authentication) ) {
        return null;
    }
    authentication = (Authentication) request.getUserPrincipal();
    Object user = authentication.getPrincipal();

    return (user instanceof MyUser)
        ?(MyUser) user
        :null;
    }
}


Code Hunter 2.06: Count occurrences of 'a' in a string

This is a nice short piece of code, though it has a number of 'features' which can be improved.

Code Style

Java code style recommends a lower-case letter to start method names.... Puzzle should be puzzle, or better, getLetterCount. You may be limited by the testing tool though.

Efficiency

Inside the method, the biggest issue I have is the poor efficiency. A string in Java is essentially an array of 'char' primitive values: char[]

Your code takes each char, converts it to a Character (autoboxing), runs the equals('a') method on that Character, which converts the char 'a' to a Character a and does the equals on that.

It's normally more efficient to compare the primitives using == instead.

Consider the following code:

public class Program {
    public static int countAChars(String s) {
        int count = 0;
        for(int i = s.length() - 1; i >= 0; i--) {
            if('a' == s.charAt (i)) {
               count++;
            }
        }
        return count;
    }
}

Note: in the loop above I go backwards from the end of the String, which has occasionally been faster than going forwards, at least in my testing.

The following alternative code is more readable, but converts the String to an array first, which will be slightly slower....

public class Program {
    public static int countAChars(String s) {
        int count = 0;
        for(char c : s.toCharArray()) {
            if('a' == c) {
               count++;
            }
        }
        return count;
    }
}

Performance

I took a moment to code up the performance of a number of different solutions that have been posted so far. I used 'MacBeth' as an input file (this link will download the XML).

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Counter {

    private interface ACount {
        int countA(String line);

        String name();
    }

    private static final ACount[] COUNTERS = { new ACount() {

        @Override
        public int countA(String line) {
            int cnt = 0;
            for (int i = line.length() - 1; i >= 0; i--) {
                if (line.charAt(i) == 'a') {
                    cnt++;
                }
            }
            return cnt;
        }

        @Override
        public String name() {
            return "charAt()";
        }
    }, new ACount() {

        @Override
        public int countA(String s) {
            int ret = 0;
            for (int x = 0; x < s.length(); x++) {
                if (((Character) s.charAt(x)).equals('a'))
                    ret++;
            }
            return ret;
        }

        @Override
        public String name() {
            return "OPCode";
        }
    }, new ACount() {

        @Override
        public int countA(String line) {
            return line.length() - line.replace("a", "").length();
        }

        @Override
        public String name() {
            return "replace";
        }
    }, new ACount() {

        @Override
        public int countA(String line) {
            int cnt = 0;
            for (char c : line.toCharArray()) {
                if (c == 'a') {
                    cnt++;
                }
            }
            return cnt;
        }

        @Override
        public String name() {
            return "toCharArray";
        }
    }, };

    private static final int countAllA(ACount counter, String[] lines) {
        int cnt = 0;
        for (String line : lines) {
            cnt += counter.countA(line);
        }
        return cnt;
    }

    private static final void reportCounts(String name, String[] lines) {
        for (ACount counter : COUNTERS) {
            long start = System.nanoTime();
            int ac = countAllA(counter, lines);
            long nanos = System.nanoTime() - start;
            System.out.printf("%10s %12s %8d  %12.3fms%n", name,
                    counter.name(), ac, nanos / 1000000.0);
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
        String[] lines = Files.readAllLines(
                Paths.get(args.length == 0 ? "macbeth.xml" : args[0])).toArray(
                new String[0]);
        for (int i = 0; i < 100; i++) {
            reportCounts("Warmup " + i, lines);
        }
        reportCounts("Real Run", lines);

    }

}

This produces the results:

  Real Run     charAt()     5065         0.311ms
  Real Run       OPCode     5065         0.872ms
  Real Run      replace     5065         3.933ms
  Real Run  toCharArray     5065         0.387ms

The 1-liner answer you have accepted (and posted as your answer), is 10 times slower than the alternatives.

Your original code (if I cast the char to Character), is twice as slow as the alternatives I suggest.

What you determine to be elegant, is not, in my opinion, a good solution. If "Code Hunt" thinks the slow solution is the best solution, then I would find a different system for evaluating my code.


I've hardly done any Haskell - so it's probably a positive thing that I can easily understand your code - but since you've no answer yet, I'll have a go. Anyway, take everything I say with a pinch of salt, and it'll just be surface stuff since I don't have experience to draw on.

Currently you code uses a linear-time search to determine if an element is in the list of closed elements. Since Ord is implemented for tuples (e.g. (Int, Int)) you can use a Data.Set instead, which will provide logarithmic-time lookup, making your code more efficient on large problems. I'd also consider making meta a Data.Map so that you can efficiently query it as well, and will allow you to dispense with that head points in constructPath.

Though you have attempted to implement a graph-search, your closed system is inadequate, as it still allows the queuing of elements multiple times. Consider the case where the same node is queued by two different other nodes before it is itself expanded (this would occur any time you had a square of 4 cells, starting in one the cell diagonally opposite will be queued twice). The easiest way to solve this is probably to append all the neighbours to closed, and add start to closed from the outset.

I don't know how people do things normally in Haskell, but I hate tuples with a passion (when they leak outside functions), and would replace your coordinate tuples with a dedicated data type, e.g.

data Position = Pos { x :: Int, y :: Int } deriving (Eq, Ord, Show)

This makes the meaning of the 2 elements clear, and ensures that only values intended to be interpreted as a position can be used. It also means you can define meaningful instances over your new type without infecting code which uses tuples.

You are mixing usage for i j and x y; I'd stick with just one of them as best you can, and try to think of something better than a b for your temporaries (dx dy for offsets?) You don't need the coordinates in constructPath; I think something like this would be clearer, though I'll concede that it's no longer entirely clear that this is operating on positions (but it's also a more generic piece of code, meaning it will work for (x, y) or Pos x y):

constructPath position meta route
    | (length points) > 0 = (constructPath (head points) meta (position:route))
    | otherwise = position:route
    where points = [to | (from,to) <- meta, from == position]

(I have also here swapped the concatenation around, which means the route will start at start and end at end, which is what I'd normally expect from a route-finder)

Ideally your code wouldn't contain magic numbers like 0 and 2; much better to create a union or type-class for the types of cells in the grid, e.g.

data Cell = Wall | NotWall deriving (Eq)

NotWall isn't a great name, but it's better than 2, and will make the intention of the filtering code in getNeighborNode (should that be getNeighborNodes?) much clearer.

You can provide a much nicer and more useful API by passing the maze and end in as parameters along with start, and providing a convenience method which calls bfsSolver with the appropriate initial conditions, e.g.

bfs start = bfsSolver [start] [] []

It's so much harder to misuse, and  your consumers would thank you for it.


X86_64 implementation of STRCHR using NASM

Bug #1
You set the DF flag, so your string operation is going to run backwards.  You should clear the DF flag to scan your string in the forwards direction.
Bug #2
If you reach the byte limit, your function will return the original string pointer in RAX.  The comment says it should return NULL.  Perhaps you meant xor rax, rax instead of mov rax, rdi?
Bug #3
According to the comments, your function should return with ZF set according to the result of the scan.  However, since you do pushf and then popf, the ZF result is wiped out by the popf.
Your own ABI
I would suggest following the standard X64 ABI rather than inventing a new ABI per function.  For one thing, you will be able to use high level languages to interface with your assembly routines.  Another thing is that it would be hard for you to remember details such as "when I call strlen, ZF set means that the terminating character was found".
Don't call it strlen
Your function is closer to strchr or strnchr than strlen.  Any reasonable person would expect a function called strlen to return a length rather than a pointer.


Simplify the if by just doing

if (first == second && second == third && third == fourth)
{....}

You said the inputs are degrees, now it’s been awhile since geometry but squares and rectangles are determined by length of side, not angle degree. Both are 4 sided objects so every angle is the same (unless you’re talking about something like a trapezoid, rhombus).


The problem statement

There's an ambiguity in the requirements, because you don't specify how to handle overlapping substrings.  For example, should findInStr("ababa", "aba") return 1, or 2?  Either of those may be useful, but be clear which interpretation is needed.  This code appears to count non-overlapping substrings.

Non-standard header

Despite its name, stdafx.h is not a standard header, so you can't use it in portable code.  Thankfully this program can easily become standard C, if you replace gets_s() with the equivalent fgets() call:

if (!fgets(str, sizeof str, stdin)) {
    perror("gets");
    return 1;
}

Note: this is not quite equivalent (thanks to Martin R for the comment), as get_s() discards the final newline; that won't make a difference unless we specifically look for a string ending in newline (which could now match once, rather than never).

Naming

I like the variable names you've used - I found it easy to understand your algorithm with the clear names.  (They do need to be a more suitable type - see Martin's answer for a very clear explanation).

I think they would be even clearer if you give them a line each for their declarations.

Bug (or undocumented constraint)

This test assumes that find will always be three characters long:

    if (findCounter == 3)
        howMany++;

We can make more versatile by counting until we see the NUL character at the end of find, like this:

    if (find[findCounter] == '\0') {
        howMany++;
        findCounter = 0;
    }

Bug

If a character is repeated in find, we don't start looking again in the right place.  We can test this with findInStr("ababaca", "abac") - this doesn't find the string because when we reach the second b, that doesn't match c and we start again from there (instead of going back to the start of the potential match).

The fix for this to subtract findCounter from strCounter before we reset it to zero, so we resume searching from the right place:

        if (str[strCounter] == find[findCounter]) {
            findCounter++;
        } else {
            strCounter -= findCounter;
            findCounter = 0;
        }

Modified version

Keeping your algorithm, but incorporating the fixes from this and other answers, I get:

#include <stdio.h>

/* Count the number of non-overlapping occurrences of find in str.
 * Returns zero if either string is empty.
 */
size_t findInStr(const char *str, const char *find)
{
    size_t howMany = 0;
    size_t strCounter = 0;
    size_t findCounter = 0;

    do {
        if (find[findCounter] == '\0') {
            ++howMany;
            findCounter = 0;
        }
        if (str[strCounter] == find[findCounter]) {
            ++findCounter;
        } else {
            strCounter -= findCounter;
            findCounter = 0;
        }
    } while (str[strCounter++] != '\0');

    return howMany;
}

I changed the test program to accept command-line arguments; this makes for easier testing.  I hope that this is educational reading (note that I check the arguments before attempting to use them).

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s haystack needle\n", argv[0]);
        return 1;
    }

    const char *const haystack = argv[1];
    const char *const needle = argv[2];

    const size_t found = findInStr(haystack, needle);

    switch (found) {
    case 0:
        printf("'%s' was not found in '%s'.\n", needle, haystack);
        break;
    case 1:
        printf("'%s' was found once in '%s'.\n", needle, haystack);
        break;
    default:
        printf("'%s' was found %zd times in '%s'.\n", needle, found, haystack);
        break;
    }

    return 0;
}

Pointer version

This is a bit more advanced, and harder to get right, but I'll show you what this looks like when converted to use pointers rather than indexes.  A good optimizing compiler will likely generate the same code for both, but you'll want to be able to study and work with pointer code when you come across it.

size_t findInStr(const char *str, const char *const find)
{
    size_t howMany = 0;

    for (const char *find_pos = find;  *str;  ++str) {
        if (*str == *find_pos) {
            /* matched this char */
            if (!*++find_pos) {
                /* reached the end of find; count it and reset */
                ++howMany;
                find_pos = find;
            }
        } else {
            /* not matched - back up and continue */
            str -= find_pos - find;
            find_pos = find;
        }
    }

    return howMany;
}

Here, I've also used simply *str rather than the longer, but equivalent *str != '\0'.

Self-test program

An alternative main() can run a test suite, which can be useful in to avoid introducing bugs as you modify the code.  Here's what I accumulated when writing the above:

/* return failure count (0 or 1) */
static int test(const char *haystack, const char *const needle, size_t expected)
{
    const size_t actual = findInStr(haystack, needle);
    if (actual == expected) {
        return 0;
    }
    /* incorrect result */
    fprintf(stderr,
            "FAIL: findInStr(\"%s\", \"%s\") returned %zd instead of %zd\n",
            haystack, needle, actual, expected);
    return 1;
}

int main(void)
{
    return
        + test("abc", "", 0)
        + test("abc", "d", 0)
        + test("abc", "cd", 0)
        + test("abc", "ac", 0)
        + test("abc", "ab", 1)
        + test("ab", "abc", 0)
        + test("abab", "ab", 2)
        + test("ababa", "aba", 1)
        + test("ababac", "bac", 1)
        ;
}

You might choose to use a preprocessor #ifdef/#else to be able to compile the test or interactive version from one source, or you might write two programs sharing a single findInStr() implementation.


Fast incremental backup algorithm using RSYNC

That seems to work but I'm wondering if anyone can come up with a simpler, more efficient algorithm or add any ideas for a better way of accomplishing this.

I think so. Use a naming scheme with a common prefix, and a variable suffix depending on the period, for example:

Hourly backups for 24 hours: hourly-$(date +%H).gz, results in:

hourly-00.gz
hourly-01.gz
hourly-02.gz
... and so on until hourly-23.gz after which it starts over from hourly-00.gz

Daily backups for 1 week: daily-$(date +%a).gz, results in:

daily-Sun.gz
daily-Mon.gz
daily-Tue.gz
... and so on until daily-Sat.gz, after which it starts over

Weekly backups for 1 month: weekly-$(($(date +%W) % 4)).gz, results in:

weekly-00.gz
weekly-01.gz
weekly-02.gz
weekly-03.gz after which it starts over from weekly-00.gz

You'll never have to delete anything. You will have the same set of files,
and rsync (with appropriate parameters) will copy only the changed ones.

As for the posted code,
the single biggest problem is the duplicate calls to $(date ...) with the same parameters:

Inefficient: multiple unnecessary process executions
Bad practice: duplicated logic
Unnecessary and error prone: the multiple calls to $(date +%w) (for example) probably expect to get the same result. So there should be only one call, saved in a variable. If the day happens to turn between two calls, may have a nasty bug, and in any case it's completely unintended situation.


Speed up query that handles auditing and versioning

You should use a provided Aggregate function sorted over a group by statement.

Select
            t.id as u_id,
            (case tn.state when 'P' then SUBSTRING(tna.id,4,100) else tn.name end) as name,
            t.version,
            tn.state
            FROM tag AS t
            INNER JOIN tag_name AS tn ON tn.tag_parent = t.id
            LEFT JOIN
            ( select max(CONCAT(format(id, '000'),name)) id,tag_name_parent  from tag_name_audit group by tag_name_parent ) AS tna
            ON tna.tag_name_parent = tn.id
            AND tn.state = 'P'
            AND tn.language = ?
            AND t.version IS NOT null
            AND tn.tag_parent IN (".$planIn.")

for 100 records your query rendered 13000700 NS for my query and 295016900 for yours :O quite remarkable difference !

You can check my test cases and see by yourself:

declare @tag table(id int NOT NULL IDENTITY(1,1), version varchar(1) NULL)
declare @tag_name table(tag_parent int,id int NOT NULL IDENTITY(1,1),name varchar(5),state varchar(1))
declare @tag_name_audit table(tag_name_parent int,id int NOT NULL IDENTITY(1,1),name varchar(5))

declare @cnt int
declare @max int

set @cnt=1
set @max=100

WHILE @cnt <= @max
BEGIN
   insert @tag(version) values (char(cast(DATEPART(nanosecond,SYSDATETIME())/1050 as int)%10+97))
   WAITFOR DELAY '00:00:00.015';
   insert @tag_name(name,tag_parent,state) values ('tn_'+char(cast(DATEPART(nanosecond,SYSDATETIME())/1050 as int)%10+97), cast( DATEDIFF(nanosecond,cast(GETDATE () as datetime2),SYSDATETIME())/90 as int)%@max+1,char(cast(DATEPART(nanosecond,SYSDATETIME())/990 as int)%2+ascii('P')))
   WAITFOR DELAY '00:00:00.015';
   insert @tag_name_audit(name,tag_name_parent) values ('tna_'+char(cast(DATEPART(nanosecond,SYSDATETIME())/1050 as int)%10+97), cast( DATEDIFF(nanosecond,cast(GETDATE () as datetime2),SYSDATETIME())/90 as int)%@max+1)
   SET @cnt = @cnt + 1;
   WAITFOR DELAY '00:00:00.015';
END;

select * from @tag order by id;
select * from @tag_name order by tag_parent;
select * from @tag_name_audit order by tag_name_parent;

DECLARE @t1 time;
DECLARE @t2 time;
DECLARE @t1_ time;
DECLARE @t2_ time;

SET @t1 = SYSUTCDATETIME() ;

Select
            t.id as u_id,
            (case tn.state when 'P' then SUBSTRING(tna.id,4,100) else tn.name end) as name,
            t.version,
            tn.state,
            tn.id tn_id,
            tna.id tna_id
            FROM @tag AS t
            INNER JOIN @tag_name AS tn ON tn.tag_parent = t.id
            LEFT JOIN
            ( select max(CONCAT(format(id, '000'),name)) id,tag_name_parent from @tag_name_audit group by tag_name_parent) AS tna
            ON tna.tag_name_parent = tn.id
            AND tn.state = 'P'
            AND t.version IS NOT null

SET @t2 = SYSUTCDATETIME () ;
SELECT DATEDIFF(NANOSECOND,@t1,@t2) AS elapsed_ms;

SET @t1_ = SYSUTCDATETIME()  ;

SELECT
            t.id as u_id,
            (case tn.state when 'P' then tna.name else tn.name end) as name,
            t.version,
            tn.state,
            tn.id tn_id,
            tna.id tna_id
            FROM @tag AS t
            INNER JOIN @tag_name AS tn ON tn.tag_parent = t.id
            LEFT JOIN @tag_name_audit AS tna ON tna.tag_name_parent = tn.id AND tn.state = 'P'
            AND  tna.id = (
                            SELECT MAX(id)
                            FROM @tag_name_audit
                            WHERE tag_name_parent = tn.id
                        )
            AND t.version IS NOT null;

SET @t2_ = SYSUTCDATETIME () ;
SELECT DATEDIFF(NANOSECOND,@t1_,@t2_) AS elapsed_ms;


The middle else if statement is redundent and can be removed. The reason that is redundent is that the only two cases are either equal or less than 5 balls gives 0 baskets and for everything else the number of baskets can be evaluated to be ceil(count($balls)/12).

Also using short hand will make it more readable I find.

$baskets = count($balls) <=5 ? 0 : ceil(count($balls)/12);


Class(es) for animating objects on a canvas

This is really cool! I do have a few small tips though.

First off, rather than creating an entire function, in this case, config, that returns configuration data, I'd store it as a public getter, like this:

class Wave {
  static get CONFIG() {
    const waveBaseLength = 5;
    return {
      color: '#4F5E5B',
      waveLengths: [waveBaseLength, waveBaseLength * 7, waveBaseLength * 15],
      velocity: 5
    }
  }
}

Using this, you can do stuff like Wave.CONFIG.color, and drop the un-needed parentheses.

Finally, you have a few, not so great variable names. A few include l and n. Names like these should be expanded for clarity and readability.


From discussion elsewhere I know you don't want to change the basic implementation, so I'll confine my comments to idiom, style and tweaks.

I would replace the for loop with a foreach

Range // addon reference required in newer versions
1 to(100) foreach(i, toBuzzWord(i) println)

The Range protocol used to be in the core library but is now an add-on, hence the reference needed before you can use it.  That said, it's a more idiomatic, expressive and robust way to deal with simple ranges.  for loops are even more fragile in Io than in C-like languages, given the optional parameter and Io's blithe tolerance of extra parameters.

I don't like chained if-then-elsif in any language, even when it's a function and not a keyword.  One alternative would be to use return

method(n,
   if (n % 15 == 0, return "FizzBuzz")
   if (n % 5 == 0, return "Fizz")
   if (n % 3 == 0, return "Buzz")
   return n
)

Multiple exit points from a function are much debated and criticised, but

Io has no switch or case function and the community doesn't want one.
lists (using a numeric index lookup) or maps (using a string key) are sometimes used for very simple switch-style control flows but that doesn't work here.

In purist OO style, Io developers prefer to use (no surprise here) polymorphism.  Send a message and let the inheritance chain pick the appropriate action.

Polymorphism is really overkill for the simple fizzBuzz implementation you have chosen.  It might be useful for a more efficient solution.


Convert numbers in a string array (#3, #1, #2, #4) to range (#1:#4)

In order to improve readability I'd say to not go too deep with the indentation. For example:

            if (IDs.Contains(plus1) && IDs.Contains(plus2))
            {
                IDs.Remove(plus1);
                IDs.Remove(plus2);
                var toInt = fromInt + 2;
                while (IDs.Contains($"#{toInt + 1}"))
                {
                    toInt += 1;
                    IDs.Remove($"#{toInt}");
                }
                i = $"#{fromInt}:#{toInt}";
            }

can be transformed in:

if (!(IDs.Contains(plus1) && IDs.Contains(plus2)))
{
    continue;
}
IDs.Remove(plus1);
IDs.Remove(plus2);
var toInt = fromInt + 2;
while (IDs.Contains($"#{toInt + 1}"))
{
    toInt += 1;
    IDs.Remove($"#{toInt}");
}
i = $"#{fromInt}:#{toInt}";

The same can be done with the conditions if (int.TryParse(i.Substring(1), out fromInt)) and if (i.StartsWith("#")) in the upper levels.

The name of the string i is a little misleading. i is usually used as an index. I think id would be a proper name.

The resulting code could be transformed from:

var newIDs = new List<string>();
for (var index = 0; index < IDs.Count; index++)
{
    var i = IDs[index];
    if (i.StartsWith("#"))
    {
        int fromInt;
        if (int.TryParse(i.Substring(1), out fromInt))
        {
            var plus1 = $"#{fromInt + 1}";
            var plus2 = $"#{fromInt + 2}";
            if (IDs.Contains(plus1) && IDs.Contains(plus2))
            {
                IDs.Remove(plus1);
                IDs.Remove(plus2);
                var toInt = fromInt + 2;
                while (IDs.Contains($"#{toInt + 1}"))
                {
                    toInt += 1;
                    IDs.Remove($"#{toInt}");
                }
                i = $"#{fromInt}:#{toInt}";
            }
        }
    }
    newIDs.Add(i);
}
return string.Join(",", newIDs);

into the following:

var newIDs = new List<string>();
for (var index = 0; index < IDs.Count; index++)
{
    var id = IDs[index];
    if (!id.StartsWith("#"))
    {
        newIDs.Add(i);
        continue;
    }
    int fromInt;
    if (!int.TryParse(i.Substring(1), out fromInt))
    {
        newIDs.Add(id);
        continue;
    }
    var plus1 = $"#{fromInt + 1}";
    var plus2 = $"#{fromInt + 2}";
    if (!(IDs.Contains(plus1) && IDs.Contains(plus2)))
    {
        newIDs.Add(id);
        continue;
    }
    IDs.Remove(plus1);
    IDs.Remove(plus2);
    var toInt = fromInt + 2;
    while (IDs.Contains($"#{toInt + 1}"))
    {
        toInt += 1;
        IDs.Remove($"#{toInt}");
    }
    i = $"#{fromInt}:#{toInt}";
    newIDs.Add(id);
}
return string.Join(",", newIDs);


Django Rest Framework - add/remove to a list

If the collection is at another model then you must setup the serializer with the 'many' kwarg.

class CollectionContainerViewSet(viewsets.ModelViewSet):
    queryset = CollectionContainer.objects.all()
    collection_ids = serializers.PrimaryKeyRelatedField(
                      many=true,
                      queryset=Collection.objects.all()
                    )

Or maybe change the collection to accept updating many?

class CollectionViewSet(viewsets.ModelViewSet):
    queryset = Collection.objects.all()
    serializer_class = CollectionSerializer(many=True)

I guess that in most situations you don't explicitly add or remove, but you are change the collection to a known state - containing a specific set of items. If that is not the case and you really must add and remove explicitly I think it is better to have two actions, one for adding and one for removing items by id.


JavaScript function for computing the checksum of a given number

Your approach is far too complicated.

How about just

function computeChecksum(num) {
  if (typeof num !== 'number' || isNaN(num)) {
    throw new Error('Number, which is not NaN, expected as Parameter.');
  }

  num = Math.floor(Math.abs(num));

  const sum = num.toString().split('').reduce(
                                  (acc, val) => acc + parseInt(val),
                                  0);
  return sum;
}

Or instead of converting between string and number you can use modulo:

function computeChecksum(num) {
  if (typeof num !== 'number' || isNaN(num)) {
    throw new Error('Number, which is not NaN, expected as Parameter.');
  }

  num = Math.floor(Math.abs(num));

  let checksum = 0;

  while (num > 0) {
    checksum += num % 10;
    num = Math.floor(num / 10);
  }

  return checksum;
}


A huge amount of you work is just plain work that has to be done.... (the joys of brute-forcing).

MessageDigest

On the other hand, this work is unnecessary:

byte[] pub2 = MessageDigest.getInstance("SHA-256").digest(pub);

This should be replaced with:

MessageDigest digest = MessageDigest.getInstance("SHA-256");

for (..... ) {

    digest.reset();
    byte pub2 = digest.digest(pub);

Accessing the security API's in every loop is a lot of wasted time, and MessageDigest classes are designed to be reused.

Parallelism...

A lot of the work you do involves getting and managing URL's... this is slow work that can be done in parallel with the hard work of generating the key hashes.

I would recommend one thread that builds a stream of hashes (with the relevant input stored) and feeds them in to a BlockingQueue with a limited queue size... then, have the controlling thread read these off the queue, and 'farm' them out to a number of other threads that create and check the URL's against the server.

The parallelsim could give you orders-of-magnitude performance improvements.... (but will heavily load the server you are bruting...)


Stacking frames of a video file horizontally into a single image

Some suggestions aimed at more general issues rather than specific details in
your lines of code:

Computers are not our friends, no need to chat. Get user input from the command line, not from input(). Interactive user
input is a bad usage model for the default behavior of a script -- with rare
exceptions. Use interactivity only for special circumstances, and always
provide a command-line option to bypass that interactivity. In addition,
input() is terrible for development because it requires you (the coder) to go
into a dialogue with your script every damn time you run it. Super
annoying. One option for handling command-line input is
argparse. See the script
below for the template that I usually follow in my scripts.

But functions are our friends. Organize your code into functions. Have each function do one thing. Among
other things, this approach allows you to test each small piece of behavior as
you write it.

Either do or talk. Do not print() inside your functions that do the actual work (aside from some quite rare exceptions). Functions should take arguments, calculate something or do
something, and return some meaningful data (or None). If the larger program
requires printing ultimately, use the data returned from functions to do that
printing. But keep computation and printing in separate realms.

No magical tokens in the castle. Keep literal strings and values out of your code. Instead put them in one
or more containers. In many situations, I usually just use a Constants class
and module-level global (con), as shown below. Good practice, but easy and
low-tech.

The script template:
import argparse
import sys

class Constants:

    EXIT_OK = 0
    EXIT_FAIL = 1

    NEWLINE = '\n'
    NAMES = 'names'
    BAR = 'BAR'
    BAR_PROPAGANDA = 'Sucker, should have picked --bar!'

    OPTS_CONFIG = (
        {
            NAMES: 'path',
        },
        {
            NAMES: '-b --bar',
            'action': 'store_true',
        },
    )

con = Constants()

def main(args):
    ap, opts = parse_args(args)
    if opts.bar:
        print(con.BAR, opts)
        exit()
    else:
        print(opts)
        exit(con.EXIT_FAIL, con.BAR_PROPAGANDA)

def parse_args(args):
    ap = argparse.ArgumentParser()
    for oc in con.OPTS_CONFIG:
        kws = dict(oc)
        xs = kws.pop(con.NAMES).split()
        ap.add_argument(*xs, **kws)
    opts = ap.parse_args(args)
    return (ap, opts)

def exit(code = None, msg = None):
    code = con.EXIT_OK if code is None else code
    fh = sys.stderr if code else sys.stdout
    if msg:
        nl = con.NEWLINE
        msg = msg if msg.endswith(nl) else msg + nl
        fh.write(msg)
    sys.exit(code)

def your_function_foo(opts):
    pass

def your_function_bar(opts):
    pass

# Etc.

if __name__ == '__main__':
    main(sys.argv[1:])


Clone and replace attributes that are instances of a specific class

You are overly complicating what you are trying to achieve by defining your Replacer class. You need two passes because your logic is:

store each id of custom objects into visited, associated to a copy of it;
change the value associated to ids of T objects into 100.

See how in 1. you already made a copy? You don't need that, you need to change how objects are copied in the first place.

The deepcopy function tries to copy a custom object x using one of 3 functions, in that order:

x.__deepcopy__;
x.__reduce_ex__(2);
x.__reduce__().

__reduce_ex__ and __reduce__ are a bit special and provided by object by default so better not to touch it. __deepcopy__, however, is copy.deepcopy own mechanism and should be used anytime you want to change how deepcopy should create new objects out of old ones.

If all you want to do is to turn all Ts into 100 when deepcopying an arbitrary object, then all you have to do is to implement T.__deepcopy__ in such a way:

class T(object):
    def __deepcopy__(self, memo): # expected signature for copy.deepcopy
        return 100

Every deepcopy will then turn each T into 100:

Ex1:

>>> b = [1,2,"hello",T(),('a',3,T()),T()]
>>> copy.deepcopy(b)
[1, 2, 'hello', 100, ('a', 3, 100), 100]

Ex2, using your A and B classes:

>>> b = B()
>>> bb = copy.deepcopy(b)
>>> bb.t2
100
>>> bb.a.t1
100

Note that in the context of your implementation and various calls, the T.__deepcopy__'s memo parameter would be an alias to visited, use it as you see fit if you want to implement custom logic. Read the last paragraph of the documentation for specific use cases.


Split a list using another list whose items are the split lengths

This is my first answer that I gave on stackoverflow:

from itertools import islice

def split_by_lengths(seq, num):
    it = iter(seq)
    for n in num:
        out = list(islice(it, n))
        if out:
            yield out
        else:
            return   #StopIteration
    remain = list(it)
    if remain:
        yield remain

Here I am not using a for-else loop because we can end the generator by using a simple return statement. And IMO there's no need to define an extra take function just to slice an iterator.

Second answer:

This one is slightly different from the first one because this won't short-circuit as soon as one of the length exhausts the iterator. But it is more compact compared to my first answer.

def split_by_lengths(seq, num):
    it = iter(seq)
    out =  [x for x in (list(islice(it, n)) for n in num) if x]
    remain = list(it)
    return out if not remain else out + [remain]


Check if a file path matches any of the patterns in a blacklist

You can build one regex out of the list of regexes by

'|'.join(IGNORE_FILES)

(Well, before running re.compile on them...)

Then your in_blacklist function becomes as easy to write and read as in_whitelist.

I further assume that you don't want to ignore paths that start with any letter, but those starting with a literal dot (which is what os.walk('.') yields). So you need to escape those leading dots.

Also, in your files() function, you should move your in_blacklist check out of the inner loop. No need to check the same root directory multiple times.

So:

IGNORE_FILES = re.compile('|'.join([
    r'^\./Vendor.*',
    r'^\./Pods.*',
]))

def in_blacklist(file):
    return IGNORE_FILES.match(file) != None

def in_whitelist(file):
    return SWIFT_FILE_REGEX.match(file) != None

def files():
    valid_files = []
    for root, dirs, files in os.walk('.'):
        if in_blacklist(root):
            continue
        for file in files:
            if in_whitelist(file):
                valid_files.append("%s/%s" % (root, file))
    return valid_files

And for more portability, you could replace "%s/%s" % (root, file) by os.path.join(root, file), but I wouldn't insist on this too hard...


You let the user pass in a char* but you don't use it. you might as well remove it and declare it as a local variable.

char *readFile (FILE* fp)
{
    char* source;

Some FILE* won't let you seek to the end (stdin and socket streams for example). You should check the return value of fseek and fall back to the classic fread then realloc, rinse and repeat method on error.

A single fread is more efficient than the repeated fgetc; so you can replace the while with:

int readBytes = fread(source, size, 1, fp);

string[readBytes] = '\0';


Go command-line tool to do some simple byte manipulation

Several things come to mind right away:

I wouldn't make a custom parseArgs function, I'd use flag.Parse. For just a pair of positional arguments it might be overkill but it makes it trivial to add more options, usage output, etc. And either way, it's better to only access os.Args from main
Instead of fmt.Fprint to os.Stderr followed by os.Exit it's more idomatic to just use log.Fatal (or Fatalf or Fatalln).
Avoid reading and writing entire files with ioutil if you can do work while streaming data. If the files are guarenteed to be small it's just a bad habit but if someone ever runs your tool on gigabytes or terabytes of data they'll be in for unpleasant surprise.
In the same vein, I'd make your function API steam-able. Either by implementing an io.Reader wrapper or by a function that takes an io.Writer and an io.Reader (like io.Copy).

You could also implementing it as a transform.Transformer; but that's probably overkill, although perhaps an interesting exercise.
Typically such command line tools in unix act as pipes, that is, if not given file arguments they read from stdin and write to stdout. Either you only work with stdin/stdout and make callers use shell redirection if they want to work to work on files or you make the filenames optional. Just initialise an io.Reader (or io.ReadCloser) variable to os.Stdin and an io.WriteCloesr variable to os.Stdout. Then when processing the arguments, if provided, open the relevant files and change the variables. Your choice if you use positional arguments as you've done or option arguments (as dd does and as I did below). Make sure to check for errors closing the destination.
By the way, on unix you can use the standard dd command to do the byte swapping for you with the conv=swab operand:

dd conv=swab if=someinput_file of=someoutput_file

using files, or in a pipe like this:

bigendian_command | dd conv=swab | littleendian_command

A quick stab at implementing it this way gave me the following.

(Also available at https://gist.github.com/dchapes/9d795a04e471319abbc5ff016afbbee9
the gist also has your version as revision 1, and a version using a function with an io.Copy like signature as revision 2).

swab.go:

package main

import (
    "flag"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    log.SetPrefix("swab: ")
    log.SetFlags(0)
    infile := flag.String("in", "", "input `path`, blank for stdin")
    outfile := flag.String("out", "", "output `path`, blank for stdout")
    flag.Usage = func() {
        fmt.Fprintf(flag.CommandLine.Output(),
            "Usage: %s [options]\n", os.Args[0],
        )
        flag.PrintDefaults()
    }
    flag.Parse()
    if flag.NArg() > 0 {
        flag.Usage()
        os.Exit(2) // To match the exit code flag.Parse uses.
    }

    var src io.ReadCloser = os.Stdin
    var dst io.WriteCloser = os.Stdout
    if *infile != "" {
        f, err := os.Open(*infile)
        if err != nil {
            log.Fatal(err)
        }
        src = f
    }
    // Closing the input isn't strictly required in main
    // nor for stdio, but it's a good habit. No need to
    // check any error; we rely on Read reporting errors of interest.
    defer src.Close()

    if *outfile != "" {
        f, err := os.Create(*outfile)
        if err != nil {
            log.Fatal(err)
        }
        dst = f
    }

    if _, err := io.Copy(dst, NewSwabReader(src)); err != nil {
        // Not this calls os.Exit so no defers get run
        // and we don't close the output either, not
        // an issue from main.
        log.Fatal(err)
    }
    if err := dst.Close(); err != nil {
        log.Fatal(err)
    }
}

type SwabReader struct {
    r        io.Reader
    b        byte // extra byte, not yet swapped
    haveByte bool // true if b is valid
    err      error
}

// NewSwabReader returns an io.Reader that reads from r
// swapping adjacent bytes. The trailing odd byte, if any,
// is left as-is.
func NewSwabReader(r io.Reader) *SwabReader {
    return &SwabReader{r: r}
}

func (sr *SwabReader) Read(p []byte) (n int, err error) {
    if len(p) == 0 || sr.err != nil {
        return 0, sr.err
    }
    i := 0
    if sr.haveByte {
        // Copy in the previous saved byte.
        p[0] = sr.b
        i = 1
        //sr.haveByte = false // not strictly required
    }
    n, sr.err = sr.r.Read(p[i:])
    n += i
    p = p[:n]
    for i := 1; i < len(p); i += 2 {
        p[i-1], p[i] = p[i], p[i-1]
    }
    // Remove and save any non-swapped trailing odd byte.
    if sr.err == nil {
        if sr.haveByte = (n&1 != 0); sr.haveByte {
            n--
            sr.b = p[n]
            //p = p[:n] // not strictly required
        }
    }
    return n, sr.err
}

And a simple test,
swab_test.go:

package main

import (
    "io"
    "strings"
    "testing"
    "testing/iotest"
)

var readFilters = []struct {
    name string
    fn   func(io.Reader) io.Reader
}{
    {"", nil},
    {"DataErrReader", iotest.DataErrReader},
    {"HalfReader", iotest.HalfReader},
    {"OneByteReader", iotest.OneByteReader},
    //{"TimeoutReader", iotest.TimeoutReader},
}

func TestSwab(t *testing.T) {
    const sz = 32<<10 + 1
    cases := []struct{ in, out string }{
        {"", ""},
        {"a", "a"},
        {"ab", "ba"},
        {"abc", "bac"},
        {"abcd", "badc"},
        {strings.Repeat("\x01\x80", sz) + "x",
            strings.Repeat("\x80\x01", sz) + "x"},
    }
    var dst strings.Builder
    var r io.Reader
    for _, rf := range readFilters {
        for _, tc := range cases {
            r = strings.NewReader(tc.in)
            if rf.fn != nil {
                r = rf.fn(r)
            }
            dst.Reset()
            //t.Logf("swabbing %s %.16q", rf.name, tc.in)
            //r = iotest.NewReadLogger("<<< src", r)
            n, err := io.Copy(&dst, NewSwabReader(r))
            if err != nil {
                t.Errorf("swab on %s %q failed: %v",
                    rf.name, tc.in, err,
                )
                continue
            }
            if want := int64(len(tc.out)); n != want {
                t.Errorf("swab on %s %q returned n=%d, want %d",
                    rf.name, tc.in, n, want,
                )
            }
            if got := dst.String(); got != tc.out {
                t.Errorf("swab on %s %q\n\tgave %q\n\twant %q",
                    rf.name, tc.in, got, tc.out,
                )
            }
        }
    }
}


Your code and Java 8 usage looks fine in general to me.

I do see an issue with the Person class, it looks like you are intending it to be an immutable class, if so, then you should also enforce it.

You need to ensure that the name and id fields can never be changed, you can do this by adding final to them. Your code currently seems to be safe, but it is not. I can extend Person and offer a method there to change the name and id fields, which violates the assumed variant of that those fields in Person are immutable.

Simply changing it to the following will do:

public class Person {
    private final String name;
    private final String id;
    ...
}

Onto the Java 8 usage now.

It is a good thing that you use the Collectors.groupingBy to provide a Map<String, List<Person>>, you cannot do it much faster either way if you want it to work with any kind of List<Person> as input and in this way you'll save yourself from nasty bugs and reimplementing what lots of people have already done, namely the grouping by operation.

Printing the offending values using Stream seems fine as well, except that you may rewrite it to look a little bit cleaner, something like this could work:

peopleById.values().stream()
    .filter(personList -> personList.size() > 1)
    .forEach(personList -> System.out.println("People with identical IDs: " + personList);

This is my personal preference on how to format it though, the only real change is to rename peopleWithSameId to personList, as it is simply a List<Person> and nothing more or less.

You've done a good job overall.


Ok, had a few suggestions with the code for you to avoid some confusion and maintain some consistency. I'll start off with the code sample and add some comments after the code block:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        private System.Timers.Timer m_mainTimer;
        private bool m_timerTaskSuccess;

        protected override void OnStart(string[] args)
        {
            try
            {
                //
                // Create and start a timer.
                //
                m_mainTimer = new System.Timers.Timer();
                m_mainTimer.Interval = 60000;   // every one min
                m_mainTimer.Elapsed += m_mainTimer_Elapsed;
                m_mainTimer.AutoReset = false;  // makes it fire only once
                m_mainTimer.Start(); // Start

                m_timerTaskSuccess = false;
            }
            catch (Exception ex)
            {
                // omitted
            }
        }

        protected override void OnStop()
        {
            try
            {
                // Service stopped. Also stop the timer.
                m_mainTimer.Stop();
                m_mainTimer.Dispose();
                m_mainTimer = null;
            }
            catch (Exception ex)
            {
                // omitted
            }
        }

        void m_mainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                // do some work

                m_timerTaskSuccess = true;
            }
            catch (Exception ex)
            {
                m_timerTaskSuccess = false;
            }
            finally
            {
                if (m_timerTaskSuccess)
                {
                    m_mainTimer.Start();
                }
            }
        }
    }
}

System.Windows.Forms.Timer versus System.Timers.Timer

At one point in your code it is clear you dragged a Timer component into the design grid of the service, clicked it creating the Tick event, and then replaced with a System.Timers.Timer instead. I recommend sticking with either one or the other, and thus to maintain clarity I replaced your timer1_Tick event handler with m_mainTimer_Elapsed, since System.Timers.Timer utilize the Elapsed event instead of the Tick event.

Use of a boolean success indicator

Versus setting the timer to null when the Service is stopped, which at that point it is already too late to affect your running event, utilize a private boolean to hold whether success is achieved (dependent on how you define success in your project's domain). If an exception occurs during the running of the task, set it to false. Then utilize an if block to only restart the timer if the last run was successful.

You do NOT need volatile

You are only ever modifying the timer in one thread. volatile is utilized when multiple threads could potentially modify the same reference variable.


Finding MinMax values and returning a tuple as a result

What bothers me with the tuple is that fields are not readonly and we cannot prevent users of the method to mess up and break flow.

We cannot prevent everything and sometimes it's just easier and quicker to use the simplest solution like tuples in this case. You can always switch to something more complex if necessary but it's good to start by following the YAGNI principle.

  I was coding some tooling stuff

It depnds on what kind of tooling stuff your are coding. If this is some tiny helper then I'd go with tuples. If I was creatng a general purpose library then and big type would be better. You could validate the parameters and make sure that min <= max etc.

As an example you can take a look at my generic Range.cs that is supported by expressions to be able to work with any comparable type BinaryOperation.cs.

Regarding your ComparerExtensions I start with what I already said in my comment: LeftStrictlyLesserThanRight - I think virtually all programming languages call this just less-than and its counterpart less-than-or-equal.

I also find the extensions are not intuitive. They should be extensions on the T and not on the comparer like that:

x.LessThen(y)

and/or

x.LessThen(y, comparer)

It's more natural (and shorter) to write than

comparer.LeftLessThenRight(x, y)

This means you can create two pairs of these extensions for each operation.

public static bool LessThen<T>(this T x, T y) where T : IComparable<T>
public static bool LessThen<T>(this T x, T y, IComparer<T> comparer)

one that uses the interface IComparable implemented by T and the other one that uses a custom comparer.


Array-based unordered list implementation in Java

I would recommend using Log4j instead of System.out.println() with some meaningful message to the user. Also, you can implement locate() method as mentioned below to avoid initializing the flag

private int locate(int data)
{
    int i = 0;
    int index = -1;
    while (i < size())
    {
        if (data == nodeElements[i].getData())
        {
           index = i;
           break;
        }
        i++;
    }
    return index;
 }

Change: Use break; to come out of the loop rather than using flag to check it.


You don't need to pass the vector itself. left and right iterators provide all the necessary information.

That said, you pass a correct right: too often people pass it as .end() - 1 which indeed leads to unnecessary complications.
Partitioning is an important algorithm on its own right and deserves to be factored out.
The lines

if (size == 2 && *pivot < *left) {
    std::iter_swap(left, pivot);
}

serve no purpose. The code works fine without them.
The trickiest part is achieving best performance.

The poor choice of pivot may result in quadratic time complexity. In a professional implementation choosing pivot is the most complex part.
In general, C++ is very good in eliminating tail recursion, but in this particular case it may use some help. Specifically, you'd want to recurse into smaller partition, and iterate over the larger one.
Another optimization is a timely switch to insertion sort. Instead of descending all the way to size <= 1 it is beneficial to stop recursion earlier (say, when size <= 16). Once the recursions are completed, the range is almost sorted, and insertion sort runs in linear time.


Does the format provided in the Rails Guides not work for you?

# Model ------------------------------------------------------------------------
class Feedstock < ApplicationRecord
  has_many :feedstocks,   foreign_key: "primary_feedstock_id"

  belongs_to :primary_feedstock, class_name: "Feedstock"
end

# Migration --------------------------------------------------------------------
class CreateFeedstocks < ActiveRecord::Migration[5.0]
  def change
    create_table :feedstocks do |t|
      t.references :primary_feedstock, index: true
      t.timestamps
    end
  end
end

EDIT: So I'm still not clear on the difference between add_foreign_key and t.references. According to this comment on SO, t.references will not create a foreign key constraint, but that was written 5 years ago, and the part of the Guides that the commenter mentioned is no longer there.

The API docs are abundantly clear about add_foreign_key creating a foreign key constraint at the database level; unfortunately, they're not so clear about t.references.

In any case, you will have to decide for yourself how to design your application. I've heard some people say that depending on ActiveModel is ‘the Rails Way’, but I haven't seen that position stated anywhere in the official docs. Alternately, others will tell you that implementing these checks at the database level is more performant and reliable, and I can't argue with that. I think in the end, the choice comes down to how strictly you believe in Rails' convention-over-configuration philosophy, and whether you're willing to sacrifice a little abstraction for performance and reliability.

EDIT 2: It appears that add_foreign_key alone is not sufficient to create a table column. You'll need t.references either way, followed by either the foreign_key: true option or a separate add_foreign_key directive.


Ok, so I made implementation very similar to yours with these modifications:

input is not being destroyed (althout it can still be adjusted to destroy it, but it just feels like such algorithm should not do this)
I compute maximum potential container area for values as I iterate them from left
I iterate the inner loop from end towards front
I use the potential to reduce the number of iterations of the inner loop.

function maxArea (input)
{
    // result value will go here
    let currentMax = 0;

    // we will need this value at least 2*(n-1) times:
    const limit = input.length - 1;

    // i<limit because having i=limit would always yield zero size container so skip it:
    for(let i = 0; i < limit; ++i) {
      const left = input[i];

      // zero size edge always yields zero size container so move to next i
      // this check may be omitted as the next will exclude it as well
      //if (left == 0) continue;

      // the largest container we can have on the right has this area:
      let potential = left * (limit - i);

      // if potential is not enough to get over currentMax, just move to next i
      if (potential <= currentMax) continue;

      // search from end towards i becase more distant j is more likely to yield larger container and only the last j can actualy yield current potential
      for (let j = limit; j > i; --j) {
        const right = input[j];

        // if right is at least as high as left then this container has the area equal to potential and no other j will do better for current left value
        if (right >= left) {
          currentMax = potential;
          break;
        }

        // if it is smaller we check if its area is greater then currentMax and use it if it is
        const area = right * (j - i);
        if (area > currentMax) currentMax = area;

        //decrease potential by 1 times left value because we will reduce distance by 1 for next iteration (--j):
        potential -= left;

        // if new potential is not enough to get over currentMax we can stop searching further j's and move to next i
        if (potential <= currentMax) break;
      }
    }
    return currentMax;
}

In conjuction this algorithm is still (like yours) O(n^2) in time and O(1) in space. But it is a  better n^2 then yours, I believe. And (unlike yours) the actual performance will be different for different input values, not only for different lengths of the input array. It is same as yours in worst case (ie strictly decreasing sequence) and actualy O(n) in best case (ie increasing sequence). And of course anywhere in between for most of the possible variations of input values.

EDIT: hehe ok I benched it on random 100k value arrays and mine takes about 4ms, yours 15+ seconds :) The worst case scenario is about 15 seconds yours, 7 seconds mine. But the worst case scenario is very small set of all posibilities, so to get it from randomness is very unlikely. Randomness holds it on few ms. So improvement by factor of several thousands for random 100k value inputs :)


Storing and Retrieving data with User Forms in Excel 2010

See this related question:
https://stackoverflow.com/questions/7589579/is-it-possible-to-store-elements-of-array-permanently-in-vba-in-excel

Summary:
To store data persistently in the workbook using VBA, you have a few options:

Store it in another worksheet. If you don't want the user to be able to see the worksheet, Sheets("ArrayValuesWorksheet").Visible = xlVeryHidden
Create a defined name which has the desired data as its value. Names("MyArrayData") = myArray
Store it in ThisWorkbook.CustomDocumentProperties -- see https://stackoverflow.com/questions/17406585/vba-set-custom-document-property
Store it in a CommandBar, hopefully the user won't find it
Use a helper XLL which can call Excel4(xlDefineBinaryName,...) and Excel4(xlGetBinaryName)

I believe storing in a hidden sheet is the most common.


Performance problem when getting text from a context node with VTD-XML

I've found a solution, which doesn't improve the performance, but is a lot shorter. I didn't know about the evalXPathToString() method.

protected String extractText(VTDNav v, String path) throws Exception {
  AutoPilot ap = new AutoPilot(v);
  ap.selectXPath(path);
  return ap.evalXPathToString();
}

Furthermore, the check in my old version whether the path contains a @ was buggy. It returned true for a path like /a[@b='c'] and executed getAttrVal() for it, which is wrong.


Interface

The name LoadVertex(…) suggests that it's going to parse the string, rather than parse the file with the given filename.  I suggest LoadVertexFile(…) for clarity.

The parameter should be a const std::string&, to avoid unnecessarily copying the string.

You test whether file2.is_open(), but the code proceeds anyway if it isn't open.  The error message is printed to std::cout; I would recommend std::cerr, if you must print anything at all.  (Throwing an exception would be better.)  Furthermore, there is no way to programmatically tell whether the whole method succeeded.  What if the number of entries in the file is not a multiple of 3?

Implementation

I don't see any point in building three vectors x, y, and z, then transposing the results to populate vertexArray.  All you need is three temporary floats.  You don't need a counter.  Just read three entries at a time into those three floats.

You don't need to read a std::string and convert it using stof().  The iostream interface knows how to read floats.

You don't need to .close() the file explicitly; the ifstream's destructor takes care of that for you.

Suggested solution

bool ModelLoader::LoadVertexFile(const std::string& fileLocation)
{
    std::ifstream file(fileLocation);
    if (!file) {
        std::cerr << "Failed to load vertex data\n";
        return false;
    }

    float x, y, z;
    vertexArray.clear();
    while (file >> x >> y >> z)
    {
        vertexArray.push_back(PhysicsEngine::PxVec3(x, y, z));
    }
    return true;
}


Here's my two cents. These are the changes that I would make:

Separate the API calls into a service.
Separate the event triggers using the model-options in the view.
Handle the monitoring using a watch. (Expensive, but it seems to be the "angular" way.)
Isolate your code into functions/files, then configure in application.js.

Helper Functions

Normally, I use !!value to test if a value is not undefined or null, but in this case I want to do things properly and make the code readable. Alternatively, if you use library like lodash or underscore, you can just call !_.isEmpty(value)

function notEmpty(value) {
    return (angular.isDefined(value) && !angular.isNull(value))
}

View

Using ngModelOptions will allow one to fine tune the view without having to manipulate the directive. One can then test different events without having to make changes in the directive.

<input type="text"
    name="username"
    ng-model="form.username"
    ng-model-options="{ updateOn: 'blur' }"
    unique-username=""
    required
/>
Username taken!

Service

Using a service is another large advantage. Currently, the directive requires $http and thus becomes bound to the api. Using a service, one can create a mock service to test the directive independently of the api.

Another advantage is that the logic for the uniqueness test is now isolated from the view. This code can then be reused in a controller, another directive, or even another service.

function UserService($q, $http) {

    this.isUnique = function(username) {
        if (notEmpty(username)) {
            var uri = '/api/checkUnique/' + username;
            return $http.get(uri);
        }
        return $q.reject("Invalid User name");
    }

}

Directive

userService is must now be injected into the directive instead of $http . Since the uniqueness test is done when the model changes, one can also create a watch on the model rather than binding it to an event.

In the future, you can use the controller.$parsers.unshift command instead of a scope.$watch. Unfortunately, $parsers doesn't allow for responses from a $promise. See issue #6416.

function UniqueUsernameDirective(userService) {
      return {
           restrict: 'A',
           require: 'ngModel',
           link: function (scope, element, attrs, ngModel) {
               scope.$watch(attrs.ngModel, function(value) {
                   userService.isUnique(value)
                              .then(function(data) {
                                   ngModel.$setValidity('unique', notEmpty(data));
                              })
                              .catch(function() {
                                   ngModel.$setValidity('unique', false);
                              });
               });
           }
      };
}

Application.js

This just keeps your application.js file nice an clean.

angular.module('app', [])
       .service('userService', ['$q', '$http', UserService])
       .directive('uniqueUsername', ['userService', UniqueUsernameDirective]);

Demo

I made a demo using a mock service to demonstrate this functionality. jsFiddle


Create a program that will take user input, reverse it, and then check if it is a palindrome

I think you have a classic case of not knowing the standard.
What you are writing is generally already available via either a normal constructor or a standard algorithm. In a few cases I would have just implemented a minor wrapper class that could be used by these facilities.
Lets have a look at a few and see how you could have utilized the standard:
  std::vector <char> stringToVec(std::string inputString) {
    std::vector <char> letters;
    for (int a = 0; a < inputString.size(); a++) {
      letters.push_back(inputString.at(a));
    }
    return letters;
  }

The first thing to point out is that you are passing the parameter by value std::string inputString. This means you are copying the parameter into the function. This can be expensive (especially with strings and vectors). Also you are not mutating them so much easier to pass by const reference.
  std::vector <char> stringToVec(std::string const& inputString) {
                                    //       ^^^^^^^
    std::vector <char> letters;
    for (int a = 0; a < inputString.size(); a++) {
      letters.push_back(inputString.at(a));
    }
    return letters;
  }

This means you can read the original parameter but can not modify it:
The method at() is a bounds checking access operator. If you know that your index is going to be in range then prefer to use operator[]. In the case above you always know that a is going to be in the correct range because you actively check to make sure it is in the correct range a < inputString.size().
  std::vector <char> stringToVec(std::string const& inputString) {
    std::vector <char> letters;
    for (int a = 0; a < inputString.size(); a++) {
      letters.push_back(inputString[a]);  // Don't need to valid range
                                          // When your loop is already
                                          // guaranteeing the range.
    }
    return letters;
  }

Most algorithms we use tend to use iterators, so get used to using them. So I would re-write the above loop in terms of iterators:
  std::vector <char> stringToVec(std::string const& inputString) {
    std::vector <char> letters;
    for (auto loop = std::begin(inputString), loop != std::end(inputString); ++loop) {
      letters.push_back(*loop);
    }
    return letters;
  }

This is such a common pattern that in C++11 they introduced the range based for expression. Basically this is a for() loop that works with an object that can accept std::begin() and std::end() being called on it. It is basically syntactic sugar to make the above loop simpler to write:
  std::vector <char> stringToVec(std::string const& inputString) {
    std::vector <char> letters;
    for (auto letter: inputString) {
      letters.push_back(letter);
    }
    return letters;
  }

But if we look at std::vector<> we see that it also has a constructor that accepts two iterators so you can simply use this to construct the vector:
  std::vector <char> stringToVec(std::string const& inputString) {
    std::vector <char> letters(std::begin(inputString), std::end(inputString));
    return letters;
  }

Or more simply:
  std::vector <char> stringToVec(std::string const& inputString) {
    return std::vector<char>(std::begin(inputString), std::end(inputString));
  }

We can go through the same processes in reverse of the next function vecToString().
std::string vecToString(std::vector<char> const& inputVec) {
  return std::string(std::begin(inputVec), std::end(inputVec));
}

Just as a little style niggle. The seporation of the template type from the class looks strange.
std::vector <char>
         ^^^^^     That space just looks strange.

Lets move to cleaning the string:
std::string cleanString(std::string inputString) {
  std::locale loc;
  for (std::string::size_type i = 0; i < inputString.length(); i++) {
    inputString[i] = std::tolower(inputString[i], loc);
  }
  for (std::string::size_type i = 0; i < inputString.length(); i++) {
    if (inputString[i] == ' ') {
      inputString.erase(i, 1);
    }
  }
  return inputString;
}

Again looking at your loops. I would convert them to using iterators and then range based for. But these are also classic algorithms supported by the standard.
Converting to lower case:
  for (std::string::size_type i = 0; i < inputString.length(); i++) {
    inputString[i] = std::tolower(inputString[i], loc);
  }

This is a standard transform:
 std::transform(std::begin(inputString), std::end(inputString), // Source
                std::begin(inputString),                        // Destination (can be source) as long as it it is already large enough.
                [&loc](unsigned char c){return std::tolower(c, loc)}
               );

Removing a particular character:
  for (std::string::size_type i = 0; i < inputString.length(); i++) {
    if (inputString[i] == ' ') {
      inputString.erase(i, 1);
    }
  }

This is a standard remove/erase
 auto newEnd = std::remove(std::begin(inputString), std::end(inputString), ' ');
 inputString.erase(newEnd, std::end(inputString));

This is so common we usually write it as a single line:
 inputString.erase(std::remove(std::begin(inputString), std::end(inputString), ' '), std::end(inputString));

Commonly referred to as the erase/remove pattern.
Simple tests can sometime be replaced by the trinary operator. BUT be careful if overused or used in bad places this technique can make the code work (so be careful of using this). But in this instance I think it makes the code easier to read:
if (cleanString(originalString) == cleanString(reversedString)) {
  return "Yes";
}
return "No";

You can simplify this to:
return (cleanString(originalString) == cleanString(reversedString))
    ? "Yes"
    : "No";

Reversing a container:
std::vector <char> reverseVec(std::vector <char> inputVec) {
  std::vector <char> reversedReturn;
  for (int a = inputVec.size() - 1; a >= 0; a--) {
    reversedReturn.push_back(inputVec.at(a));
  }
  return reversedReturn;
}

Like above you can improve your code by using iterators.
std::vector <char> reverseVec(std::vector<char> const& inputVec) {
  std::vector <char> reversedReturn;
  for (auto loop = std::rbegin(inputVec), loop != std::rend(inputVec); ++loop) {
    reversedReturn.push_back(*loop);
  }
  return reversedReturn;
}

The rbegin() and rend() provide `reverse iterators. They go in the opposite direction to your standard iterator but are basically the same.
We can expand this (like above to just constructing the container with the iterators).
std::vector <char> reverseVec(std::vector<char> const& inputVec) {
  return std::vector<char>(std::rbegin(inputVec), std::rend(inputVec));
}

There is also standard algorithm std::reverse() that reverse a container in place.
Using the above:
int main()
{
  std::cout << "Enter the string you would like reversed: ";

  std::string userInput;
  std::getline(std::cin, userInput, '\n');

  auto newEnd = std::remove(std::begin(userInput), std::end(userInput), ' ');
  std::erase(newEnd, std::end(userInput));

  std::transform(std::begin(userInput),  std::end(userInput),
                 std::begin(userInput),
                 [](unsigned char* c){std::tolower(c);});

  std::string reversedInput(std::rbegin(userInput), std::rend(userInput));

  std::cout << "Reversed: " << reversedInput << "\n"
            << "Palindrome: "
            << ((userInput == reversedInput) ? "Yes" : "No")
            << "\n";
}