Can I draw a square with pixels more efficiently?

Disclaimer
I don't have a working C compiler on my work computer, nor do I have Xlib available to me (I'm also not familiar with it, at all). That being said, given that we know our image is a square, you can do this with a single loop.
Use a simpler algorithm
The basic idea is that we know each corner of our square, and then by stepping through the length of a side, we can draw a pixel on each side of the square per iteration. This way, instead of nested looping, you do it all at once.
// assuming a coordinate system where 0,0 is the bottom-left corner of the image
// starting at each corner, draw the corresponding clock-wise line
for (int pos = LWST_VAL; pos <= HGHST_VAL++pos)
{
    // The bottom line
    my_pixel_put(&img, pos, LWST_VAL, 456);
    // The top line
    my_pixel_put(&img, pos, HGHST_VAL, 456);
    // The left line
    my_pixel_put(&img, LWST_VAL, pos, 456);
    // The right line
    my_pixel_put(&img, HGHST_VAL, pos, 456);
}

Cache behavior
The one thing that occurs to me about this implementation is that you might not do quite as well from a caching perspective - the one benefit of doing things on a side-by-side basis is that you're more likely to be operating on data from the cache instead of from memory. I don't know how &img is actually stored or what my_pixel_put is doing, so its hard to give more concrete advice about this.
If you did encounter caching issues, short of changing things to process side-by-side (or maybe top + bottom in one loop, and left + right in another), there isn't a whole lot to do. A normal technique to handle cache churn is to use blocking to break up the loop. That won't help here, unfortunately - see below for why.
Suppose we know the following (these numbers are made up):

16 lines of data can be held in the cache
4 integers can be held in the cache at the same time
img is a matrix stored as a row-wise vector, and my_pixel_put effectively becomes img[WIDTH * y + x] = 456
img is aligned such that the left-most side of the square represents the start of a cache line (there will be many cache lines to get to the right side)

Each iteration of our loop grabs 4 cache lines - one for each side of the square. The top and bottom will be able to re-use the cache line for the next three values, while the right and left will have to get a new cache line. We then have the following sequence for how many cache lines we get at a time:

4
6
8
10
14
16
etc

The 7th loop iteration would force some of the old data out of the cache. If we were going to be using data besides the border of the square (e.g. by filling it somehow) then it would be worthwhile to operate on 6x6 "blocks" of data, because then everything is in-cache instead of in-memory. Because we aren't using the interior of the square, however, we'll never actually get a benefit to blocking up the operation - most of those cache lines will always go to waste
Parallelization
Another benefit of this is that, if you wanted to parallelize this on a CPU or port it to a GPU, it'll be more straightforward. On a CPU, this is an embarrassingly parallel problem - assuming that my_pixel_put is thread-safe as long as you aren't modifying the same pixel, threading it should be trivial. On a GPU, the lack of conditional operations makes it a breeze as well.
You may want to change your memory access patterns if you go parallel, but additional detail is left as an exercise for the reader. As a hint, for CPU-based parallelism each thread should generally be working on distinct pieces of work to avoid ruining cache coherence.
Looking at your code as written, without algorithm changes
Reviewing your actual code, there are some simple ways that you can improve readability & maintainability without changing the algorithm much.

I don't like your outer while loop - you basically just have a for loop, with some extra weirdness about the top vs bottom line.
I have a very similar beef with your inner while loop - this one is even more obviously just a for loop.
Some of your conditions that you pack into your while should be separate, if only for readability's sake. Several of them are obviously removed by switching to a for loop, while others are better suited as an if statement wrapping your loop.
Your macro names are unnecessarily mangled - its okay to have vowels in your macros
Is it really necessary to have these be macros?

for (int x_position = LWST_VAL; x_position <= HGHST_VAL; ++x_position)
{
    if (x_position == LWST_VAL || x_position == HGHST_VAL) {
        for (int y_position = LWST_VAL; y_position <= HGHST_VAL; ++y_position)
        {
            my_pixel_put(&img, x_position, y_position, 456);
        }
    } else {
        my_pixel_put(&img, x_position, LWST_VAL, 456);
        my_pixel_put(&img, x_position, HGHST_VAL, 456);
    }
}

Whoops, I ended up rewriting it more than I meant to - I just couldn't make myself add another loop just because. To keep an equivalent number of loops, you could do something like this:
for (int side_count = 0; side_count < 2; ++side_count) {
    for (int x_position = LWST_VAL; x_position <= HGHST_VAL; ++x_position)
    {
        if (side_count == 0 && (x_position == LWST_VAL || x_position == HGHST_VAL)) {
            for (int y_position = LWST_VAL; y_position <= HGHST_VAL; ++x_position)
            {
                my_pixel_put(&img, x_position, y_position, 456);
            }
        } else {
            my_pixel_put(&img, x_position, side_count == 0 ? LWST_VAL : HGHST_VAL, 456);
        }
    }
}


Using regex to replace strange characters

RegEx Improvements

The regex can be shortened by using case-insensitive match with i flag. We can remove the characters which are added as both lowercase and uppercase in the regex.

After removing lowercase characters regex will be as below

\?ÕÌ_|Š|Ž|À|Á|Â|Ã|Ä|Å|Æ|Ç|È|É|Ê|Ë|Ì|Í|Î|Ï|Ñ|Ò|Ó|Ô|Õ|Ö|Ø|Ù|Ú|Û|Ü|Ý|Þ|ß|ð|ÿ|_Œ‚|__|_

Here's live demo of regex

The regex can be further improved by using character class which will make the matches faster than OR conditions

\?ÕÌ_|_Œ‚|[ŠŽÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝÞßðÿ_]+

Adding + quantifier also has positive effect on the number of steps taken to match characters when the characters in the character class are consecutive/adjacent to each other.

Here's the demo on RegEx101, without + quantifierScreenshot and with + quantifierscreenshot applied on the same data. Note that in these demos, PHP is selected as the steps taken to match is not shown for JavaScript. Also, the regex is different, it also contains lowercase counterparts of those special characters as i flag is not working with PHP and don't want to apply u(Unicode) flag as it is not supported in JavaScript.

These demos are created only to show difference when + is applied on character class. The effect should be similar in JavaScript.

Note that the __(two underscores) are redundant as _ is already added in character class and with g flag it'll remove all occurrences.

Method Chaining

As replace returns a string, any other string method can be called on it. Multiple calls to replace can be chained.

str.replace(someRegexOrString, someString)
    .replace(someOtherRegexOrString, someOtherString);

This is equivalent to

var temp = str.replace(someRegexOrString, someString);
var result = temp.replace(someOtherRegexOrString, someOtherString);

Replacing HTML

jQuery html() accepts a function which will receive the current innerHTML of the element on which the method is called as parameter and replaces the returned content to the element.

The code can be written as

$('.rte').html(function(index, currentHTML) {
    return doSomeOperationOn(currentHTML);
});

Complete Code

With above changes, the code will be

$(document).ready(function() {
    var regex = /\?ÕÌ_|_Œ‚|[ŠŽÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝÞßðÿ_]+/gi;

    $('.rte').html(function(i, oldHTML) {
        return oldHTML.replace(regex, ' ')
            .replace(/[^\x00-\x7F]|\?/g, '');
    });
});

$(document).ready(function() { is more readable than $(function() {. So, you may also consider using more expressive form.


As the ctl file can't be parameterized you'll have to create them for each infile.

As it is quite small, I'd create it on the fly from a here string with the format operator.

This sample script just echoes to screen, the commands to write/execute sqlldr are commented out.

## Q:\Test\2019\01\24\CR_212133.ps1
$dataFiles = @(
    "filelist21.dat"
    "filelist22.dat",
    "filelist23.dat",
    "filelist25.dat",
    "filelist121a.dat",
    "filelist121b.dat",
    "filelist122a.dat",
    "filelist122b.dat"
)

$ctlFile = "$PSScriptRoot\load_data.ctl"

foreach ($dataFile in $dataFiles) {
@'
load data
infile '{0}'
append
into table ogd_xml_table
fields
(
    filename FILLER CHAR(100),
    xml lobfile( filename) terminated by eof
)
'@ -f $dataFile  #| Out-File $ctlFile -Encoding ASCII
    #sqlldr mckdev@$SecretDatabase/$SecretPassword control=$ctlFile
}

> Q:\Test\2019\01\24\CR_212133.ps1
load data
infile 'filelist21.dat'
append
into table ogd_xml_table
fields
(
    filename FILLER CHAR(100),
    xml lobfile( filename) terminated by eof
)
----------------------------------------------------------------------
load data
infile 'filelist22.dat'
append
into table ogd_xml_table
fields
(
    filename FILLER CHAR(100),
    xml lobfile( filename) terminated by eof
)
----------------------------------------------------------------------
%<...snip...>%


Edit:
As coderodde excellently pointed out in his answer, your implementation has the issue of not reusing previous entries in the array that have already been dequeued. This means that your array will always keep on growing in size. See his answer for an explanation on this.

First of all, good job on improving your coding skills through an exercise like this. More people should be doing this. Now lets get into the criticism from which you will hopefully learn even more.

Constructor

It's strange that you do not allow the user to specificy the initial size of the queue. Even if this were to be a design choice, I think 2 is too low of a value. Also the magic number 2 should be moved to a constant like DEFAULT_QUEUE_SIZE to increase readability and maintainability.

Size

Your size variable is quite confusing. For a while I thought it was the current size of the queue, meaning it would start at 2 and then double over time. But later I found out that it actually represents the amount of items currently in the queue. I think that this might also be confusing to anyone calling your size() method.

isFull()

In your enqueue() method you check size == queue.length. This is essentially the isFull() method. Replacing this with a call to isFull() would not only increase the readability of your enqueue() method, but also add the isFull()method to the public API of your class, fulfilling the symmetry with isEmpty().

resize()

To improve coherence and readability, I would add two methods called doubleSize()and halfSize(), which would simply then call the resize() method with the correct parameters. This improves the readability and intentions in the enqueue() and dequeue() method and allows the explanatory comment // shrink the queue if necessary to be removed.

Comments

There are a lot of opinions about comments. I share mine with Robert C. Martin in that they show a failure of expressing yourself by means of code. The comment I mentioned in the section above about the resize() method is a good example of that.

The other comment in your code, // be sure no null items make it into the queue, can also be removed, because the code below it is perfectly clear. It is simply a duplication of information, and just as duplication of code is bad, this kind of duplication is bad as well. This is because comments tend to get out of sync with the code they were intended to enlighten.

Interface

Personally, I do not see the use of an interface for this implementation. I think it is merely clutter as it provides no additional information that the concrete class itself does not already provide.

Testing

There is a lot that could be improved in the testing department here. I will try to create a somewhat short, comprehensive list of the things that I think are missing or incorrect. You will find that most of the things I say about testing have also been said in the Code Review question that inspired you, so perhaps you should also read through the accepted answer there on testing.

Your enqueueTest function is testing size() functionality.
Your test function names are not very descriptive about the situation that is being tested and what the expected outcome should be. There is a small blogpost by Google on test function names that might be useful to read.

Test ALL the things.

You are not even scratching the surface of having all scenarios tested.

Are you sure that dequeue() actually halves the queue size when it can? You shouldn't be, because you haven't tested it.
isEmpty() is not even tested once. What happens when isEmpty() is called when the queue is empty, filled or full? Or full and then emptied again. All of these scenarios should be tested.
Your test for the size() method is way too simplistic. Does size() return 0 if the queue is empty? does it return the correct amount after enqueueing X items and dequeueing Y items? Does it return the correct amount after doubling and halving the queue X amount of times?
You should also test the FIFO (First In First Out) concept of your queue more elaborately. You started with it in dequeueTest(), but kept it way too simple.

Test examples

In this section I will provide some example tests for only the method isEmpty() to illustrate my points above.

@Test
public void testIsEmptyReturnsTrueWhenQueueIsEmpty() {
    assertTrue(queue.isEmpty());
}

@Test
public void testIsEmptyReturnsFalseWhenQueueIsFilled() {
    queue.enqueue(1);
    assertFalse(queue.isEmpty());
}

@Test
public void testIsEmptyReturnsFalseWhenQueueIsFull() {
    // Since your magic starting queue size number
    // is 2 I enqueue two items.
    queue.enqueue(1);
    queue.enqueue(2);

    assertFalse(queue.isEmpty());
}

@Test
public void testIsEmptyReturnsTrueWhenQueueIsEmptiedAfterUse() {
    for (int i = 0; i < 10; i++) queue.enqueue(i);
    for (int i = 0; i < 10; i++) queue.dequeue();

    assertTrue(queue.isEmpty());

    // This second part is debatable since you generally want
    // to test only one thing per test.
    for (int i = 0; i < 10; i++) {
        queue.enqueue(i);
        queue.dequeue();
    }

    assertTrue(queue.isEmpty());
}


New to programming. How can I write this Rock, Paper, Scissors code better?

Despite of very simple and "verbose" initial implementation it has a bunch of issues:

r_p_s = ['Rock', 'Paper', 'Scissors'] is better defined as constant of immutable values
result is accessed within response() function body as a global variable.Instead, it's better called within the function on demand:

def response():
    result = game()
    ...

instead of arbitrary strings concatenation ... + " vs. " + ..., "Roll: " + "\n" + result - use flexible f-string formatting.
For ex.: print(f"Roll: \n{result}")
the conditions like:

if "Scissors vs. Paper" == result or \
    "Paper vs. Scissors" == result:
    print("\nScissors beats Paper")

are too verbose and hard-coded to be manageable and reliable

Now, when you realize the bad things described above and wonder if there a manageable and advanced approach - take and consider the one below, which is OOP approach representing RPSGame class (as a main class) and powered by enum classes to represent the crucial shapes.
The new implementation itself is pretty descriptive (I hope). Enjoy!

import random
from enum import Enum

class RPSGame:
    class Shape(Enum):
        R = 'Rock'
        P = 'Paper'
        S = 'Scissors'

    # winning outcome bindings
    WIN_OUTCOMES = {
        (Shape.P, Shape.R), (Shape.R, Shape.S), (Shape.S, Shape.P),
    }

    @staticmethod
    def choice():
        shapes = list(RPSGame.Shape)
        return random.choice(shapes), random.choice(shapes)

    def play(self):
        shape1, shape2 = self.choice()
        print(f"Roll: \n{shape1.value} vs {shape2.value}\n")

        if shape1 == shape2:
            print("Draw! Roll again.")
        else:
            # check to swap shapes to get winning output order
            if (shape1, shape2) not in RPSGame.WIN_OUTCOMES:
                shape1, shape2 = shape2, shape1
            print(f"{shape1.value} beats {shape2.value}!")

if __name__ == "__main__":
    rps = RPSGame()
    rps.play()
    rps.play()
    rps.play()

Sample output (from 3 plays):

Roll:
Paper vs Scissors

Scissors beats Paper!
Roll:
Scissors vs Scissors

Draw! Roll again.
Roll:
Rock vs Paper

Paper beats Rock!


Outputting a logo from the Wordpress Customiser

Here are my  suggestions:

There is no point of "fetching" the image url if has_custom_logo returns false.

Instead, I would define $logo with a default value, then, if has_custom_logo is true, I would just rewrite it's value.

$logo = get_template_directory_uri() . '/img/logo.png';

if(has_custom_logo()){
  $logos = wp_get_attachment_image_src(get_theme_mod('custom_logo'), 'full');
  $logo  = reset($logos);
}

echo sprintf('<img src="%s" />', esc_url($logo));

I'm using reset method, it

  rewinds array's internal pointer to the first element and returns the
  value of the first array element.

You can convert this to a method and use it in multiple places.


As CodesInChaos pointed out in the comments, a far more secure way to hash passwords is to use a deliberately expensive hash. This will all but eliminate any hope of a successful brute-force attack.

The "best" algorithm I know of for this purpose would be BCrypt. For .NET, you can use BCrypt.Net. Disclaimer: I don't know who, if anyone, has verified the integrity of this particular port.

See this StackOverflow question for a full discussion regarding the use of BCrypt as a password hashing algorithm.

Original answer

So long as the salt is sufficiently unpredictable, the hashing function sufficiently secure, and the user's password is never stored in plain-text, emailed, or logged, then your implementation should be adequate.

While your salt is unpredictable, 8 bytes may be short for extremely sensitive information. A salt is stored in plain-text along with the hashed password, so we're not worried about keeping it a secret. What we're worried about is that someone may have already pre-computed SHA-256 hashes for common passwords and salts up to 8 bytes salt (though unlikely). Having a random length salt really doesn't add much except computational complexity and potentially wasted storage space. I would settle for a consistent-width salt of 16 bytes.

SHA-256 is a suitable hashing algorithm for most purposes at this time.
Edit: But BCrypt is better for passwords (see above).


Checking if an element sastifying a condition in a list comes before another of a different condition

Currently, you are in fact looping through the entire list three times.

Collections2.filter(list, condition1).size()
Collections2.filter(list, condition2).size()
for (T t: list)

This is a bit inefficient, as ultimately, once should be enough.

To accomplish that, we need to check each item exactly once (or technically, at most once, as it is possible to return false early).

Also, to make the method slightly more useful, you can use Predicate<? super T>.

Which is easiest, checking if the list does adhere to your requirements or checking if it does not? In my opinion, it is easier to check if one of your requirements fail, which means that we can have the method return true; as the last statement and perform some early returns for false if something doesn't match your requirements.

What I would end up with is this, which is pretty much straight-forward:

private static <T> boolean isItemWithConditionBeforeAnother(Predicate<T> condition1, Predicate<T> condition2, List<T> list) {
    int found1 = 0;
    int found2 = 0;
    for (T t: list) {
        if (condition1.apply(t)) {
            found1++;
        }
        if (condition2.apply(t)) {
            found2++;
        }
        if (found1 > 1 || found2 > 1) {
            return false;
        }
        if (found2 > found1) {
            return false;
        }
    }
    return found1 == 1 && found2 == 1;
}

Using the found variables as int instead of boolean helps greatly here. It lets us check if any condition has been matched twice, and lets us use the trick found2 > found1 to check if condition2 was matched before condition1.

Alternative approach using booleans, inspired by @janos.

boolean found1 = false;
boolean found2 = false;
for (T value : list) {
    if (found1 && condition1.apply(value)) {
        return false;
    }
    if (found2 && condition2.apply(value)) {
        return false;
    }
    found1 = found1 || condition1.apply(value);
    found2 = found2 || condition2.apply(value);
    if (found2 && !found1) {
        return false;
    }
}
return found1 && found2;

An important thing here is that once found1 is true, it will never be set to false again thanks to the short-circuiting || operator.


1 Producer, N Consumers working in parallel, each doing ~1/nth of a task

Here are some comments on your program.  Note that I am not a threads expert.

Firstly, the code runs nicely.  I'm running OSX and it compiles cleanly and
executes correctly (as far as I can tell).  I was a little surprised that
threads wake up in the same order each time - in other words if thread 123456
is the first to complete the first job, then it seems to be the first to
complete each subsequent job.  This says more about the thread implementation
than your code I guess.

The problem I have with the code is that although it seems to work, it is coded
very specifically for the problem in hand.  The barriers ensuring that all
threads come together at intervals are not separately identifiable but are
entwined in the control code.  The variable mini_tasks_complete, used in
creating the barrier is initialized to -NTHREADS, allowed to run up to zero
during the initial barrier and then cycles from 0 to NTHREADS.  This clearly
works but is inelegant (I think you will find that the initial barrier can be
omitted and worked into the loop with a bit of thought).

I would prefer to see the thread function have the simple form:

while (more_tasks) {
    barrier();
    work();
}

and the main thread have the general form:

for (...) {
    prepare_work();
    barrier();
}

Written like this one can clearly identify the synchronisation.  The barrier function
here would also preferably take a parameter identifying the barrier and not
use globals.

I assume your platform, like mine, lacks the pthread barrier.  You might write
your own barrier function.  From what I have read, barriers are normally based
upon a pair of condition variables and a pair of mutexes.  The Little Book of
Semaphores has a discussion of this and there is a useful Solaris
implementation that could be used as a template.

Some trivia:

I would find while (more_tasks) more logical than while (!no_more_tasks)
inconsistent use of camelCase


There's not much to review; that said, the input is guaranteed to be
between zero and \$2^{32}\$, so there is no point to the N & 0xffffffff really.  Also the print statement would be more upwards
compatible with Python 3 if it was used like a function,
i.e. print(...).


Possible improvement:

return directBuffer;

with:

return directBuffer.asReadOnlyBuffer();

Wanted to find a one-liner to help https://code.google.com/p/guava-libraries/wiki/IOExplained but ByteBuffer, streams nontrivial. Notice defining mutable ByteBuffer references in the method, placing each into an instance collection, one never flushed or refreshed...Servlet web container would need a restart in order to reflect changes to the files or other resources.


List comprehension is a very neat way to construct lists in Python. For instance :

stripped = []
for word in words:
    stripped.append(word.strip())

becomes

stripped = [word.strip() for words in word]

(and then you can get rid of the stripped variable altogether in your code).

The pythonic way to loop over something is not to use range and len (except if you really have to). For instance, we have first :

for i in range(0, len(word)):
    constructed += UNKNOWN_CHARACTER

which can be written :

for i in word:
    constructed += UNKNOWN_CHARACTER

Then one might argue that you can use the * operator here to write :

constructed = UNKNOWN_CHARACTER * len(word)

Sometimes, you might think that you need to use range and len because you need the index corresponding to your iteration. This is what enumerate is for. For instance :

        new_constructed = ""
        for i in range(0, len(word)):
            if word[i] == guess:
                new_constructed += guess
            else:
                new_constructed += constructed[i]

becomes :

        new_constructed = ""
        for i,l in enumerate(word): # i in the index, l is the letter
            if l == guess: # note that we don't need to get the i-th element here
                new_constructed += l # I prefer l to guess here because it's shorter :-P
            else:
                new_constructed += constructed[i]

What would be really awesome here would to be to be able to iterate over 2 containers in the same time. zip allows you to do such a thing.

        new_constructed = ""
        for w,c in zip(word,constructed):
            if w == guess:
                new_constructed += w
            else:
                new_constructed += c

Then, it's pretty cool because we can make things slightly more concise :

        new_constructed = ""
        for w,c in zip(word,constructed):
            new_constructed += w if w == guess else c

If you want to play it cool and re-use list comprehension (or even generator expression (I use fancy words so that you can google then if required)) : you build some kind of list of characters/strings and join them together with join.

        new_constructed = ''.join((w if w == guess else c for w,c in zip(word,constructed)))

This being said, I probably wouldn't build that string this way but I just pointed to point this out so that you can discover new things.

Usually, global variables are frowned upon because they make things hard to track. In your case, it is not so much of an issue but let's try to split the logic in smaller parts. It makes things easier to understand and to test too.

Here, we just need to return the list of words from load_words.

It's interesting to store the letters that have been guessed. However, a list (build with [] and populated with append()) might not be the right container for this. What you really want at the end of the day is just to be able to tell quickly whether some letter has been guessed already. This is what sets are for.

You could store all guesses or just wrong guesses. You've decided to store only wrong guesses (as right guesses can be deduced from the constructed string).

Personnally, I'd rather save all guesses on one hand and the number of wrong guesses on the other hand at it might make things a bit easier later on. I am not saying that what you did was wrong at all, I just want to show a different way to do.

Also, I'm trying to split the logic used to

display what has been found away from the logic used to
know if a letter has been guessed
know if the character has been fully found.

At the moment, the variable constructed in used for these 3 things and can make things hard to understand.

At the end, here is what I came up with :

#!/usr/bin/python

import random

UNKNOWN_CHARACTER = "*"
GUESS_LIMIT = 7

def load_words():
    words = []
    with open("dictionary.txt") as file:
        words = file.readlines()
    return [word.strip() for word in words]

def play(word):
    nb_wrong = 0
    guesses = set()
    while nb_wrong < GUESS_LIMIT:
        print("\n" + str(GUESS_LIMIT - nb_wrong) + " errors left...")
        print(''.join(c if c in guesses else UNKNOWN_CHARACTER for c in word))
        while True:
            guess = input("Guess a letter: ").lower()
            if len(guess) == 1:
                if guess in guesses:
                    print("You've already guessed that letter!")
                else:
                    guesses.add(guess)
                    break # stop when we have a valid guess
            else:
                print("Please guess a single letter.")
        if all(c in guesses for c in word):
            break # stop when all characters are found
    print("\n" + word)

def main():
    words = load_words()
    while True:
        play(random.choice(words))
        if input("Continue playing? (y/n): ").lower() not in ["yes", "y"]:
            break

if __name__ == "__main__":
    main()

(It's highly not tested but the point was more to explain you what I did than to show you a working program)


If you want not to have callback hell, my suggestion is to use classes. You can find a lot of techniques for how to define a class. I did it my way. You may change what you want. I know that many people would suggest some changes, but that will be about specific rules, not about the full decision. I suppose a majority would agree that my way has a right to live.

My problem while developing a class was that I did not know about the  semantics of your data. It is a very good start to find out the semantics, split by items, give them names. Then you would get a decision from your logic. I gave some names to variables and methods but I suppose it likely should be changed.

function Transfer(source) {
    this.source = source;
    this.result = {};
}

Transfer.prototype = {
    constructor: Transfer,

    make: function() {
        var self = this;
        _.each(this.source, function (val, key) {
            self.processNames(val, key);
        });
        return this.result;
    },

    processNames: function(data, name) {
        var self = this;
        var path = [name];
        _.each(data, function (val, key) {
            self.processIndexes(val, path);
        });
    },

    processIndexes: function(data, path) {
        var self = this;
        _.each(data, function (val, key) {
            var newPath = (path).slice(0);
            newPath.unshift(key);
            self.processCodes(val, newPath);
        });
    },

    processCodes: function(data, path) {
        var current = this.result[path[0]] = this.result[path[0]] || {};
        current = current[path[1]] = current[path[1]] || [];
        current.push(data);
    }
};

var transfer = new Transfer(initial_obj);
transfer.make();

One more improvement might be to add a static method, e.g. .make:

Transfer.make = function (source) {
    var inst = new this(source);
    return inst.make();
};

I would not advise you to return any values from a constructor, as it is just for setting options. Generally, I would use controllers only for defining properties. Otherwise you need a stub prototype while testing which is not an elegant design.

I tested your code. It works as expected. I did not use indexes when setting values to array. I just used Array#push. If you have the structure that you provided, it should work.

I know that this technique has more lines of code than yours. But it has several advantages:

it is open for testing
it is open for extending
it is more human readable
it is more clear


Adjusting the height of a div to match that of another column

You can save $(this).closest('.papers.left') into a local variable since you access it twice. This might improve performance. It can also enhance code readability:

$('img').each(function () {
    var parent = $(this).closest('.papers.left');
    if (parent.length)
    {
        $(this).on('load', function () {
            $(this).closest('.row').find('.papers.right').height(parent.height());
        })
    }
})

As an add on to your code modification, I don't know that this is faster, but why not try assigning max height to both without checking which is taller? Something like:

$('img').each(function () {
    var parent = $(this).closest('.papers.left');
    if (parent.length)
    {
        $(this).on('load', function () {
            var sibling = $(this).closest('.row').find('.papers.right');
            var height = Math.max(parent.height(), sibling.height());
            parent.height(height);
            sibling.height(height);
        })
    }

})

It's certainly shorter and more readable. Why not test it out to see how the efficiency compares?


Parsing CSV file with BufferedReader vs Scanner

I think that splitting a string on commas is the worse approach for serious CSV parsing.

There is no single standard csv format, but RFC 4180 comes close to being a de facto standard.  As described in Section 2, CSV fields may be double-quoted (and if so, a literal " would be represented as a pair of " characters).  Simply splitting a line on commas does not give you the ability to ever implement support for interpreting quoting.

With a Scanner, you can use tools such as useDelimiter(Pattern) and findInLine(Pattern) to simultaneously look for " and , characters, giving you a chance to write a real parser based on the ABNF grammar in RFC 4180.

Of course, unless are deliberately reinventing-the-wheel, you should just use an existing library, such as Apache Commons CSV or opencsv.


Templating libraries' intelligibility and their performance (compared to mine)

... as I went through others, there is always this voice in head, which says: "Oh, this is a lot of code and functionality. Is that really necessary or would it slow down the performance?"

This is a reasonable consideration, but premature optimisation is evil for a reason.   It might be a good idea to try to roll out your own solution, but it would be beneficial to learn more about the problem and other existing solutions before implementing it yourself.
As for minimalistic templating library, take a look at Underscore _.template.
It's literally 45 lines (add one or two helper functions) and does its job well.
As for your solution, I have a few points:
Don't use AJAX to load templates
If you're worried about performance, loading templates via AJAX is a bad idea. This will be a terrible bottleneck, not some hundred more lines of code in a different templating library.
Moreover, your code assumes you need to make an HTTP request each time you render something. If you have a list view with 20 items, that would be 20 requests.
This is absolutely unsuitable for production code.
Don't use synchronous AJAX calls, like, ever
The very point of AJAX is processing things asynchronously, without blocking other scripts from executing. There is rarely a reason to do things synchronously.
Again, please don't do this in production code.
Instead, put templates in HTML or (better) compile them to JS
Most, if not all, templating libraries assume the template is already available in the client code, and this is the correct way to go. Now, there are two ways how you can accomplish this:
1. You can embed templates in DOM with tricks like


Test whether two strings are anagrams of each other

You take a string, and instantly make a list from it, and so space is at least \$O(n)\$. s1.count(pos) is an \$O(n)\$ operation, and is in a loop that loops \$n\$ times, and so the loop is \$O(n^2)\$. To make the loops \$O(n)\$ you just need to add 1 to the amount, and use a defaultdict to default everything to 0.

from collections import defaultdict

def anagram(str1, str2):
    freq1 = defaultdict(int)
    freq2 = defaultdict(int)

    for char in str1:
        freq1[char] += 1
    for char in str2:
        freq2[char] += 1

    return freq1 == freq2

This can however be simplified to use collections.Counter. And so you can use:

from collections import Counter

def anagram(str1, str2):
    return Counter(str1) == Counter(str2)

And so both the above have \$O(n)\$ time and space complexity.


Scrolling in Horizontal ScrollView losing selection

I'm not familiar with Android, so just some generic notes:

int i = 0;
Button button = null;
for (; i < 11; i++)

I think the most developers more familiar with the following (equal and shorter) form:

for (int i = 0; i < 11; i++)

11 and 0 are magic numbers. Use a named constant instead of them which explains the meaning of these numbers (and probably removes some duplication and makes maintenance easier).
I think MotionEvent variable could deserve a little bit longer name for better readability. (Clean Code by Robert C. Martin, Avoid Mental Mapping, p25)
You could increase the abstraction level and readability a little bit with a new method whose name contains the purpose of the loop:

@Override
public boolean onTouchEvent(MotionEvent event) {
    Button button = getSelectedButton();
    super.onTouchEvent(event);
    button.setSelected(true);
    button.requestFocusFromTouch();

    return true;
}

private Button getSelectedButton() {
    LinearLayout linearLayout = (LinearLayout) getChildAt(0);
    for (int i = 0; i < 11; i++) {
        Button button = (Button) linearLayout.getChildAt(i);
        if (button.isSelected()) {
            return button;
        }
    }
    throw new IllegalStateException("no button selected");
}

Note that the Button variable get a smaller scope and the linearLayout local variable.

(Clean Code by Robert C. Martin, One Level of Abstraction per Function, p36; Clean Code by Robert C. Martin, G19: Use Explanatory Variables, p296; Effective Java, Second Edition, Item 45: Minimize the scope of local variables; Refactoring: Improving the Design of Existing Code by Martin Fowler, Introduce Explaining Variable)
If you return null the button.setSelected() will throw a NullPointerException (or if you don't find any selected button in the original code). I guess having zero selected button is not a valid state of the application. If it somehow happens I'd throw an exception immediately (instead of setting null as the Button reference).

private Button getSelectedButton() {
    for (int i = 0; i < 11; i++) {
        Button button = (Button) ((LinearLayout) getChildAt(0)).getChildAt(i);
        if (button.isSelected())
            return button;
    }
    throw new IllegalStateException("no button selected");
}

(The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas: Dead Programs Tell No Lies.)
super.onTouchEvent(event);
button.setSelected(true);

Are you sure that you need setSelected(true) here? It seems that it's already selected before the super call (the for loop returns a selected button) but super.onTouchEvent() might unselect it. If super doesn't change this state you could remove the button.setSelected call.


What you are doing is very basic, and the question really belongs on stackoverflow.com, but it has probably already been answered there, and therefore would be marked as a duplicate.

As I mentioned in the comment, this can be done using simple subtraction of characters when you include ctype.h>, you don't need a switch statement or anything that complcated. The example below should execute faster than the version with the switch statement, and it is a lot less code.

#include <ctype.h>

int getColRow(char input)
{
    int val = 0;
    unsigned char testValue = (unsigned char) input;

    if (isdigit(testValue))
    {
        return testValue - '0';
    }
    else if (isalpha(testValue))
    {
        testValue = tolower(testValue);
        return testValue - 'a';
    }

    fprintf(stderr, "Invalid character %c in getColRow(char input)\n", input);
    return val;
}

Most of the functions / macros in ctype.h take unsigned integers, and it is safer to use unsigned values. The unsigned char should automatically be promoted to an unsigned integer.


Wrapper that accepts both scalar and collection

I guess you could use inheritance if you really need that extra property:

public class ResourceCollection<TEntity> : Resource<ICollection<TEntity>>
{
    public ResourceCollection(ICollection<TEntity> data) : base(data)
    {
        //modify metadata if needed
    }

    public int Count => Data.Count;
}

While technically this is still two classes, you can now cast your collections to Resource<T> and process them in generic manner with your other resources.


Block same instance of a program for running again

Three calls to memcpy seem to emulate sprintf(program_path, "%s/%s", dir, buffer);
my_strtok is a not very clean substitute for dirname.
The lock file is always created in the home directory, and only accounts for the base name of the executable. It means that /usr/foo would block /opt/foo.
The locker does not account for the links (again, it only cares about the base name of the executable). Different names may refer to the physically same file; invocations via links would not lock each other out.
A callback registered with atexit is only guaranteed to be called if the program exits normally. If the program is terminated by the signal, the lock file would not be removed.


This is a good shell script. You're checking for the existence of directories and files before taking any action and using set -eu and set -o pipefail.

In no particular order, here's what comes to mind.

1) In my opinion, the logic is getting slightly too complex for a shell script. I think you'd be better off in the long run with Python / Perl / Ruby.

2) reading from stdin and processing input from stdin in a loop.

See Stéphane Chazelas' answer to this question.

https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice

If you're going to do it anyway, you should probably to use IFS= read -r dockerfilepath.

3) name="$(basename $(readlink -f "$dockerfilepath"))" should have quotations around $(readlink ...), i.e.

name="$(basename "$(readlink -f "$dockerfilepath")")".

I don't think quotes around the whole expression are necessary in this case, but it's probably better to keep them there for peace of mind.

also readlink -f is not portable.

I'm also not sure why you're using it. Are you expecting lots of symlinks in your environment?

4) ! docker images | grep "$name"

You can use grep -q -F -- "$name" if you don't need the output (and just want the exit status) and want to treat "$name" as a fixed string.

I think there are a few other places where you're using grep with $name. Always use -F -- unless you want the regex behavior.

5) cp "$dockerfilepath"/run* "$outdir/run-$name"

This is actually fine from a whitespace perspective. (http://mywiki.wooledge.org/glob)

but you may want to set nullglob or failglob just to be safe.

Also should just check for the existence of the "$outdir/run-$name" directory earlier so that the operation fails before we attempt to build the container.

I'm not sure what it means if the directory doesn't exist, but a simple

[ -d "$outdir/run-$name" ] immediately after computing name would be useful.

6) At the beginning test for the existence of "$outdir"

outdir is just like $1 except it hasa default value of out. You can move the test for the existence of ${1-} until after outdir is set.

7) since you're using sort(1), set LC_ALL=C; export LC_ALL. Also, set LC_COLLATE=C; export LC_COLLATE for good measure.

8) If you aren't going to go the portable route, you can use [[ .. ]] instead of [ .. ] for tests.

9) use printf over echo

More explanation here, basically echo does weird things with backslashes. This isn't a huge deal since you're only using echo for diagnostic information, except in $(echo "$images" | wc -w) which should be changed to $(printf "%s" "$images" | wc -w).

https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo

Here's one possible script with the changes incorporated. I changed the logic somewhat so it now says Reading next dockerfile at the very beginning and uses continue to skip the current iteration rather than having multiple levels of if-else in the main loop.

#!/bin/bash

# Script to build and save specific docker containers to the specified directory with the paths to the dockerfile directory arriving on the standard input

set -eu
set -o pipefail

shopt -s failglob

LC_ALL=C; export LC_ALL
LC_COLLATE=C; export LC_COLLATE

outdir="${1-out}"
timestamp=$(date '+%Y-%m-%dT%H-%M%Z')

if [[ ! -d $outdir ]]; then
    echo "Correct invocation is: $(basename "$0") _out-directory_ <_dockerfile-directory-paths_" >&2
    exit 1
fi

diag() {
    >&2 printf '%s\n' "$1"
}

diag "Reading dockerfile directories from std input.  Building can take a long time..."

while IFS= read -r dockerfilepath; do

    diag "Reading next dockerfile..."

    # Filter out empty input
    if [[ -z "$dockerfilepath" ]]; then
        diag "skipping empty path"
        continue
    fi

    # Process the path name
    name="$(basename "$(readlink -f "$dockerfilepath")")"
    outpath="$outdir/run-$name"

    # Check that image does not already exist
    if docker images | grep -q -F -- "$name"; then
        diag "A $name image already exists; remove it to build it again"
        continue
    fi

    # create output directory if it doesn't exist
    if [[ ! -d $outpath ]]; then
       mkdir -p "$outpath"
    fi

    # Get docker to build the image
    diag "Building $name:$timestamp from $dockerfilepath"
    docker build -t "$name":"$timestamp" "$dockerfilepath"

    # Output the image (but only one if there are duplicates with different tags)
    image="$(docker images | grep -F -- "$name" | awk '{print $3}' | sort -u)"
    if [[ "$(printf "%s" "$image" | wc -w)" -ne 1 ]]; then
        diag "Multiple images detected for $name; aborting"
        exit 1
    fi
    diag "Saving $name:$timestamp.save.xz from $image"
    docker save "$image" | xz -z9 > "$outdir/$name:$timestamp.save.xz"

    # output the image specific run script, enforcing a naming convention
    cp "$dockerfilepath"/run* "$outpath"
    diag "Use $outpath to use the image"
done


Here are some things that may help you improve your program.
Use consistent formatting
The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.
Provide complete code to reviewers
This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  Another good technique is to include test code showing how your code is intended to be used.
Use const where practical
The s string is set and never altered, so it could be const or even better in this case, static const.
Consider re-entrancy
In an embedded system, there are often many things happening at once.  The usual case is that many events are event-driven and so the order in which parts of code are executed is uncertain.  For that reason, you should be wary about using non-reentrant calls such as strtok.  Also, we don't have the complete context, but it may be worth making a copy of a buffered line of data so that subesequent data the comes in does not overwrite a line as it is being parsed.
Consider passing a length
This code makes the tacit assumption that the passed array is a '\0'-terminated text string.  If you can guarantee that is always the case, then the code is fine as it is, but a more robust system might be to explicitly pass both a pointer and a length.
Understand system variations
It is implementation-defined whether char is signed or unsigned.  If it happens to be signed on your platform, you will get warnings about sign mismatches for parameters passed to strtok and strcpy.  If you system uses unsigned chars by default, you will get no such warning, but you should be aware that this is at least a portability concern.
Simplify your algorithm
This could be simpler and more maintainble in the future if it used a state machine for parsing.  For this simple grammar we have the following valid sentences:

I2C SCAN
I2C READ n
I2C WRITE n n

I am assuming the n is a numeric value, but it's not clear from the context.  Here's the corresponding state machine:

Here's one way to code that:
void parser_i2c(mychar str[20])
{
    static const mychar s[2] = " ";
    enum { start, i2c, r1, w1, w2, error, done } state = start;
    mychar *n1 = NULL;
    for (mychar *token = strtok(str, s); state != done; token = strtok(NULL, s)) {
        switch (state) {
            case start:
                if (strcmp(token, "I2C") == 0) {
                    state = i2c;
                } else {
                    state = error;
                }
                break;
            case i2c:
                if (strcmp(token, "READ") == 0) {
                    state = r1;
                } else if (strcmp(token, "WRITE") == 0) {
                    state = w1;
                } else if (strcmp(token, "SCAN") == 0) {
                    i2c_scan();
                    state = done;
                } else {
                    state = error;
                }
                break;
            case r1:
                /* check for number? */
                i2c_read(token);
                state = done;
                break;
            case w1:
                /* check for number? */
                n1 = token;
                state = w2;
                break;
            case w2:
                /* check for number? */
                i2c_write(n1, token);
                state = done;
                break;
            default:
                printf(COLOR_RED "Illegal state" COLOR_RESET);
                state = done;
        }
        if (state == error) {
            printf(COLOR_RED "Bad Command" COLOR_RESET);
            state = done;
        }
    }
}

I've use mychar as a typedef for char on my machine.  On yours, it looks like you could use unsigned char instead.
Note that now, the flow is very easy to follow and it would not be at all difficult to make an alteration to the grammar to accommodate some other command. Because the tokens are handled as they're parsed, there's no need to store any except the first parsed number which we need for i2c_write(). If it gets any more complex than this, one could use a more sophisticated parser or use a tool like flex.


How to access a servlet in Tomcat Contanier using Java

when you are sending any data to the servlet make sure it you send it via POST/GET depending on how sensitive the information is. In your case the user and password is sent through the get which is unsafe since it can be viewed by anyone.

you can add.urlConnection.setRequestMethod("POST"); Also to get the response you have to send the request first , which in your case is missing.

dataInput= new DataOutputStream(urlConnection.getOutputStream());
String content = "param1=" + URLEncoder.encode("first parameter")
         + "&param2="
         + URLEncoder.encode("the second one...");

dataInput.writeBytes(content);
dataInput.flush();
dataInput.close();


Add user to a database and perform relevant checks

MainError can be simplified as follows,

class MainError:
    def __init__(self, code, message, errorsList):
        self.resp=jsonify(dict(errorCode=code,
                        message=message,
                        errorList=[error.serialize() for error in errorsList],
                        success=False))
        self.resp.status_code = int(code)
    def get_error(self):
        return self.resp

Now an error can be returned by return MainError('400','Incorrect Input',errorsList).get_error()

A simple function can do the above thing,

def get_error(code, message, errorsList):
    resp = jsonify(dict(errorCode=code,
                            message=message,
                            errorList=[error.serialize() for error in errorsList],
                            success=False))
    resp.status_code = int(code)

    return resp

For multiple returns define an error object like error=None and use if and elif and return error if you have errors. f.e,

error = None
if email is None or password is None:
        errorsList.append(Error("email/password","Email or Password not entered"))
        error = MainError('400','Incorrect Input',errorsList).get_error()
elif len(password) > 1024:
        errorsList.append(Error("password","Password maximum length is 1024 characters"))
        error = MainError('400','Incorrect Input',errorsList).get_error()
return error if error else jsonify(data=user.serialize())


Its very much hard coded for that single domain type, SalesmanLocation. I would instead use some kind of event aggregation pattern. The domain fires off these events and the singalr hub listenes to these events.

I have made a singalr library that seamlessly forwards events to signalr. Maybe it can give you some ideas

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki

Bascily with my design you would do

private void Save(SalesmanLocationDto dto)
{
    repository.Save(dto);
    eventAggregator.Publish(new SalesmanLocationSavedEvent{ /* map data from dto */ });
}

Its completely decoupled and nor the domain or the signalr parts know about each other


I use the following sub to speed up processing:

Public Sub AppSpeed(Optional iWhat As Long = xlDown)

    Dim bDir As Boolean

    bDir = True
    If iWhat = xlUp Then bDir = False

    On Error Resume Next

    With Application
         .Calculation = IIf(bDir, xlCalculationAutomatic, xlCalculationManual)
         .ScreenUpdating = bDir
         .DisplayStatusBar = bDir
         .EnableEvents = bDir
         .DisplayPageBreaks = bDir
         .PrintCommunication = bDir
   End With
End Sub

and I call it like

AppSpeed xlUp ' at the beginning of the app

and

AppSpeed xlDown  ' az the end of processing

The inconvenience of this solution is that you can't monitor what's happening so Dim a counter like filecounter and put the following snippet somewhere in the loop e.g. after wb.SaveAs to see that something is happening

    filecounter = filecounter + 1
    If 100 * (filecounter \ 100) = filecounter Then
        AppSpeed xlDown
        Application.StatusBar = folderpath & " " & CStr(filecounter)
        DoEvents
        AppSpeed xlUp
    End If

Next advice is to reduce the number of files in one folder. The documenations do not really help in this matter. My experience is that it is worth to keep the number of files under 1000 in one folder because access time increases enormously over that. You have a flexible structure so can quickly test it by dividing the files to multiple folders.


Function that reorders the columns of a matrix

I don't have Matlab here, and Octave's unique doesn't have the same options as Matlab's, so I can't run the entire code.

So I'll just point out a few things:

isequal( A(:,p)' * round(A(:, n)'/ A(:,p)') == A(:,n)', ones(1, size(A,1)));

Can be written:

all( A(:,p).' * round(A(:,n).'/A(:,p).') == A(:,n).');

You don't need to compare it to a vector of ones, you can just check if all entries are true. Also, conventiently, if [a, b, c, d] will only evaluate to true if all elements a, b, c, d are true. So, the if statement can simply be written:

if (A(:,p).' * round(A(:,n).'/A(:,p).') == A(:,n).');

Notice that I've added a dot . in front of all the '. That's because ' is the complex conjugate transpose, not the regular one.

You have initialized A_red = [], instead of giving it a size, most likely since you don't know the size. Luckily, you do know other things. For instance the maximum possible size, and the any zero-columns can be deleted in the end.

Initialize A_red like this (select an appropriate num_rows:

A_red = zeros(size(A,1), num_rows);`

And do this in the end to remove all the zero-columns:

result = result(:, all(result));

The code can probably be written a lot faster, cleaner and smoother. I'll leave that to someone else for now. This should at least improve the code =)


Handling access to database connection both inside and outside of classes

Use the global keyword to make globals accessible from inside of methods and functions:

class KD_sql
{
    public static function get_recipes()
    {
        global $dbh; // *** ADD THIS ***

        $qry = $dbh->query('SELECT * FROM recipes');
        $get = $qry->fetchAll();
        return $get;
    }
}

http://www.php.net/manual/en/language.variables.scope.php

Should you use globals for this?  That is another topic completely.


if word in matching_words:
    matching_words[word] += 1
else:
    matching_words[word] = 1

If you're checking if a dictionary has a key before adding to it, a defaultdict may be a better option:
from collections import defaultdict

matching_words = defaultdict(int)
matching_words[word] += 1

int returns a 0 when called without arguments, and that 0 is used as a default value for the dictionary when the key doesn't exist.

fulltext = ''
for p in ps:
    fulltext += p.get_text()

This isn't very efficient. Performance of += on strings has gotten better in later versions of Python, but it's still generally slower. The typical alternative is using join:
pieces = [p.get_text() for p in ps]
fulltext = "".join(pieces)

# Or just

fulltext = "".join([p.get_text() for p in ps])

Then similarly in sort_and_format:
output_string = "".join([f"{r}\t{dict[r]}\n"] for r in ordered_keys])

In sort_and_format, you've named the parameter dict. This is suboptimal for a couple reasons:

dict is a generic name that doesn't properly describe the data.
dict is the name of a built-in class, and shadowing it makes your code more confusing, and prevents you from using the built-in.

Indicating the type can be helpful though, so I might introduce type hints here
from typing import Dict

def sort_and_format(words: Dict[str, int]) -> str:
    . . .

This says that the functions accepts a Dictionary mapping strings to ints, and returns a string

Also for sort_and_format, I've found that when you start sticking and into names, that can suggest that the function is doing too much. You may find that the code will make more sense if the sorting and formatting happen separately. That functions can handle purely formatting, and can be handed a sequence to work with instead. If that sequence is sorted, great, if not, also great. It doesn't matter for the purposes of formatting what the sort order is.


Performance testing functions for wrapping an index

Your results do seem odd, so I tried to rewrite your test and see if I can get different results.  I suspected that you might be starting and stopping the stopwatch too frequently, which can skew your results due to the loss of precision every time you start and stop.  In my code, I only start and stop the stopwatch once per type of calculation.

Using the code below, I get results more in line with what you would expect, namely that masking is the fastest, followed by plain subtraction, followed by modulo division.

Here is a typical output from one of my test runs:

Plain: 59.7033
Mod: 64.6872
Mask: 58.1923

In various runs, Plain and Mask tend to vary with respect to each other, and sometimes show very similar numbers.  Mod always tends to be slower.

And here is the code:

static void Main(string[] args)
{
    TestPerf(WrapIndex, "Plain");
    TestPerf(WrapIndexMod, "Mod");
    TestPerf(WrapIndexMask, "Mask");
}

public static void TestPerf(Func<int, int, int, int> getIndex, string label, int numRuns = 10000)
{
    int maxSize = 4096;

    Stopwatch sw = new Stopwatch();
    sw.Start();

    for (int i = 0; i < numRuns; i++)
    {
        for (int index = 0; index < maxSize; index++)
        {
            getIndex(index, 1234, maxSize);
        }
    }

    sw.Stop();
    Console.WriteLine(string.Format("{0}: {1}", label, ((double)sw.ElapsedTicks) / numRuns));
}

EDIT: Also notice that I cast ElapsedTicks to double before dividing to avoid rounding.  You should be careful to avoid rounding in your calculations because that just adds noise to your final result.

EDIT 2:

I played around with the code snippet in your pastie link and I was originally getting the same results as you, but I think I've finally gotten to the bottom of it.

What's happening is that without that Func wrapper, the jitter is able to do some serious optimizing.  I know it's the jitter and not the C# compiler, because all of the code is intact in the ildasm output.  In fact, for 2 out of your 3 methods (mod and mask), it's able to deduce that the methods aren't accomplishing anything at all (because they're doing a simple calculation, and the return value is just discarded), so it doesn't even bother calling them.

To validate that statement, simply comment out the line in WrapIndex() and return a plain 0, which is sure to get optimized out.  Run your program again and you'll see that all three methods now report the same times.  There's no way that doing a mod or a mask has the same cost as returning a constant 0, so that tells you that the code just isn't being executed.

This is another issue you have to be aware of when doing perf tests.  If your test is too simple, the optimizer will just discard all of your code.

In my test, the Func wrapper was preventing the jitter from optimizing as much, because it doesn't know which code is going to be executed, so it can't inline and then discard the code, which is why you get more reasonable numbers.

So I think the results from my code, using the Func delegate, give a more accurate reflection of the relative costs of your three index methods.


How can I simplify these checkbox onClicks?

One way to simplify this is you can use a data attribute to group them together with the check all option.
This will allow you to add as many as groups as you want while reusing the same jquery.
Also, you will want to use change and not click as click will be triggered when someone clicks on the radio even if its the same one, but change will only be triggered when a different one is selected by the user.

$(document).ready(function(){
  $(".checkall").on("change",function(){
    $("[data-group=" + $(this).data("group") + "]").prop('checked', $(this).prop('checked'));
  });

  $("input[type=checkbox]:not(.checkall)").on("change",function(){
     $("[data-group=" + $(this).data("group") + "].checkall").prop('checked', false);
  });
});

<input data-group="g1" type="checkbox" name="X" value="1">
<input data-group="g1" type="checkbox" name="X" value="2">
<input data-group="g1" type="checkbox" name="X" value="3">

<input data-group="g1" id="g1checkall" type="checkbox" class="checkall" name="X"> Check All

<input data-group="g2" type="checkbox" name="X2" value="1">
<input data-group="g2" type="checkbox" name="X2" value="2">
<input data-group="g2" type="checkbox" name="X2" value="3">

<input id="g2checkall" data-group="g2" type="checkbox" class="checkall" name="X2"> Check All


Writing a test to validate that the repo is formatted

a short test to validate that all committed files in the repo are
  formatted.

Here are some notes I made while reading your code.

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

Writing code is a process of stepwise refinement.

Define the problem with an outline of a solution.

// checkGoFmt checks that Go source files have been formatted with go fmt or gofmt.
// checkGoFmt returns a newline separated list of files
// whose formatting differs from gofmt's and any error.
func checkGoFmt(root string) (string, error) {
    // Command gofmt
    // https://golang.org/cmd/gofmt/
    // $ gofmt -help
    // usage: gofmt [flags] [path ...]
    //  -l  list files whose formatting differs from gofmt's
    // $
}

Read the documentation for the gofmt command.

Write some code to construct and run the gofmt command. The goFiles function is a stub.

func goFiles(root string) ([]string, error) {
    var files []string
    return files, nil
}

// checkGoFmt checks that Go source files have been formatted with go fmt or gofmt.
// checkGoFmt returns a newline separated list of files
// whose formatting differs from gofmt's and any error.
func checkGoFmt(root string) (string, error) {
    // Command gofmt
    // https://golang.org/cmd/gofmt/
    // $ gofmt -help
    // usage: gofmt [flags] [path ...]
    //  -l  list files whose formatting differs from gofmt's
    // $

    files, err := goFiles(root)
    if err != nil {
        return "", err
    }
    if len(files) == 0 {
        return "", nil
    }

    args := make([]string, 0, 1+len(files))
    args = append(args, "-l")
    args = append(args, files...)
    out, err := exec.Command("gofmt", args...).Output()
    return string(out), err
}

Pay attention to program structure. The specific implementation of goFiles is hidden from checkGoFmt. If the end result is not as expected, start by looking at the list of files returned from goFiles. Consider writing a test for the goFiles function. checkGoFmt can be called from a testing package function or a program main function.

The documentation for gofmt states: "Without an explicit path, it processes the standard input." To ensure that TestGoFormatting does not wait on stdin, check that at least one Go file is found. Also, if there is nothing to do then exit.

If possible, make reasonable estimates of slice capacity to minimize allocations.

Read the documentation for filepath.Walk and filepath.WalkFunc.

  func Walk

  func Walk(root string, walkFn WalkFunc) error

  Walk walks the file tree rooted at root, calling walkFn for each file
  or directory in the tree, including root. All errors that arise
  visiting files and directories are filtered by walkFn.

  type WalkFunc

  WalkFunc is the type of the function called for each file or directory
  visited by Walk. The path argument contains the argument to Walk as a
  prefix; that is, if Walk is called with "dir", which is a directory
  containing the file "a", the walk function will be called with
  argument "dir/a". The info argument is the os.FileInfo for the named
  path.

  If there was a problem walking to the file or directory named by path,
  the incoming error will describe the problem and the function can
  decide how to handle that error (and Walk will not descend into that
  directory). In the case of an error, the info argument will be nil. If
  an error is returned, processing stops. The sole exception is when the
  function returns the special value SkipDir. If the function returns
  SkipDir when invoked on a directory, Walk skips the directory's
  contents entirely. If the function returns SkipDir when invoked on a
  non-directory file, Walk skips the remaining files in the containing
  directory.

  type WalkFunc func(path string, info os.FileInfo, err error) error

Write code for the goFiles stub.

func goFiles(root string) ([]string, error) {
    var files []string

    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if info == nil {
            return nil
        }
        if !info.Mode().IsRegular() {
            return nil
        }
        if filepath.Ext(path) != ".go" {
            return nil
        }
        absPath, e := filepath.Abs(path)
        if e != nil {
            return e
        }
        files = append(files, absPath)
        return nil
    })
    if err != nil {
        return nil, err
    }

    return files, nil
}

If an error is passed to the WalkFunc don't ignore it.

Don't panic if the info argument is nil.

The documentation for gofmt states: "Given a file, it operates on that file; given a directory, it operates on all .go files in that directory, recursively."

Only process regular files. If the directory is processed too, the file will be duplicated. For example,

├── fmt.dir.go
│   ├── fmt.file.go

fmt.dir.go and fmt.file.go will be appended to the files list and fmt.file.go will be formatted twice, once as a member of directory fmt.dir.go and once as file fmt.file.go.

Read the documentation for the Go testing package.

Write a Go testing package function.

// TestGoFormatting checks that Go source files have been formatted.
func TestGoFormatting(t *testing.T) {
    // TODO: Set root to a variable value?
    root := "../.."
    out, err := checkGoFmt(root)
    if err != nil {
        t.Error(err)
    }
    if len(out) > 0 {
        t.Error(out)
    }
}

The Go testing package prints the test function name, TestGoFormatting, on failure, There is no need for redundant logging of a test title. TestGoFormatting is more meaningful than TestFormatting. The testing package T.Error method merges the T.Log and T.Fail methods. Eliminate redundant argument error.Error() methods.

Obtaining a value for root requires more thought.

We can also write a program main function.

func main() {
    exit := 0
    // TODO: Set root to a variable value?
    root := "../.."
    out, err := checkGoFmt(root)
    if err != nil {
        exit = 2
        fmt.Fprintln(os.Stderr, err)
    }
    if len(out) > 0 {
        exit = 2
        fmt.Fprintln(os.Stderr, out)
    }
    os.Exit(exit)
}

And so on.

In Go, don't ignore errors.

Here is the complete code for a first draft of TestGoFormatting, a testing function:

package pack

import (
    "os"
    "os/exec"
    "path/filepath"
    "testing"
)

func goFiles(root string) ([]string, error) {
    var files []string

    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if info == nil {
            return nil
        }
        if !info.Mode().IsRegular() {
            return nil
        }
        if filepath.Ext(path) != ".go" {
            return nil
        }
        absPath, e := filepath.Abs(path)
        if e != nil {
            return e
        }
        files = append(files, absPath)
        return nil
    })
    if err != nil {
        return nil, err
    }

    return files, nil
}

// checkGoFmt checks that Go source files have been formatted with go fmt or gofmt.
// checkGoFmt returns a newline separated list of files
// whose formatting differs from gofmt's and any error.
func checkGoFmt(root string) (string, error) {
    // Command gofmt
    // https://golang.org/cmd/gofmt/
    // $ gofmt -help
    // usage: gofmt [flags] [path ...]
    //  -l  list files whose formatting differs from gofmt's
    // $

    files, err := goFiles(root)
    if err != nil {
        return "", err
    }
    if len(files) == 0 {
        return "", nil
    }

    args := make([]string, 0, 1+len(files))
    args = append(args, "-l")
    args = append(args, files...)
    out, err := exec.Command("gofmt", args...).Output()
    return string(out), err
}

// TestGoFormatting checks that Go source files have been formatted.
func TestGoFormatting(t *testing.T) {
    // TODO: Set root to a variable value?
    root := "../.."
    out, err := checkGoFmt(root)
    if err != nil {
        t.Error(err)
    }
    if len(out) > 0 {
        t.Error(out)
    }
}


Assume you are referring to speed, not conciseness when asking about efficiency. In which case reducing the amount of loops will not necessarily improve performance.

"type": next((data_type["type"] for data_type in DATA_TYPES if data_type["name"] == data_type_attr_name))

This can be improved so that you are not needing to go over DATA_TYPES looking for a matching name to data_type_attr_name every iteration. Instead you can make a reverse lookup dictionary once before the loop where data_type["name"] is the key.

Whenever you are searching through a list often, it can be very beneficial to create a dictionary.


Remove odd valued nodes from linked list

It seems you can simplify this by quite a lot.
I added explanation of the algorithm inside the code,
that way it might be easier to follow:

void rem_odd(struct Node** head)
{
    struct Node* curr = *head;
    struct Node* l_even;

    // iterate until the first even element, or the end
    while (curr != NULL && curr->data % 2 != 0)
    {
        curr = curr->next;
    }

    // the new head is the first even element, or the end
    *head = curr;

    // if no more elements, we're done here
    if (curr == NULL) {
        return;
    }

    // the last even element is the current element, naturally
    l_even = curr;

    // we know the current element is even, and not null, so moving on
    curr = curr->next;

    // iterate until the end
    while (curr != NULL)
    {
        // is the current element even?
        if (curr->data % 2 == 0) {

            // -> yes, it's even, so the last even element should point to it
            l_even->next = curr;

            // ... and this is the new last-even-element now
            l_even = curr;
        }
        curr = curr->next;
    }

    // last even might still point to an odd valued element, so NULL it out
    l_even->next = NULL;
}

Notice that I added spaces around the operators.
For example this is extremely hard to read:

while(curr!=NULL&&curr->data%2!=0)


Possible solution: reduce your input to required precision. Returned result construction also reads cleaner with this approach:

def as_size(s)
  units = %W(B KiB MiB GiB TiB)

  size, unit = units.reduce(s.to_f) do |(fsize, _), utype|
    fsize > 512 ? [fsize / 1024, utype] : (break [fsize, utype])
  end

  "#{size > 9 || size.modulo(1) < 0.1 ? '%d' : '%.1f'} %s" % [size, unit]
end


If I were to rewrite your code, I'd do it like this:

Option Explicit

Step one, always be explicit. Nobody likes seeing a variable being used that they never saw declared anywhere.

Public Sub ImportTextFile()

Step two, name the procedure after what it's doing, and make it do that.

    Dim filePath As String
    filePath = "filepath.txt"

    Dim fileNumber As Long
    fileNumber = FreeFile

FreeFile will give you a file number that's ok to use. Hard-coding a file number is never a good idea, even if you're only using one file.

    Dim inputData As String
    Dim lineCount As Long

    On Error Goto ErrHandler
    ToggleWaitMode True, "Importing text file..."

On Error Goto ErrHandler means if anything wrong happens (file not found, more data in the file than can fit on the worksheet, or whatever), we'll skip straight to an error-handling subroutine where we'll take good care of closing our file and toggle "wait mode" back off.

    Open filePath For Input As #fileNumber

        Do Until EOF(fileNumber)

            Line Input #fileNumber, inputData
            lineCount = lineCount + 1

            WriteLineContentToActiveSheet inputData, lineCount

        Loop

    Close #fileNumber

So the ImportTextFile procedure does nothing but reading the file's content. WriteLineContentToActiveSheet will do the worksheet-writing part.

ErrHandler:
    ToggleWaitMode

    If Err.Number <> 0 Then
        Close 'closes any file left open
        MsgBox Err.Description
        Err.Clear
    End If

End sub

The code under this label will execute even if no error occurred, this is why we're checking for Err.Number being other than 0. But regardless of whether there's an error or not, we always want to ToggleWaitMode.

Private Sub ToggleWaitMode(Optional ByVal wait As Boolean = False, Optional ByVal statusBarMessage As String = vbNullString)

    Application.ScreenUpdating = True 'ensure status message gets displayed
    Application.StatusBar = statusBarMessage
    Application.Cursor = IIf(wait, xlWait, xlDefault)
    Application.ScreenUpdating = Not wait
    Application.EnableEvents = Not Wait

End Sub

This small procedure takes two optional parameters. If none are specified, "wait mode" is toggled off - this means the status bar message is reset, the mouse cursor goes back to default, Excel resumes redrawing the screen and fires events whenever something happens. "Wait mode" is just all that reversed :)

Private Sub WriteLineContentToActiveSheet(ByVal inputData As String, ByVal targetRow As Long)
    Dim lineFields() As String
    lineFields = Split(inputData, "|")

    Dim fieldCount As Integer
    fieldCount = UBound(lineFields)

    Dim currentField As Integer
    Dim targetColumn As Integer
    Dim fieldValue As String

    With ActiveSheet
        For currentField = 0 To fieldCount

            fieldValue = lineFields(currentField)
            targetColumn = fieldCount - currentField + 1

            .Cells(targetRow, targetColumn).Value = fieldValue

        Next
    End With

End Sub

This small procedure takes a single line of data, splits it into as many fields as it has, and writes each field value into a cell of the active sheet. Using UBound we're no longer tied to a specific number of fields - if the file format changes, the procedure should still work. And if it doesn't, the procedure that called it will cleanly handle the error for us.

Local variables currentField, targetColumn and fieldValue are not necessary - they could all be inlined, but having them makes code easier to follow and allows you to place breakpoints to validate their values as you run the code line-by-line with F8 when you're debugging.

Couple observations:

You need to indent your code. Indentation makes it much easier to read, for yourself and anyone looking at it. Give that Tab button some lovin'!

Procedures define a scope, anything under it should be indented.
Within a scope, code blocks should also be indented - this includes If blocks, With blocks and any code that runs inside a loop.

OpenTextFile is a bad name for a procedure that actually imports a text file.
Be consistent with your naming: chose a convention, and stick to it.
You're reading a file, that's an I/O operation and by Murphy's Law this is going to fail one day or another. Make sure your code properly handles any error that could happen while processing the file, you don't want to leave a file handle opened by mistake.
Importing a 20mb text file will take a while, even with screen updating turned off. Tell your user you're working, give'em a hourglass cursor, and you can even update the statusbar message every couple thousand lines read/written (just call ToggleWaitMode True with a new status message) so they know it's not frozen.


Rewriting WPF GridViewColumn alignment in a less verbose way

XAML is XAML - I'm not sure what the meaning of "syntetic" is in this context, but the only thing I can see that could improve, is the closing tags for <Binding> - the empty elements can be collapsed:

<MultiBinding StringFormat="{}{0:N} {1}">
  <Binding Path="Income" />
  <Binding ElementName="UserControl" Path="DataContext.Pinco" />
</MultiBinding>

There aren't 20 different ways of specifying the horizontal alignment of a TextBlock:

<TextBlock HorizontalAlignment="Right">

I don't see anything wrong with this.

Actually the indentation could use more spaces, too - but that's cosmetic (and probably just a copy/paste glitch with the tabs):

<GridViewColumn Header="trial" Width="110">
    <GridViewColumn.CellTemplate>
        <DataTemplate>

            <TextBlock HorizontalAlignment="Right">
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0:N} {1}">
                        <Binding Path="Income" />
                        <Binding ElementName="UserControl" Path="DataContext.Pinco" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>

        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

I like using vertical whitespace to separate things - it makes the markup easier to read, and maintain.

EDIT: Considering that there would be 20x such markup, with the only thing changing being the <Binding Path="Income" /> part, as @GeorgeHowarth commented you can look into making the DataTemplate a StaticResource, like this.


Enumerate all items to find those that match a complex condition

You can't reduce code you wrote because each condition has to be checked and you're already using variables to clarify your intent. What you can do is to move all that code out of your loop, reading that code in future you won't need to scroll over all those ifs:

foreach ($workingTimes as $hour => $minutes) {
    foreach ($minutes as $shift) {
        if (!canBookRoom($hour, $shift))
            continue;

        $formatted = sprintf("%s-%s", $hour, $shift);
        $timetable[$formatted] = 'Bookable';
    }
}

...

function canBookRoom($hour, $minute) {
    if (!isThereAvailableRoom($hour, $minute))
        return false;

    return areThereAvailableResources($hour, $minute);
}

function isThereAvailableRoom($hour, $minute) {
    if (!$this->isBookable($hours, $shift))
        return false;

    return $this->checkRooms($hour, $shift);
}

function areThereAvailableResources($hour, $minute) {
    if (!$this->checkEmployees($hour, $shift))
        return false;

    return $this->checkResources($hour, $shift);
}

What has been done

Reading your loop you're not really interested in all details about availability, there you just need to know if it's bookable or not. Pulling out a function for that makes your code easier to parse and your intent explicit. If/when you'll be interested in that details you may browse to canBookRoom() function.
canBookRoom() function itself explicitly split booking availability in two logic domains: room availability and resources availability. Each one has its own function.
areThereAvailableResources() unifies resources, from a higher level point of view both humans and materials are resources you can count.
Your local variables has been dropped, if each function name is self descriptive then you don't need them.

What should be done

Your loop is still doing many things: it searches for a bookable room inside a time range and if it finds an available time then it marks that range as bookable.

At least something should be done in a separate function. Here you have two options for your hypothetical buildTimetableForAllBookableRooms() function: refactor out function to fill timetable or add one function findAllBookableRooms() which returns all available time frames when there is a bookable room plus another function formatTimetableForBookableRoom() to perform booking, called in a foreach loop.

function findAllBookableRooms() {
    foreach ($workingTimes as $hour => $minutes) {
        foreach ($minutes as $shift) {
            if (canBookRoom($hour, $shift))
                yield sprintf("%s-%s", $hour, $shift);
        }
    }
}

function formatTimetableForBookableRoom() {
    foreach (findAllBookableRooms() as $bookableTimeFrame) {
        $timetable[$bookableTimeFrame] = 'Bookable';
    }
}

Here I used generator syntax but you may also return an array. Note that findAllBookableRooms() may also return unformatted value using yeld array($hour, $shift);.

Wherever it will be your $formatted variable has a poor name. It should describe what it contains otherwise you may simply drop it).
Another thing to do (but I don't have enough context) is to rename isBookable() and checkRooms() functions, from name alone it's not clear what they're actually doing and why/how they're different. Note I renamed isBookabe() to isBookable(), I suppose it's just a typo.


It's a fine solution. I have a few minor comments.

It's easy to overlook that pathSum doesn't clear the content of paths, which will affect the returned value from subsequent calls, which is likely to be unexpected by callers. In this online puzzle it doesn't seem to matter, but I think it's better to avoid any possible confusion.
The clone with the cast is ugly. The .clone() method except on arrays is a bit controversial, with questionable benefits if any. I suggest to avoid it. You can replace it with a nice clean paths.add(new ArrayList<>(path))
The signature of traverse would be better to use List instead of ArrayList.
I would use an early return in traverse, to have less indented code.


Binary Search Tree implementation in Python 3

A few quick points that came to my mind when looking at your code:

Documentation

Your code has no documentation whatsoever. Python has so called documentation strings, which are basically """triple quoted text blocks""" immediately following def whatever(...). Example:

def print_tree(self):
    """Print the content of the tree

    This method performs an in-order traversal of the tree
    """
    # ... your code here

Since your question title indicates that you're working with Python 3, also consider using type hints to document your code.

Naming

There is the infamous Style Guide for Python Code (aka PEP 8) which recommends to use lower_case_with_underscores for variable names and (member) functions. You do this for print_tree, but use camelCase for the other member functions.

Searching the tree

Your getSearchValue function is a little bit awkward in that it always returns None. Although your code promises to "get" the value, you instead print it to the console (together with the string "True") and return the return value of print which is None (aka no return value in that case). Your function also only returns something (other than the implicit None) if the value was found. In my opinion something like

def has_value(self, data):
    """Return True or False indicating whether the value is in the BST"""
    if data == self.data:
        return True
    if data < self.data:
        if self.left is not None:
            return self.left.has_value(data)
    if data > self.data:
        if self.right is not None:
            return self.right.has_value(data)
    return False

would be a more appropriate approach. As you can see, this function returns an appropriate bool value to signal the result.

Another minor tweak: this implementation uses if ... is not None: to explicitly check for None as signaling value. Since None is a singleton in Python, you should always use is (not) to check for equality.

Unnecessary parentheses

The parentheses around the condition in while(current.left is not None): are not needed. while works the same way as if in that regard. They are sometimes used for longer conditions that span multiple lines, since Python does implicit line joining in that case.

I'm also not fully convinced about your delValue function, but unfortunately I'm a little bit short on time at the moment.


Animating one of three boxes based on a form value

This completely replaces your switch statement by using inline if statements conditional operator:

$box.hide().delay(val < 50 ? 300 : 0);
var s = val > 50 ? 'XN' : (val < 50 ? 'VN' : 'PN');
animations.animateBox($box.html('you have chosen ' + s));

the first line could be replaced by these two arguably more readable lines that omit the call to delay() function when not applicable:

$box.hide();
val < 50 && $box.delay(300);

Since @GregGuida pointed out that this code is less readable I suppose I can make it more readable by better formatting it. And I'll use the suggestion of replacing the first line with two of them:

$box.hide();

// only delay animation when value < 50
val < 50 && $box.delay(300);

var s = val > 50 ? 'XN' :
       (val < 50 ? 'VN' :
                   'PN');
// set HTML
animations.animateBox($box.html('you have chosen ' + s));

Same code but visually less chaotic (even without comments it would look less chaotic) and much much more readable. At least much more readable than OP's original code. That I'm sure of. Readability is of course an argumentative disposition. But I'll leave that to others.


++ returns a new collection, you need ++= here
Your attempt looks fine to me. Maybe you should additionally implement the Traversable trait or so, and delegate the calls to elements in order to make things a little bit more convenient.

[Edit]

class CompositeObservation(obss: Observation*)
     extends Observation with Traversable[Observation] {

  val elements = new MutableList[Observation]()

  elements ++= obss

  def hasElement(o: Observation): Boolean = elements.contains(o);

  def foreach[U](f: (Observation) => U): Unit = elements.foreach(f)
}


Your code looks pretty good. There are a few improvements that I can see.

Firstly, when following PEP8 (the official Python style convention guide) we want to avoid using multiple statements per line:

# Avoid this style.
if i == len(digits): return bits

# Use this style.
if i == len(digits):
    return bits

Because of your use of multiple statements per line, your code looks like it has an extraneous amount of blank lines (another no-no as defined by PEP8). Fixing the statements will also help mitigate the feeling that your code has too many blank lines.

Secondly, I typically try to avoid declaring functions inside of functions (unless I'm doing something REALLY funky: think async plus decorators plus magic). As many of the answers say here, functions inside functions are useful for creating closures and decorators, both of which are not really needed here in your implementation.

Thirdly, in your for loop within encode() you unpack the tuple returned from zip then take those unpacked elements and put them into a list to extend bits:

# Unpack into `b` and `w`
for b, w in zip(byte(i), byte(i+1)):
    # 'Re-pack' back into list
    bits.extend([b, w])

Instead, you can just take the tuple itself and pass that to extend():

for tup in zip(byte(i), byte(i+1)):
    bits.extend(tup)

Finally, your variable names are a tad ambiguous. They can be guessed (if you know ITF format) but we don't want to necessarily assume others know ITF format or require them to have guess what each of our variables are for.


I don't see any problems with that. It's similar to this answer on SO.

Just a couple minor things:

You don't need args in the empty log function
You should make the entire function anonymous and execute it immediately (as it's being done in the answer I linked to); I don't think there's any usecase for calling it otherwise
Don't forget var in front of the i variable, otherwise it becomes global


I do not think you can do something to reduce Complexity in any traditional way. You have to traverse all array elements in order to find the row with the max element,so m x n iterations will give you O(m+n) Complexity.


Calculate the centroid of a collection of complex numbers

Taking all of the suggestions from the other reviews, I think it's quite improved so I wanted to thank the reviewers and show the final version:
#include <iostream>
#include <complex>
#include <vector>
#include <numeric>
#include <concepts>
#include <ranges>
#include <array>
#include <iterator>

template<typename T>
concept ComplexOrFloat = std::floating_point<T>
    || std::floating_point<typename T::value_type>;

template<typename R>
requires std::ranges::range<R>
    && ComplexOrFloat<std::ranges::range_value_t<R>>
constexpr std::ranges::range_value_t<R> average(R range) {
    if (std::ranges::size(range) == 0)
        throw std::domain_error("Cannot take average of zero-length range");
    using T = std::ranges::range_value_t<R>;
    return std::accumulate(std::ranges::begin(range), std::ranges::end(range), T{0})
        / (T)(std::ranges::size(range));
}

int main() {
    using namespace std::complex_literals;
    constexpr std::array<std::complex<double>,3> points{{ {4,5}, {30,6}, {20,25} }};
    std::cout << average(std::views::all(points)) << "\n";

    constexpr std::array<std::complex<double>,3> points2{
        {  24.0 + 7.0i, 22.0 + 9.0i, 8.0 + 20.0i }
    };
    std::cout << average(std::views::all(points2)) << "\n";

    constexpr double numbers[]{1, -2, 3, 7, -8};
    std::cout << average(std::views::all(numbers)) << "\n";

    const std::vector<float> numbers2{-7, -2, 3, 7, -8};
    std::cout << average(std::views::all(numbers2)) << "\n";

    const std::vector<float> mt{};
    try {
        std::cout << average(std::views::all(mt)) << "\n";
    } catch (std::domain_error& err) {
        std::cerr << "ERROR: " << err.what() << "\n";
    }

#if 0
    int intnumbers[]{1, -2, 3, 7, -8};
    // won't compile because an `int` is not floating point or complex floating point
    std::cout << average(std::views::all(intnumbers)) << "\n";
#endif
}

I'm using C++20 concepts to avoid trying to take an average of a range of ints and returning an int.


A part of code in auth::login() of method you should move to other class, for example 'db'. Because you class auth has too much responsibility. For example if you want to have dynamic define fields in class auth:

Db class:

class db {
    public function getItem($table, $fields = '*', $conditions = array()) {
        // you code ...
        return $row;
    }
}

Your model:

class auth {
    private $table = 'users';
    private $fields = 'u_login, u_email, u_id_level';
    private $fieldLogin = 'u_login';
    private $fieldPassword = 'u_password';

    public function setTable($value) { $this->table = $value; }
    public function setFields($value) { $this->fields = $value; }
    public function setFieldLogin($value) { $this->fieldLogin = $value; }
    public function setFieldPassword($value) { $this->fieldPassword = $value; }

    public function login() {
        $db = new db();
        return $db->getItem($this->table, $this->fields, array(
            $this->fieldLogin => $this->login,
            $this->fieldPassword => $this->password
        ));
    }
}

This code is more elastic and simpler will be change it.


Custom ListAdapter with ViewHolder Pattern

Here is a complex example for your case:

  List Adapter with ViewHolder Pattern

Note:

Never use a parameter as a variable (parameters shouldn't be modified!)
I like to use an underscore at the beginning of global fields (variables, objects) names to better show their scope.
You should make a class name without any special characters and beginning with an uppercase letter.
Try to get context from the closest possible parameter (as in my example from the parent of the getView() method).
The class constructor is defined without a return type (with the same name as the class name and any parameter if you desire)!
For later data changes in the adapter, you can define a method to add items to the list (as an example).


Is there any reason why getPrevious resorts to using indexOf? As far as I can tell, it can only cause problems.

For instance:

var array = [1, 2, 3];
var iterator = cyclicIterator(array);

iterator.getPrevious();

Since current is declared but hasn't been assigned a value, this will call  arr.indexOf(undefined) and then proceed to subtract 1 from that. I doubt that's going to work out.

Alternatively, I might do this:

var array = [1, 2, 3];
var iterator = cyclicIterator(array);
iterator.getNext(); // current is now 1
array[0] = 2;       // change the first element in the array
iterator.getPrevious();

Now, getPrevious will call arr.indexOf(1) and get -1. And it will then subtract 1 from that. Again, I doubt it'll work out.

I'd also wonder why there's no getCurrent function. In fact that's what getNext does. It for some reason returns the current index, only incrementing the index afterwards. Meanwhile getPrevious decrements the index before returning anything.

You also store the length of the array when you receive it, which could lead to some weird stuff if the array is later modified.

For instance:

var array = [1, 2, 3];
var iterator = cyclicIterator(array);
iterator.getNext(); // index is now 1
array.splice(3);    // clear the array
iterator.getNext();

That last call will calculate 2 % 3 which is, well, 2. But that index doesn't exist anymore.

You could simply skip caching the length, but that could still get weird. getNext would start skipping places when "looping around", if the array's been truncated after the iterator was created.

var array = [1, 2, 3];
var iterator = cyclicIterator(array);
iterator.getNext(); // index is now 1
iterator.getNext(); // index is now 2
array.pop();        // remove one item from the array
iterator.getNext();

With no caching of the length, the last call will calculate (2 + 1) % 2 which is 1. But that'll skip index 0.

So I'd simply copy the array, to make sure there's always something to work with.

I'd do this instead:

var cyclicIterator = function (array) {
    var index = 0;
    var copy = array.slice(0);

    return {
        getCurrent: function () {
            return copy[index];
        },

        getNext: function () {
            index = ++index % copy.length;
            return this.getCurrent();
        },

        getPrevious: function () {
            if(--index < 0) {
              index += copy.length;
            }
            return this.getCurrent();
        }
    };
};