Changing desktop background to the next available one

Use while to iterate over directory elements and skip reading them all at once into array,

opendir my $WALLSDIR, '/home/chummer/pictures/walls';
while (my $file = readdir($WALLSDIR)) {
    next if $file eq '.' or $file eq '..';

    # ..
}

Since you're not checking if open() or opendir() calls were successful at all, put

use autodie;

at beginning of your script, and exceptions with description will be thrown when some of these calls fails.

Stylistic remark, my @fehbg = (); is same as just my @fehbg;

Use lexical file-handles together with three argument open (also lexical dir-handle for opendir),

open my $FEHFH, '<', '/home/chummer/.fehbg';

Again stylistic remark,

for my $i (0 .. $#files)

is a more readable/simpler equivalent of,

for (my $i = 0; $i <= $#files; ++$i)

Then foreach($files[$i+1]){ s/\s+/\\ /g; } is longer and less performant version of $files[$i+1] =~ s/\s+/\\ /g;


Extracting length-3 subsequences from a list

In any case, the minimum time complexity for a list of length \$n\$ would be $$\mathrm{nCr}(n, 3) = \frac{n!}{3!\ (n-3)!} = \frac{1}{6} n(n - 1)(n - 2)$$ because that is the number of results to expect.  That is \$O(n^3)\$.

  Explanation of the combination formula:

  Let's ignore the i < j < k requirement for now.  How many ways are there to pick one element?  (There are \$n\$ ways.)  How many ways are there to pick the next element from the remaining \$n-1\$ elements?  (For each of the \$n\$ first picks, there are \$n-1\$ second picks.)  How many choices are there for the third element?  (There are \$n-2\$.)  That means that there are \$n(n-1)(n-2)\$ permutations when picking 3 elements from a list of \$n\$, also written as \$\frac{n!}{(n-3)!}\$.

  Now, let's consider the ordering.  For any collection of 3 items, how many possible sequences exist?  There are 3 choices for the first item, 2 choices for the second item, and 1 obligatory choice for the third.  That's \$3!=3\cdot2\cdot1=6\$ orderings.  So, out of all the \$n(n-1)(n-2)\$ lists of of \$i, j, k\$, only \$\frac{1}{6}\$ of the them will have \$i, j, k\$ in ascending order.

What you can do, though, is eliminate the conditional, so that every iteration succeeds in producing a result.  (Your if i < j < k check succeeds less than \$\frac{1}{6}\$ of the time.)  I would also change print to yield for greater flexibility.

def subsequence_triplets(lst):
    end = len(lst)
    for i in range(0, end - 2):
        for j in range(i + 1, end - 1):
            for k in range(j + 1, end):
                yield lst[i], lst[j], lst[k]

for a, b, c in subsequence_triplets([6, 3, 88, 4]):
    print a, b, c


Optimize a Sql subquery containing multiple inner joins and aggregate functions

I see that in your question you said:

  "I am unable to move the subquery out to a temporary table as temporary tables are simply not supported within the programming language used by my application."

But, have you considered calling a stored procedure instead? Is this even an option, considering the limitations with the programming language?

If this is a viable option, you could simply have the results of your subquery inserted into a temp table transparently & encapsulate all the logic in the stored procedure.

Edit

I got to thinking about this some more, and perhaps the columns that you're using in your JOIN condition are of different collations. While this will usually result in a specific error message, there may be some implicit collation coversion occurring instead (see: MSDN: Collation Precedence (Transact-SQL)) between the sub-query & the data being joined.

Here are a few links about collation that might be useful to you:

Difference between collation SQL_Latin1_General_CP1_CI_AS and Latin1_General_CI_AS
Collation Hell (Part 1)
SQL SERVER – Find Collation of Database and Table Column Using T-SQL
SQL SERVER – Change Collation of Database Column – T-SQL Script

Also, you may be able to trick your programming language into using a temp table with syntax like this:

SELECT *
  FROM tempdb..#MyTempTable

Just keep in mind that sometimes the temp database has a different collation then the data you're working with too, in which case you'll need to explicitly convert the data to/from each collation.


Some couple nits.

You function read_line does not what it suggests. It reads a file line by line. So you should find an appropriate name.
Your choice of uint_fast8_t/uint_fast16_t is interesting given that your example csv table hold some larger values. Have you measured the impact vs unsigned int or std::size_t. Be aware that modern cpu can read multiple elements at once so you choice might actually have negative impact.
Every line you clear numbers and build it up again. It will be beneficial to just initialize it once via resize and then just overwrite the old value. That way you can omit the unnecessary clear
Getline takes a third argument which is the delemiter. Also getline stops at newline and end of file so you dont need all that error checking Given that you now the number of entries per line you can simply loop and accumulate

while (infile.good()) {
    for (auto&& elem : numbers) {
        std::getline(infile, buffer, ",");
        elem = 0;
        for (auto&& digit : buffer) {
            elem *= 10;
            elem += (digit - '0');
        }
    }
    callback(numbers);
}

If you want to be sure you can check getline and return if its bad.

    while (infile.good()) {
        for (auto&& elem : numbers) {
            if (!std::getline(infile, buffer, ",")) {
                return;
            }
            elem = 0;
            for (auto&& digit : buffer) {
                elem *= 10;
                elem += (digit - '0');
            }
        }
        callback(numbers);
    }


You do "the same" for all four choices - time to abstract!

import java.util.Scanner;    //imports scanners

public class Calc {

    enum Op {

        ADD("a", "add", "added to"),
        SUB("s", "subtract", "subtracted by"),
        MUL("m", "multiply", "multiplied by"),
        DIV("d", "divide", "divided by");
        public String key;
        public String command;
        public String result;

        Op(String key, String command, String result) {
            this.key = key;
            this.command = command;
            this.result = result;
        }

        public int eval(int x, int y) {
            switch (this) {
                case ADD:
                    return x + y;
                case SUB:
                    return x - y;
                case MUL:
                    return x * y;
                case DIV:
                    return x / y;
                default:
                    throw new AssertionError();
            }
        }
    }

    public static void main(String[] args) {
        while (true) //creates loop to top
        {
            System.out.println("Hello this is my calculator!");
            System.out.println("To add, type a, to subtract, type s.");
            System.out.println("To multiply, type m, to divide, type d.");

            Scanner scan = new Scanner(System.in);    //sets up scanners
            Scanner scan1 = new Scanner(System.in);

            String action = scan.nextLine();    //tells comp. to take user input

            Op op = null;
            for (Op operation : Op.values()) {
                if (operation.key.equals(action)) {
                    op = operation;
                    break;
                }
            }

            if (op != null) {
                System.out.println("Now type in the first number you would like to " + op.command + ".");
                int x = scan.nextInt();
                System.out.println("Now type the second number.");
                int y = scan.nextInt();
                int z = op.eval(x, y);
                System.out.println(x + " " + op.result + " " + x + " equals " + z + "!");
            }

            System.out.println("Would you like to start over? (yes,no)");
            String startOver = scan1.nextLine();

            if ("no".equals(startOver)) {
                System.out.println("Bye");
                return;
            }
        }
    }
}

So all operation specific information is captured in the Op enums. If you want to add other operations like min, max, and, or, xor or mod, you don't have to introduce new if-blocks, just new enums.


Detecting Tic-Tac-Toe win: Enumerate all possibilities or use nested loops?

Without an advanced math degree, I think this is a perfectly reasonable solution.  Here's a sample implementation.  It's not that complicated.  Basically, for every WIN_CONDITION that exists (each of which is a set of coordinates on the board), we check that sequence and see if the Marks are all the same.  If so, that player has won.

I don't think that's a step in the wrong direction.  It's perfectly logical and functional.

Now if it was a more vast game like Connect Four... looping through each variation might be a better option that explicitly listing each win condition, obviously.  But since Tic-Tac-Toe has such a small set, this is fine and makes the code pretty readable.

private static Mark[][] board = new Mark[3][3];

private static final int[][][] WIN_CONDITIONS = {
    //Rows
    {{ 0, 0 }, { 0, 1 }, { 0, 2 }},
    {{ 1, 0 }, { 1, 1 }, { 1, 2 }},
    {{ 2, 0 }, { 2, 1 }, { 2, 2 }},

    //Columns
    {{ 0, 0 }, { 1, 0 }, { 2, 0 }},
    {{ 0, 1 }, { 1, 1 }, { 2, 1 }},
    {{ 0, 2 }, { 1, 2 }, { 2, 2 }},

    //Diagonals
    {{ 0, 0 }, { 1, 1 }, { 2, 2 }},
    {{ 2, 0 }, { 1, 1 }, { 0, 2 }}
};

// other stuff, like an enum for Mark (Mark.X and Mark.O) and the GameState

private GameState checkWinConditions() {

    GameState won = null;

    for(int[][] condition : WIN_CONDITIONS) {
        Mark comparator = board[condition[0][0]][condition[0][1]];
        if(comparator == null) continue;

        won = comparator.getWinState();
        for(int[] coordinate : condition) {
            if(board[coordinate[0]][coordinate[1]] != comparator) {
                won = null;
                break;
            }
        }
        if(won != null) break;
    }
    return won;
}


For these things we have java.lang.Math:

public static int min(final int a, final int b, final int c){
    return Math.min(a, Math.min(b, c));
}

Wow, look how short it is!

But it's 3 numbers today, it's 10 tomorrow.
As an alternative, how about an array?

public static int min(int... numbers){
    if (numbers.length == 0){
        throw new IllegalArgumentException("Can't determine smallest element in an empty set");
    }
    int smallest = numbers[0];
    for (int i = 1; i < numbers.length; i++){
        smallest = Math.min(smallest, numbers[i]);
    }
    return smallest;
}

I'd use the java.lang.Math solution, it's very short, and very readable.


Yes, this could use a refactoring

I think your instincts are correct.  Those nested if-elses are hard to comprehend.  And the simplest way to break it apart is by creating helper functions.

Here I go through a step-by-step refactoring.  As with any refactoring, it involves a number of judgment calls.

Assumptions

First, I need to make clear one assumption, as not everything was spelled out in the question.  I'm assuming that the data properties of the event's container and previousContainer nodes, as well as your this object's userRole and userRoleCopy nodes consist of arrays of objects of the form {role: 'some string'}.

InitialCode

We start with code that looks like this:

    drop: function(event)  {
    if (event.container.id === "delete") {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (event.previousContainer === event.container) {
        moveItemInArray(
          event.container.data,
          event.previousIndex,
          event.currentIndex
        );
      } else {
        let lastRole = Object.values(
          event.previousContainer.data[event.previousIndex]
        );

        let parentRole = JSON.parse(JSON.stringify(event.container.data));

        let hasRole = parentRole.some(rola => {
          return rola.role === String(lastRole);
        });

        if (!hasRole) {
          transferArrayItem(
            event.previousContainer.data,
            event.container.data,
            event.previousIndex,
            event.currentIndex
          );
          let lastAddedRole = event.container.data[event.previousIndex];
          if (lastAddedRole !== undefined) {
            this.userRoleCopy.push(lastAddedRole.valueOf());
          }
          this.resetList();
        }
      }
    }
  },

This code implies that there two helper functions available: transferArrayItem and moveItemInArray, and also that the this object also has the method resetList and the properties userRole and userRoleCopy.  I created dummies for these, with a wrapper I creatively (:-)) called "something".  You can see it in Step 0.  I of course do not expect that these helper functions do anything like your original.  The goal here is to simply fix things up without changing the behavior.

Removing unnecessary clone

My first step was to remove an unnecessary clone made in this:

          let parentRole = JSON.parse(JSON.stringify(event.container.data));

        let hasRole = parentRole.some(rola => {
          return rola.role === String(lastRole);
        });

There is no advantage to cloning that parent role.  The call to some does not alter the data, so we can just use the original.

Thus we can just write:

        let hasRole = event.container.data.some(rola => {
          return rola.role === String(lastRole);
        });

This minor change is available in Step 1, and you can see just by switching tabs that the output remains the same.

Tweaking the search

This code seems odd:

          let lastRole = Object.values(
          event.previousContainer.data[event.previousIndex]
        );

        let hasRole = event.container.data.some(rola => {
          return rola.role === String(lastRole);
        });

Perhaps my initial assumption was wrong.  But if you're trying to see if that data object has an element whose role property matches the specified value, I believe it's much simpler.  This is available in Step 2.

        let lastRole = event.previousContainer.data[event.previousIndex].role

        let hasRole = event.container.data.some(rola => {
          return rola.role === lastRole;
        });

Stop repeating event.x.y

Repeating event.something.somethingElse all over the place makes the code both harder to read and harder to change.  We can capture values like prevData and id from the event, and the rest of the code will be simpler.  There are several ways we could do this, but I find the nicest one is with destructuring parameters.  Using that, we can simplify the code to version Step 3:

  drop: function ({
    container, container: {id, data},
    previousContainer, previousContainer: {data: prevData},
    previousIndex,
    currentIndex
  }) {
    if (id === "delete") {
      transferArrayItem(prevData, data, previousIndex, currentIndex);
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (previousContainer === container) {
        moveItemInArray(data, previousIndex, currentIndex);
      } else {
        let hasRole = pluck('role', data).includes(prevData[previousIndex].role)

        if (!hasRole) {
          transferArrayItem(prevData, data, previousIndex, currentIndex);
          let lastAddedRole = data[previousIndex];
          if (lastAddedRole !== undefined) {
            this.userRoleCopy.push({...lastAddedRole});
          }
          this.resetList();
        }
      }
    }
  }

Using helper functions

I'm still bothered by this bit:

          let lastRole = prevData[previousIndex].role

        let hasRole = data.some(rola => {
          return rola.role === lastRole;
        });

If we were working with ['role 1', 'role 2', 'role 3', ...], it would be very easy to search for our target role by just calling includes.  I happen to have handy a helper function that transforms [{x: 'a', y: 1}, {x: 'b', y: 2}, {x: 'c', y: 3}...] into ['a', 'b', 'c'], a function called pluck.  In fact it's built into the Ramda REPL I've been using, but we could write our own as easily as this:

const pluck = (prop) => (xs) => xs.map(x => x[prop])

and use it as in Step 4, like this:

        let hasRole = pluck('role', data).includes(prevData[previousIndex].role)

And now that we can extract helpers, we can do a substantial clean-up of our main function by adding a few helper methods to our object:

  deleteRole: function (prevData, data, previousIndex, currentIndex) {
    transferArrayItem(prevData, data, previousIndex, currentIndex);
    this.userRoleCopy = this.userRole.slice();
  },
  transferRole: function(prevData, data, previousIndex, currentIndex) {
    if (!pluck('role', data).includes(prevData[previousIndex].role)) {
      transferArrayItem(prevData, data, previousIndex, currentIndex);
      if (previousIndex in data) {
        this.userRoleCopy.push({...data[previousIndex]});
      }
      this.resetList();
    }
  },
  drop: function ({
    container, container: {id, data},
    previousContainer, previousContainer: {data: prevData},
    previousIndex,
    currentIndex
  }) {
    if (id === "delete") {
      this.deleteRole(prevData, data, previousIndex, currentIndex);
    } else {
      if (previousContainer === container) {
        moveItemInArray(data, previousIndex, currentIndex);
      } else {
        this.transferRole(prevData, data, previousIndex, currentIndex);
      }
    }
  }

(This is Step 5.)

Moving back to an event parameter

As we've proceeded, it seems as though the decision to destructure our event parameter is actually complicating things.  Certainly the signature of our main function is not as nice as we'd like.  If we undo that, now that we've abstracted things a bit, using these property accesses doesn't seem so ugly.

And this would let us move some of the helpers from object methods to plain functions, which are often more tractable.  There is a problem with the this property though, which would necessitate moving this line back into the main function:

   this.userRoleCopy = this.userRole.slice();

With this the code now could look like Step 6:

const pluck = (prop) => (xs) => xs.map(x => x[prop])

const transferEvent = (event) =>
  transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);

const moveEvent = (event) =>
  moveItemInArray(event.container.data, event.previousIndex, event.currentIndex)

const something = (userRole) => ({
  // ...
  transferRole: function(event) {
    if (!pluck('role', event.container.data).includes(
      event.previousContainer.data[event.previousIndex].role)
     ) {
      transferEvent(event);
      if (event.previousIndex in event.container.data) {
        this.userRoleCopy.push({...event.container.data[event.previousIndex]});
      }
      this.resetList();
    }
  },
  drop: function (event) {
    if (event.container.id === "delete") {
      transferEvent(event);
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (event.previousContainer === event.container) {
        moveEvent(event);
      } else {
        this.transferRole(event);
      }
    }
  }
})

Making plain functions out of methods

The reason we haven't been able to move transferRole into a plain function as well is that it makes reference to this.  So long as we need this, we're stuck with methods.  But it's quite easy to make it a function parameter.  When we do so we end up with a final cleaner codebase, Step 7:

const pluck = (prop) => (xs) => xs.map(x => x[prop])

const transferEvent = (event) =>
  transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);

const moveEvent = (event) =>
  moveItemInArray(event.container.data, event.previousIndex, event.currentIndex)

const transferRole = (something, event) => {
  if (!pluck('role', event.container.data).includes(
    event.previousContainer.data[event.previousIndex].role)
  ) {
    transferEvent(event);
    if (event.previousIndex in event.container.data) {
      something.userRoleCopy.push({...event.container.data[event.previousIndex]});
    }
    something.resetList();
  }
};

const something = (userRole) => ({tion: 'resetList'}),
  // ...
  drop: function (event) {
    if (event.container.id === "delete") {
      transferEvent(event);
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (event.previousContainer === event.container) {
        moveEvent(event);
      } else {
        transferRole(this, event);
      }
    }
  },
})

Lessons Learned

I was going to write a few paragraphs about choices made during this refactoring, and about alternatives that might apply.  But I'm tired now, and want to finish up.  So I'll just say although there are many good reasons to refactor code -- including performance, compliance with conventions and standards, and others -- the most important reason is to make your code easier to read and to modify.

I believe the final version makes the branching much more clear.  I believe it is easier to read.  So I believe we have improved this code.

Note: I'm seeing after writing all this up that we folded two separate changes into Step 5.  As well as pulling out helper functions, that step changed this:

          let lastAddedRole = data[previousIndex];
          if (lastAddedRole !== undefined) {
            this.userRoleCopy.push({...lastAddedRole});
          }

to this:

      if (previousIndex in data) {
        this.userRoleCopy.push({...data[previousIndex]});
      }

It does the same thing, but without introducing a temporary variable.  To me that's usually an improvement.


You seem to have too many checks for '\0'. They don't add anything. Also too many brackets, but better too many than too few.

Also, is long long guaranteed to be bigger than int? I don't think it is. Here's another version that doesn't need a bigger representation than that of int:

int atoi(const char *str)
{
    int n = 0;
    int sign = 1;

    while (isspace(*str)) {
        ++str;
    }
    if (*str == '-') {
        sign = -1;
        ++str;
    } else if (*str == '+') {
        sign = 1;
        ++str;
    }
    while (isdigit(*str)) {
        if (n > INT_MAX/10) { /* EDIT: protect against overflow */
            break;
        }
        n *= 10;
        int ch = *str - '0';

        if (n > INT_MAX - ch) {
            break;
        }
        n += ch;
        ++str;
    }
    if (isdigit(*str)) {
        return sign == 1 ? INT_MAX : INT_MIN;
    }
    return sign * n;
}

EDIT: I added a check to prevent overflow of the n *= 10

EDIT2: improved to avoid using an unsigned int - it was a hack


String compression function in python code

Encapsulate your code into functions

Your code is neither reusable nor testable, wrap it into a function and call it from under an if __name__ == '__main__' guard. This will allow you to test it more easily. You will also be able to return values instead of printing them, this will make the code more reusable:

def compress(string):
    temp={}
    result=" "
    for x in string:
        if x in temp:
            temp[x] = temp[x]+1
        else:
            temp[x] = 1
    for key, value in temp.items():
        result += str(key) + str(value)

    return result

if __name__ == '__main__':
    s = input("Enter the string:")
    print(compress(s))

You can then jump into an interactive shell and type:

>>> from your_file_name import compress
>>> compress('aaabbccccddefg')
 a3b2c4d2e1f1g1
>>> compress('b'*42)
 b42

Use existing data structures

collections.Counter offers simplified ways of counting elements of an iterable:

from collections import Counter

def compress(string):
    temp = Counter()
    result = " "
    for x in string:
        temp[x] += 1

    for key, value in temp.items():
        result += str(key) + str(value)
    return result

if __name__ == '__main__':
    s = input("Enter the string:")
    print(compress(s))

You can even simplify further as Counter can take any iterable in its constructor. You can also use str.join to simplify even further:

from collections import Counter

def compress(string):
    counts = Counter(string)
    return ''.join(letter+str(count) for letter, count in counts.items())

if __name__ == '__main__':
    print(compress(input("Enter the string: ")))

Possible bug

To me, compressing a string mean having a mean to decompress it back. Using a dictionnary keyed by each letter as you do, you lost an important information: which letter is next to which one. Also 'aabaabaabaa' will be compressed to 'a8b3' which, to me, doesn't make sense and would be better as 'a2b1a2b1a2b1a2'. But I might be wrong. In this case, itertools.groupby is much more usefull as it will keep the ordering and avoid aggregating separate groups of letters:

import itertools

def compress(string):
    return ''.join(
            letter + str(len(list(group)))
            for letter, group in itertools.groupby(string))

if __name__ == '__main__':
    print(compress(input("Enter the string: ")))


Formatting floating point number as mixed fractional in Ruby

[Answering my own question here]

Following Marc Rohloff's suggestion, I'm using Float#rationalize with an argument of 0.01 to convert the floats to rational numbers:

1.0.rationalize(0.01)
#=> (1/1)

1.3333.rationalize(0.01)
#=> (4/3)

1.5.rationalize(0.01)
#=> (3/2)

1.6666.rationalize(0.01)
#=> (5/3)

divmod can then be used to get the fixed and fractional part:

(5/3r).divmod(1)
#=> [1, (2/3)]

Applied to my method:

def format_fraction(number)
  fix, frac = number.rationalize(0.01).divmod(1)
  case frac
  when 0/1r then "#{fix}"
  when 1/4r then "#{fix}¼"
  when 1/3r then "#{fix}⅓"
  when 1/2r then "#{fix}½"
  when 2/3r then "#{fix}⅔"
  when 3/4r then "#{fix}¾"
  end
end

format_fraction(1.0)    #=> "1"
format_fraction(1.3333) #=> "1⅓"
format_fraction(1.5)    #=> "1½"
format_fraction(1.6666) #=> "1⅔"

It's not a huge change, but the when arguments now resemble the output more closely, which makes the code easier to understand IMO.

The method could be further shortened by extracting the rational => string pairs:

FRACTIONS = { 1/4r => '¼', 1/3r => '⅓', 1/2r => '½', 2/3r => '⅔', 3/4r => '¾' }

def format_fraction(number)
  fix, frac = number.rationalize(0.01).divmod(1)
  [fix, FRACTIONS[frac]].join
end


Fill a DataSet with nearly 20,0000 records using SqlDataAdapter

I would say the C# is fine, it's your database that is the issue.  Is the Stored procedure optimized?  Are the tables in the proper normalization?  Are your primary keys & foreign keys set up properly? (you should get the point by now)

Start there first since really everything is there.


1) Use collections.Counter

from collections import Counter. Counter is a subclass of dict that helps keep tallies. This way, you don't need .get(digit, 0) or if i in digit_counts, making your code look a bit cleaner.

2) Iterate in increasing order

Right now, you need a power variable to track which position to place the next digit in. If you iterated in the opposite direction (i.e. range(10)), you could do result *= 10 in each loop.

3) Use a for loop instead of while

Whenever you are iterating and incrementing/decrementing, you have the opportunity to use a for loop. In this case, for while digit_counts[i] >= 1 you don't care about the number of iterations, so you can use the _ as a "throwaway variable".

4) Code localization

Move result = 0 down so that it's just above where it starts being used. Code localization improves readability - depending on your source, the human brain can only remember 4-7 things at once. The fewer variables your reader has to track, the better.

Final Result

from collections import Counter

def sort_digits(n):
  digit_counts = Counter()

  while n > 0:
    digit_counts[n % 10] += 1
    n /= 10

  result = 0
  for i in range(10):
    for _ in range(digit_counts[i]):
      result = 10 * result + i

  return result


Perl module to deal with numbered nested objects

Just a few remarks about parts which poke the eye,

    push @ar, sub {
        return (undef) unless exists $obj->{$i};
        return squash($obj->{$i});
    }->();

introduces unnecessary subroutine call/overhead which can be replaced with do {} block, or even simpler,

    push @ar, exists $obj->{$i} ? squash($obj->{$i}) : undef;

This one is only matter of taste, so

return $obj unless ref $obj eq 'HASH';

could also be written as

return $obj if ref $obj ne 'HASH';

Usually you don't have to explicitly return undef, as in list context you may end up with list one element long, and that might not be what is intended. Instead just return; or return (); will produce empty list, or undef in scalar context. So

return (undef) if @{$obj} == 0;

could be better as

return () if @{$obj} == 0;

or perhaps,

@$obj or return;


Rails query for all questions in tournaments that a user participates in

Ok, so based on what your said your associations are you can do

class User
  has_many :tournaments
  has_many :questions, through: :tournaments
end

u = User.first
questions = u.questions

If you don't want that for some reason you can do

class User
  has_many :tournaments
end

class Question
  belongs_to :tournament
end

u = User.first
questions = Question.where(tournament_id: u.tournament_ids)

Rails will convert that into a where tournament_id in (?) sql statement


I have no problem the ternary operator.

But it is hard to tell that the result is what the comments is saying. Without having a context on what time is (which is a bad variable name) it is hard to understand the result of the function.

time: Bad variable name. Time of what?


Matching any certain selection of inputs

You can combine px and em into a single group
You can pull in the negation sign with a ?
[0-9] is equivalent (usually) to \d
^ and $ can be pulled out to the end (or use the api than only matches the entire string.

this results in:

^(-?\d+(px|em)|\d+%|auto|0)$

If you can have a negative % values then it's even simpler: ^(-?\d+(px|em|%)|auto|0)$


Convert number from one radix to another

You're re-inventing the wheel. In the Integer class, there are methods for converting numbers to and from Strings with a radix parameter. So the following class does the job:

package test;

public class Test {

    public static void main(String[] args) {
        int inRadix = Integer.parseInt(args[1]);
        int outRadix = Integer.parseInt(args[2]);
        int value = Integer.parseInt(args[0], inRadix);
        String result = Integer.toString(value, outRadix);
        System.out.printf("%s (%d) = %s (%d)%n", value, inRadix, result, outRadix);
    }
}

But let's for a moment suppose the methods weren't there and look at your solution.

First, the method name convertToDecimal shows a (quite common, I have to say) mis-understanding. An int is internally represented in binary (radix 2), not decimal (radix 10). So convertToInt would be a better name.

I'd extract the character-versus-digit-value logic into methods int digitValueOf(char ch) and char digitCharFor(int digit) (By the way, the Character class has these methods).

I'd replace the numbers like 48 by the characters they represent (e.g. '0'). Not every reader knows the Unicode table by heart.

I'd replace the Math.pow() by consecutive integer multiplication. Turn the loop the other way round, starting from the last digit with placeValue = 1. In every iteration, multiply placeValue by radix. Math.pow() is slower and less exact than integer arithmetic.

I'd get into the habit of adding Javadoc even to trivial methods. After a year or so, you'll be happy.

Personally, I'm lazy with comments inside methods. A good method name, a Javadoc explaining what the method does (not how), and a straightforward implementation within the method are typically enough for a reader to understand what's going on.

Good is the usage of StringBuilder instead of concatenating Strings (quite common performance killer).

Good is throwing an exception in case of illegal characters.

Good is following the standard Java naming conventions.


Basic event stopPropagation() example - a better way of doing so?

Your Question

Is this really the right way of doing this, or is there a better way? Something doesn't feel right here.

The term "better" is subjective so you can judge for yourself. Presuming there is not a need to have clicks on the child elements trigger any event handlers, one alternative is to use the CSS property pointer-events style. One could use the value none:

none
The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

var test = document.getElementById('test'),
    child = document.getElementById('child');

test.addEventListener('click', function (e) {
  console.log('click on parent without stopping propagation');
});
#test {
  background: red;
  display: flex;
  position: relative;
  height: 30px;
  width: 100%;
}
#child {
  background: pink;
  margin-top: 5em;
  position: absolute;
  pointer-events: none;
}

child


Enumerate k-combinations in Clojure (P26 from 99 problems)

I'm currently reading "Joy of Clojure" so I'm (very) far from being "fluent" in Clojure but what I noticed is:

your solution is clever but quite complicated, you use "imperative" habits like indexed iteration
try to keep with simple abstractions like sequence first and rest and the solution will work with any Clojure collection - see example below
your solution use cond with three checks for k - consider using condp

Here's my code:

(defn subsets [n items]
(cond
    (= n 0) '(())
    (empty? items) '()
    :else (concat (map
                    #(cons (first items) %)
                    (subsets (dec n) (rest items)))
                  (subsets n (rest items)))))


An old question, bet let's leave no question unanswered... I will go through your code (mostly) in order in which it is presented.

Asking for multiple is, in my opinion, in the wrong position, as it is separated by functions definitions from the rest of the main code. I'd move it after the functions definitions.

Closely related to that, asking the user to answer with C-like logic of 1 for "yes" or 0 for "no" is not pleasant, especially since Python doesn't share C's woes with strings. Btw, int(...) has no problem with extra spaces, so (r)stripping is not needed.

And, since we're becoming user-friendly here, let's allow users to make typos without crashes and other unexpected behaviour by asking them again if they give a nonsense answer. All together:

while True:
    answer = input("Would you like answer runs (y/n)? ").strip().lower()
    if answer in {"y", "n", "yes", "no"}:
        break
multiple = (answer in {"y", "yes"})

Creating weighted randoms can be done in a more concise and configurable way. I have chosen this:

weights = [0, 0, 0, 0.1, 0.5, 0.95, 1]
def weighted_random():
    # between 3 ft and 6 ft
    major = random.random()
    major = next(idx for idx,limit in enumerate(weights) if limit > major)
    return major + random.random()

The weights list (could've been a tuple as well) contains limits. The major value (the integer part) of the height is the index of the first value bigger than the random that was picked. So, for example, 0.05 is between 0 and 0.1, meaning that we pick major = 3 because 3 is the index of 0.1.

Apart from keeping the code short, this makes it trivial to change the weights, including adding more weight categories, as long as we keep to the premise that these define the integer part. Otherwise, we could've used a dictionary or some similar approach.

We create heights twice in the program, so let's not copy/paste this non-trivial and important code. A function is better:

def make_heights(rows=30, cols=30):
    return [[weighted_random() for j in range(cols)] for i in range(rows)]

Printing is also best done using generators and joining the elements with the space character:

def output_heights(data):
    print("Men:")
    for row in data:
        print(" ".join("%.3f" % el for el in row))

Your _zip function confused me at first. There is a zip() in Python, but it does something far more reasonable for a function with such a name. Consider renaming this to "transpose".

Either way, I think it's best to handle "the shortest of the tall ones" and "the tallest of the short ones" the same way, with a single function for each of them:

def shortest_of_talls(data):
    return min(max(row) for row in data)

def tallest_of_shorts(data):
    return max(min(row[j] for row in data) for j,_ in enumerate(data[0]))

Here, I use enumerate to get (index, value) tuples, and I use a throwaway variable _ for values because I don't need them. There are a few situations when _ is not a good choice, but that's beyond the scope of this review.

Btw, notice that I use data. It's more descriptive than array (albeit, heights or people might have been a better choice).

Your main if looks like this: if not multiple: ... else: .... Does it not make more sense to do if multiple: ... else: ...? I changed it thus, so let's first review the "multiple" code.

I prefer evalf = list() over evalf = [], as I find it more readable. You're more likely to notice a bug if you put set() instead of list() than if you put {} instead of [].

We decided above to be more user friendly, so let's keep that up when asking about the number of runs. You wanted to ask the user to give you an integer, and default to 10000 if they give 0. Here is the code that takes an empty(ish) string (we allow spaces) which is treated as the default, or a positive integer. Any other response will repeat the question:

    while True:
        times = input("Number of evaluations (leave empty for 10000)? ")
        if times.strip() == "":
            times = 10000
            break
        try:
            times = int(times)
            if times > 0:
                break
        except ValueError:
            pass

The next part of your code is biased toward what you know (expect?) is the right answer. If I got it right, this is a research question, so let's research the results properly, by counting how many "tallest of shorts", "shortest of talls", and "equals" are there:

    cnt_tos = cnt_sot = cnt_eq = 0

Since your default is to run 10000 tests, and that takes time (roughly a minute on my laptop), I decided to add progress information here. It's a neat little trick: print a message, but end with "\r" instead of "\n" to place the cursor at the beginning of the same line, instead of the next one:

    cnt_tos = cnt_sot = cnt_eq = 0
    done = -1
    for run in range(times):
        new_done = 100*run // times
        if new_done > done:
            done = new_done
            print("Done: %d%%" % done, end="\r")
        heights = make_heights()

        tall_man = shortest_of_talls(heights)
        short_man = tallest_of_shorts(heights)

        if tall_man > short_man:
            cnt_sot += 1
        elif tall_man < short_man:
            cnt_tos += 1
        else:
            cnt_eq += 1

    print("Out of %d evaluations, we got:" % times)
    print("  * {times} times ({percent:.3f}%) the shortest of tall was taller,".format(times=cnt_sot, percent=100*cnt_sot/times))
    print("  * {times} times ({percent:.3f}%) the tallest or short was taller,".format(times=cnt_tos, percent=100*cnt_tos/times))
    print("  * {times} times ({percent:.3f}%) they were equal.".format(times=cnt_eq, percent=100*cnt_eq/times))

Notice that I have removed many blank lines that you have. The Style Guide for Python, which is one of the core documents for Python programmers, suggests that those should be used sparingly. I am probably too generous with them, but I prefer separating parts of the code that do semantically different parts of the job.

I also replaced C-style formats for the newer format() function, to make the code more readable (and, in theory, easier to change/translate, as these arguments are no longer positional). I will rarely use C-style formatting if there is more than one variable involved.

I did similar changes to your "single run" branch:

    heights = make_heights()
    output_heights(heights)

    tall_man = shortest_of_talls(heights)
    short_man = tallest_of_shorts(heights)

    print("Tallest of short:", short_man)
    print("Shortest of tall:", tall_man)
    print(
        "The answer is: ",
        "tallest of short" if short_man > tall_man else "shortest of tall"
    )

As you can see, Python has ternary operator, and this is far more readable than the original print(["tallest of short", "shortest of tall"][short_man < tall_man]).

Here is my variant of your code as a whole:

#!/usr/bin/env python3

import random

# Between 3 ft and 6 ft
weights = [0, 0, 0, 0.1, 0.5, 0.95, 1]

def weighted_random():
    major = random.random()
    major = next(idx for idx,limit in enumerate(weights) if limit > major)
    return major + random.random()

def make_heights(rows=30, cols=30):
    return [[weighted_random() for j in range(cols)] for i in range(rows)]

def output_heights(data):
    print("Men:")
    for row in data:
        print(" ".join("%.3f" % el for el in row))

def shortest_of_talls(data):
    return min(max(row) for row in data)

def tallest_of_shorts(data):
    return max(min(row[j] for row in data) for j,_ in enumerate(data[0]))

while True:
    answer = input("Would you like answer runs (y/n)? ").strip().lower()
    if answer in {"y", "n", "yes", "no"}:
        break
multiple = (answer in {"y", "yes"})

if multiple:
    evalf = list()
    while True:
        times = input("Number of evaluations (leave empty for 10000)? ")
        if times.strip() == "":
            times = 10000
            break
        try:
            times = int(times)
            if times > 0:
                break
        except ValueError:
            pass

    cnt_tos = cnt_sot = cnt_eq = 0
    done = -1
    for run in range(times):
        new_done = 100*run // times
        if new_done > done:
            done = new_done
            print("Done: %d%%" % done, end="\r")
        heights = make_heights()

        tall_man = shortest_of_talls(heights)
        short_man = tallest_of_shorts(heights)

        if tall_man > short_man:
            cnt_sot += 1
        elif tall_man < short_man:
            cnt_tos += 1
        else:
            cnt_eq += 1

    print("Out of %d evaluations, we got:" % times)
    print("  * {times} times ({percent:.3f}%) the shortest of tall was taller,".format(times=cnt_sot, percent=100*cnt_sot/times))
    print("  * {times} times ({percent:.3f}%) the tallest or short was taller,".format(times=cnt_tos, percent=100*cnt_tos/times))
    print("  * {times} times ({percent:.3f}%) they were equal.".format(times=cnt_eq, percent=100*cnt_eq/times))
else:
    heights = make_heights()

    output_heights(heights)

    tall_man = shortest_of_talls(heights)
    short_man = tallest_of_shorts(heights)

    print("Tallest of short:", short_man)
    print("Shortest of tall:", tall_man)
    print(
        "The answer is: ",
        "tallest of short" if short_man > tall_man else "shortest of tall"
    )

Apart from these, I have three more comments:

Use sensible names. Apart from zip and array, there was also zeroes, which was probably meant as "those where the condition is zero (it's actually False in Python)", but this is really not informative to anyone reading the code.
Consider including docstrings in all of your functions. It's a good habit to have, lest you end up banging your head on the desk when reading trying to understand your own code in a few months.
Since you're working with matrices, using NumPy's array could be a good choice, especially because it provides a simple and fast transpose and weighted sampling.


The question title suggested that this would be a Rot47 category on NSString, but it's not.  It's an r47 category (which tells me nothing... what's "r47"?).

This is Objective-C, not C or C++ or any other language where cryptic terseness is favored.  We prefer verboseness.  The category should be called Rot47.  This should be @implementation NSString (Rot47).  The method should be called - (NSString *)rot47String;

In Objective-C, we also prefer our opening braces go on the same line, not on their own line.  For example:

for (;;) {

Braces are technically optional, but you really shouldn't think of them as such.  Apple even agrees and made them non-optional in swift.  You've left them out of your if/else blocks, which is a great way to leave your code open for future bugs.

When we implement categories on Foundation classes, we should take care to ensure their portability.  The method should be designed to work no matter what project we import this file into and no matter what the contents of the string.

The problem here is that your method doesn't do that.  Your method works fine presuming a particular encoding, but for anything else it will produce incorrect results.

Rather than a char array, we need a unichar array.

NSUInteger length = [self length];
unichar letters[length + 1];

[self getCharacters:letters range:NSMakeRange(0,length)];

Now letters is an array of unichars for us to iterate over and transform correctly.


Checking a one-dimensional numpy array in a multidimensional array without a loop

If you don't like the looping and the if ... statements you could use solely NumPy methods:

def is_row_in_array(row , arr):
    return np.any(np.sum(np.abs(arr-row), axis=1) == 0)


First of all, your palindrome function uses inefficient logic. Reversing a string takes N steps, where N is the length of the string. Comparing a string to its reverse takes some additional steps, though typically not that many for ordinary strings, near N / 2 steps for almost-palindromes, N steps for palindromes, but that's not a real concern.

The important thing is that you can check if a string is palindrome in N / 2 steps by comparing the ith character from start and end. The even more important thing is that you can use this logic to fond the index that breaks a palindrome, significantly speeding up your parse function.

As a final remark about good coding practices, your parse function does too many things, and it's also poorly named. It would be better to decompose this to multiple functions that each do one logical thing, and name them accordingly.


Authenticating an internal API with Flask

Just because you don't have many people using this API now, this does not mean that this will always be the case.

In addition, you might want to discriminate between the users of the API for various reasons:

To know how many there actually are
To know which user/application is generating all those requests suddenly
To rate-throttle some of them if needed
To disallow access for someone who abused the API or just left the company or an obsolete application

I would at least set this up in a very barebone way to have different API keys. For now you can just hardcode them in a dictionary in the config file, but this allows you to easily extract them to a database at some future point (which may never come). You can manually add users when needed (if it is only a few), or write a page that adds a user (if the manual task becomes too much).

In your config just have something like this:

config.yml

api_keys:
    08zEk8IC0le3I0kPwSF1g4XU9R5WgbpUq2vZkZ0pkQU: User 1
    ZtRE7FXwZdtCLMfFHWPTom7_d-4XFbXEkHR5bIdG2TM: User 2
    Wg1vaDs8uqFbYtNDsJ8H3gKjl_oI0T_O6Jg8qNLWJcU: App 1
    ...

Your code needs to be only minimally changed:

auth.py

def valid_auth(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        if 'x-api-key' not in request.headers:
            return "Credentials not present in request", 401
        elif request.headers['x-api-key'] not in config['api_keys']:
            return "Credentials not valid", 401
        else:
            return func(*args, **kwargs)
    return func_wrapper

Note that () around tuples are not needed in return since it is an expression and not a function.

Returning a tuple of message, status code to raise in one case and the result of the function in another case can also be a potential source of bugs. If the using code expects the return value to be a single value, checking for there being two and those two being a string and an int is not very fool-proof. Even worse if the function actually also returns a string and int tuple.

Instead, raise exceptions, which you can then deal with in api_function. Use custom classes inheriting from Exception:

class NoCredentials(Exception):
    status_code = 401

class WrongCredentials(Exception):
    status_code = 401

...
if 'x-api-key' not in request.headers:
    raise NoCredentials("Credentials not present in request")

This page in the official documentation explains in more detail how to use custom exceptions correctly in flask.


Throttled execution of an enumeration of Tasks

A TPL inside async implementation: mixing of implementaion concepts makes the code complicated or even buggy. Finally Parallel.ForEach is blocking the current thread which isn't allowed in async programming.
Also avoid blocking operations on Task e.g. .Wait() or .Result for not completed Task.
But I suggest totally different approach. Consider the simplified example.
public class ThrottledApiClient : IDisposable
{
    private readonly HttpClient _client;
    private readonly SemaphoreSlim _semaphore;

    public ThrottledApiClient(string baseUrl, int concurrentDegree = 0)
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(baseUrl);
        _semaphore = new SemaphoreSlim(concurrentDegree == 0 ? Environment.ProcessorCount * 2 : concurrentDegree);
    }

    public async Task<string[]> PostJsonRequestsAsync(IEnumerable<(string, string)> requests, CancellationToken token)
    {
        List<Task<string>> tasks = new List<Task<string>>();
        // wrap the loop with try-catch (OperationCanceledException) to handle Cancellation right here if necessary
        foreach ((string path, string json) in requests)
        {
            await _semaphore.WaitAsync(token);
            tasks.Add(PostJsonAsync(path, json, token));
        }

        return await Task.WhenAll(tasks);

        // or with filter
        //await Task.WhenAll(tasks);
        //return tasks.Where(t => t.IsCompletedSucessfully).Select(t => t.Result).ToArray();
    }

    private async Task<string> PostJsonAsync(string url, string json, CancellationToken token)
    {
        try
        {
            using HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
            using HttpResponseMessage response = await _client.PostAsync(url, content, token);
            // response.EnsureSuccessStatusCode(); // to throw on not success instead of returning result
            return await response.Content.ReadAsStringAsync(token);
        }
        // catch (HttpRequestException)
        // catch (OperationCanceledException) { return null; } // to swallow cancellation
        finally
        {
            _semaphore.Release();
        }
    }

    public void Dispose()
    {
        _client.Dispose();
        _semaphore.Dispose();
    }
}

And the demo.
(string, string)[] requests = new (string, string)[]
{
    ("/getAccounts", "{...}"),
    ("/getMediaPath", "{...}")
};

using (var api = new ThrottledApiClient("https://api.example.com", 4))
using (var cts = new CancellationTokenSource())
{
    var results = await api.PostJsonRequestsAsync(requests, cts.Token);
    //...
}

You can invoke PostJsonRequestsAsync even concurrently multiple times, even from different threads but only 4 requests will be active simoultaneously.
SemaphoreSlim is default synchronization tool in async programming for now.


Mark rows with identical values in a table

Without making algorithmic changes, we can still make some performance improvements:

$(document).ready(function() {
    var $tableRows = $("#sortable tbody tr");
    var $rowsToMark = $();

    $tableRows.each(function(n) {
        var id = this.id;
        var example = $(this).find('.content').html();

        $tableRows.each(function(n) {
            var $this;
            if (this.id != id) {
                $this = $(this);
                if ($this.find('.content').html() == example) {
                    $rowsToMark.add($this);
                }
            }
        });
    });

    $rowsToMark.css('backgroundColor', 'azure');
});

If you really want to start optimizing (I seriously doubt it's worth it, though) you could take a dynamic programming approach and do some caching. For instance:

You really don't need to call .html() on any given row more than once. Start by getting the HTML of each row and store it, then you can compare by iterating over those HTML strings rather, than the DOM elements.
If you have already determined that rows A and B are equal, you only need to compare row C against either A or B.
(other things I haven't yet thought of)

General jQuery performance/optimization information:

https://stackoverflow.com/questions/3230727/jquery-optimization-best-practices
https://stackoverflow.com/questions/6028555/jquery-selector-optimization
And many others


Stored procedure for processed orders in SQL Server

Table variables

Because you are using them only once, and as part of a bigger query, there is really no benefits in using a table variable nor a temporary table. The best choice in this case is to use a Common Table Expressions, or CTE.

A CTE basically works like a subquery but unlike a traditional subquery, it has the advantage of reading from top to bottom rather than inside out as traditionally done. Here is a sample:

WITH SalesStats AS (
  SELECT PO.SellerID, COUNT(PO.OrderId) AS NumberOfProcessed
  FROM ProcessedOrder AS PO
  WHERE PO.SellerID <> 0
  GROUP BY PO.SellerID
)
SELECT ss.SellerID, ss.NumberOfProcessed
FROM SalesStats AS SS;

Improper use of ORDER BY

Your INSERT INTO queries has a ORDER BY which contributes nothing and in fact may penalize your performance. The only time you should use an ORDER BY is in the final select.

There are legitimate cases where your INSERT INTO (or an UPDATE) may need an ORDER BY but those are the exceptions, not the rule. By putting in an ORDER BY, you are tying up the optimizer's hands because it has less choices it can make in optimizing the queries. Don't do that.

Lack of schema names

You do not qualify your tables. It's very good practice to always use two-naming as the default --- schema.table rather than just table. Consider that multiple schemas within a database could have a table with same name, that a user could be in their own schema (especially from older database where things worked differently back then), that you are forcing the server to do a search of all schema to bind the tables. I'm going to assume that your tables are in the default dbo schema. Therefore....

SELECT PO.SellerID, COUNT(PO.OrderId) AS NumberOfProcessed
FROM dbo.ProcessedOrder AS PO
WHERE PO.SellerID <> 0
GROUP BY PO.SellerID;

Note that a CTE do not have two-part naming because it is defined in the scope of query. But all real objects (e.g. tables or views or stored procedures) should all be named with schema and object names explicitly.

Column ordering

To be honest, I found it confusing to see aggregates listed first then the grouping columns last. Normally, I would write query vertically, with grouping columns first.

SELECT
  PO.SellerID,
  COUNT(PO.OrderId) AS NumberOfProcessed
FROM dbo.ProcessedOrder AS PO
WHERE PO.SellerID <> 0
GROUP BY PO.SellerID;

In a small query with only few columns it might be OK to have them as one line but for more complicated queries, vertical listing makes it much easier to see what is going out from that query. By listing the grouping columns, it helps to verify the GROUP BY as well.

Unnecessary use of DISTINCT

In all queries up to the query, you group on SellerID. Thus they are already distinct because by definition, grouping generate one row per value in that column, so it's already distinct. Don't force the optimizer to do more work than necessary.

Lack of semicolons

Upon a time, terminating a SQL statement was optional. Now, it's very much recommended that you always terminate a SQL statement. Some people cheat by adding semicolons only when they are required (e.g. before a CTE or a MERGE statement) but that makes for inconsistent and ugly code.

Furthermore, having an explicit terminator help to clearly separate each SQL statement and avoid overlapping due to ambiguity.

Potential division by zero error

You have this expression: two.TotalAmountPaid / one.NumberOfPaidOrders AS AverageAmountPaid

What if the number of paid orders is zero, not NULL? What if you later changed the queries that made it possible to put in zeroes? It's good to always guard against that to make your queries easier to change if you need to do so in future and is as simple as using NULLIF: TotalAmountPaid / NULLIF(NumberOfPaidOrders, 0). This basically substitutes the 0 with a NULL, which causes the results to be NULL without raising any runtime errors.

Putting it all together

With CTEs, we can consolidate this into a single query.

WITH SalesStats AS (
  SELECT
    PO.SellerID,
    COUNT(PO.OrderId) AS NumberOfProcessed, PO.SellerID
  FROM dbo.ProcessedOrder AS PO
  WHERE NOT PO.SellerID = 0
  GROUP BY PO.SellerID
), CountOfPaidOrders AS (
  SELECT
    AA.SellerID,
    COUNT(AA.OrderId) AS NumberOfPaidOrders
  FROM dbo.AcceptedOrder AS AA
  LEFT JOIN dbo.ProcessedOrder AS PO
    ON AA.OrderId = PO.OrderId
  GROUP BY AA.SellerID
), TotalAmountPaid AS (
  SELECT
    AA.SellerID,
    SUM(AA.Amount) AS TotalAmountPaid
  FROM dbo.AcceptedOrder AS AA
  GROUP BY AA.SellerID
)
SELECT
  SS.SellerID,
  SS.NumberOfProcessed,
  C.NumberOfPaidOrders,
  T.TotalAmountPaid,
  T.TotalAmountPaid / NULLIF(C.NumberOfPaidOrders, 0) AS AverageAmountPaid
FROM SalesStats AS SS
LEFT JOIN CountOfPaidOrders AS C
  ON SS.SellerID = one.SellerID
LEFT JOIN TotalAmountPaid AS T
  ON SS.SellerID = two.SellerID
ORDER BY SS.NumberOfProcessed DESC;

Now the optimizer can see how they all are used, and thus form a better execution plan and you don't need to worry about optimizing, beyond ensuring that the optimizer has the indices it needs.

The CTEs only live for a single SQL statement so if you had to modify the procedure that you end up accessing the CountOfPaidOrders (for instance) multiple times within a stored procedure, you do need a temporary table instead, but in this case, I don't see benefits of creating one.


MySQLi script to print the name of a user

You are vulnerable to SQL injection. Always use prepared statements with parameterized queries.

The below example fixes these issues. In this example I am using PDO instead, which is similar to mysqli but more powerful and supports other databases than just MySQL.

<?php

include "functions.php";

$a = checkLogin();

if ($a == 1) {
    $id = $_COOKIE['id'];

    // include "databaseConnector.php";
    // --------------------------------------------------------------------------------------------------
        try {
            $handle = new PDO("mysql:host=$host_addr;dbname=$database", $username, $password);
            $handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    // --------------------------------------------------------------------------------------------------

    // UNBOUND PARAMETERS VERSION
        $query = "SELECT * FROM users WHERE id = '$id'";
        $statement = $handle->prepare($query);
        $statement->execute();

    // BOUND PARAMETERS VERSION
        $query = "SELECT * FROM users WHERE id = :id";
        $statement = $handle->prepare($query);
        $params = array(":id" => $id);
        $statement->execute($params);

    $row_count = $statement->rowCount();
    $result    = $statement->fetchAll(PDO::FETCH_ASSOC);

    if($row_count > 0) {
        foreach ($result as $row => $col) {
            echo $col['firstname']." ".$col['lastname'];
        }
    } else {
        return false;
    }
} else {
    redirectIndex();
}

?>


Producing a matrix class that supports any size

Remove all var. Doesn't the book show for...yield by that point? For example:

(i,j) => {
  var sum = 0.0;
  for (k <- matrix(i).indices) sum += matrix(i)(k) * another(k)(j);
  sum
}

Can be replaced with:

(i,j) => (for (k <- matrix(i).indices) yield matrix(i)(k) * another(k)(j)).sum

The var on toString can be replaced by using mkString. I'll let you work out for yourself how to do that, now that I called your attention to that method. And, yes, it that method works on Array as well, though it doesn't appear on Scaladoc for Scala up to 2.9.2 because it is added implicitly. I suggest you use the nightly scaladoc to look things up -- the documentation there is better, though it may show things not available on release versions, and so is the tool itself.


Non-review answers

what security threats this script can prevent - sql injection
what security threats this script is vulnerable to - sql injection
how these threats are blocked - https://stackoverflow.com/questions/8263371/how-can-prepared-statements-protect-from-sql-injection-attacks

Review answer.

Your code is bloated with unnecessary operators, such as heredoc.
It is also recommended to use PDO instead of sqlite, as it will let you to use array binding, which is especially useful in this case as you are inserting equal sets of data.

Besides, you should use prepared statements for your database interactions.

There are also other improvements and fixes.

if (!empty($_POST['userMsgField']) && !empty($_POST['hash']))
{
    $my_id = $_SESSION['log_id'];
    $rep_msg = $_POST['userMsgField'];
    $hash = $_POST['hash'];
    $flag = 0;

    $sql = "SELECT * FROM connect WHERE (user_one = ? AND hash = ?)
                                     OR (user_two = ? AND hash = ?)";
    $stmt = $db->prepare($sql);
    $stmt->execute([$my_id,$hash,$my_id,$hash]);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        $user_one = $row['user_one'];
        $user_two = $row['user_two'];

        $to_id = ($user_one == $my_id) ? $user_two : $user_one;

        $data = [
            'message' => $rep_msg,
            'group_hash' => $hash,
            'from_id' => $my_id,
            'flag' => $flag,
            'to_id' => $to_id,
        ];

        $sql ="INSERT INTO messager (message, group_hash, from_id, flag, to_id)
                            VALUES (:message,:group_hash,:from_id,:flag,:to_id)";
        $db->prepare($sql)->execute($data);

        $sql ="INSERT INTO chatportal (message, group_hash, from_id, flag, to_id)
                              VALUES (:message,:group_hash,:from_id,:flag,:to_id)";
        $db->prepare($sql)->execute($data);
    }
}

Now this code is much cleaner and easier to read. And safe, of course.


Check if array contains contiguous integers with duplicates allowed in Java

Code. Separate the business logic from the IO. checkContig shall not print anything, but only return a success/failure indication. Printing is up to a caller.

Algorithm. arrNoReps.contains(i) fails to take into account the fact that arrNoReps is already sorted, effectively leading to a quadratic complexity. If the array is sorted, you can test its contiguity in a linear time:

    for (i = 1; i < arr.size(); i++) {
        if (arr[i] - arr[i-1] != 1) {
            return false;
        }
    }
    return true;

Notice that the same logic is applicable to the sorted array with repetitions. A difference between to successive elements in a sorted array is either 0 (a dupe), or 1 (contiguity maintained), or any other positive number (contiguity broken), so

    for (i = 1; i < arr.size(); i++) {
        if (arr[i] - arr[i-1] > 1) {
            return false;
        }
    }
    return true;

which means that the conversion to the set and back to array is quite redundant.


Validate whether a ransom note can be made from a dictionary of words

Algorithm

You build an array with the counts of letters in the newspaper. Then you iterate over the letters of the ransom note, and short circuit when a letter is missing (count goes below zero).

Can this be done the other way around? That is, build an array of counts from the note, then iterate over the newspaper and short circuit when the letter is completed. Yes that would work too, but using a map of counts instead of an array, deleting letters that were completed, and an empty map marking the ransom note competed.

So which way is better? Consider these questions:

Which tends to be bigger: the ransom note or the newspaper? To complete the task of making the ransom note, which one must be inevitably finite, and which one may be infinite, the ransom note or the newspaper?
What if the newspaper contains billions of letters?
What if you receive the available letters (of the newspaper) as a (possibly infinite) stream of characters?
How would you make a ransom note in real life? Cut out letter by letter from a newspaper and build neat little stacks, ready for the ransom note? Probably not ;-)

Naming

The name validateSomething sounds like it might throw an exception is invalid, or mutate state (return void). More common prefixes for boolean methods are "is", "has" and "can". In this example, instead of validateLetterCreation, I would recommend canCreateRansomNote.

The name charArray is misleading. A reader might think it's an array of characters. When it's actually counts of letters, so I would call it just like that: countsOfLetters.

Testing

One example case with a sample newspaper and a sample ransom note executed in a main method is far from enough to verify the correctness of such program. Consider looking into a proper unit testing framework, such as JUnit.


int [] arrayToBeSorted;
Scanner scan=new Scanner(System.in);

Without any modifier, members and functions are package-private. Which means that they are accessible from the same package, but not by instances extending the class. That's an extremely odd thing, actually, when looking at it from an object-oriented point of view. You want to either make them private, or if extending classes should be able to access them, protected.
Same goes for the constructor.

    System.out.println("Enter the number of elements");
    int total=scan.nextInt();
    this.arrayToBeSorted=new int[total];

You could use a List/ArrayList instead of an array, which would mean that you can receive as many numbers from the users as they want without having to specify the count beforehand. An empty input could be used for declaring the end of the list. However, that has the downside that you must use Integer instead of int, so it' is kinda hard to tell what is better. It also has the downside that detecting an empty input is that readily available from Scanner, as you'd need to use nextLine for that, with manual conversion to int.
You could also emulate a List by dynamically growing the array. Either by doing it for every item, performance does not matter in this use-case, or by doubling the size when needed.

this.arrayToBeSorted=new int[total];

You only require the this modifier if you have a variable with the same name in the same scope, for example in a constructor:
public ValueContainer(int value) {
    this.value = value;
}

It's common practice to omit this if not needed. If you ever find yourself in the situation that it is confusing whether an instance, static or local variable is used, you did something wrong there anyway.

for(int i=0;i<total;i++) {

I'm a very persistent advocate for using "real" names for variables in loops.
for (int counter = 0; counter < total; counter++) {
// or
for (int index = 0; index < total; index++) {

public void Sort() {

The Java naming conventions state that methods/functions should be lowerCamelCase.

int minIndex,min;

Personally I'd avoid declaring multiple variables on the same line. It makes it easy to miss declaration.

boolean swapRequired=false;

That's a great example of a great name for a variable, thank you!

    for(int x:this.arrayToBeSorted) {
        System.out.print(x+" ");
    }

That, unfortunately, is a bad name for a variable. Only use "x", "y" and "z" when working with dimensions. "value" or "number" would be a great name here.

Overall, it looks valid. I did not run it to test the functionality, though. What you should change is that you have logic in the constructor. Nobody expects constructors to be filled with logic, because you can't see the intent of logic from them. They should be as nothing doing as possible. That means that you should move the logic into sort or, even better, into main. Your Sorter should not be concerned with input at all, it should only be concerned with sorting values, ideally, and another class (InputReader?) should be concerned with getting the input. So what you could do is something like this:
public static final void main(String[] args) {
    InputReader inputReader = new InputReader();

    int[] values = inputReader.readValues();

    Sorter sorter = new Sorter();
    sorter.sort(value);

    // TODO Print sorted output.
}

That also has the upside that you don't need to hold state in Sorter at all, which would make it thread-safe by default.


Extracting book information from a web page, with possible missing attributes

The obvious thing to do when you have repeated functionality is to extract it into a function. In this case, it looks like the parameters for the function are the content itself, the element type to find, the classname, and a list of text to replace.

You can also tidy things up by only doing the find once.

def find_text(content, element, classname, *replacements):
    item = content.find(element, {'class': classname})
    if item:
        text = item.get_text()
        for replacement in replacements:
            text = text.replace(replacement, "")
        return text
    else:
        return 'None'

Now your main loop looks like:

for content in book_info:
    title = find_text('span', 'fn')
    author = find_text('div', 'fieldRow jr_autorestr', "Autore")
    classification = find_text('div', 'fieldRow jr_narrstrcontinente', "Classificazione")
    ... etc ....


Efficiently Generate Subset of all Permutations or Combinations with and without Repetition (C++)

I'm going to focus on the algorithmic aspects of your code rather than the style, as I don't know C++. You want to generate permutations and combinations with unique elements, so all you need to do is find the sublist of unique elements, and find the permutations and combinations of that. To uniquify, you should use a structure with a fast contains method (tree or hash set), and add each element is the vector to it if it isn't already. This will use O(n) memory, but your output is much later, so that overhead is justified given that it will save a lot of time later.


Form for OTP entry with six single-character text fields

Your solution to this particular problem is fine in its own way. However when it comes to scaling, it will become quite messy. Since I don't see any scope of improvement/tweaking in your approach, I suggest an alternative solution.

As pointed out in the comments, you can get what you want with Outlet Collections, since they are basically an array of UIKit objects, thus making it easy to manipulate them for our specific case.

Step 1

First off, connect your textfields to an Outlet Collection, and delegates in Interface Builder itself (as shown in the image below), which gets rid of the redundant

@IBOutlet var txtOTP1: UITextField!

and

txtOTP1.delegate = self

statements.

@IBOutlet var textFieldsOutletCollection: [UITextField]!

Step 2

We are going to use a dictionary with the textfield as the key and its corresponding index in the outlet collection as the value:

var textFieldsIndexes:[UITextField:Int] = [:]

override func viewDidLoad() {
    for index in 0 ..< textFieldsOutletCollection.count {
        textFieldsIndexes[textFieldsOutletCollection[index]] = index
    }
    super.viewDidLoad()
}

Step 3

The basic idea is, we can get the index of the textfield in our collection by supplying (to the dictionary) the textfield object we get in shouldChangeCharactersIn method, and then make the next or previous textfield the first responder:

enum Direction { case left, right }

func setNextResponder(_ index:Int?, direction:Direction) {

    guard let index = index else { return }

    if direction == .left {
        index == 0 ?
            (_ = textFieldsOutletCollection.first?.resignFirstResponder()) :
            (_ = textFieldsOutletCollection[(index - 1)].becomeFirstResponder())
    } else {
        index == textFieldsOutletCollection.count - 1 ?
            (_ = textFieldsOutletCollection.last?.resignFirstResponder()) :
            (_ = textFieldsOutletCollection[(index + 1)].becomeFirstResponder())
    }

}

Step 4

Now the shouldChangeCharactersIn method becomes more simple and clean:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if range.length == 0 {
        setNextResponder(textFieldsIndexes[textField], direction: .right)
        textField.text = string
        return true
    } else if range.length == 1 {
        setNextResponder(textFieldsIndexes[textField], direction: .left)
        textField.text = ""
        return false
    }
    return false
}

Final Code

With all the above code combined, your view controller should look like this:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textFieldsOutletCollection: [UITextField]!

    var textFieldsIndexes:[UITextField:Int] = [:]

    override func viewDidLoad() {
        super.viewDidLoad()
        for index in 0 ..< textFieldsOutletCollection.count {
            textFieldsIndexes[textFieldsOutletCollection[index]] = index
        }
    }

    enum Direction { case left, right }

    func setNextResponder(_ index:Int?, direction:Direction) {

        guard let index = index else { return }

        if direction == .left {
            index == 0 ?
                (_ = textFieldsOutletCollection.first?.resignFirstResponder()) :
                (_ = textFieldsOutletCollection[(index - 1)].becomeFirstResponder())
        } else {
            index == textFieldsOutletCollection.count - 1 ?
                (_ = textFieldsOutletCollection.last?.resignFirstResponder()) :
                (_ = textFieldsOutletCollection[(index + 1)].becomeFirstResponder())
        }

    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if range.length == 0 {
            textField.text = string
            setNextResponder(textFieldsIndexes[textField], direction: .right)
            return true
        } else if range.length == 1 {
            textField.text = ""
            setNextResponder(textFieldsIndexes[textField], direction: .left)
            return false
        }

        return false

    }

}

This method should theoretically work for infinite number of UITextFields with same amount of code as opposed to your approach, in which the amount of code is dependent on the number of textfields used, which is not handsome/pretty.


Indentation

To pick one example:

        for(int i=1;i<a;i++)
        {
            if(a%i==0)
        {
            sum+=i;
        }

What's going on here? My best guess would be that you're mixing tabs and spaces with a tabstop of 8. Be consistent: tabs or spaces. Changing the tabstop shouldn't break the formatting.

Names

    public static StringBuffer fact(int a)
    public static String isPrime(int a)
    public static int perfecrNo(int a)

What do these three methods do?

The first one produces a string containing the factors. Before reading the implementation I had guessed that it calculated the factorial. Name could be more descriptive: e.g. formatFactors.
The second one tests whether the number is a perfect number or not. The name is simply wrong: it claims that the method does something different to what it does. It should be e.g. isPerfectNumber.
The third one calculates the sum of the factors. The name certainly doesn't communicate that to me. It should be e.g. sumOfFactors (or aliquotSum if you don't mind the technical term).

Factoring out common code

All three of those methods have a loop which does the same thing: find the factors of a. That should be pulled out into a single method, which should have a suitable return type (e.g. Collection<Integer>, although there's a good case for Set<Integer>, or maybe some integer stream type, but I'm not up to date on Java 8).

Then two of the methods sum the factors: that's already pulled out into a method, so the other method shouldn't duplicate it. Instead you should have a very simple method

public static boolean isPerfectNumber(int a)
{
    return a == sumOfFactors(a);
}

Rethink method signatures

Why does fact return a StringBuffer? I can't think of many situations in which it makes sense to return a StringBuffer (or a StringBuilder). Either you're appending to a StringBuffer/StringBuilder, in which case it should almost always be an argument and doesn't need to be returned, or you aren't, in which case it makes more sense to return a String.

Why does isPrime (isPerfectNumber) return a string "true" or "false"? The boolean type exists for precisely the type of things which are true or false.


Object-oriented design of list of primes

As a general rule for classes: data members (variables), such as vPrime, should be private.  They can either be declared under private or outside of public (a class is private by default).
For a simple use of classes here, you don't need a mutator.  Just declare your object with an argument:

PrimeList primes(n);

Since this would make n (or let's just make it number) a data member, modify your constructor as such and initialize the object like this:

// 'n' is the parameter and 'number' is the class's data member
PrimeList::PrimeList(int n) : number(n) {initVector();}

As you can see, the constructor now calls initVector().  With number now as a data member, initVector() no longer needs an argument.  Since this function is not part of the interface, make it private.
The display for-loop in main() can also be put into a class method:

void display() const; // header declaration

// .cpp implementation

void PrimeList::display() const
{
    // your object is no longer referenced inside the class
    for (int i = 0; i < vPrime.size(); ++i)
    {
        std::cout << vPrime[i] << std::endl;
    }
}

Then simple call it in main() with your object:

primes.display();

Note the use of const fin this function.  If you're not changing any data members, create your functions as such.  If you accidentally violate this, your compiler will stop you.  This is to ensure that your data members are not unintentionally modified, depending on the functions's purpose.
Your sieve calculations can also be put into a class method.  Get the idea now?  Again, it should be private.  It will NOT be const since you're changing the vector inside the class.  You can call it in initVector() since they're both non-const (you cannot call const functions in non-const functions and vice-versa).


Setting receive_payment_on flag for employment applicants

Put your code into a method. So you get rid of the temporary variable, its cleaner and you can leave your method with a return as soon as you find the first true. (A break to leave the loop will have the same effect.)

In addition to that I'm a big friend of guard conditions. Invert if section[:applicants] ... end to if !section[:applicants] next, so you have one nesting level less.

...
config[:sections].each do |section|
   if !section[:applicants] next
   section[:applicants][:sections].each do |app_sec|
       if app_sec[:employment] && app_sec[:employment][:receive_payment_on]
           return true
       end
   end
end
return false


Your code is perfectly fine. Just a couple of comments:

It is bad-to-impossible to have any internal state in a View.

Actually SwiftUI was designed to handle state changes directly in a view. For simple cases you can easily do:
struct PageIndicator: View {
    @State private var currentPage = 0
    let numPages: Int = 5

    private let spacing: CGFloat = 2
    private let dotSize: CGFloat = 8

    var body: some View {
        VStack {
            HStack(alignment: .center, spacing: spacing) {
                ForEach(0 ..< numPages, id: \.self) {
                    DotIndicator(pageIndex: $0, isOn: self.$currentPage)
                        .frame(width: self.dotSize, height: self.dotSize)
                }
            }
        }
    }
}

PageIndicator(numPages: 5)

What's more sometimes an @ObservedObject may be reinitialised contrary to a @State property (unless you use a @StateObject available in SwiftUI 2.0).
For more information see: What is the difference between ObservedObject and StateObject in SwiftUI.

No logic in the View or so they say. Yet here and there in the code
samples I see ternary operators and loops.

True, but for simple cases creating a whole new ViewModel can actually make code less readable (as in the example above). Note that a ForEach loop is perfectly valid in a view.

Apart from the comments above you can use an Image(systemName:) instead of a Circle:
struct DotIndicator: View {
    let pageIndex: Int

    @Binding var isOn: Int

    var body: some View {
        Button(action: {
            self.isOn = self.pageIndex
        }) {
            Image(systemName: "circle.fill")
                .imageScale(.small)
                .scaleEffect(isOn == pageIndex ? 1.0 : 0.7)
                .animation(.spring())
        }
    }
}

Because a Circle consumes all available space, you need to constrain it with the .frame modifier. You don't have to do that with an Image - it reduces the code (dotSize is no longer needed) and scales automatically.


Submitting form using dynamic variable with query

A few things you could do to simplify the code:

Rather than examining every form field to determine if the form was submitted, a single check of say - the submit button - should suffice for most purposes.
Avoid using strings like "ALL" or "Choose:" for the form field values. Those are fine for display purposes, but the field values should be something more generic, like an empty string. That makes for simpler, more uniform, validation code.

For example, if the default is an empty string, a simple LEN() check is all you need to determine if a particular field was populated. (You can also use other boolean functions like IsNumeric or IsDate, when more appropriate).
Consider using cfparam to assign a default for all fields (except the submit button). That ensures the fields always exist, eliminating the need to use structKeyExists every time you access a field.
With the above changes, you could also simplify the WHERE clause logic. Start with an expression that is always true. Then add additional filters based on which form fields were populated.

NB: Using raw client supplied values in a queries puts your database at risk for sql injection. Always use cfqueryparam on all parameters. (I do not know the data types of your database columns, so modify the cfsqltype's as needed.)

<cfparam name="FORM.category_time" default="">
<cfparam name="FORM.date_month" default="">
...

<cfif structKeyExists(FORM, "submit")>

    <cfquery ....>
        SELECT Column1, Column2, ....
        FROM   work_timeline
        WHERE  1 = 1

        <!--- Filter on FORM.category_time when populated  --->
        <cfif LEN(FORM.category_time)>
            AND category_time = <cfqueryparam value="#FORM.category_time#" cfsqltype="cf_sql_integer">
        </cfif>

        <!--- Filter on FORM.date_month when populated --->
        <cfif LEN(FORM.date_month)>
            AND month(date_time) = <cfqueryparam value="#FORM.date_month#" cfsqltype="cf_sql_integer">
        </cfif>

        ... more cfif conditions
    </cfquery>
</cfif>

As an aside, regarding SQL

There is nothing technically wrong with using SELECT *, but in most cases it is preferable to supply a list of the columns you need. It makes the code a more readable, and also helps avoid pulling back extra data columns that are never used.
Using functions on an indexed database column usually prevents the database from utilizing the index. While it may not be feasible for your current query, when possible it is best to revise expressions like this:

WHERE month(column) = 12 AND year(column) = 2015

.. to use a more index friendly expression instead. For example:

   WHERE column >= '2015-12-01' -- Begin date at midnight
   AND   column <  '2016-01-01' -- Day AFTER end date at midnight


This is a legitimate substitution cipher, but it's not a Caesarean cipher. A Caesarian cipher affects only letters, and it's modulo the alphabet size: caesar 13 "Hello, world!" ⇒ "Urzzb, jbeyq!"

encode and decode can be the same function (caesar?) called with opposite shifts. (Or with the same shift, when it's 13.)

There's no need for a shift' helper.

  How can I write a function (through currying) that will subtract X from it?

(x -)


Since you are using NumPy, you should deal with grids the NumPy way instead of performing list comprehensions.

def probability_diff(x0, x1):
    probs = library_function(x0, x1)
    return probs[0] - probs[1]

results = np.vectorize(probability_diff)(X0[:, np.newaxis], X1)

I wouldn't try to get too clever with the lambdas.

Also, since the grid happens to be a square, you could use X0 again instead of defining X1.


find substring with count and return even frequency substring list

Your code is really hard to understand. When I read the description I noticed three steps:

Extract ID and message count.
Total duplicate message counts.
Return a round robin of these IDs.

You've got 1&2 mangled together, and 3 nicely by itself.

Since you're using Python, it's easier to read iterator based approaches to these things. Firstly you can replace your step 3 with a recipe from the itertools standard library. All you need to do is call itertools.repeat beforehand.

It's not immediately clear what your code is doing when you've mangled indexed iteration with business logic, with step 2 as well. And so I suggest re-writing it. You know the data will come in the form {type}{message}{amount}, where the type and amount has a length of 1, and message is either 2 or 3. And so to extract the messages and amounts you can just use next/islice on an iterator. Using a try while loop. After this totaling the message counts is simple.

Also if you're going to use typing you should use mypy too, and put type information on both the arguments and return types.

from typing import List, Iterator, Tuple, Sequence, TypeVar
    import itertools

MESSAGE_LENGTH = {
    'I': 3,
    'A': 2
}

TValue = TypeVar('TValue')

def roundrobin(*iterables: Tuple[Sequence[TValue], ...]) -> Iterator[TValue]:
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = itertools.cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = itertools.cycle(itertools.islice(nexts, num_active))

def extract_messages(input: Iterator[str]) -> Iterator[Tuple[str, int]]:
    input = iter(input)
    message_type = next(input)
    while True:
        length = MESSAGE_LENGTH[message_type]
        message = ''.join([message_type] + list(itertools.islice(input, length)))
        message_type = next(input)
        number = []
        try:
            while message_type not in MESSAGE_LENGTH:
                number += [message_type]
                message_type = next(input)
        except StopIteration:
            break
        finally:
            yield message, int(''.join(number))

def parse_message(string: str) -> List[str]:
    message_counts = {}
    for message, amount in extract_messages(string):
        message_counts.setdefault(message, 0)
        message_counts[message] += amount

    return list(roundrobin(*(
        itertools.repeat(key, amount)
        for key, amount in message_counts.items()
    )))

if __name__ == '__main__':
    print(parse_message('Akb2IAld3'))
    print(parse_message('Aqp1Iasd2Aqp4IAbd1'))
    print(parse_message('Aqp1Iasd2Aqp4IAbd10'))


Merging multiple JSON files using Python

First off, if you want reusability, turn this into a function. The function should have it's respective arguments.
Secondly, instead of allocating a variable to store all of the JSON data to write, I'd recommend directly writing the contents of each of the files directly to the merged file. This will help prevent issues with memory.
Finally, I just have a few nitpicky tips on your variable naming. Preferably, head should have a name more along the lines of merged_files, and you shouldn't be using f as an iterator variable. Something like json_file would be better.


I'm not familiar with the algorithm you've implemented. So I cannot point to improvements there. But some things in the code can be enhanced.

Use informative error messages. For instance, instead of:

    ...
    } catch (FileNotFoundException e) {
        System.out.println("file was not Found!");
    }
    ...

consider something like:

    ...
    } catch (FileNotFoundException e) {
        String detailedMessage =
               format("File [%s] was not found. Reason was [%s]!", "movies.dat", e.getMessage());
        // BTW "movies.dat" can be extracted into constant.
        System.out.println(detailedMessage);
    }
    ...

In the latter snippet you can see that error message includes detailed info about what really happened. And please note [] that surround variable data: such placeholders not only help to see corner cases in log (for example, when empty name of input file was specified by mistake) but do grep (or any other text search) efficiently.

Consider try-with-resources. That will reduce amount of boilerplate code when dealing with readers.

Move parsing logic, e.g.:

...
String[] tokenDelimiter = readFile.split("\\|");
String userID = tokenDelimiter[0];
String movieID = tokenDelimiter[1];
double rating = Double.parseDouble(tokenDelimiter[2]);
...

into separate helper method like it's already done for computeCosineSimilarity().

After all "little" improvements are done you will see the code more clearly. Then you can concentrate on the algorithm (e.g. on pure logic), add checks for corner cases (like empty input file), use strict math for floating point numbers, handle encoding of input files gracefully, improve overall processing speed for large files, etc.