Rust version of basic functional prime stream - can this be made less clunky?

On a first note, your code will panic once your iterator reaches std::u32::MAX, which admittedly would take a long time. You can fix this by returning None when this happens, which can be done easily with ?.

let mut iter = self.iter.take()?;
let res = iter.next()?;

I can't think of a better way to accumulate actual filter calls, but if I were to implement this sort of algorithm, I would probably do something like this instead:

struct Primes {
    found: Vec<u32>,
    iter: std::ops::RangeFrom<u32>,
}

impl Primes {
    fn new() -> Self {
        Primes {
            found: Vec::new(),
            iter: (2..),
        }
    }
}

impl Iterator for Primes {
    type Item = u32;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        let Primes { found, iter } = self;
        let res = iter.find(|x| found.iter().all(|p| x % p != 0))?;
        found.push(res);
        Some(res)
    }
}

Note that in your code, all the previous primes are stored in the closures, so doing it explicitly this way gives a better view of the costs of this method. Additionally, I can imagine the continuously nested dynamic dispatch adding up in costs, so this method removes any need for that.


Generating bounded & unique random numbers in the Linux kernel

What are the valid input ranges? The documentation flags two special cases and the code handles them as special cases, but

I don't see any checks for dstruct_size < 0
If max_range is very large, the implementation of mod is incorrect. Consider e.g. mod(1 << 30, (1 << 30) + 1): the addition overflows into a negative value.

On the assumption that the intention is to guarantee that max_range will be zero or positive, why int instead of uint? Using uint would encode the guarantee of non-negative return values, and would remove the need for the mod helper.

            /* Check if 'tmp' is already in array */
            if (!_is_repeated_int(randint, idx, tmp)) {
                randint[idx] = tmp;
                idx++;
            }

is very inefficient. Consider the worst case: dstruct_size == max_range. The expected number of calls to get_random_int will be quadratic in max_range, and the overall running time of the method will be cubic.

A simple improvement which requires only dstruct_size calls to get_random_int and overall quadratic time is the following (pseudocode):

for (idx = 0; idx < dstruct_size; idx++) {
    tmp = (uint)get_random_int() % (max_range - idx);
    for (cmpIdx = 0; cmpIdx < idx; cmpIdx++) {
        // Discussed below
        if (tmp >= sorted(randint)[cmpIdx]) tmp++;
    }
    randint[idx] = tmp;
}

Obviously it needs minor amendment to handle the case max_range = 0, but that's not too difficult, especially if working with uint.

The big issue is that, as JS1 pointed out in comments, the loop which increments to avoid collisions needs to process the previous numbers in ascending order. There are two ways to do this: either keep a second, temporary, buffer with the numbers sorted; or sort randint as we go and then Fisher-Yates shuffle at the end. One uses twice as much memory; the other uses twice as many calls to get_random_int(). Both use insertion sort, and leave the overall running time as quadratic.

The Fisher-Yates option, however, does allow a fairly tricky elegant insertion.

for (i = 0; i < dstruct_size; i++) {
    tmp = (uint)get_random_int() % (max_range - i);
    for (j = 0; j < i; j++) {
        if (tmp >= randint[j]) tmp++;
        else {
            tmp2 = tmp;
            tmp = randint[j];
            randint[j] = tmp2;
        }
    }
    randint[i] = tmp;
}
// TODO Now Fisher-Yates shuffle

Observe that because randint contains sorted distinct values, once we find the insertion point for tmp we will never again hit the first case. In fact, that means we could optimise the inner loop and assignment to randint[i] as

    for (j = 0; j < i && tmp >= randint[j]; j++, tmp++) {
        // Empty loop body
    }
    for (; j <= i; j++) {
        tmp2 = tmp;
        tmp = randint[j];
        randint[j] = tmp2;
    }

I've followed your code in taking get_random_int() modulo a value, and that's ok if you don't need uniformity. However, in some cases the fact that get_random_int() % m is more likely to be 0 than m-1 (unless m is a power of two) is a problem. In that case you'd want an auxiliary get_uniform_random_int(m).


isValidValue() is needlessly simple – you check all 9 values for every field always. Instead, try implementing "pencil marks" that humans use when solving sudoku. For every field without a value, you should explicitly store which values can still be entered into this field. (In say a boolean[rows][cols][value]).

Then, when you place a number, remove it as a candidate value from other fields in the row/col/box, and add it again as you backtrack out of that try.

Other techniques humans use can also be implemented in software. Once you track pencil marks, Hidden Single should be fairly straightforward. (In fact it might be better to try that one before a backtracking search.) You could also try to speed up the search by filling in squares with the fewest possible candidates first, and by trying the digits you've already placed the most first. (I'm less certain that these will help a software solver, but they might reach a conflict that will cause a backtrack earlier.)


You could break out your validation functions into a separate object, like so:

validators =
  isinteger: (input) ->
    # check that value is an int

  notblank: (input) ->
    # check that value is present

These functions could return a simple boolean, or they could return an error message if validation fails and null if it passes.

The point is that you keep the functions separate, so they're easier to manage and customize. But it also means that you can give your inputs data attributes like data-validator which simply is the name of the validation method to use. So you can say, for example

method = $(input).data "validator"
result = validators[method]?(input)

With a little string-splitting, you could make the field plural, like data-validators="isinteger, notblank", and check each.

You could also make the error-throwing into an event you can listen for elsewhere. Then you avoid having your error presentation mixed up with your validations, and you don't have to rely on a predefined .errorContainer element. For instance:

throwError = (message, input) ->
  $(input).trigger 'validation:error', message

# ... elsewhere ...

$(document).on 'validation:error', 'input', (event) ->
  # handle error event

Other stuff I noticed:

Don't bind to the submit button's click event! Forms can also be submitted by simply pressing enter/return, without ever clicking the submit button. Instead, bind the form element's submit event which is fired regardless of how the form is submitted, and use preventDefault() to stop the submission if necessary.
Your notblank logic won't complain if the user just enters some space characters. In most cases the field should probably be considered blank, if it only contains whitespace. So use $.trim() on the value first, to trim off leading and trailing whitespace.
HTML5 has a required attribute you can add to inputs - no need to have your own syntax for say an input should be notblank. Check for the required attribute instead (if $(input).attr('required') ...). It makes the HTML more semantically correct.

I don't know if you already have solutions for the specific things you mention, but here are my ideas:

You can use .closest("form") to find the form element instead of parent().parent()
If you store all validation failures in an array, you just need to check the array's length, to see if the were any errors. Multiple validations won't override each other, and you don't need errorCount


It appears that you are reading records from a file, processing them in some way and then using the processed data to insert records into a table. Some of the processing involves getting data out of the database.

It looks like you are creating one insert statement for each row from the source file.

I think you would be more likely to get better performance if you broke the processing up into two parts. First, read the file, process the data and create the final version that is going to go into the database. Then, in a separate operation, load the data into the database.

In the first part of the process, you may be able to find ways to improve the performance by caching query results.

You may be able to write the results of the processing out to a temporary file that can be easily imported using an Oracle tool. This question may be helpful


Separate construction phase from constructed phase

First of all, you are right, what you have there is not a builder class, but more like a factory class. Which is roughly equivalent to a static factory method.

Now, the question of using constructors vs static factory methods is one over which there has been a lot of talk, and for the most part no conclusive, universally-applicable answers. (Just search for "c# constructor vs static factory method" and you will see.) However, specifically for your case, where both the constructed class and the code constructing it are private within another class, the advantages of "discoverability" and "recognizability" that the new keyword has are not applicable, so I'd definitely go with a factory method or class.

With regards to whether you should be using a factory class or a static factory method, I think that the factory class is fine. The overhead for the generation of an additional object which gets immediately discarded is negligible, (especially compared to the amount of work that the object will do,) and might even be optimized away by the compiler. On the other hand, having a factory class instead of a static factory method could turn out to be useful if in the future you decide to introduce some state into your builder.


As you said in the question you don't think this is very performant.

You only need two loops. If you go through every \$i\$ and \$j\$, then you have gone through every \$k\$ and \$l\$.
And so you don't need the \$k\$ and \$l\$ loops.

After this you have the equation:

$$\text{outcome} = i^3 + j^3$$

Since you know what \$\text{outcome}\$ is, it doesn't make sense for it to be what you're finding.
Instead if you re-arrange your code so that you can find \$j\$ for each \$i\$, then you can do everything in one loop.

$$j = (\text{outcome} - i^3)^{\frac{1}{3}}$$

And so to generate a list of \$i\$ and \$j\$ you can:

def generate_products(total):
    for i in range(int(total ** (1/3))+1):
        t = total - i ** 3
        # fix floating point error
        j = round(t ** (1/3))
        if t == j**3:
            yield i, j

After this you want to then combine these. If you're ok with \$i = k,j = l\$ then you can use itertools.product, otherwise you'd want itertools.permutations.
Which can produce all the numbers from 1 to 5000 in a couple of seconds.

def generate_products(total):
    for i in range(int(total ** (1/3))+1):
        t = total - i ** 3
        # fix floating point error
        j = round(t ** (1/3))
        if t == j**3:
            yield i, j

def generate_taxicab_numbers(outcome):
    for (i, j), (k, l) in itertools.permutations(generate_products(outcome), 2):
        print("{} = {}**3 + {}**3 = {}**3 + {}**3".format(outcome, i, j, k, l))

if __name__ == '__main__':
    for outcome in range(1000, 5000):
        generate_taxicab_numbers(outcome)

The slowest part of this is the print calls, and so if you move them out of the loops the code becomes even faster.

def generate_products(total):
    for i in range(int(total ** (1/3))+1):
        t = total - i ** 3
        # fix floating point error
        j = round(t ** (1/3))
        if t == j**3:
            yield i, j

def generate_taxicab_numbers(outcome):
    for (i, j), (k, l) in itertools.permutations(generate_products(outcome), 2):
        yield i, j, k, l

if __name__ == '__main__':
    to_print = []
    for outcome in range(1000, 5000):
        for nums in generate_taxicab_numbers(outcome):
            to_print.append("{} = {}**3 + {}**3 = {}**3 + {}**3".format(outcome, *nums))
    print('\n'.join(to_print))


Ok, so... there's a lot to talk about here. I've simply gone through it line by line, and added comments. So prepare for a pretty long review.

As for the indentation, the reason it's different when you paste it here is probably that you're still using tabs. It should be soft tabs, i.e. just 2 space characters. Not 1 tab character set to be 2 characters wide, but actual spaces.

Anyway, long review incoming.

# BuildShape is a poor name for a class. Classes should generally be nouns,
# but "Build shape" is an imperative. It's true that the class does build a
# shape, but the class in itself is not "the act of building".
class BuildShape

  # This class has no "initialize" method, but because its parent
  # class (which is Object, when nothing else is specified) has one,
  # I can still call "BuildShape.new.buildSquare" (for instance). But
  # if I do, things will be weird, because @text and @texture haven't
  # been defined. And without an initialize method (or attribute
  # setters), there's no way to define them.

  # Don't duplicate the name of the class in the names of its methods.
  # There's simply no need to do that; you don't need to name a file
  # on your computer after the folder it's in.
  # Also, Ruby uses underscored method names, so if anything, it should
  # be called "build_shape_check"
  def buildShapeCheck
    if @text == "square"
      self.buildSquare   # no need for "self." here
    else
      self.buildTriangle # or here
    end
  end

  # This produces a 5x3 rectangle - not a square!
  # It looks like a square because of the font you use to
  # show it, but that's coincidental and may not hold true
  # in all situations. So either make the method produce a
  # real NxN square, or make it very clear in the comments
  # that "by square, I do not actually mean a square" (i.e.
  # admit the deceit and its reasons)
  def buildSquare
    (1..3).each do # you could also just use "3.times do"
      puts @texture*5
    end
  end

  # again: Underscore naming style
  def buildTriangle
    j = 1  # This is completely unnecessary...
    (1..5).each do # ...if you just add |j| as a block argument
      puts @texture*j
      j += 1 # And then this can go too
    end
  end
end

# When I said "classes should be nouns" I meant *singular* nouns.
# The String class is not called "Strings" for instance.
# If anything, this should be called "Texture"
# But more importantly, this class doesn't make sense. You use
# class inheritance because you have a generic class and want to
# make a specialization of that class. E.g. you have a class called
# "Vehicle", and you make a class called "Car" or "Boat". Those are
# specializations of a common thing: a vehicle.
# But here, you seem to be making a new class for a completely
# different reason - a reason I can't quite figure out.
class Textures < BuildShape

  # Again, no initialize method...

  # Again you're kinda-sorta repeating the name of the class
  # in the method name, because - due to inheritance - this class
  # is a BuildShape. It'd be enough to call the method "check".
  # ... buuut, this method isn't checking anything, so it'd
  # still be a terrible name.
  def shapeCheck
    # This is unnecessary; @texture *will* be set to either "#"
    # or to "*" - there's no reason to set it to anything else
    # beforehand.
    @texture = ""

    # Another thing is that this method is pointless in many ways.
    # You can't set the @texture variable anywhere else, which means
    # @texture is 100% dependent on what @text is. Which, in turn,
    # means you can just figure out the right texture when you're
    # drawing the shape. You don't even need the @texture variable;
    # the methods that print the shape are already different depending
    # on whether you want a triangle or a square; they can just print
    # the correct character themselves.
    if @text == "square"
      @texture = "#"

      # Don't call this here, *and* in the else-block: Call it *after*
      # the if-else instead, since you want to call independent of
      # what the @text is
      buildShapeCheck
    else
      @texture = "*"
      buildShapeCheck # Again: Delete this
    end
  end
end

# Ok, this is a better name of a class. UserInput sounds like a
# class name. But of course, your inheritance chain is saying that
# "UserInput is a kind of Textures, which is a kind of BuildShape"
# Do you see how that doesn't make sense?
# It also highlights why the other classes are problematic: You
# can't use them on their own. Only after 2 levels of inheritance
# do you get the class that actually solves the task. The preceding
# classes don't solve anything by themselves, you're simply
# treating them as stepping stones to the class you actually want.
# They're dependent on you extending them, which, to reuse the
# analogy from earlier, is like saying that vehicles don't work
# until someone builds a boat; it's backwards.
class UserInput < Textures

  # Yay! An initialize method!
  def initialize(text)
    @text = text
  end

  # Ok, it prints the input - but it also checks the input
  # and that's not at all obvious. Your methods should only
  # do what it says on the tin.
  def printInput
    print "you entered: "
    puts @text
    self.testIfValid
  end

  # Uh, no. The name of this method is again pretty wrong.
  # Does it mean "it only does its test, if things are valid"?
  # The Ruby-like name for this thing would be "valid?"
  # And again, the method isn't just testing; it's also
  # the method that actually produces the output! AND it
  # completely duplicating code from *outside* the class.
  # What's worse, it creates a instance of itself, within
  # itself, and... honestly, I don't know how to best explain
  # how weird this is. Sorry, but that the case.
  def testIfValid
    if @text == "square" || @text == "triangle"
      puts "#{@text} is a valid shape."
      shapeCheck
    else
      puts "#{@text} is not a valid shape, try again"
      newUserInput = UserInput.new(gets.chomp.downcase)
      newUserInput.testIfValid
    end
  end
end

# If you just used single quotes, you wouldn't have to escape
# the inner double quotes...
puts "Enter either \"triangle\" or \"square\""

# Terrible naming: "user_input" is *not* a UserInput object;
# that's "newUserInput"! Which, again, shouldn't be CamelCased
# and just plain shouldn't be called that.
user_input = gets.chomp
newUserInput = UserInput.new(user_input.downcase)

# So... when you say printInput, you actually mean
# "do everything and print the *output*"?
newUserInput.printInput

Here's a different way of doing things:

def print_triangle(size = 5)
  size.times { |count| puts "*" * count }
end

def print_square(size = 5)
  size.times { puts "#" * size }
end

while true # loop until further notice
  puts 'Please type either "triangle" or "square"'
  type = gets.chomp.downcase
  if %w(triangle square).include?(type) # did the user enter something valid?
    send("print_#{type}")               # call the proper method
    break                               # stop looping
  else
    puts "Sorry, that didn't make sense. Try again."
  end
end

And done. I know this doesn't use any class hierarchy or anything like that, but that's also to illustrate that it isn't always necessary. Just because you can doesn't mean you should.


LeetCode: Binary Tree Zigzag Level Order Traversal C#

Your implementation is close, but it can be a bit shorter. You correctly use two stacks, but you duplicate the code alternating between using the two. That's a bit of a waste of space. Instead, at the end of the first while loop, you can just assign nextLevel to currentLevel, create a new stack to nextLevel, and repeat:

    while (currentLeveL.Count > 0 || nextLevel.Count > 0)
    {
        var nodes = new List<int>();
        while (currentLeveL.Count > 0)
        {
            var curr = currentLeveL.Pop();
            if (curr.left != null)
            {
                nextLevel.Push(curr.left);
            }

            if (curr.right != null)
            {
                nextLevel.Push(curr.right);
            }
            nodes.Add(curr.val);
        }

        if (nodes.Count > 0)
        {
            result.Add(nodes);
        }
        currentLevel = nextLevel;
        nextLevel = new Stack<TreeNode>();
    }

The while condition can also be made easier, nextLevel is known to be empty when it is evaluated:

while (currentLeveL.Count > 0)

Since you're looping over the stack, only removing each item, not adding items back or anything, you can just replace the while for a foreach:

public static IList<IList<int>> ZigzagLevelOrder(TreeNode root)
{
    List<IList<int>> result = new List<IList<int>>();
    if (root == null)
    {
        return result;
    }
    Stack<TreeNode> currentLeveL = new Stack<TreeNode>();
    Stack<TreeNode> nextLevel = new Stack<TreeNode>();
    currentLeveL.Push(root);
    while (currentLeveL.Count > 0)
    {
        var nodes = new List<int>();
        foreach(var curr in currentLeveL)
        {
            if (curr.left != null)
            {
                nextLevel.Push(curr.left);
            }

            if (curr.right != null)
            {
                nextLevel.Push(curr.right);
            }
            nodes.Add(curr.val);
        }

        if (nodes.Count > 0)
        {
            result.Add(nodes);
        }
        currentLeveL = nextLevel;
        nextLevel = new Stack<TreeNode>();
    }

    return result;
}


The first location of the leftOf method is the way to go. Putting it in Piece isn't very cohesive. The latter would be just as ugly or uglier (b.pieceAt(3,3).getLeftPiece(b)). The syntax board.leftOf(b.pieceAt(3,3)), read aloud, communicates roughly your intent but might read better as board.getPieceLeftOf(b.pieceAt(3,3)). Further, the best way is to remove the middle man and change the interface:

public Piece getPieceLeftOf(int x, int y) {
    int leftLocation = x - 1;
    // Validate that location
    return pieceAt(leftLocation, y);
}

//  ...later
board.getPieceLeftOf(3, 3);

Some style notes/thoughts:

Since this is written in Java, you should be following the standard naming conventions. camelCase for method names
You have a lot of package and package-private fields, it's a better practice to make them private and then expose the ones that actually need to be exposed outside of the class. (Effective Java Item 13).
If there is no error checking for the pieceAt or leftOf methods then add it and communicate through javadocs what happens if there is no left piece, a request is made out of bounds, etc. Those are both implemenation and game-type rules that need to be considered.
It seems like a simple 2D array is fine for this application. That is a pretty common structure for 2D chess/checkers type games (quick access, easy mental model, etc).


You've implemented a very basic version of the Quicksort algorithm, where you choose the first element as pivot element.

The running time of the quicksort algorithm is however very dependent on the quality of the pivot element. (The pivot should try to split the problem in equal problems). Making it fixed isn't really useful.

For example: say you want to run quicksort on an already sorted list. If you keep using the first element as pivot element, you will end up with a quadratic running time.

A 'solution' is to use random pivot elements, where in each recursive call you choose the pivot randomly (each element has an equal chance). You can find more on this approach online. But the idea is to end up with an average running time of \$O(n*log(n))\$

In addition you implement it by creating 2 new lists and merging them together. Quicksort normally has the advantage that everything can happen in-place,  which is a great advantage memory wise.


Using numpy polynomial module - is there a better way?

NumPy computes the roots of a polynomial by first constructing the companion matrix in Python and then solving the eigenvalues with LAPACK. The companion matrix case looks like this using your variables (as a==1):

[0 0 0 -e
 1 0 0 -d
 0 1 0 -c
 0 0 1 -b]

You should be able to save some time by updating a matrix like this directly on each iteration of base. Then use numpy.linalg.eigvals(m).max() to obtain the largest eigenvalue. See the sources.


JS, TS, handle 3 consecutive ifs / ternaries

let textMessage = 'Next, select the '
switch (props.sceen) {
  case 'dd':
    textMessage += 'dd'
    break
  case 'ff':
    textMessage += 'ff'
    break
  case 'ss':
    textMessage += 'ss'
    break
  default:
    textMessage = ''
}

or

messageDictionary = {
  dd: 'Next, select the dd ',
  ff: 'Next, select the ff ',
  ss: 'Next, select the ss '
}
textMessage = messageDict[props.screen] || ''

By using the second way, it will be easier for you to add the new screen option.


Simple autoloader, but trying to make it psr-compliat

Well, your class is psr-1 compliant. But i think you mean psr-0.

To have a maximum compliance to the psr-0 autoloader. simply copy paste it...

Your method for instance doesn't work for Class_Name

if you call your autoload with \namespace\ClassName the first \ doesn't get trimmed. This will leed to problems. (php will load /path/to/lib//namespace/ClassName.php)

as mentioned in the comments, the use of the $this->dirSeparatorSymbol is weird. You don't need it. so don't use it.

Edit: 'unused' namespace

Often you will have multiple libraries at different places. Your own will probably reside under ROOT.'/lib/' but other libraries you downloaded should/will be under ROOT.'/vendor/AwesomeLibrary/src/'. to accomodate this. You will register 2 autoloaders:

$personalLoader = new ClassLoader\Loader('Personal','/lib/');
$personalLoader->register();

$awesomeLoader = new ClassLoader\Loader('AwesomeLibrary','/vendor/AwesomeLibrary/src/');
$awesomeLoader->register();

Now your autoloader should check or it is allowed to load the file. For instance if I use
AwesomeLibrary/MyClass; the personal loader shouldn't do anything since it knows nothing about AwesomeLibrary. the second awesomeLoader however knows how to load the AwesomeLibrary.


First things first, I am against using different names in things that are inherently the same. If you do not have any other option, you could the data coming from the DAO as soon as they are fetched from the server.

If that is not an option, since this code is indeed messy, I would move this logic into a function while indicating the mapping from one state to the other (this is similar to what Redux does with mapStateToProps).

const mapFinancialAssesmentToState = (fa, state) => {
  const mapping = {
    anticipated_account_turnover: fa.account_turnover,
    occupation: fa.cfd_score
    //...
  };
  const nextState = {};
  Object.keys(mapping).forEach(key => {
    nextState[key] = { ...state[key], value: mapping[key] };
  })
  return nextState;
}

async componentDidMount() {
  let { get_financial_assessment } = await DAO.getFinancialAssessment();
  if (get_financial_assessment) {
      this.setState(mapFinancialAssesmentToState(get_financial_assessment, this.state))
  } else {
    console.log('nope');
  }
}


Canvas performance and stable frames per second

As far I understand your code, here's are some bumps:

Cache your values

Property access in objects causes a very minor overhead. A very common example of this case is a normal loop. In this version of the loop, you'd be accessing length i times during the course of the loop.

for(i = 0; i < someArray.length; ++i){

It may not matter in normal array use, where array length is less than a hundred records at best. But when you are aiming for at least 60fps and doing pixel operations in between, these minor optimizations do give you that edge.

Just to point you to the right perspective, a canvas of 1024x768 has 3,145,728 entries in the image data array! Imagine doing a loop at that scale, manipulating pixels on every iteration, do this on every frame for 60fps. I tell you, my CPU (fan) screamed.

So instead of the code above, the following code solves the problem by caching the length, and in effect, only accessing length on the object once.

var arrayLength = someArray.length;
for(i = 0; i < arrayLength; ++i){

Use a closure

Sure, cache the variables, but where? I assume you made the Engine object as your namespace to avoid globals. But if property access is an overhead, where should we place your code?

Well, you should create a closure for your code. That way, you have a scope to play with, where:

You can place your code freely without using a namespace (thus avoiding property access).
At the same time not polluting the global space.

Consider this:

(function(ns){

  var Update = function(){/*Engine.Update code*/}
  var Canvas = function(){/*Engine.Canvas code*/}
  var GameLooper;

  function GameLoop(){
    requestAnimationFrame(GameLoop);
    Update();
    Canvas();
  }

  //Expose init to our namespace
  var Init = ns.Init = function(){/*Init code*/}

}(this.Engine = this.Engine || {}));

window.onload = function(){
  Engine.Init(320, 320);
}

As you can see, you don't need to call Engine.something(). You can directly do something() directly. This solves your property access and namespacing problems, two birds with one stone.

rAF

requestAnimationFrame, often abbreviated as rAF, is a more optimized timer compared to setTimeout and setInterval. It's basically built with animations in mind, and is optimized to give you the best framerates as possible. It's also an efficient timer since it slows down if the tab is set to the background, thus not eating up processing time.

However, I notice that you are hampering the rAF call with a setTimeout.

GameLoop : function () {
  Engine.GameLooper = setTimeout(function () {
    requestAnimFrame(Engine.Update, Engine.Canvas);
  }, 10);
},

This code has several bad effects as well, aside from those mentioned earlier:

Your game loop runs in intervals of ~10ms. You are not reaping the benefits of rAF at all. You are basically slowing down the game loop.
Also, timer delays don't really reflect the actual time they execute, thus in this code, the delay isn't 10ms. It could be greater, depending on what JS is doing at the moment.
You are creating a timer and an anonymous function on every iteration. setInterval would have been a better option (but not better that rAF) because it creates only one timer and one anonymous function.

With rAF, try this instead:

// Aapplying our no-property access policy
var GameLoop = function () {

  // Schedule the next frame ASAP
  requestAnimFrame(GameLoop);

  // In the meantime, call the functions for this frame
  Update();
  Canvas();
}

Notice that the scheduled call is GameLoop. This way, your functions Update and Canvas don't need to call back GameLoop to run the next frame. The next frame is already scheduled with this call.

Date....now()!

Yes, in recent browsers, there's Date.now() which is an optimized substitute to +new Date() and new Date().getTime() to get the current timestamp.

In classical OOP terms, it's a "static" member, which means you don't need to create an instance of Date to use it. This way, you are not generating a new object every time just to get the current time, thus saving you memory.


Really accurate highlghting is a big challenge, and even if your implementation is not totally falsy it's very incomplete.

First some obvious points, easy to correct:

your PHP reserved words list lacks a number of words, such as (not exhaustively) global, const,  if, else, switch, case, default, do, exit, break, continue try, catch, finally, ...
you look for PHP multiline comments like /*...*/ but not for simple line ones like //..., nor for HTML comments <!--...-->.
you look for double-quoted strings "..." but not for single-quoted ones '...'.

Now some harder issues:

you currently don't take care of escaped (single or double) quotes in a quoted string: "quote \" inside quoted string" breaks the highlighting.
you don't look for numbers (integer or float)

Lastly, not a lack but might be improved: you don't distinct between HTML tags and their attributes.

Please note that this is not to criticize your work! At the opposite, since you said it is:

  to extend my knowledge in JS and regular expressions

I hope it encourages you to rise to the challenge :)

EDIT. Two points I forgot to mention above.

The first one comes from a preliminary general advice: try to follow best practices, notably in that, instead of:

for(var i=0;i<obj.length;i++){

you should write:

for (var i = 0; i < obj.length; i++) {

and so on evrywhere...

So here is the point since when looking for reserved words you wrote this:

data = data.replace(/(new|echo|...|include|include_once)[^=]/g, ...

There you added [^=] to avoid selecting something like $new=....
Right but regarding the above advice you must realize that one may have written $new = ... instead. Then you'll select new as a reserved word, while it's not!

So actually you'd better looking for a prepended $ rather than an appended =:

data = data.replace(/[^\$(new|echo|...|include|include_once)/g, ...

The other point is only for convenience: currently you force tab to be arbitrarily replaced by 4 spaces, which may sometimes be undesired. So you might merely write something like this:

function codeHighlighter(tab) {
  tab = tab ? tab : 4;
  for (var i = 0; i < obj.length; i++) {
    ...
    data=data.replace(/\\t/g, repeat("&nbsp;", tab);
    ...
  }
}


Function that loads a random image using an array of paths to images

To answer your immediate question, you need to initialise your flagImageSources once, and store it as a field in the class. That allows you to split the two actions into separate methods - one to get your list of flags, and one to get a random flag.

public partial class Form1 : Form
{
    private string[] flagImageSources;

    private void InitializeImageSources()
    {
        flagImageSources = new string[196];
        StreamReader flagImageSourceReader = File.OpenText("flagImageSourceFile.csv");

        for (int i = 0; i < flagImageSources.Length; i++)
        {
            string s = flagImageSourceReader.ReadLine();
            flagImageSources[i] = s;
        }
    }

    private string GetRandomImageLocation()
    {
        Random numberGenerator = new Random();
        int imageNumber = numberGenerator.Next(0, 196);

        return flagImageSources[imageNumber];
    }
}

But I think we have some other concerns here.

Firstly, you open your file but forget to close it again. C# has a handy way of making sure this doesn't happen - something that gets opened and closed should implement IDisposable (and StreamReader does just that). So you can change your code a little to make use of that, like this:

        using (StreamReader flagImageSourceReader = File.OpenText("flagImageSourceFile.csv"))
        {
            //do stuff with flagImageSourceReader
        }

Secondly, you're using the magic number of 196 in a couple of places in your code - both to set the initial size of your array, and to set the upper bound of your random number generator. I would suggest that rather than using a fixed-size array, you should use an IList, which is dynamically sized. Then, if North and South Korea should merge, or Scotland or Catalonia or Tibet become independent countries, your code will still work even as you add or remove flags :)

Here is my final code that solves both of those problems:

public partial class Form1 : Form
{
    private IList<string> flagImageSources = new List<string>();

    private int NumberOfFlags => flagImageSources.Count;

    public Form1()
    {
        InitializeComponent();

        InitializeImageSources();
        flagPictureBox.ImageLocation = GetRandomImageLocation();
    }

    private void InitializeImageSources()
    {
        using (StreamReader flagImageSourceReader = File.OpenText("flagImageSourceFile.csv"))
        {
            while (!flagImageSourceReader.EndOfStream)
            {
                flagImageSources.Add(flagImageSourceReader.ReadLine());
            }
        }
    }

    private string GetRandomImageLocation()
    {
        Random numberGenerator = new Random();
        int imageNumber = numberGenerator.Next(0, NumberOfFlags);

        return flagImageSources[imageNumber];
    }

    private void submitBtn_Click(object sender, EventArgs e)
    {
        flagPictureBox.ImageLocation = GetRandomImageLocation();
    }
}


Call a method from all GameObjects implementing a specific interface in Unity

In the first loop I think, you could do:

if (projectiles.Any(p => p.IsActive))
{
  return;
}

In the second you could do something like:

foreach (var currentComponent in sceneObjects.Select(so => so.GetComponent<IRewindable>()).Where(r => r != null))
{
  currentComponent.Rewind();
}

But be aware, that using linq is not necessarily the most optimized approach (performance wise) , so you'll have to do some tests.


Concisely merging objects can be done with spread syntax instead of Object.assign. The ADD_USER case can use:
return { ...state, user: action.user };

Using spread syntax instead of Object.assign doesn't have a big impact here, but it makes things so much easier when the state structure grows to be large and complicated.
Functional programming does not reassign variables - everything should be declared with const. If you want to be more functional, change addUser to use the conditional operator to either assign the empty string or the extractUser result to the user variable:
export const addUser = (resp) => {
  const user = validResp(resp) ? extractUser(resp) : "";
  return {
    type: "ADD_USER",
    user
  };
};

(Note that if the key is named the same as the variable the value is in, you can use shorthand property names like above. You could also return the whole object at once without declaring a user variable first.)
useEffect bug Since you didn't provide a dependency array to useEffect, its callback will run on every render. I'm pretty sure this isn't desirable - you want it to run only on the initial render, right? Pass an empty dependency array to useEffect so that the callback inside only runs on mount:
useEffect(() => {
  axios.get(url).then((resp) => dispatch(addUser(resp)));
}, []);

Error handling If the axios.get Promise rejects, no indication is given. Always .catch Promises somewhere. You might want something like
useEffect(() => {
  axios.get(url)
    .then((resp) => dispatch(addUser(resp)))
    .catch((error) => dispatch(addError(error.message)));
}, []);

or something of the sort, to show that an error occurred.


Project Euler problem #19: counting months that began on Sundays

int day = 4; // Lets number the days of week from 1:7 && Sunday is the first day;;; note : 1 jan 1901 was Tue day

The comment gets lost on the right edge of this narrow screen.

The position of the comment implies that it is specific to the variable day, but that's not true of the first sentence.

For working with % it would be less confusing to use 0 to 6 rather than 1 to 7.

Given that day = 4, why does the comment tell us that 1 jan 1901 was Tue day? What does day represent here? If it's 1900-12-01 then the comment should talk about that date. In general, day is not a self-explanatory name.

            for(int mon = 1; mon <= 12; mon++) {

mon for Monday? Again, not the most helpful name.

                day += days(mon, year);
                if(day%7 == 1)
                    sundays++;

Is overflow of day a risk?

    public static int days(int num, int year) {
        int res = 0;
        int feb = 28;
        if(isLeapYear(year))
            feb = 29;
        switch(num) {
            case 1 : res = 31; break;
            case 2 : res = feb; break;
            ...
            case 12 : res = 31; break;
        }
        return res;
    }

num? That's completely uninformative. I know it's a number because I can see that its type is int.

Early returns would make this shorter and more obviously correct:

        switch (month) {
            case 1 : return 31;
            case 2 : return isLeapYear(year) ? 29 : 28;
            ...

It's bad practice to have a switch without a default, even if the only thing the default does is throw new Exception("This should be unreachable code").

One option would be to group the cases according to a well-known rhyme, and pull the sanity checking out of the switch:

        if (month < 1 || month > 12) throw new IllegalArgumentException("month");

        switch (month) {
            // 30 days have September, April, June and November...
            case 9:
            case 4:
            case 6:
            case 11:
                return 30;

            // ... All the rest have 31 ...
            default:
                return 31;

            // ... except for February alone.
            case 2:
                return isLeapYear(year) ? 29 : 28;
        }

    public static boolean isLeapYear(int year) {
        if(year%4 == 0)
            if(year%100 == 0) {
                if(year%400 == 0)
                    return true;
            } else
                return true;
        return false;
    }

Simplifying from the inside out, and putting in the necessary {} to be sure that the code does what we expect, we get:

    public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                return year % 400 == 0;
            }
            return true;
        }
        return false;
    }

    public static boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            return y % 100 > 0 || year % 400 == 0;
        }
        return false;
    }

    public static boolean isLeapYear(int year) {
        return year % 4 == 0 && (y % 100 > 0 || year % 400 == 0);
    }

    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && y % 100 > 0) || year % 400 == 0;
    }

Of course, given that we're only interested in years 1901 to 2000, this could be simplified further.


Put these

if (!field.checkIfBlocked(getfieldX() + 1, getfieldY())) {
    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals("friend")) {
           endMessage();
    }
    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals("bazooka")) {
        plusAmmo();
        LevelMaker.removeBazooka();
    }
    if (field.checkIfItem(getfieldX() + 1, getfieldY()).equals("helper")) {
        showShortestRoute();
    }

into a function.

Example:

public boolean performActions(int x, int y) {
    if(field.checkIfBlocked(x, y)
        return false;

    String status = field.checkIfItem(x, y);
    if(status.equals("friend")) {
        endMessage();
    } if(status.equals("bazooka")) {
        plusAmmo();
        LevelMaker.removeBazooka();
    } if(status.equals("helper")) {
        showShortestRoute();
    }
    return true;
}

and checkAndMove() becomes:

public void checkAndMove(String direction) {
    switch (direction) {

        case "up":
            if (performActions(getfieldX(), getfieldY() - 1)) {

                // rest of the stuff
            }
            break;
        case "down":
            if (performActions(getfieldX(), getfieldY() + 1)) {

                // rest of the stuff
            }
            break;
        case "left":
            if (performActions(getfieldX() - 1, getfieldY())) {

                // rest of the stuff
            }
            break;
        case "right":
            if (performActions(getfieldX() + 1, getfieldY())) {

                // rest of the stuff
            }
            break;
    }
}


Find two distinct subsets of a list that add up to the same value

Some "more pythonic" suggestions which also improve performance:

use Counter.elements()

in partition_into_equal_parts this code:

second = []
# Fill second with items from counter
second_counter = Counter(l) - Counter(first)
for number, amount in second_counter.items():
    second.extend([number] * amount)

can be merely replaced by

second = list((Counter(l) - Counter(first)).elements()

As Counter.elements returns a chained iterable of the expanded elements according to their count. So no need to do that with a loop and an extra list.

Cache the indexed element

In recursive_calculate, you have to use the index in

for idx in range(start, len(lst)):

but why not storing lst[idx] in a local variable? It's repeated a lot of times, and accessing a list element is costly. Just cache this access since you're not writing in lst (well you're writing to the end of it, recursively, but lst[idx] isn't udpated because the index is low enough).

def recursive_calculate(k, lst, start):
    for idx in range(start, len(lst)):
        element = lst[idx]
        if element == k:
            return [element]
        elif element < k:
            rest = recursive_calculate(k - element, lst, idx + 1)
            if rest is not None:
                rest.append(element)
                return rest
    return None

Small note: python functions implicitly return None, but "Explicit is better than implicit" (The Zen Of Python) so it's better to actually return it.


It seems like you are mixing up the number of segments and the number of elements per segment. In your example, both are the same, so the result is correct, but in other cases it will not be. For instance, i1 is created as the number of elements per segment, with the number of segments being hard-coded as 5.0. Then, in the loop, you treat i1 as the number of segments, while the number of elements per segment is hard-coded as 5. Mistakes like this will be easier to spot if you use properly named variables, like numSegments or segmentSize instead of i1 or integer constants.

Also:

no need to wrap the sublists into new ArrayList
you can just count by increments according to the number of elements per sublist instead of using two counters, for the current sublist and the offset
you could use a ternary ... ? ... : ... instead of that if/else

How about this:

public static void main(String[] args) {
    List<String> arrayList = new ArrayList<String>();
    for (int i = 0; i < 23; i++) {
        arrayList.add(String.valueOf(i));
    }

    int size = 5;
    for (int start = 0; start < arrayList.size(); start += size) {
        int end = Math.min(start + size, arrayList.size());
        List<String> sublist = arrayList.subList(start, end);
        System.out.println(sublist);
    }
}

Here, size is the number of elements in each sublist. So instead of counting the segment of the list and increasing a second counter by 5 each time, you can just increase the first counter by five in the third argument of the for loop. Also, you can use the result of subList directly, without passing it to a constructor first. And you can get rid of the if-else by using min to determine the end index.

Output:

[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22]

If instead of sublists with 5 elements you wanted five sublists, then use this (same result for the given example, but different for other list sizes):

int size = (int) Math.ceil(arrayList.size() / 5.0);


VB.Net interfacing with F# Euclidean Distance Algorithm

type MyColor =
  { Name: string;
    Values: float[];
    }

The usual syntax is to put the opening { right after =.
Also, why are you using floats (or Doubles in VB) for the values? Integers should be enough. And it might be easier to use existing Color type, either from System.Windows.Media or from System.Drawing. As an added advantage, you could reuse the existing definitions for various colors.
type MyFSColorTable(name: string, rgb:float[]) = class

Collection really shouldn't take its first member in constructor. Either take all colors in the constructor (which means you wouldn't need mutable collection inside), or have a method for adding new colors.
Also, using class here is not necessary. If you remove that, don't forget to also remove the end.
let mutable myHash = Hashtable()
let mutable CurName = name
let mutable CurDist = 0.0

These members don't seem to be used in the program, so you should remove them. Also, try to avoid using mutable.
let mutable CurColor =
  { Name = name;
    Values = rgb;
    }

This is only used to support the first item from constructor, remove it.
let mutable CurList = [CurColor]

CurList is not a very good name. Don't use abbreviations like Cur, they are unclear. And in this case, it doesn't add anything. A better name would be Colors.
member x.AddColor name rgb = CurList <- List.append CurList [{Name = name; Values = rgb}]

Adding to the end of list is inefficient. You can add a value to the front of the list by using ::: {Name = name; Values = rgb}::Colors.
member x.Name   = name

This member is not used. And it's very confusing, because it returns the name of the first color that was added to the collection. Remove it.
member x.Dist (V1: float[]) V2 =

This function doesn't use any instance fields, so it should be static. And it should be probably also private (i.e. static let dist V1 V2 =)
Array.map(fun (v1, v2) -> (v1 - v2) * (v1 - v2))

You could avoid the repetition by using pown: Array.map (fun (v1, v2) -> pown (v1 - v2) 2).
// Loop thru color hash and find the nearest match
member x.ColorSearch (R1: float[]) =

The comment is inaccurate, the function doesn't use any hash.

R1 is a really bad name. And ColorSearch is not a great name either, something like FindNearestColor would be much better.

The whole method is written in a purely imperative style. If you're going to write this way, there pretty much isn't a reason why you should use F#, F# is a poor imperative language.
A better way to write this method would be to use List.minBy:

member x.FindNearestColor (rgb : float[]) =
  let nearestColor =
    Colors |> List.minBy (fun color -> dist rgb color.Values)
  nearestColor.Name

Also, it seems you think searching through the list could be inefficient (because it seems you attempted to use a hash table). But you can't use hash table for something like this. You could use something like an R-tree, but implementing that would be much more complicated. So I would do that only if performance of this method was really bad.
Dim objFSColorTable As New MyFSColorTable("GreenYellow", GreenYellow)
objFSColorTable.AddEntry("Lavender", Lavender)
objFSColorTable.AddEntry("Orange", Orange)
objFSColorTable.AddEntry("Magenta", {255, 0, 255})
objFSColorTable.AddEntry("DarkGoldenRod", {184, 134, 11})

This is quite verbose. A better way would be to use collection initializer. How exactly would that look depends on how do you decide to fix initialization of MyFSColorTable.


The Timeout class doesn't solve the problem you have

If you write:

message = (read from bluetooth);
if(timeout.timeout() == true)
    message = "timed out";

Then it will first wait for the message to be read from Bluetooth, which might take more than 10 seconds, and then once you have the message, it will check whether more than 10 seconds have passed since the start, and if so it will discard the message you got. The fact that the timer is run in its own thread does not magically make (read from bluetooth) exit after the timer expires.

What you instead have to do is run the (read from bluetooth) command in a thread, and wait at most 10 seconds for that to complete. With C++11, you can do this very easily with std::async():

#include <future>
#include <chrono>

...

auto future = std::async(std::launch::async, [] {
    return (read from bluetooth);
});

auto status = future.wait_for(std::chrono::seconds(10));

if (status == std::future_status::ready)
    message = future.get();
else
    message = "timed out";

The problem however is that if there is a timeout, the thread running the Bluetooth read command is still running. When exiting the scope, the destructor of future will block until the thread finishes execution. So this kind of approach has a limited use.

The best solution would be to find some wait to make (read from bluetooth) itself give up after 10 seconds, or have some way to cause it to stop waiting for data.

Identifiers with double underscores are reserved

You should not use identifiers that start with underscores, or contain double underscores, as they are reserved, and might be used by the compiler and/or the standard library. This even applies to macros, so instead of:

#ifndef __timeout_h__
#define __timeout_h__

Write:

#ifndef timeout_h
#define timeout_h

Or use the following pragma that most compilers understand, and that ensure that a header file is only read once:

#pragma once

Store durations as std::chrono::duration

Avoid storing timeouts as int, this limits the resolution. Instead, consider using std::chrono::duration to store the timeout period.

Make member functions const where appropriate

If a member function doesn't modify any member variables, mark it as const, like so:

class Timeout {
    ...
    bool timeout() const;
}

Ensure variables are properly initialized

You never initialize alert to false, so a call to timeout() might return an uninitialized value.

Use std::atomic<> variables when communicating between threads

If you write:

Timeout timeout(10);
// do something
if (timeout.timeout())
    ...

Then the compiler might know that alert is set to false in the first line, and if it can prove that do something never touches the variable timeout, then it can assume in the third line that alert will always be false. To ensure the compiler does not make such assumptions when threads are involved, you have to tell it that it should atomically read and write this flag.

Do you need a separate thread at all?

The only thing your Timeoutthread does is sleep for a certain amount of time, then set a variable. You know that the threads sets that variable a given number of seconds after it starts. So instead of using a thread, you can just store the current time when an instance of Timeout is created in a separate member variable, and in timeout() just check the difference between the current time now and the time stored in that member variable.


Aside from stylistic concerns (as a Java/Clojure guy, I'll let you C#'ers decide on that stuff), I don't see how this a correct algorithm, unless additional constraints are given in the problem statement. Consider this input:

([] ())

Now, clearly that is balanced. And if you reverse it, you get:

))( ][(

But if you compare this reversed input with the original input, you don't find that each open bracket matches up with its closing bracket in the reversed string: the first character and the last are fine, but the inner pairs don't balance at all!

So, unless you are given the further guarantee that the input consists of N opening brackets followed by N closing brackets (ie, no opens after the first close), you can't just compare the reversed string.


How to put apt and python packages in a list and check if installed or not then install

Use for loops for expandability and readability.
If you want to test for individual utilities, try using command -v pip instead of which and comparing against that.
Look up and understand the functional difference between single bracket comparisons and double bracket. [ ] vs [[ ]]
`` syntax is very out of date, use $()
If you have to call /usr/bin/env for the location of bash, but broadly assume apt is the package manager on the system, it's much safer to use /bin/bash.
Python requests is also stored as an apt package, I moved it into the first for loop statement.

#!/bin/bash

for PACKAGE in python-pip python-pip3 speedtest-cli tar python-requests; do
    if [[ ! $(dpkg -l ${PACKAGE}) ]] ; then
        echo "${PACKAGE} is not installed, installing now."
        sudo apt-get install ${PACKAGE} -y
    else
        echo "${PACKAGE} is installed."
    fi
done

pip3 install -U pip

for PACKAGE in mysql-connector-python pymysql sqlalchemy ; do
    pip3 install -U ${PACKAGE}

    if [[ $? -ne 0 ]] ; then echo "${PACKAGE} failed to installed" ; fi
done

cd $HOME
echo "Iniating download..."
curl -sL "http://my.domain.com/config" -o "config.tar"

tar xvf config.tar

sudo chmod 604 ucc.py
## I don't know why you need to use sudo to chmod an item inside your own home dir, but ill leave this here.
## Also, you can tar a package with certian perms and then unpack it to obey those specific permissions.

for ITEM in ucc.py ucc.service client.conf; do
    if [[ -e ${ITEM} ]] ; then
         echo "${ITEM} is installed."
    else
        echo "${ITEM} failed to download"
    fi
done

sudo mv ucc.service /lib/systemd/system/
sudo mv client.conf /etc/openvpn/
sudo mv -f client.conf /etc/openvpn/

sudo systemctl restart openvpn@client
sudo systemctl status  openvpn@client


Vue.js: extracting data from a nested object using for...in

Your original question has a partial answer here I believe. In fact, ESLint is telling you the exact method(s) to use, which is Object.keys(el), for example.

Aside from that, there are a few semi-related things you can refactor...

Object.keys(users.stats || {}).map(key => users.stats[key]) is essentially the same as Object.values(users.stats || {}).

...as well as unrelated ones:

Names like arr, el, newArr, obj, key, and str are extremely abstract, and dealing with them in real code forces spending brain cycles on decrypting their meaning instead of understanding the intent of the code. In fact, I would hesitate to post a question before renaming the variable into something meaningful. See, the readers don't know the complete structure of the object(s) you're working with and it complicates the review process.
Unnecessary temporary objects may be avoided, if map(), filter(), reduce() and other chaining-friendly functions are used together.
A guarding construction if (!users) return [] is more idiomatic for JavaScript/TypeScript and reduces the nesting (fewer {s and }s).

The result may look something like this. I'm sorry if I missed something — I don't know how to reliably test that my refactoring went well. Plus, it's a late night in my timezone now, so my brain acts funny. :)

getUsersData({ users: { data: { users } } }) {
  if (!users) return [];

  return Object.values(users.stats || {})
    .map((statValues) => {
      Object
        .getOwnPropertyNames(statValues)
        .filter(key => !key.includes('active'))
        .reduce((result, key) => {
          result[key] = statValues[key];
          return result;
        }, {});
    });
}


How to deal with method which throws 7 exceptions

This depends on what you want to do in case of an exception. If your handling is just printing the stack trace your solution is OK. But you might want to react in a different way depending on the problem.

Just an example:

an IO problem could mean that you have to retry (in case on network)
a malformed URL might mean that you have to generate an error message and ask the user to re-enter the data
and so on

If you do not try to recover from the error, I don't know if it makes sense to catch the exception, print the stack trace and then continue. It might be the same as letting the application crash (and print the exception anyway).


Filtering a long list of files through a set of ignore patterns using iterators

You can simplify the loop by using a generator expression like this:

for filename in filenames:
    if any(fnmatch(filename, pattern) for pattern in ignore_list):
        print 'Ignore', filename
        continue


Is this an acceptable way of writing PHP code(in scriptlets)

A few points:

Put the session_start() and as much of processing as possible on top of the file, before any output. This will be useful for emitting http-headers.

When using a database: don't forget to handle exceptions.

When using a database: don't forget to handle  charsets.

When selecting from the database: always limit your results. Add pagination of some kind.

Do not use mysql_*, use a db library that offers prepared statements and is as db-independent as possible. I would recommend PDO.  I would also recommend getting the data from the db as objects. If necessary you can define a class to hold some methods you need for these objects.

I cuncur with Cygal: using php as the templating language is quite ok.  See Wordpress for an example where this is used extensively in themes.

Try to write your HTML in a compact, readable way. No matter what you use for templating: HTML is an important part of your code, and should be just as readable as any other code you write.

Output valid HTML. Don't forget question marks around attribute values, don't forget -Tags.

   <?php

      session_start();
      include "config.php";
      if( ! $DB_NAME ) die('please create config.php, define $DB_NAME, $DB_USER, $DB_PASS there');

      try {

          $dbh = new PDO("mysql:dbname=$DB_NAME", $DB_USER, $DB_PASS);
          $dbh->exec('SET CHARACTER SET utf8') ;

          $result = $dbh->query("SELECT * FROM products LIMIT 0,20");
          $products = $result->fetchAll(PDO::FETCH_OBJ);

      } catch( Exception $e ) {

          error_log( $e->getMessage() . " ".  $e->getTraceAsString() );
          include("500-failwhale.php");
          exit;
      }
    ?>

    <!DOCTYPE html>

      <title>Products</title>
      <meta charset="utf-8">

            Product ID
            Name
            Description
            Price
            Image
             Action

    <?php foreach($products as $p) : ?>

            <?= $p->p_id          ?>
            <?= $p->p_name        ?>
            <?= $p->p_description ?>
            <?= $p->p_price       ?>
            <?php if ( $p->p_image_path ) : ?>
                   <img src="<?= $p->p_image_path ?>" alt="<?= $p->p_name ?>">
            <?php endif; ?>
            edit
            delete

    <?php endforeach; ?>


API with revealing module pattern in Javascript

Not using prototypes is completely fine. It can be advantageous at times to make use of them, but I agree that there is not much / any advantage to using them in this case.

If an error occurs, you should throw the error. Just logging it and moving on can result in some incredibly confusing behavior.

The biggest issue I see with using this code as an API is the inability use more than one number at once. If I want to use it to generate multiple numbers at once I can't. As a consumer of the library I would expect the following to work.

let a = gMath.number(50).scatter(50);
// Scatter twice by the same number
let b = a.scatter(a.getNumber()).scatter(a.getNumber()).getNumber();

There is another way to do method chaining that would solve the problem illustrated above. Instead of modifying the current state and returning this, return a new immutable gMath with the correct number set.

I'll point out a few potential problems / improvements with the current code, and then show how I would structure this api while keeping the usage the same.

There's no need to define isNumber. There is a built in method Number.isNaN that can check that with the additional benefit of handing NaN values (typeof NaN === "number")
There's no need to check gotNumber twice in the number function. This chain of if statements can be quickly improved if you throw errors for invalid inputs.

if (Number.isNaN(number)) {
    throw Error('This function only accepts numbers');
}
if (gotNumber) {
    throw Error('Cannot define 2 numbers. Only use .number() once or call .getNumber() to clear the current one.');
}
currentNumber = number;
gotNumber = true;

It looks like randomize might have a bug, it accepts a number but doesn't use it.
atleast can be simplified by using Math.max instead of the ternary.
None of your methods except number check if gotNumber is set. This leads to confusing behavior especially since number says calling getNumber clears the current number.

gMath.number(10);
gMath.getNumber(); // 10
gMath.subtract(5);
gMath.getNumber(); // 5

isCurrentNumber implies that the function returns a boolean. If you decide to keep with your current design of a single instance, this should probably be renamed to hasNumber and should return a boolean that the caller can log.

With this in mind, here is how I would write this module, keeping the same methods as the original for the most part. The one change is that instead of calling gMath.number(#) you call gMath(#) to create an instance.

function gMath(number) {
    if (Number.isNaN(number)) {
        throw Error('This function only accepts Numbers as arguments.');
    }

    let instance = {
        scatter(range) {
            let num = Math.floor((number + (Math.random() * range * 2) - range) + 1);
            return gMath(num);
        },

        randomize() {
            return gMath(Math.floor(Math.random() * number));
        },

        atleast(lowerBound) {
            return gMath(Math.max(lowerBound, number))
        },

        add(num) {
            return gMath(number + num);
        },

        subtract(num) {
            // Safer than using `this` as `this` can be changed
            // by how the function is called.
            return instance.add(-num);
        },

        show() {
            console.log(number);

            return instance;
        },

        getNumber() {
            return number;
        },
    };

    return instance;
}

let a = gMath(10).scatter(40).getNumber()
console.log(a);


Manually writing a function matrixpower() in R

It would be more efficient to use binary exponentiation.

Suppose that you want to raise an n by n matrix to the \$k^{th}\$ power.

The current method requires that you do a normal matrix multiplication \$k-1\$ times.

This of course has complexity \$k\$ multiplied by \$f(n)\$, Where \$f(n)\$ is the complexity of a matrix multiplication ( This is usually \$n^ 3\$ unless you write some fancy shmancy code that no one writes)

If you use binary exponentiation you reduce the number of multiplications to \$log(k)\$. Specifically the number of multiplications is the ceiling of \$log_2(k)\$ plus the number of 1 bits in the binary representation of \$k\$.

This is of course much more efficient for large values of \$k\$.


Your concerns about style and format are warranted, +1 for striving to make the code more elegant and declarative!

First of all, whatDoYouFindEasierToRead: mixed_caps_or_underscores?

For that reason, using underscores is the Prolog convention for naming predicates.

Second, Prolog is all about relations between things. You are using low-level moded arithmetic (is/2), which can only be used in one direction.

Instead, use constraints: They are completely general relations that can be used in all directions.

Third, since you are describing a list of bytes, consider using DCG notation. Do not use side-effects (opening a file etc.), because they prevent you from using your program in all directions. Instead, focus on a clear declarative description, and use pure features like library(pio) to apply a DCG to file contents.

All in all, consider the following program, tested with SWI-Prolog:

:- use_module(library(clpfd)).

:- set_prolog_flag(double_quotes, codes).

bytes([])     --> [].
bytes([B|Bs]) --> byte(B), bytes(Bs).

byte(Byte) -->
        [A,B,C,D,E,F,G,H],
        { foldl(pow, [A,B,C,D,E,F,G,H], 0-7, Byte-_) }.

pow(X0, Val0-Pow0, Val-Pow) :-
        X in 0..1,
        X #= X0 - 0'0,
        Val #= Val0 + X*2^Pow0,
        Pow #= Pow0 - 1.

Notice that I am not using any side-effects at all, and I don't have to, because I can do everything I need on the toplevel:

?- phrase(bytes(Bs), "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100"), maplist(char_code, Chars, Bs), maplist(write, Chars).
Hello World
Bs = [72, 101, 108, 108, 111, 32, 87, 111, 114|...],
Chars = ['H', e, l, l, o, ' ', 'W', o, r|...] .

And now the beauty of the declarative approach: In fact, the program is much more general than that, and I can also use it in the other direction:

?- phrase(bytes("Hello"), Codes), maplist(char_code, Chars, Codes), maplist(write, Chars).
0100100001100101011011000110110001101111
Codes = [48, 49, 48, 48, 49, 48, 48, 48, 48|...],
Chars = ['0', '1', '0', '0', '1', '0', '0', '0', '0'|...].

In fact, I can even leave everything unspecified and still obtain answers:

?- phrase(bytes(Bs), Codes).

Thus, the program is now much more general.

I would like to add that logic programming is very well suited for such kinds of problems. In fact, one of the very first applications of Prolog was concerned with language translation, and parsing a list of bytes like that was certainly part of that. Just stay in the pure and declarative part of Prolog (use constraints, pure input etc.), and you will obtain pretty nice programs.

EDIT: As requested, a few more comments about the code. The main part of the program, the grammar rule byte//1, is a declarative description of what we consider a byte in this notation. Now this is easily described: A byte in this particular notation is just a list of 8 bits [A,B,...,H]. And these bits are related to the byte B via the well-known relation B = A*2^7 + B*2^6 + ... + H*2^0. The pow/3 predicate defines this relation for each of the bits, using a running sum and position indicator as one of its arguments. Of course I have to subtract the ASCII code of 0 (Prolog: 0'0) from each of the given bits, because they are themselves specified in ASCII already, hence X #= X0 - 0'0 to obtain the "true" value of the bit X, 0 or 1.

Well and that's pretty much there is to it. A list of such bytes is readily described with DCG notation, and we use the phrase/2 interface to access DCGs.

I leave figuring out the rest as an easy exercise. Remember that you can always use the graphical tracer with ?- gtrace, your_goal., if you are interested in any particular execution details. In general though, I recommend you instead read the program declaratively and understand the relations that are being defined.


Command-line utility to capitalize long words in a file

As a Command Line Utility

The Argparse module is designed to facilitate the creation of command line utilities. It makes processing command line arguments much easier, and will even automatically display usage information if the user incorrectly enters arguments.

Potential Flaws

Your program does not preserve whitespace. This could be by design but I suspect it is not.
Example:

the      quick      brown  fox

will become

the Quick Brown Fox


Ruby function to join array with commas and a conjunction

Rails (actually ActiveSupport, part of the Rails framework) offers a very nice Array#to_sentence method.

If you are using Rails or ActiveSupport, you can call

['dog', 'cat', 'bird', 'monkey'].to_sentence
# => "dog, cat, bird, and monkey"

The method is automatically customized according to I18n settings. For example, in Italy you should omit the last comma before the and.

['dog', 'cat', 'bird', 'monkey'].to_sentence
# => "dog, cat, bird e monkey"

If you want something without depending on ActiveSupport, you can start using the method source code.

This is just an example

class Array
  def to_sentence
    default_words_connector     = ", "
    default_two_words_connector = " and "
    default_last_word_connector = ", and "

    case length
      when 0
        ""
      when 1
        self[0].to_s.dup
      when 2
        "#{self[0]}#{options[:two_words_connector]}#{self[1]}"
      else
        "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
    end
  end
end


What takes precedence: readability or elimination of side effects?

(I'm making my comment into an answer.) You can separate everything that is static (not using the state of instances of CookieManager) into a companion object (and import the object at the beginning of the class for convenience). This way, it is clear what functions use this directly or indirectly (by accessing class variables). This often helps me make my code clearer, and prevents stupid mistakes such as confuse class variables with function arguments etc.

class CookieManager {
  import CookieManager._

  var cookieJar = new CookieJar

  def getCookie(domain: String): Set[Cookie] = {
    cookieJar = removeExpiredCookies(cookieJar)
    cookieJar.find(_._1 endsWith (domain))
  }
}

object CookieManager {
  type ExpiryDate = Long
  type CookieJar = scala.collection.immutable.HashMap[String, (Cookie, ExpiryDate)]

  private def removeExpiredCookies(jar: CookieJar): CookieJar = {
    val currentDate = System.currentTimeMillis / 1000L
    jar.filter(_._2._2 > currentDate)
  }
}


Speed Efficiency of Decompression Algorithm

I can't test it at the moment, but I suspect that the culprit is
output += chunk

in a couple of places. This line potentially has O(n^2) complexity because of copying output to a new place in memory that has room to append chunk to it.  It would be more efficient to append chunk to a list and then use b''.join() at the end to concatenate all the chunks.
def decompress_lz2(data):
    global loop_count
    lb_len = 0
    lb_dist = 0
    escape = 0x16

    off_input = 0

    output = []               # <-- make output a list

    while off_input < len(data):
        loop_count += 1
        if lb_len:
            off_output = len(output) - lb_dist

            repeat = max(0, off_output + lb_len - len(output))

            chunk = output[off_output:off_output + lb_len - repeat]
            output.append(chunk)  # <-- changed '+=' to '.append()'

            if repeat:
                repeat_chunk = bytes([chunk[-1]]) * repeat

                output.append(repeat_chunk)  # <-- changed '+=' to '.append()'

            lb_len = 0

        if escape:
            chunk = data[off_input:off_input + escape]
            output.append(chunk)  # <-- changed '+=' to '.append()'
            off_input += escape
            escape = 0

        flag = data[min(off_input, len(data) - 1)]
        off_input += 1

        lb_len = flag >> 5

        if lb_len:
            if lb_len == 7:
                while True:
                    next_ = data[off_input]
                    off_input += 1
                    lb_len += next_
                    if next_ != 0xff:
                        break

            lb_len += 2

            lb_dist = (flag & 0x1F) << 8
            lb_dist += (1 + data[off_input])
            off_input += 1

            if lb_dist == 0x2000:
                lb_dist += (data[off_input] << 8)
                off_input += 1
                lb_dist += data[off_input]
                off_input += 1

        else:
            escape = flag + 1

    return b''.join(output)  # <-- concatenate the chunks


Accounts payable buckets (Current,30,44,48,60)

I wrote methods for determining if the date falls within the desired range. This doesn't really solve the cluster of if else statements, but it is more readable.

I also used a few built-in Python functions, filter and reduce. These are tailor-made for handling these kinds of boiler-plate tasks.

I also changed if ref_date to if ref_date is None. Quoted from PEP 8

  beware of writing if x when you really mean if x is not None

Finally, I replaced your list initialization for totals to according to this SO question.

def _get_balances(self,ref_date=None):
    if ref_date is None:
        ref_date = datetime.date.today()
    totals = [Decimal('0.0')] * 5
    for invoice in self.invoices:
        if invoice.date is not None:
            payments = filter(lambda: payment.check.date <= ref_date)
            total_amount_paid = reduce(lambda: total, payment: payment.amount + total, payments, 0)
            invoice_total = invoice.amount - total_amount_paid
            if self.__invoice_date_is_before(invoice.date, ref, date, 29):
                totals[0] += invoice_total
            elif self.__invoice_date_is_between(invoice.date, ref_date, 30, 43):
                totals[1] += invoice_total
            elif iself.__invoice_date_is_between(invoice.date, ref_date, 44, 47):
                totals[2] += invoice_total
            elif self.__invoice_date_is_between(invoice.date, ref_date, 48, 59):
                totals[3] += invoice_total
            elif self.__invoice_date_is_after(invoice.date, ref_date, 60):
                totals[4] += invoice_total
    return tuple(totals)

def __invoice_date_is_between(self, invoice_date, ref_date, start_of_period, end_of_period):
    return invoice_date <= ref_date - relativedelta(days=start_of_period) and \
                invoice_date >= ref_date - relativedelta(days=end_of_period)

def __invoice_date_is_after(self, invoice_date, ref_date, end_of_period):
    return invoice_date <= ref_date - relativedelta(days=end_of_period):

def __invoice_date_is_before(self, invoice_date, ref_date, start_of_period):
    return invoice_date >= ref_date - relativedelta(days=start_of_period)


1) Add another common class (using toggle in the example) to all of your tags

data

data

data

data

data

data

data

2) on your click handler add data tags (using data-show in this example) for what you want to show

<button data-show="home">home</button>
<button data-show="headr">header</button>
<button data-show="about">about</button>
<button data-show="skills">skills</button>
<button data-show="experience">experience</button>
<button data-show="education">education</button>
<button data-show="examples">examples</button>

3) Set up one function to handle all clicks

$('button').click(function(event) {
  $('.toggle').hide();
  $('.' + event.currentTarget.data.show).show();
  console.log(event.currentTarget.data.show + ' clicked');
});


Concurrency mechanism for ensuring repeated threads are executed in a given order

Because of the initial constraints (a for loop for two threads different why one prints "foo" and the other one prints "bar") set by leetcode site on the problem I see no alternatives to the way you solved it. Answering your first question:

Do you see any cases, where this solution would not work? (Assuming
the input is correct, i.e. n>=1.)

None, because you are setting the guard condition to one initial value (0) and you are ensuring the alternate order with wait and notify.
Your second question:

Do you see any issues with performance? (I know the code waits in a
while-loop, but it calls wait, which is supposed to be optimal.)

Again, following leetcode constraints there are no alternatives, while it seems that from some solutions posted on the site if you are less strict with constraints performance can be better, but this is probably bound to the fact that
threads just print one string and nothing else, so wait and notify calls represent a significative portion of working time.
Your third question:

In general, is there a way this solution could be improved?

You can use for the lock instead of your static class an Object instance and a boolean variable for the condition, but result should be quite similar.
Fourth question:

Does this pattern (threads running multiple times in a given order and
waiting for each other) have a name, or a high-level Java concurrency
object which implements them? (Slightly related: what better name
would you give to syncer?)

I see this situation like a token ring anomalous case where the token is in this case the value of the status guard, with more than two threads you could use a String token with the name of thread that would be activated.


Don't use a for loop to iterate over program output. See http://mywiki.wooledge.org/BashFAQ/001
Try this -- extract the keys, urls, rules all at once:
jq -r 'keys[] as $k | [$k, .[$k].url, .[$k].rule] | @tsv' "$sources" |
while IFS=$'\t' read key url rule; do
    case $key in
       ...

If, for some reason, your shell does not understand $'\t', use
while IFS="$(printf '\t')" read ...


Returning a collection of unique elements: List using Contains() or HashSet

Checking if an item exists in a list or a hashset has very different order of complexity:

\$O(N)\$ in a list: all items are checked one by one until a match is found. If no match, the entire list will be scanned
(amortized) \$O(1)\$ in a hashset: calculate hashcode, check if it exists

With today's computers, the performance with ~25 elements should be virtually the same. Even if you had a 1000 elements, you might still not notice a difference. If in doubt, measure it.

Note that converting the list to a hashset would have the consequence of losing the ordering. An alternative could be a SortedSet, if you don't mind sorting instead of ordering. For a data structure that preserves ordering and the time complexity of hashset operations, you could consider a linked hashset implementation discussed for example here.

To conclude, if you know you will only ever have few entries (< 1000),
the performance difference won't be noticeable.
However, as a matter of principle, it might be a good idea to use a hashset anyway, especially if you don't care about the order of entries.
A sorted set would be even better, to have consistent ordering, and fewer surprises.

You use the boolean literal false at many places, for example:

if(IncludeSystemAccounts.IsPresent == false)
{
    users = users.Where(user => user.IsSystemObject == false);

It's more natural to not use boolean literals like this, but write instead:

if (!IncludeSystemAccounts.IsPresent)
{
    users = users.Where(user => !user.IsSystemObject);


Is this file a good starting point for accessing data inside this json file via javascript classes?

Some issues:

The constructor recognizes an error if the file doesn't exist but, after logging, just behaves as if nothing is wrong.  It does not communicate back an error.  Probably, you should just let the exception go back to the caller or don't test it at all in the constructor and let the operation that actually uses the file get the error and communicate that error back to the caller then.

You're using a mix of synchronous and asynchronous file access.  That's usually a wrong choice because if you are in a programming situation where synchronous access is fine (like startup code or a single user script), then it's just simpler to use synchronous access everywhere.  If not (like in a server environment) and you should be using asynchronous access everywhere, then you should be using asynchronous access everywhere.

If you're doing this synchronously in nodejs, then require() of a filename with a .json file extension will automatically read and parse the file for you.

It's not clear why any of this involves methods on an instantiated object.  These are all stand-alone functions.  While you do access this.filename, that is not required if you just pass the filename to getAll().


Simple alphabet scrambler --- usage of vectors

Before discussing whether the algorithm is good or not, there are many small things that you could improve to make the code more readable:

Your program won't compile with some compilers if you don't explicitly include <cstdlib> for rand and srand and <ctime> for time.
It is good practice to always fully qualify with std:: the names of the standard library components you use. Therefore, you should explicitly write std::rand, std::srand and std::time.
Don't keep commented out comments. They will hardly help you and will probaby just be in the way. If you need to look again at old pieces of code, revision control software are there for you.
This loop:

std::vector<char> vuser_pass;
for ( decltype(user_password.size()) i = 0; i <= user_password.size(); ++i ) {
    char letter_hold = user_password[i];
    vuser_pass.push_back(letter_hold);
}

If I am not mistaken, you are simply asiigning every element of the string user_password to the vector vuser_password. In this case, please use the std::vector's constructor which takes two iterators:

std::vector<char> vuser_pass(std::begin(user_password), std::end(user_password));

This do what you need and you will avoid having to manually write a for loop. Note that it is also valid for the alpha/valpha conversion.
That said, do you need std::vectors at all? You can as well iterator directly on std::string since it implements the containers methods.
This loop:

for ( decltype(vuser_pass.size()) i = 0; i < vuser_pass.size(); ++i) {
    std::cout << vuser_pass.at(i);
}

If you use get rid of the vectors and simply use strings, you can directly output the resulting string to std::cout:

std::cout << user_password;

You don't need to return 0; at the end of main. If nothing is returned, the compiler wil automagically add a return 0; for you at the end. Not wirting it by yourself amy help to document the fact that you won't ever be returning anything else than 0.
You could a range-based for loop to simplify the latest remaining loop:

for (char& c: user_password) {
    c = alpha[rand() % 25];
}

Also, std::rand and std::srand are kind of advised against in modern C++ since there are safer alternatives in the new <random> header. However, the alternative is not that easy to use yet.

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 25); // will produce ints in [0, 25]

Now, you can create random integers between 0 and 25 by calling dis(gen).
Since alpha is not meant to be modified, it would be better to make it const.

So, let's take all of these modifications into account and write your code again:

#include <algorithm>
#include <iostream>
#include <random>
#include <string>

int main(){

    // random number generator in [0, 25]
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 25);

    std::cout << "Welcome, to the scrambler: " << std::endl;
    std::cout << "Enter the string (all lowercase letters) you want to be scrambled: " << std::endl;
    std::string user_password;
    std::cin >> user_password;

    std::cout << "Select the type of encryption you want: " << std::endl;
    std::cout << "1. Standard alphabet scrambler " << std::endl;
              //Add support for other types...
    int choice = 0;
    std::cin >> choice;

    if (choice == 1) {

        const std::string alpha = "abcdefghijklmnopqrstuvwxyz";

        for (char& c: user_password) {
            c = alpha[dis(gen)];
        }

        std::cout << user_password;
    }
}

Voilà! Your program has been converted to somewhat clean modern C++. Now, all you have to do is to provide more scrambling algorithms and to provide a mechanism to tell the user that they have chosen an invalid option and that they should chose again.


This seems like a perfect opportunity to leverage the standard library. I would make a function to toggle a single character and then use std::transform on top of that. Not only is it more consise, it will be more performant (you should use reserve to preallocate the resulting string -- otherwise the string may allocate over and over again).

#include <cctype>
#include <string>
#include <algorithm>

int toggle_case(int chr) {
    return std::islower(chr) ? std::toupper(chr) : std::tolower(chr);
}

std::string toggle_case(std::string str) {
    std::transform(std::begin(str), std::end(str), std::begin(str), toggle_case);
    return str;
}

Note that standard islower and isupper were used instead of comparison against character literals. Not only is it more compact and clearer, C++ does not guarantee that 'A', 'B', ..., 'Z' are contiguous.

Also, since you're (presumably) including the C++ version of ctype.h, cctype, you should be using std::toupper and std::tolower. C++ versions of C headers are allowed to place symbols in the global namespace, but they're only required to place them in std. There's no existing compiler I know of that doesn't also place them in the global namespace, but it can never hurt to strive for portabiltiy, especially when it's easy.

return std::islower(chr) ? std::toupper(chr) : std::tolower(chr);

This might look a little weird, but std::tolower and std::toupper are guaranteed to have no effect if no opposite-cased character exists for the input. In other words, std::tolower(c) is guaranteed to have no effect unless std::toupper(c) is true. To me, this makes sense and this short-cutted logic seems fairly natural. I could see this being rather weird to read though, so it might be better as a more explicit conditional chain.

I should also mention that the code makes an implicit copy of the string via the parameter. If you wanted to make the copy more explicit, you could, but that would actually be potentially hampering performance since it would disable movement into the parameter. In short, with the implicit copy, there's a potential that a copy will not actually happen. With an explicit copy, a copy will always happen.


Function from WordPress VoteItUp function

These are my suggestions

Don't use mysql functions to connect and query Wordpress posts.
You can replace the first SQL statement with this WP_Query.

$query = new WP_Query('post_type=post&post_status=publish&orderby=date&order=DESC');
$pageposts = $query->get_posts();

This way the code is somewhat protected from future Wordpress database changes.
The second select statement is a bit unnecessary as each $post in the $pagepost already contains the post id.
Only thing missing is the limit, but we'll add that to the WP_Query by adding

$query = new WP_Query('post_type=post&post_status=publish&orderby=date&posts_per_page='.$upperlimit);

Refactor and remove unused/unnecessary code

global $wpdb, $voteiu_databasetable - are not needed anymore
$upperlimit - assignment can be done on one line
$lowerlimit - not used anymore as it's enough with the $upperlimit
$output = $pageposts; - assigmentent before return is unnecessary

So the complete ShowPostByVotes in votingfunctions.php would look something like this now:

function ShowPostByVotes() {

    $upperlimit = is_numeric(get_option('voteiu_limit')) ? get_option('voteiu_limit') : 100 ;

    $query = new WP_Query('post_type=post&post_status=publish&orderby=date&posts_per_page='.$upperlimit);
    $pageposts = $query->get_posts();
    $votesarray = array();
    foreach ($pageposts as $post) {
        $vote_array = GetVotes($post->ID, "array");
        array_push($votesarray, array(GetVotes($post->ID)));
    }

    array_multisort($votesarray, SORT_DESC, $pageposts);
    return $pageposts;

}

And you can use it in your index.php by using this code

 <?php $pageposts = ShowPostByVotes();  ?>
 <?php if ($pageposts): ?>
  <?php global $post; ?>
  <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>

    <div class="post" id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
      <?php the_title(); ?>

      <?php the_time('F jS, Y') ?>

         <?php the_content('Read the rest of this entry »'); ?>

Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>
      <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?>

  <?php endforeach; ?>

  <?php else : ?>

Not Found

Sorry, but you are looking for something that isn't here.

    <?php include (TEMPLATEPATH . "/searchform.php"); ?>
 <?php endif; ?>


This looks like CSV. You are probably better off using the python csv module.

            holding=[]                      # start a temp array
            for var in line.split(','):     # for each value append it to the temp array
                    holding.append(var)
            services.append(holding)        # append the temp array to the services arra

Can be written as

services.append( line.split(',') )

line.split() returns a list already, there is no need to copy the elements into another list.


Check if vector of strings has matching brackets

Comments

You have overwhelming amount of comments. It looks to be too much. Usually code should document itself by having good names and intuitive behavior. Intuitive behavior would be one of standard library, for example. Other candidate is int type. In the extreme case you should write why the code does what it does, not what it does.

Implementation

It is really hard to understand what your code does, since it's not straightforward. Code should aim at correctness first, clarity second, performance third.

It's good that you're using range loops.

   if (type.first == c){  //if it's an opening bracket, add a new open bracket to the vector
                incr = 1;
                counts[c].push_back(0);
                break;
            }
            if (type.second == c){  //if it's a closing bracket, set incr to decrement each value
                incr = -1;
                break;
            }

This place of the code is very confusing. In the beginning I thought that we could use else to chain this, but then I noticed that it's type.first and type.second, which changed my opinion. But then I found that it always compares to c, so now it's pretty clear that there have to be else, since second shouldn't be checked if first condition is met. It is good both clarity and performance wise.

        int incr;

outside loop. It should be inside, because it's logical scope belongs to the loop. If you worry about performance, compiler should be able to figure that out, so your code will be both readable and performant.

Your braces function violate single responsibility principle. The principle greatly improves the code if used correctly.

Names are ambiguous in some places.

So lets make the code better.

Suggested implementation

First of all, lets nail down the name of the "entry point" function. is_valid_brace_sequence in my opinion is alright.

std::vector<std::string> is_valid_brace_sequence(const std::vector<std::string>& input)

Notice const std::vector<std::string>&. Algorithm doesn't need a copy. Copying will probably decrease performance.

If it wouldn't be part of problem statement, I would suggest having 2 input iterators for the beginning and end of the input, and one output iterator for the beginning of the output, so algorithm wouldn't mess with allocations.

Next, the algorithm goes over input, calls checker function on every element and records the results:

std::vector<std::string> results;
results.reserve(input.size());
for (const auto& element : input)
{
    bool result = check_validity(element);
    if (result)
    {
        results.push_back("YES");
    }
    else
    {
        results.push_back("NO");
    }
}

return results;

Using reserve increases performance, since vector won't need to resize. Also, it should be used in places where the size of the input in elements is known before hand.

Next, is check_validity function. It will also preserve const correctness:

bool check_validity(const std::string& input)

The algorithm used will be the following: if either left sided brace is encountered ('(', '[','{'), right sided brace will be put into stack. If right sided brace is encountered, top of the stack is checked for the exactly same brace, if it's not, return false.

bool check_validity(const std::string& input)
{
    std::stack<char> sequence;
    for (const auto& character: input)
    {
        switch (character)
        {
        case '(':
            sequence.push(')');
            break;
        case '{':
            sequence.push('}');
            break;
        case '[':
            sequence.push(']');
            break;
        case ')':
            if (!is_expected_brace(sequence, character))
            {
                return false;
            }
            break;
        case '}':
            if (!is_expected_brace(sequence, character))
            {
                return false;
            }
            break;
        case ']':
            if (!is_expected_brace(sequence, character))
            {
                return false;
            }
            break;
        default:
            continue;
        }
    }

    return true;
}

So the reason the algorithm works is that stack is LIFO container (last in first out). Since the type of the right sided brace should match the last left sided, so stack matches needs of the algorithm perfectly. Notice the use of switch. It increases performance because it generates jump table.

I've put all the boilerplate code of checking on encounter of right sided brace into the separate function:

bool is_expected_brace(std::stack<char>& sequence, char brace)
{
    if (sequence.empty() || sequence.top() != brace)
    {
        return false;
    }
    sequence.pop();
    return true;
}

Notice the logical OR operator (||). It provides short circuit ifs, so accessing the stack won't be undefined behavior.

Although it increases readability of the caller function, both of them has tight coupling between each other, so it limits the usability of them in case they are separated.

Put together

#include <vector>
#include <stack>
#include <string>
#include <iostream>

bool is_expected_brace(std::stack<char>& sequence, char brace)
{
    if (sequence.empty() || sequence.top() != brace)
    {
        return false;
    }
    sequence.pop();
    return true;
}

bool check_validity(const std::string& input)
{
    std::stack<char> sequence;
    for (const auto& character: input)
    {
        switch (character)
        {
        case '(':
            sequence.push(')');
            break;
        case '{':
            sequence.push('}');
            break;
        case '[':
            sequence.push(']');
            break;
        case ')':
            if (!is_expected_brace(sequence, character))
            {
                return false;
            }
            break;
        case '}':
            if (!is_expected_brace(sequence, character))
            {
                return false;
            }
            break;
        case ']':
            if (!is_expected_brace(sequence, character))
            {
                return false;
            }
            break;
        default:
            continue;
        }
    }

    return true;
}

std::vector<std::string> is_valid_brace_sequence(const std::vector<std::string>& input)
{
    std::vector<std::string> results;
    results.reserve(input.size());
    for (const auto& element : input)
    {
        bool result = check_validity(element);
        if (result)
        {
            results.push_back("YES");
        }
        else
        {
            results.push_back("NO");
        }
    }

    return results;
}

int main()
{
    std::vector<std::string> test_input{ "{{}}", "[[[]]", "[](){}", "[[])", "{[()]}" };
    std::vector<std::string> results = is_valid_brace_sequence(test_input);
    for (const auto& element : results)
    {
        std::cout << element << " ";
    }

}


Set id in constructor, or generate it when asked for?

I would go with lazy loading. Generate the id when requested
private $id;

public function getId()
{
    if ($this->id === null) {
        $this->id = //your logic to generate the id here
    }
    return $this->id;
}

and don't use anywhere else $this->id even inside the class. Use $this->getId() everywhere.
using $this->getId() everywhere will ensure that you always get the generated id (the same one everytime) and you are sure you don't get the null initial value.