Converting a ResourceSet of bitmaps into a sorted List

First of all let's try to make it more concise:

var zoomLevels = Properties.Resources.ResourceManager
    .GetResourceSet(CultureInfo.CurrentUICulture, true, true);
    .Cast<DictionaryEntry>()
    .Select(x => ParseZoomLevelAndNormalize(x.Key))
    .OrderBy(x => x);

Note that you do not need to create multiple temporary lists (not that you will ever note this waste) using ToList(). Also note that parsing code has been moved to a separate function. Let's talk about that...

static float ParseZoomLevelAndNormalize(object resourceName)
{
    string zoomLevel = Convert.ToString(resourceName).Substring(1);

    return Single.Parse(zoomLevel,
        NumberStyles.Number, CultureInfo.InvariantCulture) / 100;
}

If you do not thin it's clear enough then you should introduce separate functions to explain what it is doing:

var precalculatedMaps = new PrecalculatedMaps();
var zoomLevels = precalculatedMaps.ZoomLevels.Select(x => x / 100);

Where PrecalculatedMaps hides the implementation detail (now it's a resource file, in future might be a folder in file system). ZoomLevels property simply return a standard IEnumerable<float> of available zoom levels (in range [0...100]). Proof of concept:

sealed class PrecalculatedMaps
{
    public IEnumerable<float> ZoomLevels
    {
        get
        {
            if (_zoomLevels == null)
                _zoomLevels = ReadAvailableZoomLevels().OrderBy(x => x);

            return _zoomLevels;
        }
    }

    private IEnumerable<float> _zoomLevels;

    private static IEnumerable<float> ReadAvailableZoomLevels()
    {
        return Properties.Resources.ResourceManager
            .GetResourceSet(CultureInfo.CurrentUICulture, true, true);
            .Cast<DictionaryEntry>()
            .Select(x => ParseZoomLevel(x.Key));
    }

    private static float ParseZoomLevel(object resourceName)
    {
        string zoomLevel = Convert.ToString(resourceName).Substring(1);

        return Single.Parse(zoomLevel,
            NumberStyles.Number, CultureInfo.InvariantCulture);
    }
}

Note that here I made few assumptions which you can't ignore:

Resource names are valid numbers (otherwise Single.Parse() will throw an exception).
Numbers are formatted using en-US locale. In your code you're parsing using CultureInfo.CurrentCulture (the default if you do not specify any IFormatProvider). For integer numbers you will probably never have trouble but it's better to be sure, right?
There is always a leading underscore (that might be VS default but you can change resource name by hand). Do you want to handle the case? Change .Substring(1) with .TrimStart('_').
If you have only natural numbers then you can use NumberStyles.Integer instead of NumberStyles.Number (which allows decimals).

OK, that was about your actual code but let me say few words about the algorithm. Zooming an image is not an incredibly slow operation, I don't know how you did it and which technology you use for UI then I can't give you better ideas but:

You limit zooming to integer factors.
You can cache those generated images.
You can generate images only at special thresholds (for example 200%, 50%, 25%) leaving the exact scale in/out duty to UI controls (which are pretty good at this). This might not be applicable if your zoom algorithm is REALLY slow and undoubtedly better than canonical decimation/interpolation algorithms already in use.
You can debounce zoom requests to do not generate hundreds images when user is zooming from 100% to 10% and he's not interested in the intermediate images (leaving the duty to scale things to UI controls).


This can be improved and made more Pythonic.  First, there is the in and not in keyword, which you already know of as you used it.  Why not utilize that instead of doing two loops?
You will have to change the logic slightly:
def is_pangram(phrase):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    phraseLetters = ""
    for char in phrase:
       if char in alphabet:
            phraseLetters += char
    for char in alphabet:
        if char not in phrase:
            print phraseLetters, alphabet
            return False

    return True

I iterate over the letters in phrase, checking if they are in the alphabet, and add them to the phraseLetters string.  Then, I iterate over the alphabet and check whether each character is in the phrase.
This can be simplified even further if you are not interested in printing the letters that are in the phrase.  I would recommend cutting it down even further to this:
def is_pangram(phrase):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    for char in alphabet:
        if char not in phrase:
            return False

    return True

This way, you can check whether the phrase is a pangram without always printing to the screen, which is good for re-using the code later; you can then write another method to print the strings in the phrase and the alphabet.  Additionally, I would recommend printing the letters in phrase alphabetically so it is easy to see which letter is not in phrase, which will also make it easier for any potential debugging you have to do.
Edit:
Thanks to matsjoyce in the comments, you can simplify it even further to this:
def is_pangram(phrase):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    return not (set(alphabet) - set(phrase))

This way, you can even return the letters not in phrase for ease of reference by just removing the not keyword, but you would also have to change the name of the method as is_something implies a boolean value being returned.
Additionally, you should probably name alphabet in all caps to signify it is a constant variable.


Identifying first negative number in array of doubles

I believe the parameter names val and array are switched around.  An array shouldn't be a single variable, and a value shouldn't be an array.  Otherwise, the names themselves are okay.
It's preferred to index through a C-style array with an std::size_t, especially if the array size is larger than an int.  This could be helpful if you'll be working with very large numbers, although the recursion aspect here may render that unlikely.  Even if you're not, it's best to develop that habit.
This looks a bit misleading:

if(val[instance] < 0) return instance;
instance++;

At first, I thought the instance++ was missing indentation and belonged to the if statement.  To make this clearer, you could separate the two lines or, even better, have curly braces for the if statement.  The latter also helps with better maintainability.

if (val[instance] < 0)
{
    return instance;
}

instance++;

Again, some of the naming is misleading:

if(array < 1) return 0;

From a glance, that just looks incorrect as you cannot check an array like that.  Proper naming is very important, even for a small program like this.


Determining which vehicle Rob wants to buy

decimal [] max_array = {3000, 5000, 7000, 9000};  //max prices

Let's try something:

int[] maxPrices = {3000, 5000, 7000, 9000};

Or even:

var maxPrices = new[] {3000, 5000, 7000, 9000};

The cutoff prices in the problem statement are all integers, so you don't need to bother with a decimal and floating-point errors here. And since you're using an array initializer to initialize a local variable with a handful of integers, the type of maxPrices is obviously int[].

Notice also, that you stop needing the comments when the code can speak for itself: the informative and useful part of max_array is max - the rest of the useful meaning is hidden in a comment. Seeing // max prices next to a variable declaration tells me one thing: that this comment wouldn't need to be there if the variable was called maxPrices (notice camelCase).

Convention for locals and parameters, is camelCase. Your code suffers from a severe Notationis Hungarianum - symptoms being that d_ for "decimal", that s_ for "string" and that i_ for "integer". Don't do that. Here's why:

  vUsing adjHungarian nnotation vmakes nreading ncode adjdifficult.

  write a function using nested if/else statements

Your function is structured like this:

if
else if

for

if
else if
else if
else if
else

I see no nested if conditions. And you know what? That's awesome: nested ifs are usually not pretty, you'd normally want to avoid resorting to them.

Nested conditions would look like this:

if

if

if
else

else if

if
else

else

else

If doing that exercise should teach you one thing, it's to recognize that shape in your code. That shape has a name: it's arrow code, and it's usually not the code you want to be maintaining.

So, what then?

He will spend:

  up to $3000 for a 2000 or older model
  up to $5000 for a 2001-05 model
  up to $7000 for a 2006-09 model
  up to $9000 for a 2010 or newer model

Also, he:

  will not buy a red truck
  will pay 20% more for a white truck
  will pay no more than $10,000

I think I'd use the built-in Color enum, just because it's there and appropriate for this.

I'd first eliminate the red truck, and return early:

if (color == Color.Red || price > 10000) { return false; }

And your code does exactly that. Well done!

Now the fun part. You went with arrays, and a if..else if construct. The problem is that when you read the code you can't help but notice the [0], the [1], the [2] and the [3] one under the other, all in order.

If I could map a year to the maximum price I'm willing to pay for, my life would be much simpler!

var maxPrices = new Dictionary<int,int>
{
    { 2000, 3000 },
    { 2005, 5000 },
    { 2009, 7000 },
    { 9999, 9000 },
};

Then we can iterate the dictionary entries, return true and break out when the parameters compare favorably against the Key (year) and the Value (maximum price)

var result = false;
foreach(yearPrice in maxPrices.OrderBy(item => item.Key)) // note: item.Key is the year
{
    var maxPrice = yearPrice.Value;
    if (color == Color.White)
    {
        maxPrice *= 1.2;
    }

    if (year <= yearPrice.Key && price <= maxPrice)
    {
        result = true;
        break;
    }
}
return result;

I don't understand the requirement for nested if statements. Specs usually tell you what to do, not how to do it. And imposing nested constructs (or anything really) sounds like some kind of "coding game" - however if you want to be writing professional code, that isn't the kind of code you want to be writing. Or rather, maintaining.


Any comments are welcomed, but I am mostly annoyed by terminalNode

From my opinion, it's more natural to provide default values for case classes:

case class Node[+T](value: T, left: Option[Node[T]] = None, right: Option[Node[T]] = None) {//...

Then you can simply use Node(42) anywhere in your code.

  Node looks like a monad. Could I get all other operations such as flatMap and foldLeft for free somehow?

Typically, any methods in Monads are based on flatMap and unit methods. Therefore you need to implement flatMap method, as unit method you already have (Node.apply).

flatMap needs to accept a method, which returns new instance of Node, e.g. def flatMap[V](f: T => Node[V]): Node[V]. Then it should look like the following:

def flatMap[V](f: T => Node[V]): Node[V] = {
    f(value).copy(
      left = left.map(_.flatMap(f)),
      right = right.map(_.flatMap(f))
    )
}

And it you create a new test, it produce the same output, as for map:

println("map: " + tree1.map(i => s"Hello$i"))
println("fmap: " + tree1.flatMap(i => Node(s"Hello$i"))) //will be the same outputs

But, you should handle cases, when f(value) may return new node with existing left and/or right values, otherwise the implementation above may override the result. You need to consider this in your final implementation.

Then, according to the rule of map, it can be present as map(f) = fmap unit f, so you can create method map2 with flatMap:

def map2[V](f: T => V): Node[V] =
  flatMap(t => Node(f(t)))

Then you will have the same outputs:

println("map: " + tree1.map(i => s"Hello$i"))
println("map2: " + tree1.map2(i => s"Hello$i")) //will be the same outputs

Regarding foldLeft: typically you can almost everything implement with foldLeft, but not otherwise. So we need to understand, what foldLeft should do (DSF?), and then we can express other methods with this.

Also couple notes, I'd change (it's arguable, of course, but worth considering):

Instead of left.map(l => l.map(f) I'd use left.map(_.map(f))
tree.map(t => (output = t :: output)) this can be replaced with mutable ArrayBuffer for 2 reasons: it should be slightly faster and slightly more well-looking.

Consider this code:

 def dfs2[T](tree: Node[T]): List[T] = {
   val output = ArrayBuffer[T]()
   tree.map(output += _)
   output.toList
 }

And outputs again will be the same:

println("dfs: " + dfs(tree1))
println("dfs2: " + dfs2(tree1)) //will be the same outputs

Hope that helps.


Displaying API results inside a WordPress page template

I see three things

I'm not too terribly familiar with custom wordpress tempaltes, but I'm fairly certain you shouldn avoid doing the API logic in the view. You should call the API in a controller and pass the result to the view, if at all possible. This is a standard separation of concerns.

Additionally, you shouldn't assume the API call will work. If they're server or dns has issues, or they make a breaking change to their API, you should handle it gracefully and inform the user that there are issues. Right now it appears foreach($response->body->members as $member) would fail if the API failed.

Finally, it's a good idea to keep the "Basic KEY" in a config or something, so you don't need to touch the code to update the key.


Highlight the active link in a navigation menu

querySelectorAll

Here's another approach, if you don't mind older browsers. You can use querySelectorAll instead of document.links. That way, you end up with a smaller result set rather than all links, and save you CPU cycles for running the loop.

In this case, we get only those links that have the same href value as the current document url:

var links = document.querySelectorAll('a[href="'+document.URL+'"]');

However, note the browser compatibility and there are quirks across implementations.

Not all links need active

Now if you think about it, not all links with the document.URL need to have active. Say you have active set the font to 2em. If you get all links that point to the same page, they'd be 2em in size, regardless of where they are in the page!

Most likely, you only need it for the primary navigation. Consider adding a class to further refine the result set.

Home

News

Contact

About

// Getting only the links that are in .navigation
var links = document.querySelectorAll('.navigation a[href="'+document.URL+'"]');

// More specific CSS
.navigation a.active {background:red;}

className

Now you have to note that setting className replaces it with the value, like this example. If the links you have happen to have existing classes (and styles that come with them), your script will unintentionally remove their styles due to the replaced className.

What you can do is get the existing className value, split them by spaces (multiple class names are separated by spaces), append your class name, join them back and then change the value, like I did here:

var element = document.getElementById('change');
var classNames = element.className.split(' ');
classNames.push('huge');
element.className = classNames.join(' ');


There are several problems with your code.

Style

is-prime is C/Java style. Lispers use primep or prime-number-p.
zerop is clearer than (= 0 ...).
Lispers use indentation, not paren counting, to read code.  Your
code is thus virtually unreadable.  Please use Emacs if you are
unsure how to format lisp properly.

Stack overflow

is-prime is tail-recursive, so if you compile it, it should become a
simple loop and there should be no stack issues.

However, do not rush with it yet.

Algorithm

Number of iterations

Let us use trace to see the
problems:

> (prime-factors 17)
1. Trace: (IS-PRIME '17)
2. Trace: (IS-PRIME '17 '15)
3. Trace: (IS-PRIME '17 '14)
4. Trace: (IS-PRIME '17 '13)
5. Trace: (IS-PRIME '17 '12)
6. Trace: (IS-PRIME '17 '11)
7. Trace: (IS-PRIME '17 '10)
8. Trace: (IS-PRIME '17 '9)
9. Trace: (IS-PRIME '17 '8)
10. Trace: (IS-PRIME '17 '7)
11. Trace: (IS-PRIME '17 '6)
12. Trace: (IS-PRIME '17 '5)
13. Trace: (IS-PRIME '17 '4)
14. Trace: (IS-PRIME '17 '3)
15. Trace: (IS-PRIME '17 '2)
16. Trace: (IS-PRIME '17 '1)
16. Trace: IS-PRIME ==> T
15. Trace: IS-PRIME ==> T
14. Trace: IS-PRIME ==> T
13. Trace: IS-PRIME ==> T
12. Trace: IS-PRIME ==> T
11. Trace: IS-PRIME ==> T
10. Trace: IS-PRIME ==> T
9. Trace: IS-PRIME ==> T
8. Trace: IS-PRIME ==> T
7. Trace: IS-PRIME ==> T
6. Trace: IS-PRIME ==> T
5. Trace: IS-PRIME ==> T
4. Trace: IS-PRIME ==> T
3. Trace: IS-PRIME ==> T
2. Trace: IS-PRIME ==> T
1. Trace: IS-PRIME ==> T
(17)

You do 17 iterations when only (isqrt 17) = 4 iterations are necessary.

Recalculations

Now compile is-prime to turn recursion into a loop and see:

> (prime-factors 12345)
1. Trace: (IS-PRIME '12345)
1. Trace: IS-PRIME ==> NIL
1. Trace: (IS-PRIME '2)
1. Trace: IS-PRIME ==> T
1. Trace: (IS-PRIME '12345)
1. Trace: IS-PRIME ==> NIL
1. Trace: (IS-PRIME '3)
1. Trace: IS-PRIME ==> T
1. Trace: (IS-PRIME '4115)
1. Trace: IS-PRIME ==> NIL
1. Trace: (IS-PRIME '3)
1. Trace: IS-PRIME ==> T
1. Trace: (IS-PRIME '4115)
1. Trace: IS-PRIME ==> NIL
1. Trace: (IS-PRIME '4)
1. Trace: IS-PRIME ==> NIL
1. Trace: (IS-PRIME '4115)
1. Trace: IS-PRIME ==> NIL
1. Trace: (IS-PRIME '5)
1. Trace: IS-PRIME ==> T
1. Trace: (IS-PRIME '823)
1. Trace: IS-PRIME ==> T
(3 5 823)

You are checking the primality of the same numbers several times!

Extra optimization

primep can find a divisor, not just check primality.

Optimized algorithm

(defun compositep (n &optional (d (isqrt n)))
  "If n is composite, return a divisor.
Assumes n is not divisible by anything over d."
  (and (> n 1)
       (> d 1)
       (if (zerop (rem n d))
           d
           (compositep n (- d 1)))))

(defun prime-decomposition (n)
  "Return the prime decomposition of n."
  (let ((f (compositep n)))
    (if f
        (nconc (prime-decomposition (/ n f))
               (prime-decomposition f))
        (list n))))

Note that one final optimization is possible -
memoization of
compositep:

(let ((known-composites (make-hash-table)))
  (defun compositep (n &optional (d (isqrt n)))
    "If n is composite, return a divisor.
Assumes n is not divisible by anything over d."
    (multiple-value-bind (value found-p) (gethash n known-composites)
      (if found-p
          value
          (setf (gethash n known-composites)
                (and (> n 1)
                     (> d 1)
                     (if (zerop (rem n d))
                         d
                         (compositep n (- d 1)))))))))

or, better yet, of prime-decomposition:

(let ((known-decompositions (make-hash-table)))
  (defun prime-decomposition (n)
    "Return the prime decomposition of n."
    (or (gethash n known-decompositions)
        (setf (gethash n known-decompositions)
              (let ((f (compositep n)))
                (if f
                    (append (prime-decomposition (/ n f))
                            (prime-decomposition f))
                    (list n)))))))

note the use or append instead of
nconc.

Another interesting optimization is changing the iteration in
compositep from descending to ascending.
This should speedup it up considerably as it would terminate early more
often:

(let ((known-composites (make-hash-table)))
  (defun compositep (n)
    "If n is composite, return a divisor.
Assumes n is not divisible by anything over d."
    (multiple-value-bind (value found-p) (gethash n known-composites)
      (if found-p
          value
          (setf (gethash n known-composites)
                (loop for d from 2 to (isqrt n)
                  when (zerop (rem n d))
                  return d))))))

PS. This is identical to https://stackoverflow.com/a/49369108/850781


Creating a percentage complete method for a form

Looking only at your last block:

Why return the string "0" instead of the number?
The hard coded array is cryptic, and a potential maintenance hassle. I'd recommend moving it to a method on the Score model to abstract things.
The hardcoded 100/6.0 is basically a magic number. It'd be better to get the length of whatever array you're working with than assume it's always 6.
Why is @status an instance variable? Your method is meant to return something. If it returns at the first return line, you never even set @status to anything, which'll lead to errors later on, if you expect it to be set. Conversely, if you don't expect it to be set, or don't intend to use it, why set it?

I imagine you could do something like this:

def percent_complete(user, patient)
  score = Score.where(user_id: user.id, patient_id: self.id).first
  return 0 if score.nil? || score.steps.empty?
  100.0 * score.completed_steps.length / score.steps.length
end

where Score#steps and Score#completed_steps look like:

def steps
  [dx1, dxcon1, db1, dbcon1, biopsy, mgt]
end

def completed_steps
  steps.reject(&:blank)
end


Couple of things I noticed:

When you connect to the database, you don't check that the connection succeeded. The most common way I've seen to do this in Perl is:

my $connect = DBI->connect($dsn, $username, $password)
   or die "Connection Error:  DBI::errstr\n";

If the connection fails, the program will then display the connection failure message so you can see what's going on.

I see that you use two different ways of accessing the database. It would be better to pick one and use it for all your inserts/updates unless there is a compelling reason not to - it keeps future readers from trying to figure out why you did it differently. In this case I'd reccomend using execute since it allows you to execute multiple times:

$query_handle = $connect->prepare("INSERT INTO dbtable (id, demo) VALUES (?, ?)");
$query_handle->execute($id, $demo);
$id = 2;
$demo = "test2";
$query_handle->execute($id, $demo);

Also don't forget to disconnect:

$connect->disconnect;


Remove an event listener after firing once or any number of times

Consider using event.currentTarget instead of event.target, since your handlers are probably bound to an ancestor element, not the current element.


Your code was very readable and easy to follow. Most of my suggestions center around trying to showcase some more Rust idioms and features.

A collection of registers in normally called a register file.
Since the constant for the number of registers is only used to declare the register file, create a type alias and use that. This sets you up nicely to make it a standalone type in the future.
I'm glad to see names for registers in Instruction, but maybe give them more meaningful names? Add is a great example - which registers are the inputs and which is the output?
You almost always want to derive Debug for a type. Copy and Clone are also very common. Implementing PartialEq will allow easier test writing.
There's a distinct lack of types and methods, overall the code feels pretty C-like. I'd associate functions with types, making them methods. For example, decode is the most obvious change to me.
Returning an Option from decode is iffy. Failing to decode an instruction doesn't seem like the absence of a value, it feels like a failure, which is normally reserved for Result.
When splitting match arms onto a different line from the pattern, use braces.
Consider inlining some of the instruction implementations into execute as many are only one line long anyway.
In a processor, it's very typical to automatically increment the program counter every instruction. Branch offsets take that automatic increment into account. This is nice here because it removes pc from all the non-branching methods. I just subtracted 1 when applying the jump, but it's probably better to fixup the offsets.
Create a type for sequences of instructions, I used Program. This will give you somewhere to hang fetch.

type RegisterFile = [u16; 3];

#[derive(Debug, Copy, Clone)]
enum Instruction {
    Halt,
    Load { reg: usize, value: u16 },
    Swap { reg1: usize, reg2: usize, reg3: usize },
    Add { reg1: usize, reg2: usize, reg3: usize },
    Branch { offset: usize }
}

impl Instruction {
    fn decode(encoded_instruction: u16) -> Option<Self> {
        let operator = encoded_instruction >> 12;
        let reg1 = ((encoded_instruction >> 8) & 0xF) as usize;
        let reg2 = ((encoded_instruction >> 4) & 0xF) as usize;
        let reg3 = (encoded_instruction & 0xF) as usize;
        let offset = (encoded_instruction & 0xFFF) as usize;
        let value = encoded_instruction & 0xFF;

        match operator {
            0 => Some(Instruction::Halt),
            1 => Some(Instruction::Load { reg: reg1, value: value }),
            2 => Some(Instruction::Swap { reg1: reg1, reg2: reg2, reg3: reg3 }),
            3 => Some(Instruction::Add { reg1: reg1, reg2: reg2, reg3: reg3 }),
            4 => Some(Instruction::Branch { offset: offset }),
            _ => None,
        }
    }

    fn execute(&self, registers: &mut [u16], pc: &mut usize) -> bool {
        match *self {
            Instruction::Load { reg, value } => {
                load(reg, value, registers);
            },
            Instruction::Swap { reg1, reg2, reg3 } => {
                swap(reg1, reg2, reg3, registers);
            },
            Instruction::Add { reg1, reg2, reg3 } => {
                add(reg1, reg2, reg3, registers);
            },
            Instruction::Branch { offset } => {
                branch(offset, pc);
            },
            Instruction::Halt => {
                halt(registers);
                return false;
            },
        }

        true
    }
}

fn halt(register_file: &[u16]) {
    println!("{:?}", register_file[0]);
}

fn load(register: usize, value: u16, register_file: &mut [u16]) {
    register_file[register] = value;
}

fn swap(reg1: usize, reg2: usize, reg3: usize, register_file: &mut [u16]) {
    register_file[reg3] = register_file[reg1];
    register_file[reg1] = register_file[reg2];
    register_file[reg2] = register_file[reg3];
}

fn add(reg1: usize, reg2: usize, reg3: usize, register_file: &mut [u16]) {
    register_file[reg3] = register_file[reg1] + register_file[reg2];
}

fn branch(offset: usize, pc: &mut usize) {
    *pc -= offset - 1;
}

struct Program<'a> {
    instructions: &'a [u16],
}

impl<'a> Program<'a> {
    fn fetch(&self, pc: usize) -> u16 {
        self.instructions[pc]
    }
}

fn cpu(program: Program) {
    let mut pc = 0;
    let mut registers = RegisterFile::default();

    loop {
        let encoded_instruction = program.fetch(pc);
        let decoded_instruction = Instruction::decode(encoded_instruction);

        match decoded_instruction {
            Some(instr) => {
                if !instr.execute(&mut registers, &mut pc) { break }
            }
            None => break,
        }

        pc += 1;
    }
}

fn main() {
    let encoded_instructions = Program { instructions: &[0x1110, 0x2100, 0x3010, 0x0] };

    cpu(encoded_instructions);
}


Include (only) what you use
Users of Server.h don't need most of those headers; they can be reduced to
#include <string>

You might need some of the other headers in the implementation, but try to avoid polluting users' namespaces (and slowing their compilations).
Consider adding daemonize code
Most servers want to be able to daemonize before they start - provide a facility to do the forking and dissociation of controlling terminal and the rest.  Make sure it's optional, so users can run in foreground if they want (e.g. for debugging, or when controlled by a supervisor like systemd).
Report errors back to caller
Consider this code:
    if(newsockfd < 0){
        perror("Error: Failed to connect to incoming connection.\n");
    }

This prints a message to stderr, and then keeps going.  How does the server (subclass) know that we failed?  What if we want to syslog the failure?  It's better to communicate this information in return value or an exception, so the application can take the right action - here, in a library, we don't know what's appropriate, nor whether standard error stream is even available to us.


First attempt incorporating backbone.js in my code

Alternative Approach:

In your case, I believe that the use of a model is not really necessary for this task.  I would construct this using a master view with child views for each step:

A TourView that contains a variable tracking which step is currently active and listenting for an event from it's child views for navigation.

A TourStep1View .. TourStepNView for each step of the tutorial whose render function contains corresponding show and close function contains the hide.

Launch the TourView and have it render a child view for the first step.  The child view should throw an event to signal the parent view to swap it out for the next child view.


Here are some tips.

1) Have a function that returns the grade value.

This helps avoid duplicated code and increases readablilty.

Code:

function getGradeValue($val){
  switch ($val) {
  case "K":
    $val = 0;
    break;
  case "Adult":
    $val = 13;
    break;
  default:
  }
  return $val;
}

2) Create a function to retrieve the final output.

This allow for an easier way to test the overall functionality and helps to eliminate global variables.

3) Create unit tests to speed up testing

Simple Testcases:

function println( $str ){
  print( $str . "<br/>\n" );
}
function testThis( $arr, $expect ){
  $result = getGroupedGradesAsString( $arr );
  if( $result == $expect ){
    println( "Passed:" );
  }else{
    println( "Fail:" . $result . " != " . $expect );
  }
}
testThis( array("K", 1, 2, 3, 5, 6, 7, 10, 11, "Adult"), "K - 3, 5 - 7, 10 - 11, Adult" );
testThis( array("K"),  "K" );
testThis( array("K", "Adult"),  "K, Adult" );
testThis( array("K", 1, 2, 7, 11, 12), "K - 2, 7, 11 - 12" );
testThis( array( 6, 7, 8), "6 - 8" );
testThis( array("K", 2, 4, 6, 8, 10, 12), "K, 2, 4, 6, 8, 10, 12" );
testThis( array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, "Adult"),  "1 - Adult" );

4) Use a loop to find the last consistent number.

Refer to getGroupedGradesAsString() in the final code for more information.

Final Code:

<?php
// By Larry Battle [http://bateru.com/news/]
function getGradeValue($val){
  switch ($val) {
  case "K":
    $val = 0;
    break;
  case "Adult":
    $val = 13;
    break;
  default:
  }
  return $val;
}
function getGroupedGradesAsString($arr) {
  $output = "";
  for ($i = 0, $len = count($arr); $i < $len; $i++) {
    $output .= (($i) ? ", " : "" ) . $arr[$i];
    if( getGradeValue($arr[$i]) == getGradeValue($arr[$i+1])-1 ){
      do{
        $i++;
      }while( getGradeValue($arr[$i]) == getGradeValue($arr[$i+1])-1);
      $output .= " - " . $arr[$i];
    }
  }
  return $output;
}
?>

Demo here: http://codepad.org/zi8oavlv

Here's a shorter version but might be a litter bit harder to understand.

<?php
    // By Larry Battle [http://bateru.com/news/]
function getGradeValue($val){
    return ( $val == "K" || $val == "Adult" ) ? (($val == "K") ? 0 : 13 ) : $val;
}
function getGroupedGradesAsString($arr) {
  $output = "";
  for ($i = 0, $len = count($arr); $i < $len; $i++) {
    $output .= (($i) ? ", " : "" ) . $arr[$i];
    if( getGradeValue($arr[$i]) !== getGradeValue($arr[$i+1])-1 ){
        continue;
    }
    while( getGradeValue($arr[++$i]) === getGradeValue($arr[$i+1])-1);
    $output .= " - " . $arr[$i];
  }
  return $output;
}
?>


Summing digits of an alphanumeric string

Your question is surprising in the sense that you use the somewhat obscure isDigit method (not many people are aware of that one), yet you do not use the similar Character.getNumericValue(...) method.

Using that method, you can remove the second loop (as you suspected). It also answers the second question - there is no need for a StringBuilder, or the int conversion:

int total = 0;
for (char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
        total += Character.getNumericValue(c);
    }
}
return total;


Find the missing number and repeated number

Removing trailing whitespace, renaming variables, reordering the code to group statements about the same concepts and introducing temporary variable to avoid writing and computing the same expressions multiple times and adding comments:

def repeat_num_and_missing_num(array):
    """ Return the value of repeated number and missing number in the given array
    using the standard formulaes of Sum of n Natural numbers and sum of squares of n Natural Numbers"""

    sum_of_num = 0
    sum_of_squares = 0
    for num in array:
        sum_of_num += num
        sum_of_squares += num*num

    x = len(array)
    sum_of_num_expected = (x * (x+1)) / 2
    sum_of_squares_expected = ((x) * (x+1) * (2*x+1)) / 6

    # Assuming A is present twice and B is missing:
    # B - A
    b_minus_a = sum_of_num_expected - sum_of_num
    # B^2 - A^2 = (B-A) * (B+A)
    b2_minus_a2 = sum_of_squares_expected - sum_of_squares
    # B + A
    b_plus_a = b2_minus_a2 / b_minus_a

    a = (b_plus_a - b_minus_a) / 2
    b = (b_plus_a + b_minus_a) / 2
    return a, b


Trie Data Structure Implementation in C++11 using Smart Pointers

Your include guard might clash with another file.  After all, you used an outer namespace because the name is not unique enough; the same is true for the header.  Suggest you use a UUID for that, and also #pragma once .  (Personally, I chose to use the pragma only with the idea that if I ever need guards they can be mechanically generated, all correctly.  But all the major platforms take the pragma so I never needed guards.)

#define ALPHABET_SIZE 26

Noooo…  Don’t use #define for simple constants, especially in a header file!

Let’s look at your node constructor:

(and what's with all the this-> on every member access?)

this->end = false;

You should not be assigning initial values in the constructor.  You should initialize things.  Here, you can simply use an inline initializer on the data member declaration, and be done with it.

// data member
bool end = false;

Continuing with the node constructor:

for (int i = 0; i < ALPHABET_SIZE; i++) {
      this->children[i] = NULL;

Wow!  Lots to go over here.

First, don’t use NULL.  Not ever!  If you are writing in C++11, it is dead and should be forgotten about.

Second, don’t write legacy for loops to go over a collection.  Use the range-for form instead.

for (auto el : children)
    el.reset();

Third, don’t write loops at all if you can use algorithms.

std::fill (std::begin(children), std::end(children), nullptr);

but I don’t like the need to give two separate points like that when I just want the whole thing.  The std algorithms are behind in this respect.  But, we have Boost as a proving ground for library stuff that we want to add to the standard or simply make commonly used:  (see doc page)

boost::fill (children, nullptr);

But… just don't!  A shared_ptr is automatically initialized to the empty state, which means the constructor is already doing this before the body of your code is run!

So, add the inline initializer for end, and then delete the entire constructor.

Now look at the constructor for tree.

Same thing:  don’t assign in the body, but initialize members.  The inline member init will work fine here.

// data member of tree
std::shared_ptr<node> root = std::make_shared<node>();

and then delete the whole tree() constructor function.

tree::insert

In C++ (unlike C) the style is to put the * or & of the type with the type, not the name being defined.  So write string& name not string &name.

Use auto (almost everywhere).

auto n = root;

For the for loop, the same comments as before.  Stop thinking of index numbers into an array or other collection that then need to be subscripted.  Rather, think about iterator positions in any kind of collection, or constructs that do the traversal and just give you a reference to the item to work on.

So, no i.

for (auto ch : key) {

Don’t compare pointers (or smart pointers) against null.  They have a truth value that works for this directly.

Remember you can make a reference (an alias) to any part of your data, so don’t repeat children[index] three times.

auto& slot = n->children[index];
if (!slot)  slot = make_shared<node>();
n= slot;

Similar for search.
Returning a const bool doesn’t do anything; just return bool.
At the end of that function, testing against true is just silly.  It is already a bool!  What value does it hold?  true.

Also, not explicitly testing against nullptr here helps you see how the idiom works well for guarding the real test:

return n && n->end;

Oh, and don’t put redundant parenthesis around return values.

BTW, your algorithm and approach is quite sound.  It’s only the C++ language fluency and idioms that I commented on.


To decode binary data, use struct.unpack().

>>> import struct
>>> byte_range = bytearray(b'\x85W\xe2\xa2I')
>>> date_header, timestamp = struct.unpack('>BL', byte_range)
>>> date_header
133
>>> timestamp
1474470473


Find All Permutations of String in Scala

The code looks to be correct, yes, the testing looks good too.  I was
thinking whether List(List()) for the input List() makes sense, but
it seems like that's a sensible output.
For the code readability I'd rename str, especially since it's not
really a string, but a list.  The complicated match expression in
permutations can just be simplified to case _ and in the body the
original argument can be reused again.
I'd also inline shifteds value since it's just a single call and the
name doesn't really tell me anything.  On that note, docstrings for the
functions might be a nice touch, especially for the shift and shiftN
methods.
The unused case labels can also just be _ everywhere.  Depends of
course, for me this makes it clearer that really there's always just two
cases, either matching an empty list, or a non-empty one, there's no
third case.
Would look like this then:
object Permutations {
  def permutations[A](list: List[A]): List[List[A]] =
    list match {
      case Nil => List(Nil)
      case _ =>
        shiftN(list, list.length).flatMap {
          case head :: tail =>
            permutations(tail).map(head :: _)
          case _ => Nil
        }
    }

  def shiftN[A](list: List[A], n: Int): List[List[A]] = {
    if (n <= 0) Nil
    else {
      val shifted: List[A] = shift(list)
      shifted :: shiftN(shifted, n - 1)
    }
  }

  def shift[A](list: List[A]): List[A] = list match {
    case head :: tail => tail ++ List(head)
    case _ => Nil
  }
}

Lastly, performance-wise it depends what your constraints are: For
List input and List output, restricting it to single linked lists,
this is fine, though I haven't benchmarked them of
course.  Potentially converting the shifted :: shiftN(...) call into
using an accumulator might be worth a bit, instead of having a deep call
stack, but again, it'll probably only matter for longer inputs.
But there are way quicker algorithms, though you might want to copy the
input into a vector that can be accessed in constant time for each
index.  (I found the
QuickPerm algorithm, as explained here
absolutely straightforward to implement from scratch.)


The main issue I have with your approach is that it is non-standard and purely for the way that you work.  Others looking at your code may be a bit confused as to what you are doing and why.  In your example, there is (IMHO) little benefit in being able to fold the code as there is not really enough code to need to fold the code up, but in larger code segments there may be a use for it.

For me - it looks as though you are in the initial stages of identifying logically grouped functionality within your code, something that could then be extended by extracting these logical groups into new class methods.

The exact approach I would take depends on how much other processing you have with the cart either pre or post this main chunk of code.

If there is a lot of other processing around what the cart does, then you could just pass the cart and the request to a new method and get something like...

class CartController extends Controller
{
    public function create(Request $request)
    {
        $cart = new Cart;

        $this->setCartFields ( $cart, $request );

        $cart->save();
    }

    private function setCartFields ( Cart $cart, Request $request ) {
        $cart->field1 = $request->field1;
        $cart->field2 = $request->field2;
        $cart->field3 = $request->field3;
        $cart->field4 = $request->field4;
        $cart->field5 = $request->field5;
        $cart->field6 = $request->field6;
    }
}

If the data from the request forms the basis of the data for the cart, then this could instead create it's own cart, initialise the data and return the newly created cart for further processing...

class CartController extends Controller
{
    public function create(Request $request)
    {

        $cart = createCart ( $request );

        $cart->save();
    }

    private function createCart ( Request $request ) : Cart {
        $cart = new Cart;
        $cart->field1 = $request->field1;
        $cart->field2 = $request->field2;
        $cart->field3 = $request->field3;
        $cart->field4 = $request->field4;
        $cart->field5 = $request->field5;
        $cart->field6 = $request->field6;

        return $cart;
    }

}

The problem being that you could eventually end up with all of the processing in the newly created method and rather than relieve the problem you have just moved it.  This is only something you can decide on a per instance basis.


Why do you create named temporary files within your named temporary directory? The whole directory (including its contents) will be deleted as soon as the context ends.

So, just create a fixed (or random if you want to) number of zero byte files in that directory:

import os
import tempfile

...

with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary directory\n', tmpdirname)
    n = 34 # create 34 files
    for i in range(n):
        open(os.path.join(tmpdirname, str(i)), "w").close() # create the empty file
    print('created', n, 'files')
    self.assertEqual(n, f.count_files(tmpdirname))


Triggering a callback when user put in the Konami cheat code anywhere in the page

You clone an array 3 times by using:

currentSequence = Array.prototype.slice.call(konamiSequence);

but with ES6, you can also use the spread operator to clone an array:

currentSequence = [... konamiSequence];

It took me a while to figure out the complex outer construction in your code:

const {onKonamiSequenceTriggered, clearKonamiSequanceTriggered} = (() => {

    .... actual code ...

    return {
        onKonamiSequenceTriggered,
        clearKonamiSequanceTriggered
    };
})();

It is an object destructuring assignment which is assigned two methods by using a self-executing anonymous function. I guess the advantage is that you can use local scope within the anonymous function. Note that you could leave out all of the code, in the excerpt above, and your code would still work, albeit completely in global scope.

I did find code on Stack Overflow which looks similar, but it is obviously not the same.

I'm not an Javascript expert, so that's all I have. I learned something from this, but I still think that Javascript has some awful language constructs (in other words: I'm not used to it).


Simple k-means implemention using Python3 and Pandas

You have a few problems with your documentation.

First off, your documentation is incomplete in a few places.

For example, in your corrpairs function, you didn't fill in any of your documentation, except for the rtype part.

And, in your kcluster function, you only filled in type rows, type k, and rtype.

Finally, also in kcluster, you called the parameter "rows" in the documentation and called it "cols" in the function signature. Choose one and stick with it.

Documentation is a very important part of every function.

import pdb
def kcluster(cols, k=4):

You should not have an import in the middle of your code; all the importing should be done at the very top of your code like you were doing before.

This review was just mean to point out practices. I had trouble understanding the content of the code (a better documentation probably would've helped).


Rust recursion pattern in simple cat program

Where clauses go on separate lines; easier to see them as they change the functionality so much.
Move the actual argument skipping near to the comment.
There's no need to call eq; use == instead.
String::as_str can often be avoided, just take a reference via &.
The code always builds the failure string, even when it doesn't fail! To avoid this, use unwrap_or_else, which allows access to the specific error as a closure argument.
Similarly, the code always gets Path::display, even when there is no failure.
There's no need to get the display anyway, the code already has the user-provided arg.
There's no need for Path at all; strings are convertable to OsStr, which is what File::open needs.
The name argument and the Method enum are always correlated one-to-one and they should be combined.
The error text in cat_recursive is incorrect; the file / stdin are already open, this error denotes failure to read from it.
Remove useless comments ("recurse"). As an aside, it was pointed out to me many years ago that the verb form is "recur", and an algorithm is "recursive"; "recurse" isn't really a word.
If you are going to document a function, use Rustdoc formatting.
If you are going to document an argument that is a standalone type, consider documenting the type instead. This is one reason to have types at all - to has a package of related meaning.

use std::{env, io};
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;

const STDIN: &'static str = "-";
const BUFFER_SIZE: usize = 4096;

/// Read line-by-line or to read the entire input
enum Method<'a> {
    File(&'a str),
    Line,
}

impl<'a> Method<'a> {
    fn name(&self) -> &str {
        match *self {
            Method::File(name) => name,
            Method::Line => "stdin",
        }
    }
}

fn main() {
    // skip the first element as it is the program name
    let args = env::args().skip(1);
    if args.len() == 0 {
        cat(io::stdin(), Method::Line);
    } else {
        for arg in args {
            if arg == STDIN {
                cat(io::stdin(), Method::Line);
            } else {
                let file = File::open(&arg)
                    .unwrap_or_else(|e| panic!("cat: failed to open {}: {}", &arg, e));
                cat(file, Method::File(&arg));
            }
        }
    }
    io::stdout().flush().unwrap();
}

/// Read from `input` and print to stdout.
fn cat<R>(input: R, m: Method)
    where R: Read,
{
    let mut reader = BufReader::with_capacity(BUFFER_SIZE, input);
    cat_recursive(&mut reader, m);
}

fn cat_recursive<R>(reader: &mut BufReader<R>, m: Method)
    where R: Read,
{
    let mut s = String::new();
    let n = match m {
        Method::Line => reader.read_line(&mut s),
        Method::File(..) => reader.read_to_string(&mut s),
    };
    let n = n.unwrap_or_else(|e| panic!("cat: failed to read {}: {}", m.name(), e));
    if n > 0 {
        print!("{}", s);
        cat_recursive(reader, m);
    }
}

The big points

The algorithm isn't really recursive for files. The entire file is read in via read_to_string. This means that memory is allocated to hold the entire file. Then we recur once to read nothing and end.
When reading line-by-line, the String is reallocated for every call. This will increase memory usage with each call, up to the last call, at which point we will have allocated the entire input size again.
Which leads to the important point: Rust doesn't have tail recursion! Writing an unbounded recursive function is eventually going to end in tears for someone.
Additionally, this cat doesn't support binary files, as it crams everything into a String.
I'm not sure why there are two methods of reading, one for files and one for stdin. Why not always read line-by-line or as one big blob?


Function that performs a test of whether a number is greater or less than some expected result

That's a very unconventional usage of the term "precision".  I think that "comparison" would be the appropriate word here.

The Test class is severely underdeveloped.  The constructor fails to construct a useful object.  Furthermore, representing the comparison as one of four magic strings is cryptic and unhelpful.  On top of that, the Test class doesn't even know how to execute its own test, forcing you to write a separate handle_non_exact_answer() function.

It's rather weird that handle_non_exact_answer() returns True or False to indicate whether the comparison was one of the four recognized magic strings.  I would consider an unrecognizable comparison as an error, and raise an exception — preferably when the Test is constructed, not when you try to perform the test.

Printing the "passed" or "failed" result limits the function's reusability.  It should return True or False instead, and let the caller decide what to do with the result.

The if-else chain is more idiomatically done using a dictionary lookup.

Your main() test isn't very effective.  You don't print the randomly chosen number, so it's hard to tell whether the results are correct.  Also, you've used test to mean two different things: the first test ("greater than 0"), and also the iteration variable (for test in tests: …), which is unnecessarily confusing.

Suggested solution

import operator
import random

class ComparisonTest:
    COMPARATORS = {
        'less': operator.lt,
        'more': operator.gt,
        'lesser': operator.le,
        'greater': operator.ge,
    }

    def __init__(self, comparison, threshold):
        try:
            self._func = lambda n: self.COMPARATORS[comparison](n, threshold)
        except KeyError:
            raise ValueError('Invalid comparison: {0}'.format(comparison))

    def __call__(self, n):
        return self._func(n)

def main():
    n = random.randint(-1, 1)
    print('n = {0}'.format(n))
    test0 = ComparisonTest('greater', 0)
    test1 = ComparisonTest('lesser', 0)
    test2 = ComparisonTest('more', 0)
    test3 = ComparisonTest('less', 0)
    for test in [test0, test1, test2, test3]:
        print("passed" if test(n) else "failed")

if __name__ == "__main__":
    main()

More compact implementation

Here's a more compact way to write ComparisonTest, using functools.partial().  (Use the same main() function as above.)

from functools import partial
import operator

def ComparisonTest(comparison, threshold):
    try:
        return partial({
            'less': operator.gt,  # Comparisons are intentionally reversed
            'more': operator.lt,
            'lesser': operator.ge,
            'greater': operator.le,
        }[comparison], threshold)
    except KeyError:
        raise ValueError('Invalid comparison: {0}'.format(comparison))


So far my tests indicate that the performance is slightly better in the larger test cases because there is no hashing involved when accessing elements in deleteStatusArray. There are also no array copy operations.

public static void ZRemoveIndex<T>(this T[] array, int[] indices, out T[] rest, out T[] removed)
{
    int arrayLength = array.Length;
    int indicesLength = indices.Length;

    if (indicesLength == 0 || arrayLength == 0)
    {
        rest = array;
        removed = new T[0];
        return;
    }

    rest = new T[arrayLength - indicesLength];
    removed = new T[indicesLength];
    //memo to remember which array indices are removed
    //all elements will be false by default
    var deleteStatusArray = new bool[array.Length];

    foreach (var removeIndex in indices)
    {
        //mark index that should be considered deleted
        deleteStatusArray[removeIndex] = true;
    }

    var notRemovedCounter = 0;
    var removedCounter = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if(!deleteStatusArray[i])
            rest[notRemovedCounter++]= array[i];
        else
            removed[removedCounter++] = array[i];
    }
}


Count character replacements needed to make string a palindrome

for (int i = 0; i < Math.ceil(chars.length / 2); i++) {
      char currentChar = Character.toLowerCase(chars[i]);
      char oppositeChar = Character.toLowerCase(chars[chars.length - 1 - i]);

You'll get the identical answer from Math.floor

    for (int i = 0; i < Math.floor(chars.length / 2.0); i++) {
      char currentChar = Character.toLowerCase(chars[i]);
      char oppositeChar = Character.toLowerCase(chars[chars.length - 1 - i]);

For one thing, you would get the integer result from the original since you were dividing two integers.  But even if you fix that, realize that both return the same answer.  Because when i == chars.length - 1 - i, the absolute value of the difference will always be zero.  And that case is the one that the second version does not do.

    for (int i = 0; i < chars.length / 2; i++) {
      char currentChar = Character.toLowerCase(chars[i]);
      char oppositeChar = Character.toLowerCase(chars[chars.length - 1 - i]);

This does the same thing through the magic of integer math which implicitly takes the floor for you.

You can save some math by using two variables.

    for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
      char currentChar = Character.toLowerCase(chars[i]);
      char oppositeChar = Character.toLowerCase(chars[j]);


int main(int argc, char *argv[]){
    //Declare Variables.
    string input;
    int size;

Don't declare variables until you actually need them, and don't declare variables you don't need. In this case, you're not using the arguments passed into main, either don't name them, or use the version of main that takes no arguments:

int main() { /* space or newline between paren and curly is usual */

cin >> input;

I'm not sure this is what you want. If the user enters a "sentence" with spaces in it, you'll only get what they typed up to the first space (not included). If you want the whole line, use std::getline.

std::string input;
std::getline(std::cin, input);

//Copy the string into a character array.
const char * chars = input.c_str();

This comment is dangerously wrong. You don't get a copy at all, you get a pointer to std::string's internals. The string data is not copied, and the pointer returned will become invalid as soon as input's lifetime ends.

std::string's length() member returns an unsigned quantity. While there's no problem in this case assigning it to an int, the correct type to use is:

std::string::size_type size = input.length();

or more conveniently:

auto size = input.length();

(And you'll need to use an unsigned quantity for the loop counter too, to avoid warnings.)

A different way of doing your loop would be to use the range-based variant. It works for std::string.

for (auto c: input) {
  std::cout << "Char \"" << c << "\" has value " << static_cast<int>(c)
            << std::endl;
}

This avoid getting the size altogether.


The docs on "use strict" are vague but I'm not entirely sure putting it inside a function makes it apply to the function definition.
var shuffle = function shuffle (array) { seems unnecessarily redundant. I would just use function shuffle (array) {
Use const and let instead of var (unless you're trying to support older browsers)
It doesn't make sense to initialize randomIndex or temporaryValue.
I would write while (currentIndex > beginningIndex) { especially if the indexDecrement could be something other than 1. Actually I would prefer a for loop though its arguable given the way your loop is structured.
I would use destructuring assignment to swap values:

[ array[currentIndex], array[randomIndex] ] = [ array[randomIndex], array[currentIndex] ];

If you use const or let you can move the definition of randomIndex and temporaryValue inside the loop block.
You return the shuffle function but your IIFE doesn't assign it anywhere. Apart from the fact that this seems unnecessarily complex I wonder if this even works?


Generic Implementation for Api call in c#

A few points that come to mind:

A lot of your code closely follows the underlying API of the HTTP client instance. It would be better to have a function that generates your client with its default settings (the ones you're setting in the constructor), then just use the appropriate methods on the HttpClient.
There arent many (any?) good use cases for calling Result on a task. You should make your method async and await the task instead.
Your use of Task.Run is redundant. You're wrapping one task inside another.
What happens if there is an error? Incorrect URI, no network etc...


Acquiring the number of contracts for persons

Sometimes, when doing left-join aggregation with a simple function (count()), it is easier to move the aggregation to be part of the select clause instead of as a subquery on the from clause.

As long as you are only pulling one aggregate from the sub table, it's easy.

Also, I presume there is at least one index on Contract where the PersoonID is the first (or only) column.

select (select count (*)
        from Contract
        where PersoonID = CAN.PersoonID
       ) as ContractCount
,      CAN.PersoonName
,      ... /* some fields from table Candidate (more than 25) */
from   Candidate CAN
where CAN.Type = 11


Conceptually, I feel like you are doing this backwards. You should be storing an array of strings instead of repeatedly splitting a string into an array.

Here's my take on it:

function WordCounter(){
   this.words = []; // You should just use an array. It makes more sense here.
}

WordCounter.prototype.addWords = function(){
    // this allows you to pass in words as multiple arguments, or as an array of words
    // i.e.:
    // myWordCounter.addWords(["one","two","three"]);
    // or
    // myWordCounter.addWords("one", "two", "three");
    this.words = this.words.concat([].slice.call(arguments));
}
WordCounter.prototype.count = function(){
    return this.words.length;
}
WordCounter.prototype.toString = function(){
    //this replaces the text property
    return this.words.join(" ");
}
WordCounter.prototype.getFrequenciesAsHash = function(){
    // reduce is much more elegant here.
    // if you have to support older browsers, just use a shim to fill in array method support
    return this.words.reduce(function(hash, word){
        // no need to do a typeof.
        if(hash[word] === undefined)
            hash[word] = 0; // no reason to create an object

        hash[word]++;

        return hash;
    }, {});
}

If you want to be able to add words from a multi-word string, I would suggest a separate method for clarity:

WordCounter.prototype.extractWords = function(string){
    this.addWords(string.match(/\w+/g));
}

The naming could be better.


Find next consecutive prime and find nth prime

This question is very similar to the Project Euler #7 challenge. This was asked recently: Suggestions for improvement on Project Euler #7. I answered that question there, and a lot of my suggestions there will follow through here. I also suggested an object-oriented class that will significantly improve the performance of this problem....

Your solution is very different, but similar issues can be found...

Some basic 'hygiene':

double-negative logic is hard to read. if (!nonprime[m]) should be if (prime[m]). If you cannot get the booleab values to be right (Arrays.fill(prime, true)) then you should revert to constants (private static final boolean PRIME = false;) and == comparisons: if (primeflag[m] == PRIME)
you also do double-negative logic in the nextPrime() method: boolean notPrime = true; and if (notPrime). This should be something like if (!prime) ....

First though, you actually have two very different solutions for 'find nth prime' and 'find primes less than x'. Your find nth prime algorithm is very slow. It does not use the Sieve of Eratosthenes at all. It is a 'naive' and slow mechanism for checking every value against all primes. There is a way to estimate the value of the nth prime, and you should use that, combined with the mechanism for calculating primes less than the estimate. This is illustrated in that other answer (reference Wikipedia)

:

you have blindly followed the wikipedia recommended algorithm/suggestion of doing an incremental progression on a sieve of numbers.
if you make 2 a special case, then you only actually need to process every second value (m += 2 instead of m++).
you do not cache previously computed prime numbers, as a result, calling your methods multiple times will require many re-computations of prime values.
Integer.MAX_VALUE happens to be a prime.... what happens if you run: nextPrime(Integer.MAX_VALUE - 1); ?


Well .. you do not understand MVC design pattern. You seem to got all three parts wrong. Since I am quite lazy person, I will just direct to some older posts of mine that might help you to deal with handling pdo, some initial studies for the subject, basics of views, model layer, some minor note on controllers. Also there is a bit about access control in context of MVC, that might be useful to you.

Now! To the code ...
File: model.login.php

Model is not subtype of database connection (wel .. model is not even a class). This class is violating SRP [1], [2], [3] .

Aside from making a pointless wrapper for PDO, there is also a serious problem there: md5(sha1( ... )) should NEVER be used for hashing passwords. Please read the following three posts from @ircmaxell.

File: controller.login.php

You should learn how to use autoloader. Start by reading the documentation about spl_autoload_register(). Also I would recommend to look into what are namespaces and how then can be used together with autoloading schemes.

Don't us static method calls. Just because you wrap something in a class does not make it object-oriented (notice how it isn't called "class-oriented programming" .. there is a distinction). When used this way, your class acts only as namespace for your global-scope functions.

... the rest, IMHO, is covered in the linked posts above.


I don't really see how lens will help you at all here, but you can certainly take advantage of monad transformers to handle part of your calculations, and make it so that you can layer you stack operation language on top of any monad. (so that you can, as I show below, print out the stack in the middle of the calculation)

{-# LANGUAGE LambdaCase #-}

module Main where

import           Control.Monad.State
import           Control.Monad.Except
import           Control.Monad.Identity

type StackMT s m a = ExceptT String (StateT [s] m) a
type StackM s a = StackMT s Identity a

push :: (Monad m) => s -> StackMT s m ()
push a = modify (a:)

pop :: (Monad m) => StackMT s m s
pop = get >>= \case (x:xs) -> put xs >> return x
                    _      -> throwError "Stack underflow"

safely :: (Monad m) => StackMT s m a -> StackMT s m (Either String a)
safely act = liftM Right act `catchError` (return . Left)

safely_ :: (Monad m) => StackMT s m a -> StackMT s m ()
safely_ act = (act >> return ()) `catchError` (\_ -> return ())

runStackT :: (Monad m) => StackMT s m a -> [s] -> m (Either String a, [s])
runStackT = runStateT . runExceptT

runStack :: StackM s a -> [s] -> (Either String a, [s])
runStack act stack = runIdentity $ runStackT act stack

runOnEmpty :: StackM s a -> (Either String a, [s])
runOnEmpty = flip runStack []

runOnEmptyIO :: StackMT s IO a -> IO (Either String a, [s])
runOnEmptyIO = flip runStackT []

-- Stack operations that cannot crash program.
--
-- To avoid passing stack back and forth in pure language, use State monad.
-- To avoid `if` statements for overflow checking, use Either monad.
-- To avoid code duplication use parameterized and high-order types.
main :: IO ()
main = do
    print =<< runOnEmptyIO (do push "Hello"
                               _ <- pop
                               safely_ $ pop >>= push . (++" World!")
                               get >>= liftIO . putStrLn . ("Stack: " ++) . show
                               pop)
    print $ runOnEmpty $ do push (2::Double)
                            safely_ (pop >>= push . (**7))
                            pop

As you can see, I also added a few convenience methods.

Note that the way this is set up, the StackMT monad transformer has to be the outermost in the stack; that is, if you attempt to apply ListT or ReaderT to something of the form StackMT s m, then in the resulting monad push and pop won't work.


$(function () {
    var extended = $('.extended').hide(),
        hidden = true;
    $('<button></button>', {
        text: 'Read more'
    }).appendTo('.intro').on('click', function () {
        extended.slideToggle();
        hidden = !hidden;
        $(this).text(hidden ? 'Read More' : 'Read Less');
    });
});

You only need to bind the click event once (toggle is a shortcut for binding to click and attaching two alternating event handlers).


Single letter names are not readable in general. i, p and q, for example, would be easier to read as identification, price, and quantity. This is also a common pattern, where parameters to be stored as fields are named the same as the fields.
The last three lines should be in a main function, called if __name__ == '__main__'.
item_dictionary would be better expressed either by making Product a dict subtype or making an as_dict method.
product_1 and product_2 should be passed as either a products array argument or a *products star argument to Inventory().
Why unpack the products in Inventory?
The code directly inside Inventory (for loop and print()) should be in a method. I've never even seen Python code with something other than method definitions at the top level.
Product quantity is a property of an inventory, not a product.

I would probably implement this as follows (untested):

class Product:
    def __init__(self, identification, price):
        self.identification = identification
        self.price = price

class Inventory:
    def __init__(self, products):
        self.products = products

    @property
    def value():
        return sum(product.price for product in self.products)

def main():
    product_1 = Product(32, 23)
    product_2 = Product(23, 65)
    inventory = Inventory(2 * [product_1] + 3 * [product_2])
    print(inventory.value)

if __name__ == '__main__':
    main()


Windows function to use NamedTemporaryFile

After some research I found that tempfile.NamedTemporaryFile is broken on Windows (you could have a temporary file, or you could get a filename - but you cannot have both).

This is just flat out wrong. Maybe you're misunderstanding something and conflating two things. But this is just factually incorrect. And can be seen in your code:

temp_pptx.close()  # needed on windows systems to access file
prs.save(temp_pptx.name)

The first line is closing the temporary file, and the second is getting it's filename.

  needed on windows systems to access file

This is due to a security feature.

  The file is created securely, using the same rules as mkstemp().

  Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open(). The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes.

Clearly you don't need this, so tempfile is pretty much useless to you and you will be fighting it.
Your code looks very much like a mix of an exploit of how generators and garbage collection work, and some dodgy monkey patch to get around tempfile. Both are on a level of wtf/m that I'd suggest just writing your own temporary file class.

import os

class TemporaryFile:
    __slots__ = ('_file',)

    def __init__(self, file):
        self._file = file

    @classmethod
    def open(cls, *args, **kwargs):
        return cls(open(*args, **kwargs))

    def __enter__(self):
        return self._file.__enter__()

    def __exit__(self, exc_type, exc_value, traceback):
        ret = self._file.__exit__(exc_type, exc_value, traceback)
        os.remove(self._file.name)
        return ret

if __name__ == '__main__':
    with TemporaryFile.open('foo.txt', 'w+') as f:
        pass
    with TemporaryFile(open('foo.txt', 'w+')) as f:
        pass

I can write to the file using Atom using the above. Even if Excel has more security operations, then you can easily work around them without monkey patches.


Redux: button click potentially fires 3 action for different reducers

I was wondering if when the user clicks “Save” it is better to call a function in the List component that calls “addNew” and “deleteB” and finally “editSave” to only update the state for the “editing” state property.

I would avoid this. Ideally, all your logic should live either the reducer or the thunk, NOT in components. This way, your logic is in one place, are easily and uniformly testable, and are not affected by things such as re-implementation of the UI (i.e. changing of components, replacing the UI library, etc).

Reducers are just pure functions - they take in old state and an action, and they return new state. As long as you follow that basic principle, you're good. When you call a reducer from another reducer, you're effectively just composing reducers - which isn't a strange concept in Redux. So it's not weird to have something like this:

export const add = (state, action) => { ... }

export const edit = (state, action) => { ... }

export const delete = (state, action) => { ... }

export const someWeirdCaseOfAddEditDelete = (state, action) => {
  if(action.type === state.editing.type) {
    return edit(state, action)
  } else {
    const intermediateState = add(delete(state, action), action)
    const finalState = doMoreStuffWith(intermediateState, action)
    return finalState
  }
}

As an added bonus, when the time comes when someWeirdCaseOfAddEditDelete starts to deviate from your regular add, edit and delete, you can simply replace its implementation and its tests without having to meddle with the other three reducers.

To address your concerns in the comments:

  I thought that was an anti-pattern because it's like dispatching an action inside a reducer that got executed from an action.

Calling dispatch in a reducer is the antipattern. But composing functions (i.e. breaking up your reducer into subfunctions that deal with specific parts of the state) is totally fine.

It may be easier to wrap your head around the idea by dropping the assumption that the common operation is a reducer. Think of it as just a common utility function:

const thatCommonFunction = (somePartOfTheState) => ({
  thatOnePropertyYouNeedToChange: { ... }
})

const reducer1 = (state, action) => ({
  ...state,
  ...thatCommonFunction(state.some.part)
})

const reducer2 = (state, action) => ({
  ...state,
  ...thatCommonFunction(state.some.part)
})

  Every time I call "deleteB" or "add" from "someWeirdCaseOfAddEditDelete" the state will update, before returning the intended "finalState".

If the state updates before all of your reducers return the new state to Redux, then there's something wrong with your code.

Redux receives the updated state only after it runs through all the reducers. The state should never update while execution is still in the reducer.

Under the hood, at the very basic, Redux does something like this:

const createStore = (rootReducer, initialState = {}) => {
  let currentState = initialState;
  const subscriptions = [];

  return {
    dispatch(action) {
      // This part is where control is handed over to your reducers.
      currentState = rootReducer(currentState, action);

      // Only after the line above should your state be updated.

      // After that one line, the UI is informed of the update.
      subscriptions.forEach(s => s(currentState))
    },
    subscribe(fn) {
      subscriptions.push(fn)
    }
  })
}


Encryption/decryption of a string with a salt

Salt

Your salt isn't a salt, it's a key.

And you are generating a random key if none is given, and the user has no acces to this key. This means that if I do this:

$encryptedPassword = $safePassword->encryptString($passwordBefore);
$decryptedPassword = $decrypt->decryptString($encryptedPassword);

My output will be:

Current Password: TestPassword
Encrypted: ZWZNn1FC8F0NCO7Ac7YZojlUITPupOXsDV3BLvS3W2M=
Decrypted: æÁSLkz-HGÐyV]l¥S3]‹*õA"VÚX'

This shouldn't happen.

I would remove the generation code in encryptString and rename salt to key.

Hashing vs Encryption

Generally, passwords are not encrypted, they are hashed. Is there a reason you are encrypting your passwords?

Padding oracle attacks

You are vulnerable to padding oracle attacks. I linked to some resources about this in this post.

Object creation

Why are you creating two stringEncryption objects? One would be enough.

Style

be consistent: either curly brackets go on the same line or the next
follow conventions: class names start with an uppercase letter

If you want to learn more about OOP in PHP, I would suggest you write something where your objects have a state (for example Conway's Game of Life).


You don't have to initialize the list's capacity and with only 6 items you won't notice any difference anyway so why making the code overcomplicated? As a matter of fact you need only a single query to get what you need so it's not only the capacity that makes it unecessarily more difficult to read by the entire implementation.

You can just Concat the alternativeDocumentIds to the optional documentTypeCode:

private RequiredDocumentEntity GenerateRequiredDocumentMapping(string documentTypeCode, params string[] alternativeDocumentIds)
{
    var satisfyingDocuments =
        from docId in
            string.IsNullOrEmpty(documentTypeCode)
                ? Enumerable.Empty<string>()
                : new string[] { documentTypeCode }).Concat(alternativeDocumentIds)

        select GetDocumentType(docId);

    return new RequiredDocumentEntity()
    {
        SatisfiedBy = satisfyingDocuments.ToList()
    };
}

but if the the documentTypeCode is optional anyway why don't you simply include it in the params array? It doesn't make any difference for the result and the method becomes really simple:

private RequiredDocumentEntity GenerateRequiredDocumentMapping(params string[] documentIds)
{
    var satisfyingDocuments =
        from docId in documentIds
        where !string.IsNullOrEmpty(docId)
        select GetDocumentType(docId);

    return new RequiredDocumentEntity
    {
        SatisfiedBy = satisfyingDocuments.ToList()
    };
}

or

private RequiredDocumentEntity GenerateRequiredDocumentMapping(params string[] documentIds)
{
    return new RequiredDocumentEntity
    {
        SatisfiedBy =
            documentIds
                .Where(docId => !string.IsNullOrEmpty(docId))
                .Select(GetDocumentType).ToList()
    };
}

whatever you prefer.


Synchronized implementation of a bank account in Java

In terms of the basic thread locking, it looks like it is doing the right thing, but there are a number of issues in how you are calculating the account balance, and also some escaped locking as well.

Note, your post is titled "Synchronized implementation", but it is not, it is a locked implementation. Synchronization is different, and, in this case, it may be a simpler mechanism.

Locking

Even if you don't catch exceptions, you should always use the try/finally mechanism for locking. Here, for example, it's possible that the addition may throw an exception (even though you don't catch it):

public void addAmount(double amount) {
    this.accountLock.writeLock().lock();
    try {
        this.balance.add(new BigDecimal(amount));
    } finally {
        this.accountLock.writeLock().unlock();
    }
}

In case you think that's extreme, well, the amount could be NaN or infinity, and that would throw a NumberFormatException, etc. Even if it were impossible for the logic to throw an error, you should still use the try/finally mechanism because it makes the logic obvious.

The balance method has the most to gain:

public double getBalance() {
    this.accountLock.readLock().lock();
    try {
        return this.balance.setScale(2, RoundingMode.HALF_DOWN).doubleValue();
    } finally {
        this.accountLock.readLock().unlock();
    }
}

You are also leaking the lock through the public method to get it. You really should not allow other people to manipulate the lock strategy you have in your class. It is intended to be internal for a reason.

Speaking of that lock, you should also make it final...

private final ReadWriteLock accountLock;

Bugs

The most glaring issue is not with your locking, but with the balance management itself. BigDecimals are immutable. They cannot be changed. This does nothing: this.balance.add(new BigDecimal(amount)); .... that should be this.balance = this.balance.add(new BigDecimal(amount));.

The accountNumber and accountHolder should be final as well.

Finally, the getBalance method will not always return a 2-decimal double value. Not all values in binary floating-point are representable in decimal.


Read file with over 300k words and filter through appropriate filter to return list of matching words

First off I'd change how you are making char1filter.
Here's what I'd do differently:

Remove the is True as it's implied.
Change the element.startswith('') to element[0] == 'a'.
Merge all the element checks into one, using in. element[0] in 'bptsmdcgfl'.
Use a list comprehension.

Merging all this together we should get:

char1filter = [
    element
    for element in lines
    if len(element) == 5 and element[0] in 'bptsmdcgfl'
]

Id however store 'bptsmdcgfl' with filterlist2, filterlist3 and filterlist4.
And instead just remove all element that aren't 5 long.

five_long = [
    element
    for element in lines
    if len(element) == 5
]

This leaves you with four roughly identical pieces of code.
And so I'd change all the filterlists to be a single list to loop through.
And then perform the transformations inside this.

data = five_long
for to_filter in filter_lists:
    data = [
        element
        for element in data
        if element[0] in to_filter
    ]
    print(data)
    print(len(data))

If however you just want the last filter list, then you can merge all the filters into one, and then do a single filter on that.

filter_list = [e for l in filter_list for e in l]
data = [
    element
    for element in five_long
    if element[0] in filter_list
]
print(data)
print(len(data))

You should also read PEP8 to style your code correctly, like I have above, which makes your code much easier to read.
You should also use with when opening files, tuple(open('')) is bad and should instead be:

with open('words.txt', 'r') as f:
    lines = tuple(f)

And so the code could be:

FILTER_LISTS = [
    ['b', 'p', 't', 's', 'm', 'd', 'c', 'g', 'f', 'l'],
    ['a', 'r', 't', 'h', 'i', 'v', 'o', 'y', 'l', 'e'],
    ['a', 'l', 't', 'o', 'i', 'n', 's', 'r', 'm', 'f'],
    ['a', 'm', 'd', 'k', 'e', 's', 'x', 'p', 'l', 'y'],
]

with open('words.txt', 'r') as f:
    lines = tuple(f)

data = [
    element
    for element in lines
    if len(element) == 5
]
for to_filter in FILTER_LISTS:
    data = [
        element
        for element in data
        if element[0] in to_filter
    ]
    print(data)
    print(len(data))


Some possible improvements:

You select the bookList multiple times. You only need to select it once, in the outer scope, and let lexical scoping do the rest - you can remove the line that re-declares it without issues.

Inserting characters from user input directly into a string of HTML markup can occasionally result in unexpected elements appearing when the input contains < brackets. (This can also allow for arbitrary code execution)

const bookItem = document.querySelector('tr');
const title = 'Title <Subtitle in brackets>';
const author = '<img src onerror="alert(\'evil\');"';
bookItem.innerHTML =`
  ${title}
  ${author}
`;

Either escape < brackets first, or insert the s without content, then select them afterwards and assign to their textContent (which won't have any escaping issues).

${this.title.replace(/</g, '&lt;')}
${this.author.replace(/</g, '&lt;')}
${this.isbn.replace(/</g, '&lt;')}
<button type="submit" class="delete">X</button>	`;

The return value from addBook is not used, so there's no need for it to return a value. Unless you're intending consumers of Book to use the created
, you can remove the return from the end of the function.

Your deleteBook function is odd - whenever anything in the bookList is clicked, it will remove the grandparent element. This does not seem desirable. You probably want to remove a
 only when the X button is clicked. Add an event listener to the button instead:

addBook(){
  const tr = document.createElement('tr');
  tr.innerHTML =`
  ${this.title.replace(/</g, '&lt;')}
  ${this.author.replace(/</g, '&lt;')}
  ${this.isbn.replace(/</g, '&lt;')}
  <button type="submit" class="delete">X</button>	`;
  const button = tr.querySelector('button');
  button.addEventListener('click', () => {
    tr.remove();
    showNotification('Deleted Item', 'success');
  });
  bookList.appendChild(tr);
}

You could also keep using your listener on the whole bookList, but you'd have to make sure that the clicked element is the X button before removing elements - check if the target .matches('.delete'). (but even then, it's strange for that functionality to be outside of the Book class - it would make more sense for it to be encapsulated)

If you do use the delegation method, use event.target, not event.originalTarget (which is non-standard and only works on Firefox - on any other browser, it will throw an error). (also, best to name the variables appropriately - you're passing the event to deleteBook, not the event.target, so calling the parameter target is confusing)

You can make the submit listener a bit less repetitive by calling e.preventDefault on the first line of the function, that way you don't have to write it twice later, nor do you have to worry about accidentally not calling it in case you add more logical paths to the function. (And if you call preventDefault(), there's no need to return false, nothing needs to be returned)

In getFields, you're implicitly creating a global variable fields. This doesn't do anything useful, and will throw an error in strict mode (which you should be using). Just remove the fields = part:

function getFields(){
  return {
    'title': document.getElementById('title').value,
    'author': document.getElementById('author').value,
    'isbn': document.getElementById('isbn').value
  };
}

Doesn't matter much here, but if you had more fields, to be less repetitive, you could replace that with:

function getFields() {
  return Object.fromEntries(
    ['title', 'author', 'isbn'].map(
      id => [id, document.getElementById(id).value]
    )
  );
}

It's good to prefer const whenever possible - using let is a warning to future readers of the script (including yourself) that you may be reassigning the variable later. So, you could replace

for(let [key, value] of Object.entries(fields)){

with

for(const [key, value] of Object.entries(fields)){

Or, even better, since you don't care about the keys at all, only that none of the values are empty:

function validateForm(fields){
  return Object.values(fields).every(Boolean);
}

When alert is used as an identifier in Javascript, it usually refers to window.alert. Calling a different variable alert can be confusing. Consider changing

const alert = document.createElement('div');

to something like alertDiv.

Template literals look nicer than concatenation with +, but if there's no concatenation going on, and there aren't any ' or " characters causing escaping issues, there's no point in a template literal. Replace

alertDiv.classList = `${type}`;

with

alertDiv.classList = type;

But the classList is generally understood to be a read-only DOMTokenList. While you can change the class of an element by assigning to the classList property, it looks quite odd. If you want to assign a class, either use classList.add, or (if you don't care about overwriting the existing class) assign to the className property:

alertDiv.className = type;

Using document.createTextNode is often unnecessarily verbose. You can just assign to the textContent of the element instead. Replace

alertDiv.appendChild(document.createTextNode(message));

with

alertDiv.textContent = message;


Connecting and getting mysql connection object

Obvious (dumb) point - I'd suggest using logging instead of print
I would have some kind of builder for _CFG so I could choose if I use environment variables for configuration or something else
Instead of str.format, you may want to use fstring: f"{_CFG["user"]} connecting to {_CFG["database"]} on {_CFG["host"]}."
Instead of yield None you may want to reraise exception (from the docs, "If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception"). Otherwise, your code will fail with a funny exception.


Find the maximum value of | Ai - Aj | + | i - j |:

The minor problem is that you are printing the result in the wrong place.

The major problem is that n may be up to 100,000.  This means you need to run 10,000,000,000 of your inner test.  And you may have only 0.02 seconds to do that.

The trick to dealing with that is probably to determine the maximum possible score of a given i and l[i], and skip the inner loop if it isn't worth it.  As part of this, you might find it beneficial to determine the range of the l[] values.

As an example, if you determine that all l[i]<=5, then it isn't worth looking at i>6 and i<n-6 (or thereabouts... I'm not positive about the border condition).


Find two numbers in a sorted array whose sum is closest to a given number

The "intermediate array" takes no extra space due to lazy evaluation. minimumBy . comparing is minimumOn. Yes, swapping the parameters makes sense. Inline then and else once more. I wouldn't worry so much about constant factors - have you compiled it with -O2 and tested (eg with criterion)?

import Data.List (minimumOn)

closestPairSum :: (Num a, Ord a) => a -> [a] -> (a, a)
closestPairSum n xs = minimumOn (abs . (n-) . uncurry (+)) pairs where
  pairs = sums xs (reverse xs)
  sums xxs@(x:xs) yys@(y:ys) = (x, y) : if n < x + y
    then sums xxs ys
    else sums xs yys
  sums _ _ = []


You can make basePrimes a lateinit non-null var to avoid !!.
sieve and initialPrimes are only assigned once so they can be marked with val instead of var
sequenceOf(2, 3, 4, 7).iterator() can be used along with Iterator.hasNext and Iterator.next instead of mutableListOf(2, 3, 5, 7) with somewhat difficult to read !initialPrimes.isEmpty() and initialPrimes.removeAt(0) (although if you really prefer to use a collection instead of an iterator then you can use isNotEmpty instead of !collection.isEmpty).
Instead of explicitly declaring a temp variable you can use apply to take the current value of a variable, use/change it, and return the initial value.
As an alternative to sieve.containsKey(j) you can use j in sieve.
As an alternative to candidate += 2 } candidate += 2 you can move the latter += 2 to relatively the beginning of computeNext (requires a few other changes, see below). The name candidate would no longer really fit though, but I think a generic property name like value is sufficient enough (we know what "value" we care about so we know what we're computing as we go, etc.).
You probably shouldn't implement Iterator<Int> and Sequence<Int> in the same object. e.g. When invoking with(PostponedPrimeSequence()) { repeat(2) { take(20).forEach(::println) } } I would expect it as a Sequence<Int> to print the first 20 primes twice (or throw "IllegalStateException: This sequence can be consumed only once.") but as an Iterator<Int> I would expect it to print the first 40 primes. These are conflicting expectations. I recommend only implementing one. A Sequence is understood to possibly be constrained to be iterated only once so I would implement the base Iterator and then wrap it as a Sequence in a top-level function for convenience.

e.g.

fun generatePrimeSequence() = PostponedPrimeIterator().asSequence()

class PostponedPrimeIterator() : AbstractIterator<Int>() {
    private lateinit var basePrimes: PostponedPrimeIterator
    private var basePrime = 0

    private val sieve = mutableMapOf<Int, Int>()
    private val initialPrimes = sequenceOf(2, 3, 5, 7).iterator()
    private var value = 0

    override fun computeNext() {
        if (initialPrimes.hasNext()) {
            value = initialPrimes.next()
            setNext(value)
        } else {
            value += 2

            if (value == 9) {
                basePrimes = PostponedPrimeIterator()
                basePrimes.next()
                basePrime = basePrimes.next()
                assert(value == basePrime * basePrime)
            }

            while (value > 0) {
                val factor = sieve.remove(value) ?:
                        if (value == basePrime * basePrime) {
                            basePrime.apply {
                                basePrime = basePrimes.next()
                            }
                        } else {
                            assert(value < basePrime * basePrime)
                            setNext(value)
                            break
                        }
                var j = value + 2 * factor
                while (j in sieve) {
                    j += 2 * factor
                }
                sieve[j] = factor
                value += 2
            }
        }
    }
}

Usage:

generatePrimeSequence().take(20).forEach(::println)


Finding the count of all repeats in an array of integers

Your code has a for-loop with a nested while-loop. Typically this would indicate an \$O(n^2)\$ time complexity for your solution.... but, your code is only actually \$O(n)\$... how does that happen?

Because you do for-loop control variable manipulation outside the for-loop control block. This is a bad practice. A for loop has three control statements: for (initializer, terminator, stepper). A for loop is designed to have those three mechanisms in one place. In your code, you have split the logic of the stepper in to two places, which makes the for-loop hard to read, and unconventional. Your i variable is stepped, and also you have i=j-1; later in your loop.

If you cannot implement a clean for-loop structure because your code demands some other mechanism, then you should instead use a while-loop, or find a different way to express your step-process.

Bhushan has provided an answer which solves the problem, but does not implement a clean break-processing loop. His code implements the logic check when leaving a clump, rather than when entering the clump. If you do the check when the clump starts, the logic becomes much simpler:

public int countClumps(int[] nums) {
  boolean inclump = false;
  int clumpcnt = 0;
  // note the start-from-1 loop
  for (int i = 1; i < nums.length; i++) {
      if (nums[i] == nums[i - 1]) {
          // we are in a clump
          if (!inclump) {
              // this is the first time for this clump.
              inclump = true;
              clumpcnt++;
          }
      } else {
          inclump = false;
      }
  }
  return clumpcnt;
}


Your code looks clean. Fizzbuzz is a very simple program and the most frequent reasons people get it wrong is because they go for optimizations that do not exist, rather than focusing on solving a rather simple problem.
Anything you do to optimize away those 3 branch statements is just calling for potential bugs down the line. However, in the spirit of codereview, I will give a suggestion:
DRY (Don't Repeat Yourself)
Two repetitions I noticed.

Printing a string (all the li $v0, 4)
Printing a new line.

These can be done away with by coordinating between branching and jump instructions i.e. function calls.
.data

    fstring:    .asciiz     "Fizz\n"
    bstring:    .asciiz     "Buzz\n"
    hstring:    .asciiz     "FizzBuzz\n"
    nl:         .asciiz     "\n"

.text

.globl main

main:
    li  $s0, 0

loop:
    bgt     $s0, 99, exit
    addi    $s0, $s0, 1
    move    $a0, $s0       # the function takes input with registers $a0 to $a3
    jal     check_fizzbuzz # call the function
    move    $a0, $v0       # the function returns a string in register $v0, so move it to $a0 so that it can be printed
    li      $v0, 4
    syscall                # print the string
    b loop

check_fizzbuzz:
    la      $v0, hstring
    rem     $t1, $a0, 15
    beq     $t1, 0, return_fizzbuzzz

    la      $v0, fstring
    rem     $t1, $a0, 3
    beq     $t1, 0, return_fizzbuzzz

    la      $v0, bstring
    rem     $t1, $a0, 5
    beq     $t1, 0, return_fizzbuzz

    li      $v0, 1
    syscall
    la      $v0, nl

return_fizzbuzz:
    jr $ra

exit:
    li      $v0, 10
    syscall


Async distributed locking with StackExchange.Redis

As mentioned in my comment I think in general Dispose is expected to be synchronous hence it should block until finished which is easy enough to achieve:

_db.LockReleaseAsync(Key, Value).Wait();

One other gripe I have with the code is the static IDatabaseAsync member of DataCacheLock. Maybe I'm missing something but I think this can get you into trouble. Assume you have two databases you want to talk to and you fire off to calls to AcquireLockAsync - now the member is set to whatever instance where the calls happened to be executed last which will probably cause funny results as LockTakeAsync might now wait on the wrong database instance for one of the calls and/or in Dispose the lock will be released against the wrong instance.

While this might be a rare use case I don't see the benefit of making this a static member in the first place - it's only accessed locally in either the task  trying to acquire the lock or in the Dispose method. For the Dispose case a non-static member would work fine. For the locking task the instance can be captured locally in the closure as it's passed in. So it should be easy enough to remove the problematic hidden gotcha.


Blocking and async UDP communication with an IR camera

Constructors and Generics
It is customary to use constructors to set values for instances in Java. This code:

private class SendAndWaitForACK implements Callable<Result> {
    private CameraCommands cmd;

    @Override
    public Result call() throws Exception {
        // does not return on timeout
        result.dataBytebuffer = postCommand(cmd);
        result.isSuccess = true;
        return result;
    }

    /**
     * setCommand must be called prior to use.
     *
     * @param cmd
     *            : CameraCommands
     */
    public void setCommand(CameraCommands cmd) {
        this.cmd = cmd;
    }
}

Would more typically be written as:
private static class SendAndWaitForACK implements Callable<Result> {
    private final CameraCommands cmd;

    SendAndWaitForACK(CameraCommands cmd) {
        this.cmd = cmd;
    }

    @Override
    public Result call() throws Exception {
        // does not return on timeout
        result.dataBytebuffer = postCommand(cmd);
        result.isSuccess = true;
        return result;
    }

}

Note that I have replaced the setter with the constructor. I have also made the class static, which saves a tiny amount of memory, but it is good practice because it makes Java GC easier, and has some other benefits.
You will need to change the way you use that class, and your calling code will change from:

Future<?> future = executor.submit(sendAndWaitForACK);

to
Future<Result> future = executor.submit(new SendAndWaitForACK(cmd));

Note, the SendAndWaitForACK implements Callable<Result>, so it will produce a Future<Result> when submitted. As a result, I have changed the generic type of the Future to Future<Result>. This also means that you no longer need the explicit cast and it can simply be:
result = future.get(waitMS, TimeUnit.MILLISECONDS);

Network
Note that your class does not do a clean handling of the network. When you submit a Callable you start a thread, and you run the Callable on that thread. Then, in your code, you set a timeout to wait for the Callable to complete. If the callable does not complete within that specified time, you get a timeout. This does not stop the Callable from running in the other thread. All that happens is that the callable keeps running, and eventually it gets something back from the camera... and, what it gets back, may be something belonging to another command sent later.
Fundamentally, your protocol/communication is a little flawed in this regard. As long as things work as expected, you won't notice it, but, if things go screwy, then your code will make the screwy situation even more screwy.
I strongly recommend, in cases like this, to not use threading at all. At least, don't use multiple threads to communicate over a single socket.
One of the benefits of UDP is the easy way to build simple protocols on top of it.
If this were me, I would:

have a single class that manages the socket, and protocol.
have a thread on that class that checks periodically to see that the camera is there, and working (perhaps every second or so, a 'heartbeat').
that class has a ConcurrentBlockingQueue on the input side that takes a SendAndWaitForACK
(I would probably make the 'heartbeat' one of these SendAndWaitForACK instances)
When a callable is queued, the class will give that command a unique number, and it will 'transmit' that command every 10 or so milliseconds, until it gets a response, or until the timeout happens
when it gets the response (or timeout), it will notify the caller.

I would make the camera-side of the system return the unique ID for the command as part of the response. That way you can make sure you are getting the right data back.
Doing things this way means that:

only one thread accesses the network socket.
only one command can be 'in transit' at any one time.
you do not need to worry about threading or concurrency on the socket.
you always have a 'state' of the camera.

Obviously, that recommendation is very different to what you have at the moment.... but, bottom line, is that almost all UDP-based communication channels will have some form of simple protocol established above the raw network layer.