Using += to concatenate strings in a loop scales very badly. Each iteration creates a new string instance by copying the previous string and the new character into a new string, and that string grows for each iteration. Using a StringBuilder (as Dmitry suggests) would be a great improvment.

However, you don't need to build the string character by character. You could use a regular expression to replace the fifth space with a newline:

string t = Regex.Replace(s, "^([^ ]+(?: [^ ]+){4}) ", "$1" + Environment.NewLine);

Explanation of the pattern:

^       mathces the beginning of the string
(       starts a catching group
[^ ]+   matches the first word (a sequence of non-space characters)
(?:     start a non-catching group
space   matches a space
[^ ]+   mathces a word
)       ends the non-catching group
{4}     repeats the group four times
)       ends the catching group
space   matches the fifth space

The $1 in the replacement string gets the value caught by the group.

Another alternative would be to loop through the string and look for spaces, then use Substring to get the parts before and after the fifth space:

int cnt = 0, index = 0;
while (cnt < 5) {
  if (s[index++] == ' ') cnt++;
}
string t = s.Substring(0, index - 1) + Environment.NewLine + s.Substring(index);


First, your game doesn't have a name! (Which is why I renamed the question like that...)

A few direct things to focus on:

if (MetalKingABC === 1) {
    MetalKingABC = "Metal King A";
}
else if (MetalKingABC === 2) {
    MetalKingABC = "Metal King B";
}
else {
    MetalKingABC = "Metal King C";
}

This is not how you do that.

Instead of using 1 + Math.floor get rid of the 1 as 0 is a valid array index, and is helpful in many situations.

Instead of using * 2, alongside an array, use * array.length.

Instead of using an if-else loop with duplicate logic (string assignment), use an array instead.

var metalKingTypes = ['A', 'B', 'C'];
var metalKing = metalKingTypes[Math.floor(Math.random() * metalKingTypes.length)];

Instead of using MissOneCritical: use a switch

After you decide who to attack, and then attack them, the game is over! Even if you miss or only do 1 damage!

Set a isActive variable to keep the game going.

A few indirect things:

WhichOneToAttack: could be better named: DecideOpponent
FleeOrFight: You naming structure should be camelCase where the first word is entirely lowercase.
You can use this to get a random true or false value: Math.floor(Math.random() * 2)

Your structure:

You have a bunch of loose functions that aren't linked to one another in any other way than the fact that they call each other.

Use a class structure, or a prototype chain, that way you can avoid passing parameters around:

Taking those changes into consideration would give you something like this:

    function Game(){
        alert("Metal Kings (A, B, and C) have appeared!");

        /* Which Metal King (A, B, or C) will Angelo decide to attack?
         * 33% probability for each.
         */

        var metalKingTypes = ['A', 'B', 'C'];
        this.monster = "Metal King " + metalKingTypes[Math.floor(Math.random() * metalKingTypes.length)];
        this.isActive = true;
        while (this.isActive) {
            this.DecideOpponent();
        }
    }
    Game.prototype.DecideOpponent = function(){
        alert("Angelo is about to attack " + this.monster + ".");

        // Metal King has a 50% chance of fleeing the battle.

        var fleeOrFight = Math.floor(Math.random() * 2);

        if (fleeOrFight) {
            alert(this.monster + " flees like lightning!");
            // The battle ends here before Angelo attacks.
            return false;
        }
        // 70% chance of MISS, 20% of ONE damage, 10% of Critical.
        var attackOptions = ['evade', 'normal', 'critical'];

        var attack = attackOptions[Math.floor(Math.random() * attackOptions.length)];
        switch (attack) {
            case 'evade':
                alert(this.monster + " swiftly evades Angelo's attack.");
                break;
            case 'normal':
                alert("Angelo inflicts 1 point of damage on " + this.monster + ".");
                break;
            case 'critical':
                var CriticalRange = 197 + Math.floor(Math.random() * 60);

                alert("Angelo lands a critical hit on " + this.monster + ", dealing massive " +
                      "damage of " + CriticalRange + " points! Angelo defeats " + this.monster + ".");

                // When defeated, Metal King drops a shield with an 80% probability.

                var shieldDrop = Math.floor(Math.random() * 2);

                if (shieldDrop) {
                    alert(this.monster + " drops a shield. Angelo obtains a Diamond Shield!");
                }
                this.isActive = false;
                break;
        }
    };

    // Finally, call the function.

    var g = new Game();

Additionally, instead of using alert consider building each line of the game to the console or to a HTML element.

Something like:

function buildToHTML(text){
    var field = document.getElementById('gameField');
    field.text += text;
}


First, we encounter interface IParse.

public interface IParse {
    void Parse(string[] txtFile);
    void Add(List<char> map);
}

You should use C# conventions.

interface name should be a noun or noun phrase IParse -> IParser
use a plural name for a variable that represents a sequence of items txtFile -> segments??
use a meaningful name to describe structures map -> ?? -> doesn't say anything
use the correct types, preferrably interfaces, when dealing with sequences; For instance, IEnumerable to iterate, IList to manipulate.
Note that your interface does not have any state or return values. We are never able to interact with it bi-directionally. Too much encapsulation perhaps?

Refactored:

public interface IParser {
    void Parse(IEnumerable<string> segments); // or whatever we are talking about ?
    void Add(IList<char> map); // what is map ?
}

Let's move on to ParseObstacles.

Your state is public, is this as designed or a code smell? Again, use conventions.

public Dictionary<char, string> Dict;
public List<Entity> Entities;

private IDictionary<char, string> values; // they are values I suppose
private IList<Entity> entities;

Next, we find method Parse.

the signature is already changed by interface implementation
Only use i as an index in an iterator
perform i.Split(')') once
Dict is already renamed previously

public void Parse(string[] txtFile) {
    foreach (var i in txtFile) {
        if (i.Contains(")")) {
            var tile = i.Split(')')[0].ToCharArray()[0];
            var name = i.Split(')')[1].Trim();
            Dict.Add(tile, name);
        }
    }
}

After changing the method:

 public void Parse(IEnumerable<string> segments) {
      foreach (var segment in segments) {
          if (segment.Contains(")")) {
              var tokens = segment.Split(')');
              var tile = tokens[0].ToCharArray()[0];
              var name = tokens[1].Trim();
              values.Add(tile, name);
          }
      }
 }

Next up, method Add. This is a black-box for us. Consider the fact ParseHelper adds cyclomatic complexity to your API. Perhaps its code should be divided into the other classes.

public void Add(List<char> map) {
     ParseHelper.AddEntities(map, Dict, Entities);
}

public void Add(IList<char> map) {
       // not convinced about ParseHelper ..
       ParseHelper.AddEntities(map, values, entities);
}

And finally, ParserFacade.

Let's have a look at the singleton.

A private constructor, well done.
A nested static class holding the singleton, good design.
all caps -> take it easy: INSTANCE -> Instance
a getter method is best substituted with a property getter: getInstance() -> Instance

private ParserFacade() { }

private static class ParserFacadeHolder {
    public static readonly ParserFacade INSTANCE = new ParserFacade();
}

public static ParserFacade getInstance() {
    return ParserFacadeHolder.INSTANCE;
}

After changes:

private static class ParserFacadeHolder {
    public static readonly ParserFacade Instance = new ParserFacade();
}

public static ParserFacade Instance => ParserFacadeHolder.Instance;

I don't like this helper class, but I did expect it to be static. Here you used an instance.

  private ParseHelper parseHelper;

Public state detected. Code smell?

 public ParseExits exits;
 public ParseObstacles obstacles;
 public ParsePlatforms platforms;
 public ParseCustomers customers;

Method StartParse:

What bothers me here is the inconsistent and convoluted design of parsing behavior. ParseExits (and sibling classes) can parse the file. But then the facade calls the infamous helper to parse additional data, to then forward this data to ParseExits. This design is too complex in behavioral complexity.

 exits = new ParseExits();
 exits.Parse(file);
 exits.Add(ParseHelper.GetAllTiles(file));


I can give you two ways to approach this: via JavaScript or CSS.
JavaScript
You can use the .closest() method of the HTMLElement interface. You need to pass it a CSS selector, and it will find you the closest DOM ancestor of the element that matches the given selector, or null if no such ancestor was found.
In this case, you could use it like this:
function openModal(e) {
  if (e.target.closest('.project-box__picture-box')) {
    modalEl.classList.add('open');
  }
}

(full method reference here)
CSS
The other option is to use the pointer-events CSS property. If you set this to none on all elements inside the clickable box, then those elements will not be allowed to be the targets of mouse events; instead, the target will be the closest ancestor that has pointer events enabled.
In this case, you'd need to add this CSS:
.project-box__picture-box * {
  pointer-events: none;
}

And this JS:
function openModal(e) {
  if (e.target.classList.contains('project-box__picture-box')) {
    modalEl.classList.add('open');
  }
}

(full property reference here)


The efficiency and options of my PNG sequence JS class

I would suggest a few minor changes:

Use setTimeout instead of setInterval to ensure that callbacks don't stack up if they can't be serviced on time.  This implies re-invoking this.interGo at the end of the callback to re-trigger the timer.
Only declare and use self in the functions that need it, to avoid traversing the scope chain unnecessarily.
Remove over-reliance on the Number constructor.


Using Bluebird with fs to read a file within each of an (variable length) array of directories

Several things you could simplify:

You don't need to use .spread() since the data is already in an array.
If you just process each file as it is read, you can avoid the .map() iteration entirely.
You can avoid some temporary variables.
You should declare all local variables with const, let or var as appropriate.

Here's modified code:

var gulp = require('gulp')
  , path = require('path')
  , Promise = require('bluebird')
  , fs = Promise.promisifyAll(require('fs-extra'));

let components = [
    'comp1',
    'comp2',
    'comp3'
];
let npmScope = '@myscope';
gulp.task('getstyle', () => {
    const componentsBaseLocation = path.join(__dirname, 'node_modules', npmScope);
    Promise.map(components, (componentName) => {
        return fs.readFileAsync(path.join(componentsBaseLocation, componentName, 'package.json'), 'utf8').then(data => {
            const packageDatum = JSON.parse(data);
            const tempName = packageDatum.name.match(new RegExp(`${NpmScope}\/(.*?)$`))[1];
            return {
                name: tempName,
                style: path.join(componentsBaseLocation, tempName, packageDatum.style)
            };
        });
    }).then(components => {
        console.log(JSON.stringify(components, null, 2));
    });
});

You may also want to handle a failure in JSON.parse() with a local try/catch handler so rather than end the entire operation, you can handle an individual error and continue with the rest of the processing, but that depends entirely upon how you're using this code and what you want to happen if a parse failure occurs.

You may also want to handle a failure in packageDatum.name.match().


Is it really necessary to split vertex and fragment shaders into their own type? It causes the type to go from 4 bytes to 16 bytes on a typical 64 bit processor, just for it to store a vtable ptr for the destructor that's never going to do anything different.

They could privately inherit and not have a virtual destructor, but I would rather they just be a single class and let incorrectly assigning shaders to a program be a runtime error. There's already a potential failure point when creating the shader program, and the gl error should alert the client to what went wrong, so it's not introducing a new point of failure.

You can't use the default move functions because they won't zero-out the id, and glDeleteShader will be called twice on the same id.

Consider using a factory function to create shaders from file instead of doing file IO in the constructor. It will make it easier to test, and it's also not obvious that this is a blocking function that shouldn't be called on UI threads.

It also makes it more portable to possibly use in a context that doesn't want to use fstreams for doing file IO, for example if you had zipped shaders or hosted them on a cloud it would make more sense to pass in a byte array which is what  glShaderSource will expect.

If you're going to use a path constructor, consider std::filesystem::path.


IKM C++ assessment asks about std::unordered_set, part #1

Defining an operator== for your own type is overloading.  The overload set includes all the built-in signatures.
Based on how you worded it, I agree with (1).  It is not true that you must define operator== for that struct in order to use it with std::unordered_set.  You can use the template argument, or you can cause the default predicate to work in other ways especially in newer versions of C++ (e.g. default the spaceship operator).
As for the example, doesn't it also need to specialize std::hash in order for it to work?  std::unordered_set<ikm_test_struct, ikm_test_struct> doesn't make sense.
If this test is going to be read by other prospective team members, then essaying what you thought is going to communicate to them that you (1) know your stuff; and (2) will be likely to apply the same skill to interpreting requirements.  Finish by correcting the sloppy nomenclature, linking to cppreference and/or a copy of the Standard, and reviewing the code of the sample (with citations to the Standard Guidelines).
If you're passed on as "overqualified", you'll be glad in the long run.
If it's a multiple-choice computer-based thing that just reports the score, that can be a real pain.  I recall encountering one where the expected results were sometimes just plain wrong, or out of date, or the question was worded poorly.  You should contact the people who made the test.


Identifiers with leading underscore(s) followed by a capital letter are reserved for the implementation and should not be used in your own code. It's easiest to just avoid leading underscores.
When using enable_shared_from_this it's important to use a static factory function and make the other constructors private. This prevents calling the Example constructor directly (where calling shared_from_this will be undefined behaviour, since we don't have a shared_ptr).

Do we really need enable_shared_from_this? The whole thing could be more easily written as:

    class Example
    {
    private:

        Example() { }

    public:

        static std::shared_ptr<Example> Create()
        {
            auto example = std::make_shared<Example>();
            example->do_the_thing();

            return example;
        }
    };

It really depends on what do_the_thing() is...

If we have to register the class somewhere after creation (or consistently perform some action), perhaps that logic doesn't belong in the Example class at all.

struct Example {};

struct Registry
{
    template<class T, class... Args>
    std::shared_ptr<T> CreateAndRegister(Args&&... args)
    {
        auto object = std::make_shared<T>(std::forward<Args>(args)...);
        Register(object);
        return object;
    }
};

auto registry = Registry();
auto e = registry.CreateAndRegister<Example>();

While an object has control over it's own copy / move semantics, it generally shouldn't care who / what owns it.

So the question is: why does Example need to "break the 4th wall" and know that it exists inside a shared_ptr?

Large inheritance hierarchies are out of fashion nowadays (with good reason), but with a general solution, you may need to cope with:

struct ExampleA : enable_defer, enable_shared_from_this<ExampleA> {};
struct ExampleB : ExampleA {}; // what if B wants to defer something?

and

struct ExampleA : enable_defer, enable_shared_from_this<ExampleA> {};
struct ExampleB : enable_defer, enable_shared_from_this<ExampleB> {};
struct ExampleC : ExampleA, ExampleB {}; // uh oh... ?

shared_from_this is quite complicated to use as it is with a class hierarchy.


Flatten to get all child controls of certain type in a UIView

Let's start with the method and parameter names (this part is highly
opinion based :)

flatten() does not describe well what you method does: It traverses
recursively a tree-like structure and maps the elements to some values.
Swift already has a flatMap() function (and similar methods for
arrays and other types) which does a similar thing, but only one level
deep. Therefore I would call the method recursiveFlatMap().

Also the descendants of a node in a tree are usually called "children",
so I would choose that as name for the second parameter. (And perhaps
you want to generalize the code for other types, such as sequences.)

for original in self { ... }

iterates of the array elements, therefore I would write that as

for element in self { ... }

let transformed = transform(original)
if transformed != nil {
     result.append(transformed!)
}

can be simplified with optional binding:

if let transformed = transform(element) {
    result.append(transformed)
}

Then we have:

extension Array {
    func recursiveFlatMap<TResult>(transform: (T) -> TResult?, children: (T) -> [T]) -> [TResult] {
        var result = [TResult]()
        for element in self {
            if let transformed = transform(element) {
                result.append(transformed)
            }
            result += children(element).recursiveFlatMap(transform, children: children)
        }
        return result
    }
}

Now let's have a look how the method is called:

let labels = someView.subviews.recursiveFlatMap(
                { $0 as? UILabel },
                children: { $0.subviews })

What strikes me is that you have to specify subviews twice:
In someView.subviews and in $0.subviews.
If the method were called on someView itself then we would have to
specify only once how to descend to the "child nodes".

This means that instead of an Array extension method we have a
(free) generic function which takes the "root of the tree" as the
first argument:

func recursiveFlatMap<T, TResult>(root: T, transform: (T) -> TResult?, children: (T) -> [T]) -> [TResult] {
    var result = [TResult]()
    if let value = transform(root) {
        result.append(value)
    }
    for child in children(root) {
        result += recursiveFlatMap(child, transform, children)
    }
    return result
}

The for-loop can be replaced by the built-in flatMap() method:

func recursiveFlatMap<T, TResult>(root: T, transform: (T) -> TResult?, children: (T) -> [T]) -> [TResult] {
    var result = [TResult]()
    if let value = transform(root) {
        result.append(value)
    }
    result += children(root).flatMap( { recursiveFlatMap($0, transform, children) } )
    return result
}

The function is called as

let labels = recursiveFlatMap(someView,
                { $0 as? UILabel },
                { $0.subviews as! [UIView] })

Finally, you can mark the two closure parameters with the @noescape
attribute. This is new in Swift 1.2 (described in the
Xcode 6.3  release notes) and tells the compiler that
the closure is used only during this function call and
does not outlive the lifetime of the call. This allows some
compiler optimizations:

func recursiveFlatMap<T, TResult>(root: T,
    @noescape transform: (T) -> TResult?,
    @noescape children: (T) -> [T]) -> [TResult]
{
    var result = [TResult]()
    if let value = transform(root) {
        result.append(value)
    }
    result += children(root).flatMap( { recursiveFlatMap($0, transform, children) } )
    return result
}

More thoughts (inspired by this blog post):

recursiveFlatMap() does actually three things:

Recursively traverse a tree-like structure,
transform each object, and
select the objects for which the transformation succeeded.

Swift has built-in methods for the second and third task: map()
and filter(). So you could just define a function that recursively
flattens the given object (in your case the tree of subviews):

func recursiveFlatten<T>(root: T, @noescape children: (T) -> [T]) -> [T] {
    return [root] + children(root).flatMap( { recursiveFlatten($0, children) } )
}

and then use it as

let labels = recursiveFlatten(someView, { $0.subviews as! [UIView] })
    .filter( { $0 is UILabel } )
    .map( { $0 as! UILabel } )

The advantage is that you have a simpler function and a clear
separation into different tasks.

There is a small drawback: an array of all subviews is created first,
and then the labels are extracted. But that is probably tolerable if
the number of subviews is not too large.

(One could work around this problem by defining a method which returns
a "lazy sequence", posted separately as Recursive flattening of Swift sequences.)


I would say you do too many things at once. The important thing here is this check:

if (userManager.IsInRole(currentUserId, thisRole.Name))
{
    return true;
}

This needs a list of role-names to iterate over:

foreach (var roleName in roleNames)
{
    if (userManager.IsInRole(userId, roleName))
    {
        return true;
    }
}

return false;

The list of role-names seems to be dependent of some given permissions and a company:

var givenPermissions = GetGivenPermissions();
var roleNames = GetRoleNames(companyId, givenPermissions);

The first is easy enough to extract from the given code:

IEnumerable<string> GetGivenPermissions()
{
    return Permissions.Split(',').ToArray();
}

The other one is trickier, but I think I got it right:

IEnumerable<string> GetRoleNames(string companyId, IEnumerable<string> givenPermissions)
{
    var existingPermissions = db.Permissions.Select(p => p.ActionName);
    var relevantPermissions = givenPermissions.Intersect(existingPermissions);

    foreach (var permission in relevantPermissions)
    {
        var allRoles = db.Roles.Select(x => x.Id);
        var relevantPermissionRoles = db.PermissionRoles
                                        .Where(p => p.Permission.ActionName == permission && p.CompanyId == companyId)
                                        .Select(x => x.RoleId)
                                        .ToList();

        var relevantRoles = allRoles.Intersect(relevantPermissionRoles).ToList();

        foreach (var role in relevantRoles)
        {
            var thisRole = db.Roles.Find(role);
            var name = thisRole.Name;
            yield return name;
        }
    }
}

This is one nasty query:

It's a good mix of things querying the database and things filtered in memory. - It's hard to figure out what it actually do, and what the requirements for the roles really are.
It's also a mix of code operating on objects and primitive values, which is probably why db.Roles is queried twice.

What I would like to see in here is something that:

First retrieve necessary data from the database, once.
Filter it against in-memory data.
Return the resulting role names.


Nicely tabulate a list of strings for printing

A slightly more readable version:

def tabulate(words, termwidth=79, pad=3):
    width = len(max(words, key=len)) + pad
    ncols = max(1, termwidth // width)
    nrows = (len(words) - 1) // ncols + 1
    table = []
    for i in xrange(nrows):
        row = words[i::nrows]
        format_str = ('%%-%ds' % width) * len(row)
        table.append(format_str % tuple(row))
    return '\n'.join(table)

Most notably, I've defined width to include padding and using string formatting to generate a format string to format each row ;).


bash wrapper around 'git commit' to automatically bump (Python) package CalVer and create matching CalVer tag on new commit

First of all I'd like to recommend shellcheck (online, GitHub) as a very useful tool to detect errors (even small misspellings of variables) and possible misbehaviours, etc.. With this you would have been warned about double-quoting your variables to prevent accidental splitting.

#! /bin/bash

There is no need to export these variables, since they won't be used after the termination of the script.
I'd personally stay clear from all caps variable names, if they are not environment variables. (By this convention, shellcheck will not complain for these variables if they are unset, as it assumes these to be provided by the shell.)
In principle, there is no need to double-quote a subshell, but it does not hurt.

timestamp="$( date '+%Y.%m.%d.%H%M' )"
verpath='.verpath'

Since you have just set the variable, this if clause will never trigger, as it is never empty. You probably would like to check whether the file exists (and is readable).

if [ -z $VERPATH ]
then
  # Complain and exit
  echo "ERROR: Path to files with versions to update must be provided in {repo root}/.verpath"
  echo " "
  exit 1
fi

I second switching to the bash built-in test [[ expression ]].
For debugging purposes I try to stick with positive evaluations, usually inserting a statement that it works as intended.
While in a simple script like this, echo is perfectly fine, I still recommend looking at printf for more complex things. I'd probably use something like the following:

if [[ -f "$verpath" && -r "$verpath" ]] ; then
  :  # do nothing (or give a debug statement)
else
  # complain and exit
  printf 'ERROR: Paths to files with versions to update should be provided in %s.\n\n' "$verpath"
  exit 1
fi

Be aware that read without the option -r will mangle backslashes (see SC2162). If for whatever reason the carriage return is missing from the last line, it will be ignored, better use the following while loop, where -n tests for a non-zero length string:

while read -r verfile || [[ -n "$verfile" ]] ; do
  : # do something
done < "$verpath"

Like in the other answer suggested, I also prefer to keep track of temporary files, instead of assuming they have been created as intended. This will also spare you of reading in the file again.
Since you are making backups, I would also switch to a different ending like .bak. Initialise the array first:

declare -a backups

I'd again check whether the file exists and is readable.
Since these are backups, I'd also use the -a option to cp to archive them. I'd advise on exiting if the command fails. You might also want to consider checking whether the target backup file does already exist and exit if it does.
The inline substitution with sed might have a catch, if there are fewer of more spaces in the search pattern. I think you could be a bit more greedy.

if [[ -f "$varfile" && -r "$varfile" ]] ; then
  printf 'INFO: Updating %s.\n' "$varfile"
  # Add backup file to array
  backups+=( "$varfile.bak" )
  [[ -e "${backups[-1]} ]] && { printf 'WARNING: backup %s exists.\n' "${backups[-1]}" ; exit 1 ; }
  cp -a -- "$varfile" "${[backups[-1]}" || { printf 'ERROR: backup of %s failed.\n' "$varfile" ; exit 1 ; }
  sed -i "s/^__version__.*$/__version__ = '$timestamp'/" "$verfile"
  git add "$verfile" || { printf 'ERROR: adding %s to repository failed\n' "$verfile" ; exit 1 ; }
  printf '\n'
else
  printf 'INFO: file %s not found.\n\n' "$verfile"
fi

# So user can see what was updated
sleep 2s

The bash built-in $@ is an array, it needs to be double-quoted to prevent resplitting. On the other hand, $* is a string, i.e. it looses the elements of an array. Unquoted, it will also be resplit, which is hardly ever anything you would want.
Always check the exit state of a command directly to prevent it being overwritten.

# Actually do the commit, passing through any parameters
if git commit "$@"
then
# Commit succeeded: tag HEAD with $timestamp and delete backup file(s).
  git tag -f "$TIMESTAMP" || { printf 'WARNING: Adding tag failed.\n' ; }
  rm -f -- "${backups[@]}"
else
# Commit failed: restore the backups to its original location.
  for file in "${backups[@]}" ; do
    mv -- "$file" "${file%.bak}" && git reset HEAD "$file" &> /dev/null
  done
fi

Generally I do all file handlings much more verbose, wrapping everything into a function and switch off the output of that function as necessary, i.e.

#! /bin/bash
mybackup ()
{
  while [[ -n $1 ]] ; do
    : # Things to do
    source="$1"
    shift
    target="$source.bak"
    cp -vp "$source" "$target" >&3 2>&3
  done
  : # more things to do ...
}

if [[ "$1" == "-s" ]] ; then
  exec 3> /dev/null
  shift
else
  exec 3>&1
fi

mybackup "$@"

This would also make things simpler if you were to create logfiles of your script, but that is beyond this review.

Right now your versioning depends on an auxiliary file, that you probably create manually. I don't know how large your repositories are and how often you are using the versioning statements. It might be better to either check every file, or hardcode the ones that need to be checked into the script, instead of an external file.


How to efficiently loop through paragraphs and make simple changes with Word VBA (Specially reverse loop to Delete Paragraphs)

Answering my Own question to share with community the Height of stupidity in my code and gradually how over 1 or 2 sleepless nights of testing, the problem was reduce to workable.

First the height of stupidity is the line

     If i < .Paragraphs.Count Then

even after knowing well that while working with such giant document interaction with document is to keep minimum, I resorted to  .Paragraphs.Count in every loop of 56 K paragraphs. Whereas .Paragraphs.Count had already been assigned to variable PrCnt.  Also the If is used to only avoid the error trying to access next para while in the last loop of paragraphs and intended to act once only.

Replacing it with 'PrCnt` make the code somehow stable and could run through the code while disabling write on the document.

Next Thanks to @Ryan Wildry suggestion and tried to go for For Each Loop. Since I am deleting paragraph marks. I tried to go for a Forward For Each loop and test the conditions and take the paragraphs number of the paragraphs to be deleted to a Array. This loop takes only 1-2 minutes to collect the desired information form 56 K paras.

Now after completing the loop, started replacing the paragraphs in reveres loop in this fashion

 For i = UBound(ParaNumToDelete) To 1 Step -1
 .Paragraphs(ParaNumToDelete(i)).Range.Characters(LnArr(i)).Text = " "

but this also found taking around 6-7 hours to complete 2.4 K page 56 K paragraphs (and 16 k paragraphs marks to replace) document.  150 seconds to replace 50 paragraphs in the start loop (i.e. near bottom of documents) and hardly 1-2 seconds do replace 50 paragraphs at the end of loop (i.e. near start of the document). Code execution is unstable and feared to be in Non Responding state even with single click.

So one more measures added to Save the document at say every 200 replacement, so code could be run again to complete the uncompleted task any time later.

Finally again thanks to  @Ryan Wildry's comment and a Range Array was created in the First For Each loop (taking 1-2 minutes) and next the range array was iterated in reverse order to replace paragraph marks. It takes only around 10 minutes to complete without save (or around 15 minutes  with save at 200 replacement)

The final code:

Sub TestPara()
Dim Para As Paragraph, PrvLn As Long, xRng As Range, PrvRng As Range
Dim i As Long, ln As Long, tm As Double, PrCnt As Long
Dim ChrSize As Integer, PrvChrSize  As Integer, LastChrSize As Integer
Dim ChrFont As String, PrvChrFont  As String, LastChrFont As String
Dim ChrItalic As Boolean, PrvChrItalic As Boolean, LastChrItalic As Boolean
Dim OnOff As Boolean, DelCnt As Long, DoSave As Boolean
Dim RngArr() As Range, Pos As Long
tm = Timer

TurnOn False

  With ActiveDocument
  PrCnt = .Paragraphs.Count
  Debug.Print PrCnt
  DelCnt = 0
  PrvChrSize = 0
  PrvChrFont = 0
  PrvChrItalic = False
  PrvLn = 0
  i = 1

    For Each Para In .Paragraphs
    ln = Para.Range.Characters.Count
    Pos = Para.Range.End
    Set xRng = ActiveDocument.Range(Pos - 1, Pos)

        If ln > 1 Then
            With Para.Range.Characters(ln - 1).Font
            LastChrSize = .Size
            LastChrFont = .Name
            LastChrItalic = .Italic
            End With

            With Para.Range.Characters(1).Font
            ChrSize = .Size
            ChrFont = .Name
            ChrItalic = .Italic
            End With
        Else
        LastChrSize = 0
        LastChrFont = 0
        LastChrItalic = False
        ChrSize = 0
        ChrFont = 0
        ChrItalic = False
        End If

        If (ChrSize = 15 And ChrFont = "Arial" And ChrItalic) _
        And (PrvChrSize = 15 And PrvChrFont = "Arial" And PrvChrItalic) Then
        DelCnt = DelCnt + 1
        ReDim Preserve RngArr(1 To DelCnt)
        Set RngArr(DelCnt) = PrvRng
        End If

        PrvChrSize = LastChrSize
        PrvChrFont = LastChrFont
        PrvChrItalic = LastChrItalic
        PrvLn = ln
        Set PrvRng = xRng

        If i Mod 2000 = 0 Then
        Debug.Print i & "/" & PrCnt
        End If
    i = i + 1
    Next
Debug.Print " paragraph to delete:" & DelCnt
Debug.Print " Seconds taken to Calc:" & Timer - tm

TurnOn False
DoSave = True

    For i = UBound(RngArr) To 1 Step -1
    RngArr(i).Text = " "

        If i Mod 1000 = 0 Then
        .UndoClear
        DoEvents
        Debug.Print i, Timer - tm
        End If

        If DoSave Then
        If i Mod 200 = 0 Then
        .Save
        DoEvents
        Debug.Print "Save at delete Countdown " & i & "/" & Timer - tm
        End If
        End If
    Next

End With

Debug.Print "  Delete completed in Seconds:" & Timer - tm

TurnOn
Debug.Print " pagination Completed:"
Debug.Print " Seconds taken:" & Timer - tm
End Sub
Sub TurnOn(Optional OnOff As Boolean = True)
Application.ScreenUpdating = OnOff
    With Options
    .Pagination = OnOff
    .CheckSpellingAsYouType = OnOff
    .CheckGrammarAsYouType = OnOff
    End With
End Sub

Hope my ordeal will help the community in similar situation


Calculate regression coefficients for specific conditions in a data frame

A bunch of things to say.

You're looping 3 times on the same vector "TANK", once would have be enough.
You're growing vectors in each loop
One loop just recreate the same vector reversed (more on this later)
One loop repeat a vector as much as there's entries in TANK (which is  not what you're after I'm pretty sure).
You're creating a local data.frame just to return it.

For your questions:

  it does return the list in reverse order 30 - 1

You're making the vector by prepending the value before the actual state:

for(i in TANK)
     tank <- c(i, tank)

Using tank <- c(tank, i) will give you the normal order.

  it changes the treatment labels from letters ("A", "B", "C", etc...)
  to numbers ("1", "2", "3", etc...).

I highly suspect TREATMENT to be of class factor, concatenation in the vector drop the factor and keep only the indices values.

DISCLAIMER I made the assumption that your variables are:

All of length 90
Matching by the TANK name position

You code can be optimized to:

k.tank <- function() {
  # allocate the vector once before the loop
  k <- numeric(30)
  treat <- character(30)
  tanks=unique(TANK)

  for(i in seq_along(tanks)) { # loop on indice instead of value
    # Assign the result in the proper place directly
    treat[i] <- TREATMENT[TANK == i][1]
    k[i] <- coef(summary(lm(log(MASS)[TANK == tanks[i]] ~ DATE[TANK == tanks[i]])))[2, 1]
  }

  # create the data.frame, as last statement this will be the function return value
  data.frame(tanks, treat, k)
}

With sample values:

set.seed(42)
MASS=runif(90)*100
TANK=rep(1:30,3)
TREATMENT=rep(rep(LETTERS[1:5],6),3)
DATE=sort(rep(seq.Date(Sys.Date(),by=1,length.out=3), 30))

This gives:

   tanks treat           k
1      1     A -0.15155006
2      2     B  0.02382969
3      3     C  0.48811951
4      4     D -0.19125411
5      5     E  0.14033970
6      6     A -0.50391863
7      7     B -0.49942663
8      8     C  0.90820123
9      9     D  0.02682661
10    10     E -0.53769180
11    11     A -1.18268285
12    12     B -0.81647939
13    13     C -0.73156739
14    14     D  0.31479427
15    15     E -0.42545699
16    16     A -0.13376959
17    17     B -2.41040604
18    18     C  0.58095049
19    19     D  0.03985375
20    20     E -2.93855112
21    21     A -0.22053714
22    22     B  0.06480414
23    23     C -0.50659181
24    24     D -0.19135960
25    25     E  1.12094187
26    26     A  0.04589634
27    27     B -0.25630776
28    28     C -1.15457853
29    29     D -0.82633221
30    30     E -0.50380311

Now you read until there, and still assuming your variables are of same length (but if not I can't really get your code) you may try doing something more direct:

# Create a data.frame with your observations
df <- data.frame(TANK,MASS,TREATMENT,DATE, stringsAsFactors=FALSE)
# Create a function for ease of use, taking a data.frame as input
tank.coef <- function(int.df) {
  coef(summary(lm(log(int.df$MASS) ~ int.df$DATE)))[2,1]
}

# run the above function on global data.frame, subsetting by TANK value
k <- by(df,df$TANK,tank.coef)

This will return a by object (coef by tank):

> head(k)
df$TANK
          1           2           3           4           5           6
-0.15155006  0.02382969  0.48811951 -0.19125411  0.14033970 -0.50391863

You can get rid of the name with as.vector and recreate a data.frame with:

> rdf <- data.frame(tank = df$TANK[df$TANK==names(k)], treat = df$TREATMENT[df$TANK==names(k)],k = as.vector(k))
> head(rdf)
  tank treat           k
1    1     A -0.15155006
2    2     B  0.02382969
3    3     C  0.48811951
4    4     D -0.19125411
5    5     E  0.14033970
6    6     A -0.50391863


Multiplayer Peer-To-Peer position interpolation

I recommend you always write access modifiers for class members and for classes itself. It will make code more clear and understandable. So instead of

Queue<Vector3> positions = new Queue<Vector3>();
Queue<Quaternion> rotations = new Queue<Quaternion>();
...
void Start() { ... }

write

private Queue<Vector3> positions = new Queue<Vector3>();
private Queue<Quaternion> rotations = new Queue<Quaternion>();
...

private void Start() { ... }

Also these queues are not supposed to be changed so mark them with readonly keyword:

private readonly Queue<Vector3> positions = new Queue<Vector3>();
...

It is a matter of taste but it is more common for C# to place opening curly braces on the next line:

private void Start()
{
    photonView = gameObject.GetComponent<PhotonView>();
    moveTowards = transform.position;
}

This code

if (Mathf.Abs(Vector3.Distance(transform.position, moveTowards)) < 0.001f) {
    moveInProgress = false;
} else {
    moveInProgress = true;
}

can be simplified to

moveInProgress = Mathf.Abs(Vector3.Distance(transform.position, moveTowards)) >= 0.001f;

Also it would be better to declare 0.001f as named constant like

private const float DistanceEpsilon = 0.001f;

You should definitely rewrite these conditions:

if (frameNumbers.Count > 0 && ((frameNumbers.Peek() + amountBuffered <= lastReceivedFrameNumber) || frameNumbers.Peek() <= expectedExecuteFrameNumber - amountBuffered)) {
    if (lastReceivedFrameNumber - frameNumbers.Peek() > amountBuffered)

First of all, you use frameNumbers.Peek() multiple times here so store the result of it to variable:

var firstFrameNumber = frameNumbers.Peek();

I recommend to use Any method for checking a collection on emptiness:

frameNumbers.Any()

instead of

frameNumbers.Count > 0

Thanks @Nikita B for pointing out that frameNumbers.Any() should be done before frameNumbers.Peek(). In your case you can just return from the method if there are no elements in the frameNumbers:

if (!frameNumbers.Any())
    return;

These conditions

frameNumbers.Peek() + amountBuffered <= lastReceivedFrameNumber
lastReceivedFrameNumber - frameNumbers.Peek() > amountBuffered

can be written in one form:

lastReceivedFrameNumber - frameNumbers.Peek() > amountBuffered
lastReceivedFrameNumber - frameNumbers.Peek() >= amountBuffered

Now we see that we can store lastReceivedFrameNumber - frameNumbers.Peek() to variable since this expression is used multiple times. So the final form of conditions above will be

if (!frameNumbers.Any())
    return;

var firstFrameNumber = frameNumbers.Peek();
var frameNumbersDifference = lastReceivedFrameNumber - firstFrameNumber;

if (frameNumbersDifference >= amountBuffered ||
    firstFrameNumber <= expectedExecuteFrameNumber - amountBuffered)
{
    if (frameNumbersDifference > amountBuffered)

Also I recommend to extract all subconditions to methods with appropriate names. It will make your code much more easy to read and understand.

Small note: you don't need to write == true or == false when checking value of bool variable. This

if (moveInProgress == true) {

should be rewritten as

if (moveInProgress)
{


All of your if char == '>': ptr += 1 and similar checks should use elif after the first check. By using if for all of the checks, you're forcing them all to run, even once you've found a match. This is wasteful because the checks are necessarily exclusive of each other. Once one check is true, none of the other checks can be. For example, you should have:

if char == '>': ptr += 1
elif char == '<': ptr -= 1

elif char == '+': values[ptr] = (values[ptr] + 1) % 256
elif char == '-': values[ptr] = (values[ptr] - 1) % 256

Now the checks stop once a match is found which prevents unnecessary equality checks.

I'd also try to break this down into a few functions to help testing. Right now, you can only test bf_interpreter as one whole. You could have a function that takes the current character, and the state of the program (the brackets, ptr, outputs...), and returns a new state. That way you can easily test for a given state if a certain command produces a correct new state.

I'm assuming this loop is just to add padding so you don't go off the end of the slots?:

while length <= ptr:
    length += 1
    values.append(0)

You could make that a little neater by just using math and some concatenation. You could also just get rid of length and use len(values):

needed = ptr - len(values)
values += [0] * needed

ptr - len(values) calculates how many slots are needed, then [0] * needed produces that many 0s, and += adds them to values. If needed is negative, [0] * needed will produce [], and essentially cause no change.

If you want to avoid the temporary list that [0] * needed creates, you could replace that with:

values += (0 for _ in range(needed))

Now += just pulls from a generator that produces values as needed.

And then, just like how you don't need length, you don't need code_length either. len(code) is fine; len runs in constant time. You don't need to cache it for performance reasons.

Here's some timings to show the difference in runtime this can cause:

import timeit

TEST_CODE = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."

>>> timeit.timeit(lambda: bf_interpreter_orig(TEST_CODE), number=int(2e5))  # Two hundred thousand tests
77.3481031  # Takes 77 seconds

>>> timeit.timeit(lambda: bf_interpreter_len(TEST_CODE), number=int(2e5))
88.93794809999997

Where bf_interpreter_orig is your original code, and bf_interpreter_len is your original code but using len.

Yes, there's a difference. Note though, that's a ~11 second difference across 200,000 calls. That works out to roughly 58 microseconds per call to the interpreting function.

Unless you're calling bf_interpreter hundreds of thousands of times in a tight loop, the difference is unlikely to matter. This also likely has nothing to do with the fact that you're requesting a length, and more to do with one extra function call. Function calls aren't super fast in Python. Likely any extra call to any function would have similar effects.


Place integers into a vector, sum each adjacent pair, refill vector with only the sums of each pair i.e remove all the original data from the vector

It seems to me that a tiny bit of calculation can simplify the code quite a bit:

auto dest = numbers.size() % 2; // 0 if even, 1 if odd

for (auto src = dest; src < numbers.size(); src += 2, ++dest)
    numbers[dest] = numbers[src] + numbers[src + 1];

numbers.resize(dest);

Although it has the same big-O complexity (linear in both cases) I'd expect this to typically be at least a little faster than the solution @larkey posted, for a couple of reasons. First, it avoids conditional execution by simply computing the starting source/destination positions. Second, when it resizes the array down to the correct size after the additions, it does so in one fell swoop, so to speak, instead of doing a pop_back individually on each item being removed.

If the vector contained objects with non-trivial destructors, the destructor for each object being removed would have to be invoked, so the resize would be linear on the number of items being removed. Given that these are ints, there's really no dtor to run, so the resize can be done with constant complexity (and I'd expect most current implementations of std::vector to include the specializations necessary to actually achieve constant complexity too).

More importantly (at least in my opinion), this seems to me to simplify the code so it's considerably easier to read and understand the intent and result.


Particle simulator using Python - Why is the NumPy version slower than pure Python?

Community wiki - update as posted by the OP in the question based on review by Graipher and AlexV

As Graipher and AlexV mentioned the problem with NumPy version was that the inner loop which updates particle positions (x and y) should be performed independently (not repeated in each timestep). The updated version is as follows,

def evolve_numpy(self, dt):
    timestep = 0.00001
    nsteps = int(dt / timestep)
    r_i = np.array([[p.x, p.y] for p in self.particles])
    ang_vel_i = np.array([p.ang_v for p in self.particles])
    for i in range(nsteps):
        norm_i = np.sqrt((r_i ** 2).sum(axis=1))
        v_i = r_i[:, [1, 0]]
        v_i[:, 0] *= -1
        v_i /= norm_i[:, np.newaxis]
        d_i = timestep * ang_vel_i[:, np.newaxis] * v_i
        r_i += d_i
    for i, p in enumerate(self.particles):
        p.x, p.y = r_i[i]

Doing this improves the results considerably (see the figure below) which shows that the results stated in the book were accurate and this was my mistake (as expected:)),

(The runtime of numpy method is now less than 4 seconds.)


Get consecutive integer number ranges from list of int

Your code takes a list, ensures it's sorted and distinct, then assembles and returns another list. This approach is problematic when the input is in fact a generator, in which case your code forces the entire list to memory first. Also, the data might already be sorted or the caller might not be interested in the entire result.

public static List<(int from, int to)> get_consecutive_ranges(List<int> fids)
{
    if (fids == null || fids.Count == 0) return null;

    fids = fids.OrderBy(a => a).Distinct().ToList();

A much more idiomatic approach is to build an extension method that works on IEnumerable and yields its results. The call to Distinct().OrderBy(a => a) should be left to the caller. Also note that Distinct doesn't guarantee any particular order, so the sorting must always happen afterwards. The actual logic is overly complicated in your code and be greatly simplified as well. Here is how I would do it:

public static IEnumerable<(int begin, int end)> Ranges(this IEnumerable<int> nums)
{
    var e = nums.GetEnumerator();
    if (e.MoveNext())
    {
        var begin = e.Current;
        var end = begin + 1;
        while (e.MoveNext())
        {
            if (e.Current != end)
            {
                yield return (begin, end);
                begin = end = e.Current;
            }
            end++;
        }
        yield return (begin, end);
    }
}

Add a simple helper function for pretty printing, which should also be an extension method:

public static string Show(this IEnumerable<(int begin, int end)> ranges)
{
    return "[" + string.Join(",", ranges.Select(r => r.end - r.begin == 1 ? $"{r.begin}" : $"{r.begin}-{r.end-1}")) + "]";
}

Example usage:

Console.WriteLine(new int[] { }.Ranges().Show());                             -> "[]"
Console.WriteLine(new int[] { 1 }.Ranges().Show());                           -> "[1]"
Console.WriteLine(new int[] { 1, 2, 3, 4, 5 }.Ranges().Show());               -> "[1-5]"
Console.WriteLine(new int[] { 1, 2, 3, 5 }.Ranges().Show());                  -> "[1-3,5]"
Console.WriteLine(new int[] { 1, 3, 5, 6 }.Ranges().Show());                  -> "[1,3,5-6]"
Console.WriteLine(new int[] { 1, 3, 3, 3, 5, 6 }.Distinct().Ranges().Show()); -> "[1,3,5-6]"
Console.WriteLine(new int[] { 6, 3, 5, 1 }.OrderBy(i => i).Ranges().Show());  -> "[1,3,5-6]"


Parse HTTP header using Python and tcpflow

New Lines and indentations help the interpreter know where the code terminates and blocks end, you have to be super careful with them

Like in your if condition, you can't have a newline in between the conditions.

if header.find(" ")==0 or
    header.find("\t")==0:
    continue

This code will error out because you can't have a new line in your condition statement.

Python is New Line Terminated.  It should read like this

if header.find(" ")==0 or header.find("\t")==0
    continue

Same with this piece of code

while headers[i].find(" ")==0 or
    headers[i].find("\t")==0 :
    fields[key]=fields[key]+" "+headers[i].strip()
    i=i+1

It should read:

while headers[i].find(" ")==0 or headers[i].find("\t")==0 :
    fields[key]=fields[key]+" "+headers[i].strip()
    i=i+1


If you were going to use the above you could still utilise Java's autoboxing feature, but there is a shorter form as hinted at by Darth Beleg.

Untested:

int[] ret = new int[c.getCount()];
if (c.moveToFirst())
    for (int i = 0; i < c.getCount();) {
        ids[i++] = c.getInt(2);
        c.moveToNext();
    }
}

Although it is not pertinent to your case it is worth remembering that

ret[i] = iterator.next().intValue();

could throw a NPE.


Puzzle game - converting binary numbers to decimal

Style

Please follow PEP8 conventions on naming: function names should be lowercase_with_underscores

On documentation: information on functions should be put below their definition in the form of a docstring, in order to allow programmatic access via help(function).

generatePassword

List comprehension

The explicit loop in generate_password is unnecessary, it is too long making the reader forget about the logic behind such function.

def generate_password_and_binary(n):
    """ A "password" is a list of length `n` containing random digits. """
    password = [random.randint(0, 9) for _ in range(n)]
    return password, [to_bin(digit) for digit in password]

This version with list comprehension is shorter and more to the point.

I also incorporated the comment into the function name (self-documenting code is better than code + comments) and added a more detailed docstring.

printPassword

I think your printPassword has a serious bug:

>>> generatePassword(8)
([2, 1, 7, 6, 4, 5, 7, 3], ['10', '1', '111', '110', '100', '101', '111', '11'])
>>> printPassword(_)
############
##        ##
##        ##
##  0010  ##
##  0001  ##
##  0111  ##
##  0110  ##
##        ##
##        ##
##        ##
##        ##
##        ##
##        ##
############

Only the first four digits where printed and the rest ignored.
This bug is probably a result of over-complication caused by indexes and comparison, while a plain for iteration over the collection is sufficient, here is a simpler (and correct!) way to write this function:

def print_password(binary_version): # No need to pass all password if only binary part is shown
    wall = "#" * 12
    spaced = "{0}{1}{0}".format("##", " " * 8)
    print(wall, spaced, sep="\n")
    for binary_digit in binary_version:
        print("{0}{1}{2}{1}{0}".format("##", "  ", binary_digit.rjust(4, "0")))
    print(spaced, wall, sep="\n")

Now all of the password is printed:

>>> print_password(['10', '1', '111', '110', '100', '101', '111', '11'])
############
##        ##
##  0010  ##
##  0001  ##
##  0111  ##
##  0110  ##
##  0100  ##
##  0101  ##
##  0111  ##
##  0011  ##
##        ##
############


Linq query performance that use ToList()

You can indeed improve the query by changing the strategy.

If you first GroupBy file extension and Count them inside the GroupBy element selector you can remove ToList and the query will be executed on the server and it won't be necessary to download all the data to group it later on your machine. You will then only get a few groups and their number of elements.

Now for the few file extensions it's very easy and quick to get the category names:

var result =
    Files
    .GroupBy(x => x.Extension, (ext, fs) => new
    {
        Extension = ext,
        Category = Categories.Single(c => c.Extension == ext).Name,
        FileCount = fs.Count()
    })
    // the second GroupBy sums categories with multiple file extensions like pdf, doc etc.
    .GroupBy(x => x.Category, (cat, counts) => new
    {
        Category = cat,
        FileCount = counts.Sum(y => y.FileCount)
    });

This will produce the following query:

SELECT SUM([t3].[value2]) AS [FileCount], [t3].[value] AS [Category]
FROM (
    SELECT (
        SELECT [t2].[Name]
        FROM [Category] AS [t2]
        WHERE [t2].[Extension] = [t1].[Extension]
        ) AS [value], [t1].[value] AS [value2]
    FROM (
        SELECT COUNT(*) AS [value], [t0].[Extension]
        FROM [File] AS [t0]
        GROUP BY [t0].[Extension]
        ) AS [t1]
    ) AS [t3]
GROUP BY [t3].[value]

I've tested it with 1.000.000 rows:

and compared with the ToList version:

In the last rows of the statistics you can see that short version is about 3 times faster then the original one.


Writing computer generated music to a .wav file in C

Endianness
Your program works on little endian machines only.  If you care for it to work on any machine, you would need to fix up all of the fwrite() calls to output specifically in little endian format.
Use struct for header
I would suggest creating a struct for the file header.  That way, you could fill in all the fields (in an endian correct manner) and then do one single fwrite().  From the code it looks like you can combine all the fields into a single header, but if it makes more sense you could have multiple headers (RIFF header, format header, data header, etc).


implode works

        $insertString = '';
        foreach ($ch as $element) {
            $insertString .= '(' . $element . '), ';
        }

        $insertString = rtrim($insertString, ", ");

You can replace this section of code with just something like

        $insertString = '(' . implode('), (', $ch->all()) . ')';

This is shorter with fewer failure points.  And of course, it avoids having to trim off the extra comma at the end.

Bound parameters

But actually, it would be better to replace it with something like

        $insertString = implode(', ', array_fill(0, $ch->count(), '(?, ?)'));

and then pass the values to DB::insert as an array.  I'd write more of the code for this, but I'm not sure exactly how the Laravel Collection objects work.

Naming

Data is already plural (the singular is datum).  There is no datas.

I'd prefer $chunk to $ch.


No it is not secure.
For simplicity assume that your data D is exactly one block long.
Then the ciphertext contains 3 16-byte blocks as follows.

C0 || C1 || C2
=  D xor AES(IV) || MD5(D) xor AES(IV+1) || IV

(The IV is normally prepended to the message, but that is rather irrelevant here).
If an attacker can guess D then the attacker can derive AES(IV) and AES(IV+1) and subsequently
generate another valid ciphertext by computing

D' xor AES(IV) || MD5(D') xor AES(IV+1) || IV

for whatever message D' he likes.
An unkeyed hash just does not give the integrity that you would like. As usual one should use a HMAC or something similar instead of the MD5. Hence the biggest weakness in your protocol is not the primitives that you use, but the fact that you are not using them properly. And just to answer another question posed here: People on SO are far from being competent enough to find every flaw in a new protocol. So you'd better look for an existing standard.
Let me also add, that protocols similar to the one here have been proposed in the 80s. E.g., Kerberos had a similar flaw. Better message authentications such as HMAc were designed exactly to prevent this kind of ciphertext manipulations.


Counting combinations of consecutive symbols in Java

I would build a Map with a custom keying function and just iterate over the length (minus one) of the array of values.

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupFrenquency {
    public static <T> Map<String, Integer> groupFrenquencies(T[] arr, Function<List<T>, String> keyFn) {
        Map<String, Integer> frequency = new HashMap<>();
        for (int i = 0; i < arr.length - 1; i++) {
            String key = keyFn.apply(Arrays.asList(arr[i], arr[i + 1]));
            frequency.put(key, frequency.containsKey(key) ? frequency.get(key) + 1 : 1);
        }
        return frequency;
    }

    public static void main(String[] args) {
        Integer[] sequence = { -1, 0, 0, 1, 0, -1, 0, -1, 1 };
        Function<List<Integer>, String> keyFn = (items) -> String.format("%s,%s", items.get(0), items.get(1));

        System.out.println(groupFrenquencies(sequence, keyFn).entrySet().stream()
                .map(e -> String.format("The count of %-4s = %d", e.getKey(), e.getValue()))
                .collect(Collectors.joining(System.lineSeparator())));
    }
}

Output

The count of 0,0  = 1
The count of 0,1  = 1
The count of 1,0  = 1
The count of 0,-1 = 2
The count of -1,1 = 1
The count of -1,0 = 2

Using reflection, you can create a copy of the array instead of creating an entire list object, when creating the key. The only downside is that you need to pass in the class type of the array, because you cannot initialize a generic array without knowing the type.

import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupFrenquency {
    public static <T> Map<String, Integer> groupFrenquencies(Class<T> type, T[] arr, Function<T[], String> keyFn) {
        Map<String, Integer> frequency = new HashMap<>();
        for (int i = 0; i < arr.length - 1; i++) {
            String key = keyFn.apply(copyArray(type, arr, i, 2));
            frequency.put(key, frequency.containsKey(key) ? frequency.get(key) + 1 : 1);
        }
        return frequency;
    }

    @SuppressWarnings("unchecked")
    private static <T> T[] copyArray(Class<T> type, T[] source, int startPos, int length) {
        T[] copy = (T[]) Array.newInstance(type, length);
        System.arraycopy(source, startPos, copy, 0, length);
        return copy;
    }

    public static void main(String[] args) {
        Class<Integer> type = Integer.class;
        Integer[] sequence = { -1, 0, 0, 1, 0, -1, 0, -1, 1 };
        Function<Integer[], String> keyFn = (items) -> String.format("%s,%s", items[0], items[1]);

        System.out.println(groupFrenquencies(type, sequence, keyFn).entrySet().stream()
                .map(e -> String.format("The count of %-4s = %d", e.getKey(), e.getValue()))
                .collect(Collectors.joining(System.lineSeparator())));
    }
}


Right, one general opinion coming up:

Static's, at least the way you're using them, are just globals in drag. Don't do that. If you need both the View and DB class(or at least some tables from it) in the object, of which you posted a method: either Inject, or lazy-load them. A call to a static method is bound to be slower, and, by the looks of things DB::table is sort-of a factory method. Why call it time and time again, if it's already created and returned the desired object once before. You can injected/lazy-loaded them, or just assign them to a property.
Anonymous functions (lambda's or closures, whichever name you prefer) aren't my favorite addition to PHP. They feel, to me at least, like a typical PHP afterthought. In essence, they're just syntactic sugar. What they actually do is create an instance of the Closure class. I'm not sure on the internals, but I wouldn't be at all surprised if your code were to create instances of Closure on each iteration of the loop. This isn't that bad in a language like JavaScript, where function objects are very cheap, but in PHP, it'd be far cheaper to define a private method, and pass a callable array to usort. Something along the lines of usort($champion->sales, array($this, 'privateSorterMethod'); will almost certainly be faster, especially since you can declare & assign the array outside of the loop. This gives you more control on when and where the array is constructed: not in the loop, if you don't put it there, that's for sure.
Getting data from the database, and returning the view is doing 2 things, and thus a violation of the Single Responsibility Principle. build your $champions array, and return it back to the controller, or whatever called the get_prediction method. The controller is what should link the Model-layer to the view. That's its job: the controller gets the request, decides what the Model-layer needs to do, and sends the output of the model layer back to the view. The model layer should be unaware of the view and vice-versa.
Performing that second query inside the loop is, in all likelihood, not the best way forward. Consider using JOIN, to get all data in one go.
Maintainability: if I were to be assigned your project some time in the future, I'd have to check the actual DB's, to see what you're getting from the sales table. even if you're getting all fields, specify them.
How are you getting your data? As (assoc-)array's? Objects (Stdclass or another object)? Personally, I prefer data models that are directly mapped to the tables. The properties of these data-models correspond to the field names, and they should have a getter and setter for each property. At least, that's what I'd do.

Notes: Calling a static is slower than calling it once, and assigning its return value for re-use. Adding the getTable methods (see below) does mean added overhead (+1 method call), but the overhead will only be noticeable once.
Dropping the anonymous function means better performance, I've made a test-script, and it using a callable array is 50~100% faster. Caching enabled or not, it's the fastest way to go, still.
Fetching rows as data-models with predefined properties is faster than using single stdClass instances, at least: as far as property access is concerned. Basically because the lookup is done using a hashtable, to get the offset of the corresponding zval*. A bit more details here

Just to clarify what I mean by Inject or lazy-load them:

class Foo
{
    private $table = null;
    privte $view = null;//this is a bad idea anyway, but just as an example
    public function __construct(array $tables = array(), View $view = null)
    {//you can pass DB and or view instance to constructor
        $this->tables = $tables;
        $this->view = $view;
    }
    public function setTables(Table $inject)
    {//if you didn't pass to constructor, or need another DB instance for something:
        $this->table[$inject->getName()] = $inject;
    }
    public function setView(View $view)
    {//this is standard DI (dependency Injection)
        $this->view = $view;
    }
    //This is GUARANTEED to return an instance of DB
    //Unless a fatal error occurred.
    protected function getTable($name)
    {
        if (!isset($this->table[$name]))
        {//if table isn't set, load instance on the fly => lazy-loading
            $this->table[$name] = DB::table($name);//get the instance
        }
        return $this->table[$name];
    }
    private function sortCallback($a, $b)
    {
        return strcmp($b->days_since, $a->days_since);
    }
}


Is this the most efficient way to track word changes in a string?

Ruby is fundamentally more about simplicity (readability) than about time/memory efficiency. Otherwise you should choose another language. There are such high level languages, that can beat Ruby, like for example Javascript. And even Python handle strings faster than Ruby at the cost of eternal problems with encodings (don't waste your time on crutches, choose tools wisely).
And even inside Ruby single replacements of one method chain with another can either be efficient or not, depending on your platform (jruby? rubinius? etc.) while there are still different ways to measure an algorithmic complexity especially for your unique kind of input data.

So anyway.

The matrix creation I would write in one of these two ways:

matrix = (0..second.size).map{ |i|
  (0..first.size).map{ |j|
    i==0 ? j : j == 0 ? i : 0
  }
}

matrix = (0..second.size).map{ |i|
  i==0 ? (0..first.size).to_a : [i]+[0]*first.size
}

There is also a solution via transpose, but not functional, and one via zip in which I doubt.
You can omit the return keyword at the last line in Ruby functions.

And this is not Ruby-related, but in the main loop try to iterate through 0...second.length instead of 1..second.length (same for first). In that way you'll swap i-1 with i and i with i+1, getting rid of two decrements in total.


Count the number of inversions using Binary Indexed Tree in an array

def __init__(self, n):
        self.n = n + 1
        self.bit = [0] * self.n

bit has a well-known interpretation in programming which distracts from the intended interpretation here. IMO even something as generic as data would be better.

    def update(self, i, k):
        """Adds k to element with index i
        """
        while  i <= self.n - 1:
            self.bit[i] += k
            i = i + (i & -i)

The loop condition would be more familiar as while i < self.n.

I don't see any reason to avoid +=.

A reference to explain the data structure would be helpful, because otherwise this is quite mysterious.

        mid = left + ((right - left) >> 1)

The reason for this particular formulation of the midpoint is to avoid overflow in languages with fixed-width integer types. Since that's not an issue in Python, I'd favour the more straightforward mid = (left + right) >> 1. It might even be a tiny bit faster.

    q = [ int( i ) for i in raw_input().strip().split() ]

    index = map(lambda t: binary_search(arr, t) + 1, q)

Why the inconsistency? I think it would be more Pythonic to use comprehensions for both.

    # Copy q and sort it.
    arr = sorted(deepcopy(q))

    # index array.
    index = map(lambda t: binary_search(arr, t) + 1, q)

This seems like a rather heavyweight approach. Why not just

    index = sorted((val, idx) for idx, val in enumerate(q))

?

Although asymptotically I don't see any reason why this would be \$\omega(n \lg n)\$, it has a few \$\Theta(n \lg n)\$ stages. The standard algorithm for this problem, which is essentially merge sort, has the same asymptotic complexity but probably hides a much smaller constant behind the \$\Theta\$ / \$O\$.


recursive function : filtering large multidimensional array by key element to HTML list

You can choose a (key => value) pair recursively with this function:

function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

This function makes use of array_walk_recursive() to push into a placeholder array whatever value is pointed to by whichever key matches our needle key.

Proof code:

$array = array(
    'id' => 0,
    'name' => array(
        'it' => 'Tutti',
        'ca' => 'Tots',
        'es' => 'Todos',
        'de' => 'Alle' ,
        'fr' => 'Tous',
        'nl' => 'Alle',
        'en' => 'All'
    ),
    'languages' => array(
        "d" => 33
    ),
    'subTypes' => array(
        0 => array(
            'id' => 1,
            'name' => array(
                'it' => 'Tutti',
                'ca' => 'Tots',
                'es' => 'Todos',
                'de' => 'Alle' ,
                'fr' => 'Tous',
                'nl' => 'Alle',
                'en' => 'All'
            )
        ),
        1 => array(
            'id' => 1,
            'name' => array(
                'it' => 'Tutti',
                'ca' => 'Tots',
                'es' => 'Todos',
                'de' => 'Alle' ,
                'fr' => 'Tous',
                'nl' => 'Alle',
                'en' => 'All'
            )
        ),
        2 => array(
            'id' => 1,
            'name' => array(
                'it' => 'Tutti',
                'ca' => 'Tots',
                'es' => 'Todos',
                'de' => 'Alle' ,
                'fr' => 'Tous',
                'nl' => 'Alle',
                'en' => 'All'
            )
        )
    )
);

print_r(array_value_recursive("de", $array));

The above test code, which seeks all "de" keys, will output:

Array (
    [0] => Alle
    [1] => Alle
    [2] => Alle
    [3] => Alle
)


It's not guaranteed that $TMP_PROGRAM_FILE is on the $PATH, so you need to either set the $PATH or use an absolute path for $TMP_PROGRAM_FILE.

You have problems with mktemp.

-t option: It means different things on GNU/Linux mktemp(1) and Mac OS X mktemp(1).

On GNU/Linux:

-t    interpret TEMPLATE as a single file name component,
      relative to a directory: $TMPDIR, if set; else the
      directory specified via -p; else /tmp [deprecated]

On OS X:

mktemp [-t prefix] template …
mktemp -t prefix

    -t prefix
            Generate a template (using the supplied prefix and TMPDIR if set) to create a filename tem-plate. template.
            plate.

Perhaps the confusion is the reason why the GNU/Linux man page indicates that it is deprecated.  I think you just want to run mktemp TEMPLATE without the -t option.
Cleanup: Use trap "rm $TMP_SOURCE_FILE $TMP_PROGRAM_FILE" EXIT as a more robust way to delete the temporary files, in case your script aborts before reaching the rm commands.
.c suffix:  By writing TMP_SOURCE_FILE="$(mktemp -t sourceXXXX).c", you end up getting mktemp to create the file sourceXXXX.  That file does not get cleaned up.  Also, when you do cat > $TMP_SOURCE_FILE, you may be creating sourceXXXX.c, or worse, truncating an existing file.

On GNU/Linux, a remedy would be to use the --suffix .c option.  Unfortunately, the BSD/OS X version doesn't support it.  One workaround is to rename the file after creation using mv -i — which might fail, but at least it's secure.

A better workaround would be to use gcc -x c to tell GCC that it is C source code, without considering the filename extension.

An even better solution would be…
Avoid $TMP_SOURCE_FILE altogether: gcc can take its source code from its standard input!  Use - as the filename.

gcc -o "$TMP_PROGRAM_FILE" -x c - <<- END_OF_SOURCE
…
END_OF_SOURCE


There is one bug, in that the function doesn't quite do what you want it to. It does not loop though the randomized array, persisting the order until you've reached the end. As you seem to want from your description. What it does do is to randomize the array once, then once more if there is no array index 0 (which is only true if the array is empty). Then it retrieves the first image ID from the array, increases the counter, generates the URL. Before it finally promptly forgets everything done inside the function, except the finalized URL.

If you want true persistence on the order of images, then you need to store it somewhere. Either in the session, or in a database.

As for the last two questions, I've refactored your code to be more in line with recommended practices:

function randomImageLink ($width, $height, $images) {
    // Using mt_rand () instead of array_rand () due to randomization issues.
    $loc = mt_rand (0, count ($images) - 1);

    // Get a random image ID from the array.
    $id = $images[$loc];

    return 'https://unsplash.it/' . $width . '/' . $height . '?image=' . $id;
}

$imageList = [1048, 1049, 1061, 1064, 983, 972, 964];
$imageLink = randomImageLink (800, 600, $imageList);

Note that this is based upon the function you wrote, not the function you wanted. It should, however, work as an example on how you can restructure your code in general.

PS: I've assumed that the list of image IDs come from a external source, such as a "glob()" on a folder or a DB query.


Script to calculate width, and either resize, show, or hide HTML menu

Suggestion: The Math.max method is shorter than ternary operator:

maxWidth = Math.max(maxWidth, $(this).width());
maxWidth = maxWidth > $(this).width() ? maxWidth : $(this).width();


Let's inline stuff that's only used once and replace recursion with library combinators.

import Control.Monad.State (evalState, modify, gets)
import Control.Monad.Loops (takeWhileM)
import Control.Applicative ((*>))
import Data.Char (isSpace)

filterBetween :: [Tag String] -> [Tag String]
filterBetween = (`evalState` 1) . takeWhileM step where
  step tag = modify (+ bracket tag) *> gets (>0)
  bracket tag
    | tag ~== "<span>" = 1
    | tag ~== TagClose "span" = -1
    | otherwise = 0

main = do
  [word] <- getArgs
  http <- simpleHTTP $ getRequest $ escapeURIString isUnescapedInURI $ "http://jisho.org/word/" ++ word
  html <- getResponseBody http
  putStrLn
    $ Data.Text.unpack $ Data.Text.Encoding.decodeUtf8 $ Data.ByteString.Char8.pack
    $ dropWhile isSpace $ reverse $ dropWhile isSpace $ reverse
    $ innerText $ filter (~== TagText "")
    $ filterBetween
    $ tail $ head $ partitions (~== "<span class=\"furigana\">") $ parseTags html

I left the <span> and </span> tags themselves out of what is printed, that's easier to code up so might be the correct way.

Edit: More existing combinators :D

{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.TagSoup.Match (getTagContent)
import Data.Text (strip)
import Data.Text.Encoding (decodeUtf8)
import qualified Data.Text.IO as T

main = do
  [word] <- getArgs
  http <- simpleHTTP $ getRequest $ escapeURIString isUnescapedInURI
    $ "http://jisho.org/word/" ++ word
  html <- getResponseBody http
  T.putStrLn $ strip $ decodeUtf8 $ innerText
    $ getTagContent "span" (== [("class","furigana")]) $ parseTags html


There is no need for the switch (c). Instead, check to see if c is in the keys of the dictionary using ContainsKey; if not, throw. After that, unconditionally Dna[c]++;.

if (!Dna.ContainsKey(c))
    throw new ArgumentException("Strand has invalid nucleotides.");
Dna[c]++;


Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020

Your code is well done and shows familiarity with Rust.
The best I can do is comment on some parts of the code and provide two small, concrete pieces of advice. There is very little room for improvement in the code.
I see your Vecs in function parameters are well motivated. The one in find_triple is motivated by the need to do pop, and the one in find_pair just follows the other for consistency between parts of the task.
The decision to introduce Number as a type alias is ok, and works and looks fine, but keep in mind that it adds an extra mental hop for the reader.
Return types
Acting by intuition I'd change the return types to have const-length arrays instead of tuples. This brings attention to the fact that the array/tuple is homogeneous. I would change:
-> Option<(Number, Number, Number)> and return Some((a, b, number));
to
-> Option<[Number; 3]> and return Some([a, b, number]);
Typo?
It's good to be correct and consistent in naming. The function name is find_triple - but 'triple' is not a noun, 'triplet' is.


Display factorial with user-entered number

The difficult part of the task was no additional variables, subroutines/functions, or loops.

I'll keep that in the back of my head, but it's far more important to know what tools to use when, than being able to implement functionality x using language features y or z.

It's also much more important to know how to separate concerns and why - this "no additional subroutines/functions" so-called requirement is a very questionable idea, especially if that's something someone is tasking you to do.

In the real world, your client (or boss, or project manager, or whatever) tells you what the program needs to do: how it does it is at your [team's] discretion, and you[r team] will want to write code that's easy to maintain and extend, because that client never seems to stop adding new requirements - and if you do it wrong, one day a new requirement will come and shatter some fundamental assumption your code was making, and you need to rewrite a big part of it, and then doing so you introduce bugs that you will want to identify and fix quickly.

Writing a "god procedure" that literally does everything goes against every sane design principle, so I'm going to toss that non-functional bogus requirement away - because what you really want is to write maintainable, extensible code that's easy to read and easy to debug.

The "god procedure" also fails at abstraction, which is one of the four pillars of Object-Oriented Programming (OOP), and happens to be the paradigm VB.NET was designed for.

The functional requirements are:

User needs to be able to input a number, which must be a positive integer.
The program needs to compute the factorial of that number.
The program needs to output the result and the calculations made to get there.

I'll take the specified output as a firm functional requirement, and add:

For input 5, the program should output 5 X 4 X 3 X 2 X 1 = 120.

That's what the program needs to do - these are the main concerns. We'll see if additional variables or loops are needed as we see fit. Let's start.

Review

I like starting with the signature:

Private Sub FactorialCalculation()

Procedures do something; they're actions. By convention, procedure names start with a verb, and describe what's going on. Their parameters have meaningful names, like local variables; nouns that describe their purpose.

Naming is already hard, but a procedure that does too many things is even harder to name accurately: we know FactorialCalculation has something to do with calculating factorials, but what's going on here is impossible to tell just by reading the name of the procedure: even CalculateFactorial would be a misleading name, because it doesn't talk about user input. Looking at the code, the only name that comes to mind is PromptAndValidateUserInputAndCalculateFactorialAndOutputResult, which sounds ridiculous for a reason.

Dim Number, Factorial As Integer

If you're writing VBA as well as VB.NET, this is a dangerous way to declare your variables: in VBA Number would be an implicit Variant, and while it's great that VB.NET fixed that annoyance, it's better to declare variables on separate instructions, as close as possible to their first use - and ideally assigning them a value.

Console.WriteLine("Please enter a number")
Number = CInt(Console.ReadLine)

CInt is perhaps a VB-ish way to do this, but as a C# dev looking at it, you wonder how that conversion function is going to do with a non-numeric string input, for example - whereas more .NET-idiomatic conversion methods leave no ambiguity about what's going on:

Dim input As String = Console.ReadLine()
Dim value As Integer
Dim isInteger As Boolean = Integer.TryParse(input, value)

So, the output needs to be in descending order. Why is the loop ascending then?

For Count As Integer = 1 To Number

Seeing how almost every reference to Count is for computing Number - Count, I would have reversed the loop:

For Count As Integer = Number To 1 Step -1

Lastly, in order to know whether the output matches what's expected, we need to mentally iterate that loop and "build" the output - that's not ideal.

There's a better way.

Testability

Let's say you want to test whether your program fulfills all the requirements. You can run the program and see it with your own eyes - and that's a mandatory thing to do every once in a while. But testing your code like this, for every single edge case, and re-doing all the tests every time you make a change to the code, gets tedious. Professional code is testable, meaning that you can write code that executes your program and verifies that it works correctly: here there's only a handful of points to clear, but in a real code base there could be thousands of tests that run every time something changes in the code. These tests not only help identifying regression bugs, they also document the requirements and assumptions the code is making.

  QA engineer walks into a bar. Orders a beer. Orders 0 beers. Orders 999999999 beers. Orders a lizard. Orders -1 beers. Orders a sfdeljknesv.

  https://twitter.com/JimFraeErskine/status/527564769302433792

Before you even write a single line of code, you can look at the requirements and, knowing that a 32-bit integer input is maxed at 12 and a 64-bit integer is maxed at 20, start thinking of what you'll need to test:

Whether the user input is deemed valid with a negative integer
Whether the user input is deemed valid with sfdeljknesv for input
Whether the user input is deemed valid with a positive integer under 12
Whether the user input is deemed valid with a positive integer under 20
Whether the user input is deemed valid with a positive integer above 20
Whether the program logic correctly computes the factorial of 0
Whether the program logic correctly computes the factorial of a positive integer under 12
Whether the output format matches the specifications

That's 8 tests we know we can write right away. There's a development methodology called Test-Driven Development that works exactly like this: you actually write the tests, then you write the code that makes these tests pass. One of the benefits of that methodology is that it's impossible to write untestable code, since you're only ever implementing just enough code to make a test pass.

Your implementation will throw unhandled exceptions with several of these tests, but the problem is that it's impossible to test a single procedure that does everything.

Separating Concerns

If we wanted to merely be able to write these tests, we would need separate procedures for:

Validating user input
Computing the factorial of a given integer
Generating the output

One implementation that comes to my mind would leverage an iterator to Yield a counter, and an <Out()> ByRef parameter to output the current result. Something like this:

Public Iterator Function CalculateFactorial(ByVal value As Integer, <Out()> ByRef result As Integer) As IEnumerable(Of Integer)
    If result < 0 OrElse result > 12 Then Throw New ArgumentException()

    result = 1
    For i As Integer = value To 1 Step -1
        result *= i
        Yield i
    Next

End Function

The calling code could look like this:

Dim input As Integer = 12
Dim result As Integer
Dim values As IEnumerable(Of Integer) = CalculateFactorial(input, result)

Notice how decoupling the user input from the factorial-computing logic now allows us to test the logic with any given valid or invalid Integer input. Also notice that the logic is separated from the formatted output we're going to end up with.

If we wrote unit tests for it, we could already test all these:

Whether and how the program logic handles invalid input (throws an ArgumentException)
Whether the program logic correctly computes the factorial of 0 (returns 1 as expected)
Whether the program logic correctly computes the factorial of a positive integer under 12 (does it?)

To test the input validation logic, we would have to implement a separate function - one that takes a String input and returns a Boolean, for example:

Public Function IsValidInput(ByVal input As String, <Out()> ByRef result As Integer) As Boolean
    If String.IsNullOrEmpty(input) OrElse Not IsNumeric(input) Then Return False

    Dim value As Integer
    Dim isInteger As Boolean = Integer.TryParse(input, value)
    If isInteger AndAlso value > 0 AndAlso value < 12 Then
        result = value
        Return True
    End If
End Function

With that function we can test all these:

Whether the user input is deemed valid with a negative integer
Whether the user input is deemed valid with sfdeljknesv for input
Whether the user input is deemed valid with a positive integer under 12
Whether the user input is deemed valid with a positive integer under 20
Whether the user input is deemed valid with a positive integer above 20

And now the calling code looks like this:

Dim input As Integer
If IsValidInput(Console.ReadLine(), input) Then
    Dim result As Integer
    Dim values As IEnumerable(Of Integer) = CalculateFactorial(input, result)
Else
    Console.WriteLine("Invalid input.")
End If

All that's left to do, is to assemble the yielded values into a String, and output it. A dedicated function can do this:

Public Function GenerateOutput(ByVal IEnumerable(Of Integer) values, ByVal result As Integer) As String
    Return String.Format("{0} = {1}", String.Join(" X ", values), result)
End Function

And now this test can pass:

Whether the output format matches the specifications

Result

Putting it all together, the resulting code might look like this - notice how the higher abstraction level of the Main procedure makes it easy to instantly grasp what's going on, with as little effort as it takes to just read it; the output is sent to the console once, and all the lower-level code can be tested independently:

Public Sub Main()
    Dim input As Integer
    If IsValidInput(Console.ReadLine(), input) Then
        Dim result As Integer
        Dim values As IEnumerable(Of Integer) = CalculateFactorial(input, result)
        Console.WriteLine(GenerateOutput(values, result))
    Else
        Console.WriteLine("Invalid input.")
    End If
End Sub

Public Function IsValidInput(ByVal input As String, <Out()> ByRef result As Integer) As Boolean
    If String.IsNullOrEmpty(input) OrElse Not IsNumeric(input) Then Return False

    Dim value As Integer
    Dim isInteger As Boolean = Integer.TryParse(input, value)
    If isInteger AndAlso value > 0 AndAlso value < 12 Then
        result = value
        Return True
    End If
End Function

Public Iterator Function CalculateFactorial(ByVal value As Integer, <Out()> ByRef result As Integer) As IEnumerable(Of Integer)
    If result < 0 OrElse result > 12 Then Throw New ArgumentException()

    result = 1
    For i As Integer = value To 1 Step -1
        result *= i
        Yield i
    Next

End Function

Public Function GenerateOutput(ByVal IEnumerable(Of Integer) values, ByVal result As Integer) As String
    Return String.Format("{0} = {1}", String.Join(" X ", values), result)
End Function

Is this the best way to implement it? Probably not. But it's testable, so go ahead and implement these tests, and then refactor the code to get rid of the <Out()> parameter in CalculateFactorial - if you break anything in the process, the tests will tell you.


Updating dimensions when focus is lost from any of 9 columns

I don't do C# so pardon the syntax, but you should be able to reduce the amount of code by using a for loop over a string array with your column names.

Again I don't do C# but in Java you could do something like this:

for(String col : new String[]{"article", "account", "dim_1", ...}) {
    if (e.SourceCol == _detailSpread.GetColNumber(col)){
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol),
                            _detailSpread.Rows[e.SourceRow]);
        break;
    }
}

I would consider extracting the string array to a constant.

Or if your table is static you could just use a HashSet (or whatever it's called in C#):

// Somewhere in a constructor or static initializer
HashSet<Integer> focusChangeColNumbers = new ...;
colNumbers.put(_detailSpread.GetColNumber("article");
colNumbers.put(_detailSpread.GetColNumber("account");
...

// Then do:

private void _detailSpread_OnCellFocusChange(object sender, CellFocusChangeEventArgs e)
{
    if(focusChangeColNumbers.contains(e.SourceCol)){
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol),
                            _detailSpread.Rows[e.SourceRow]);
    _detailSpread.Validate();
}

Note that this is going to be \$O(1)\$ in the number of columns where the other options are \$O(n)\$ in the number of columns.

Another option (if the API permits, I have no idea) is to simply turn it around:

String[] focusColNumbers = new String[]{"article", "account", "dim_1", ...};
if(focusColNumbers.contains(_detailSpread.GetColName(e.SourceCol))){
    ...
}


Google FooBar Level 3 - Shortest path to 1

Your intuition is correct. A blind subtraction is the root cause of the problem.

The odd number has the least significant bit equals to 1. An even number has it equal to 0. The more zeroes a number has at the tail, the more divisions you can perform (this is what makes powers of 2 so special - they have all bits but most significant equal to 0). So what you really want is to compute number of trailing 0 bits in n + 1 and n - 1 and pick one which has more:

    tz0 = trailing_zero_bits(n + 1)
    tz1 = trailing_zero_bits(n - 1)
    if tz0 > tz1:
        n = n + 1
    else:
        n = n - 1

Notice how it eliminates computation of closest power of 2.

I leave the implementation of trailing_zero_bits for you. Hint: it is a one-line bit manipulation.


Readability is extremely important, particularly in large projects with many programmers involved with the same code. What you do, using local Boolean variables to clarify potentially complex conditions, is a very good way of improving readability that I try to imprint on my co-workers.

That said, in your example, if I wrote that method from scratch, I would do it similarly to your first re-write. However, if I just happened upon the existing code, I would do just about exactly as your second re-write. It is good enough, and I do not really like to change other peoples code unless it is either incorrect, or directly violates the coding standard (which it incidentally does two-fold: The conditional line is too long, and our standard also tells us to place sub-conditions on separate lines).

So, in my humble opinion: You have it right - I like how you do it, and you should take pride in writing readable code. But do not waste time on re-writing working code when a simple re-formatting is good enough.


Associate an object with a regular expression in Python

You should be able to see that you do lambda u: data + [u] on all of the commands.
The exception to this is when you do u.replace('%23', '#', 1),
this can be replaced by urllib.unquote and will allow for more urls.

You should put base, commands and re into global scope.
If you also change the commands so that you don't use lambda's and just have the lists then you can get:

try:
    #Python2
    from urllib import unquote
except ImportError:
    #Python3
    from urllib.parse import unquote
import re

BASE = ['wget', '--content-disposition', '--continue', '--quiet']
COMMANDS = [
    (
        r'(https?://)?examplesite\.com/.+$',
        ['/usr/bin/torify'] + BASE + ['--referer=http://referersite.com']
    ),
    (
        r'https://mega\.nz/.+$',
        ['megadl', '--no-progress']
    ),
    (
        r'(https?://)?othersite\.com/.+$',
        ['downloadtool']
    )
]

def get_command(url):
    """Return command for downloading a particular url."""
    url = unquote(url)
    commands = next((f for p, f in COMMANDS if re.match(p, url)), BASE)
    return commands + [url]


Read from SQL database table, store in list of objects

This code is very tightly coupled with the specific database engine. That makes it hard to change if you decide to go with different database engine. And it's not possible to unit test it at all.

Instead of using the specific MySql classes for connections, etc., change it to use the base interfaces, and then pass the connections and the queries from outside.

Also, I generally avoid using "return" inside a code block like "using" and if/switch, if it does not make the code too clunky. That way the code path is much easier to follow.

Bellow is an example of this particular method as part of some class, which can be reused in many different situations, incl web pages, services, etc. and with different databases, w/o changing the implementation of this class itself.

private IDatabaseProvider _dbProvider; //initialized in ctor, etc.
private IConnectionStringProvider _connectionStringProvider;
private IWebSiteMapper _mapper; //the db schema may change, or you may need to map from other source

public IList<WebSite> GetWebSitesForUser(int userId)
{
    var wsl = new List<WebSite>();
    var con = _dbProvider.GetNewConnection(); //returns IDbConnection
    var cmd = _dbProvider.GetWebSiteListQueryCommand(con, userId); //IDbCommand, and addParam goes there

    conn.Open(); // no need of try/catch or using, as if this fails, no resources are leaked
    using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) //close con on reader.Close
    {
         while (reader.Read())
         {
             wsl.Add(_mapper.CreateFromReader(reader));
         }
    }

    return wsl;
}


Singly Linked List Implementation (With Nodes)

I recommend you compile with more warnings enabled.  That would alert you to these problems:

g++ -std=c++11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds  -Weffc++       208038.cpp    -o 208038
208038.cpp: In instantiation of ‘class LinkedList<int>’:
208038.cpp:50:21:   required from here
208038.cpp:4:7: warning: ‘class LinkedList<int>’ has pointer data members [-Weffc++]
 class LinkedList
       ^~~~~~~~~~
208038.cpp:4:7: warning:   but does not override ‘LinkedList<int>(const LinkedList<int>&)’ [-Weffc++]
208038.cpp:4:7: warning:   or ‘operator=(const LinkedList<int>&)’ [-Weffc++]
208038.cpp: In instantiation of ‘T LinkedList<T>::pop() [with T = int]’:
208038.cpp:61:14:   required from here
208038.cpp:40:31: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
         if (n == NULL) return NULL;
                               ^~~~
208038.cpp: In instantiation of ‘LinkedList<T>::Node::Node(T) [with T = int]’:
208038.cpp:27:22:   required from ‘void LinkedList<T>::push(T) [with T = int]’
208038.cpp:52:16:   required from here
208038.cpp:14:11: warning: ‘LinkedList<int>::Node::value’ will be initialized after [-Wreorder]
         T value;
           ^~~~~
208038.cpp:13:15: warning:   ‘LinkedList<int>::Node* LinkedList<int>::Node::next’ [-Wreorder]
         Node* next;
               ^~~~
208038.cpp:15:9: warning:   when initialized here [-Wreorder]
         Node(T val) : value(val), next(NULL) {}
         ^~~~

The lack of consideration of copy/move behaviour is particularly concerning, given that we have a pointer which we own.  The destructor is also faulty, failing to release the allocated resource:

valgrind -q --leak-check=full ./208038
Empty: 1
Empty: 0
Size: 6
Size: 5
9
8
7
6
5
Linked List Deleted!
==18193== 96 (16 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6
==18193==    at 0x4835E2F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18193==    by 0x1094BD: LinkedList<int>::push(int) (208038.cpp:27)
==18193==    by 0x109276: main (208038.cpp:57)
==18193==

Remember the guideline - whenever you write new or new[], make sure you know where the corresponding delete or delete[] is!  (Don't forget that you need a delete in the pop() method, too).

There's no need for Node to be a class:

struct Node
{
    T value;
    Node* next;
};

void push(T val) {
    head = new Node{std::move(val), head};
    ++_size;
}

I think it would be better if it didn't need to be public, either - there's nothing to stop broken code messing up the guts of the list.  We'd like a way to iterate through the values of the list without having to understand its innards, and without being able to accidentally change it (potentially breaking the size invariant).

Finally, std::size_t is written incorrectly throughout, and is missing its header (<iostream> is not one of the headers specified to define this type).


How to improve this functional python fast exponentiation routine?

You haven't said anything against itertools, so here's how I'd do it with generators:

from itertools import compress
from operator import mul

def radix(b) :
    while b :
        yield b & 1
        b >>= 1

def squares(b) :
    while True :
        yield b
        b *= b

def fast_exp(b, exp) :
    return reduce(mul, compress(squares(b), radix(exp)), 1)