The model has failed

I would expect from an animal shelter to actually store animals.
(Well, in programming terms, a representation of animals.)
Your implementation is not an animal shelter, it's an animal-relative-arrival-time shelter. I cannot add animals to it, and cannot retrieve animals from it. I can only add animal types, and retrieve meaningless sequence numbers. This is not an acceptable model of an animal shelter.

Failure to generalize

It's important to read the problem description attentively.
Notice that dogs and cats are not part of the essence of the problem,
they are casually mentioned examples. The target system should support animals of all types, and that seems to be a reasonable expectation.

I think the expected interface is something like this:

interface AnimalShelter {

    add(Animal animal);

    Animal get(AnimalType type);

    Animal get();
}

Notice that I didn't call these methods enqueue and dequeue.
Those are implementation terms,
not the terms of the problem domain.
(Probably they could be improved, if I knew anything about the real-world domain of animal shelters.)
Different animal shelters may have different policies for adding and getting animals.
Your task is to implement one with a specific policy,
which could be reflected in the name of the class in your implementation,
but this interface can stay as is.

Testing

What you called "testing" is "demonstrating".
It's not testing anything.
Testing should involve assertions (of truths) about the implementation.
Here's an example:

@Test
public void should_return_the_right_type_in_fifo_order() {
    AnimalShelter shelter = new FifoAnimalShelter();

    Animal fluffy = new Cat("fluffy");
    shelter.add(fluffy);

    Animal sparky = new Dog("sparky");
    shelter.add(sparky);

    Animal smelly = new Cat("smelly");
    shelter.add(smelly);

    assertThat(shelter.get(AnimalTypes.CAT)).isEqualTo(fluffy);
    assertThat(shelter.get(AnimalTypes.CAT)).isEqualTo(smelly);
}

Discussion

For all problems in this book, it's important to carefully consider the time and space complexity of the implementation. In your current implementation, this was trivial: all the dequeue* methods have \$O(1)\$ complexity. That should have been a warning sign, indicating that there's more to this exercise. Indeed, if you extend to support all animal types, the complexity analysis becomes more interesting.

Take for example the get() and get(AnimalType) methods. If you use one queue per type, then get(AnimalType) will be \$O(1)\$, and get() will be \$O(k)\$, where \$k\$ is the number of types. If you use one queue for all animals, then get(AnimalType) will be \$O(n)\$, and get() will be \$O(1)\$. Further variations and optimizations will be possible, it's good to think about them and practice calculating their time and space complexity tradeoffs.


Insert into array in reverse while iterating forward

Let's try the other way:

function loadPath(path, chunkSize, dataSize, depth, index) {
  for(var i = 0; i < depth; i++) {
    path[depth - i - 1] = index % chunkSize;
    index = Math.floor(index / chunkSize);
  };
};

var path = Array(3);
console.log("loadPath(path, 5, 100, 3, 41)");
loadPath(path, 5, 100, 3, 41);
console.log(path);
console.log("loadPath(path, 5, 100, 3, 50)");
loadPath(path, 5, 100, 3, 50);
console.log(path);
.as-console-wrapper { max-height: 100% !important; top: 0; }

What do you want to do if index >= chunkSize^3?


I'll proceed top to bottom.

mail_error

Which would you rather read: x.body = e.message or mail.body = exception.message?  Don't try to save a few characters on naming — your fellow programmers will like you better.  In particular, x has a connotation of being a floating point number, which this isn't.

scanning_all_servers and server_status

Net::SSH#start does not return a "check".  Rather, it returns a connection.  conn = Net::SSH.start(…) would be more appropriate.  Even better, you should call start with a block so that the connection gets closed without an explicit call to close.

As noted in a review of your previous question, scanning_all_servers should be named scan_server, since it acts on just one server.  The :error symbol isn't doing anything.  Either move it to the end as the implicit return value, or get rid of it.

However, the way that server_status and scanning_all_servers cooperate is weird.  scanning_all_servers plays a part in interpreting the result, but only does a partial job.  Yet, it tries to log that result anyway.  It is also odd that the codepath for writing to the screen is so different from the codepath for writing to the log file.  What you want is one function whose job is to scan the server and produce a status code.  Everything else belongs in some other function.

status_message and write_data

status_message would look slightly tidier using a case.

write_data has a File.exist? test for no reason.  Mode 'a+' will create the file if it doesn't already exist.  But why does the append case call write instead of puts, so that there is no newline written?  Also, minor note: s looks like a string, so prefer f as the variable name for a file.

You seem to be more careful about logging failures than successes, but the successes are just as important, and should also be written to the log file.  Also, all results, whether printed to screen or to the log file, should have timestamps.

Suggested solution

require 'rubygems'
require 'net/ssh/gateway'
require 'work/mail/gem'
require 'etc'

def mail_error(exception)
  mail = AD::Mail.new
  mail.from     = 'email@example.com'
  mail.to       = 'email@example.com'
  mail.subject  = "Server down"
  mail.body     = exception.message
  mail.send
end

def scan_server(server)
  begin
    Net::SSH.start(server, @username, :password => @password) do |ssh|
      case ssh.exec!("ping -c 1 #{server}")
      when /1 received, 0% packet loss/i
        :online
      else
        :offline
      end
    end
  rescue => e
    :error
  end
end

def status_message(server, status)
  sprintf("[%s]: %s\n", Time.now,
    case status
    when :online
      "server online: #{server}"
    when :offline
      "SERVER OFFLINE: #{server}"
    else
      "Error connecting to server: #{server}"
    end
  )
end

def log(message)
  File.open('path/to/log', 'a+') { |f| f.puts(message) }
end

@username = Etc.getlogin
@password = …

server_list = %w(all of our servers)

server_list.each do |server|
  status = scan_server(server)
  message = status_message(server, status)
  log message
  puts message
end


Jasmine unit tests for simple toggle class

To begin with, don't interact with the DOM. The reason for that is imagine that you have hundreds of unit tests. Do you want to clean up the DOM after them? Are you going to forget sometimes? If you forget will you be able to find why unit tests are failing? When you will be setting up a Continuous Integration process which will run the unit tests will you use a JavaScript engine tool that is aware of a DOM? What I'm getting at is only test the logic.

In order to make your class unit testable it needs to be refactored. To begin with, you need to make the constructor not do anything except set the this.options and this._status and move all the other code to an init method:

MySwitch = function(options) {
    this.options = options;
    this._status = 0;
};

MySwitch.prototype.init = function() {
    this._$el = $(options.element);
    this._$el.data("value-on") ? this._valueOn = this._$el.data("value-on") : this._valueOn = "ON";
    this._$el.data("value-off") ? this._valueOff = this._$el.data("value-off") : this._valueOff = "OFF";
    if (!this._$el.text()) this._$el.text(this._valueOff);

    this._$el.on("click", $.proxy(this.toggle, this));
};

Now refactor the toggle method:

MySwitch.prototype.toggle = function() {
    this.toggleStatus();
    this.setText();
    this.runToggleFunction();
};

MySwitch.prototype.runToggleFunction = function() {
    if (typeof this.options.onToggle === "function")
        this.options.onToggle.call(this, this._status);
};

MySwitch.prototype.toggleStatus = function() {
    this._status = this._status === 0 ? 1 : 0;
};

MySwitch.prototype.setText = function() {
    this.getEl.text( this._status ? this._valueOn : this._valueOff );
};

MySwitch.prototype.getEl = function() {
    return this._$el;
};

Now you can test the code:

describe("MySwitch", function() {

    it("toggle()", function() {
        var mySwitch = new MySwitch();

        spyOn(mySwitch, 'toggleStatus');
        spyOn(mySwitch, 'setText');
        spyOn(mySwitch, 'runToggleFunction');

        mySwith.toggle();

        expect(mySwitch.toggleStatus).toHaveBeenCalled();
        expect(mySwitch.setText).toHaveBeenCalled();
        expect(mySwitch.runToggleFunction).toHaveBeenCalled();
    });

    describe('runToggleFunction()', function() {
        it('callback provided', function() {
            var func = jasmine.createSpy('func');
            var mySwitch = new MySwitch({onToggle: func});
            var status = 1;

            mySwitch._status = status;
            mySwitch.runToggleFunction();

            expect(func).toHaveBeenCalledWith(status);
        });

        it('no callback', function() {
            var mySwitch = new MySwitch();

            try {
                mySwitch.runToggleFunction();
                expect(true).toBe(true);
            } catch (e) {
                expect(true).toBe(false);
            }
        });
    });

    it('toggleStatus()', function() {
        var mySwitch = new MySwitch();

        mySwitch._status = 1;
        mySwitch.toggleStatus();

        expect(mySwitch._status).toBe(0);
    });

    describe('setText()', function() {

        var valueOn = "on";
        var valueOff = "off";
        var mySwitch;
        var $el;

        beforeEach(function() {
            mySwitch = new MySwitch();

            $el = {
                text: function(){}
            };

            spyOn($el, 'text');
            spyOn(mySwitch, 'getEl').and.returnValue($el);
        });

        it('status 0', function() {
            mySwitch._status = 0;
            mySwitch.setText();
            expect($el.text).toBe(valueOff);
        });

        it('status 1', function() {
            mySwitch._status = 1;
            mySwitch.setText();
            expect($el.text).toBe(valueOn);
        });
    });

});


readStrings() is better named readCharacters() because that is what it does.
I prefer Array(...) instead of .map { $0 } to convert a sequence into an array,
but that is a matter of taste:

/// Reads one line from standard input and returns the result
/// as an array of characters.
func readCharacters() -> [Character] {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    return Array(line.characters)
}

My main point of criticism is that
the logic in your main function is far too complicated. The outerLoop: label is not
used. The inner loop is confusing, and comments like

    // append closing bracket so YES doesn't print when breaking

    // stack has opening brackets and hasn't reach if statement in case } ] )

clearly indicate a code smell. The problem is that you have one single function doing
all the work.

It immediately becomes simpler if you separate the I/O from the
actual computations (which is generally a good idea):

func isBalanced(sequence: [Character]) -> Bool {
    // ... return `true` or `false` ...
}

func balancedBrackets() {
    let numSequences = readInteger()
    for _ in 0..<numSequences {
        let sequence = readCharacters()
        let balanced = isBalanced(sequence)
        print(balanced ? "YES" : "NO")
    }
}

balancedBrackets()

This makes the code more modular, better readable, and  allows you to add
test cases easily. The isBalanced() function can "early return" if a non-match
is found, making the labels and the special edgeCase variable obsolete:

func isBalanced(sequence: [Character]) -> Bool {
    var stack = [Character]()
    for bracket  in sequence {
        switch bracket {
        case "{", "[", "(":
            stack.append(bracket)
        case "}", "]", ")":
            if stack.isEmpty
                || (bracket == "}" && stack.last != "{")
                || (bracket == "]" && stack.last != "[")
                || (bracket == ")" && stack.last != "(")  {
                return false
            }
            stack.removeLast()
        default:
            fatalError("unknown bracket found")
        }
    }
    return stack.isEmpty
}

But the repeated usage of character literals is still error-prone.
Better define an enumeration:

enum Bracket: Character {
    case Left = "("
    case Right = ")"
    case LeftCurly = "{"
    case RightCurly = "}"
    case LeftSquare = "["
    case RightSquare = "]"
}

Determining the matching open bracket for a given closing bracket can be
made a computed property of this enumeration:

enum Bracket: Character {
    case Left = "("
    case Right = ")"
    case LeftCurly = "{"
    case RightCurly = "}"
    case LeftSquare = "["
    case RightSquare = "]"

    /// For a closing bracket, the corresponding opening bracket is returned.
    /// For an opening bracket, `nil` is returned.
    var matchingOpen: Bracket? {
        switch self {
        case .Right:        return .Left
        case .RightCurly:   return .LeftCurly
        case .RightSquare:  return .LeftSquare
        default:            return nil
        }
    }
}

Now the isBalanced() function does not use any explicit bracket values anymore:

func isBalanced(sequence: [Character]) -> Bool {
    var stack = [Bracket]()
    for char in sequence {
        if let bracket = Bracket(rawValue: char) {
            if let open = bracket.matchingOpen {
                // `bracket` is a closing bracket and `open` the corresponding opening bracket:
                guard let last = stack.last where last == open  else {
                    return false
                }
                stack.removeLast()
            } else {
                // `bracket` is an opening bracket:
                stack.append(bracket)
            }
        } else {
            fatalError("unknown bracket found")
        }
    }
    return stack.isEmpty
}

If you decide to add another type of brackets later (e.g. «») then only the
enumeration needs to be extended, but not the isBalanced() function.


You haven't mentioned exactly what triggers this code, but it might run on any open workbook, even if that workbook is confidential to the active user. You might want to consider checking if the activeworkbook is actually a workbook that you want to save. For example, you could check for a document property or a sheetname.

I've made a few changes

The InStr function can be case-insensitive, so you don't need to use the LCase statement

The FileSystemObject makes it easier to work with files and folders, than using MkDir and Dir.

The FileSystemObject has a BuildPath method that makes building paths easier than using concatenation and worrying about whether you need a backslash

Your function and variables were a little ambiguously named... Better to use names that have explicit meanings.

Your SaveAs file name uses mm-dd-yyyy format, but you'll probably be better off with yyyymmdd as your files will then sort alphabetically and chronologically (and it's an ISO standard)

Your SaveAs file name is missing a file extension. It's good practice to add an extension, even if your Explorer settings don't show them, as extensions help Windows to determine which application to use, and they help users identify the files they need to keep/discard.

 Sub ExtractFile()
  'Add a reference to Microsoft Scripting Runtime
  If InStr(1, ActiveWorkbook.Name, "extract", vbTextCompare) > 0 Then
    Exit Sub
  Else
    Dim oFSO As Scripting.FileSystemObject
    Dim folMyDocs As Scripting.Folder
    Dim sExtractsPath As String
    Dim sFilePath As String

    Set oFSO = New Scripting.FileSystemObject
    Set folMyDocs = oFSO.GetFolder(CreateObject("WScript.Shell").SpecialFolders("MyDocuments"))
    sExtractsPath = oFSO.BuildPath(folMyDocs, "Extract Files")
    If Not oFSO.FolderExists(sExtractsPath) Then
      oFSO.CreateFolder sExtractsPath
    End If
    'sFilePath = oFSO.BuildPath(sExtractsPath, Format(Now, "mm-dd-yyyy hh_mm"))
    sFilePath = oFSO.BuildPath(sExtractsPath, Format(Now, "yyyymmdd-hhmmss") & ".xlsx")
    ActiveWorkbook.SaveAs Filename:=sFileName, FileFormat:=xlOpenXMLWorkbook
  End If

End Sub


Encrypting data on client side and passing it to server side

What information should be private?

The key should be private, everything else can be public (the iv, the source, etc).

  How is the logic here flawed

You are using a symmetric key algorithm, which means that the same key decrypts and encrypts data, which in turn means that you would have to exchange the key between the parties (which would need to happen over a different channel, for example paper mail).

What you actually need is an asymmetric algorithm, which has a public key for encryption and a private key for decryption.

If you need to encrypt more data than showing here, you can use an asymmetric algorithm to exchange the key of a symmetric algorithm (as asymmetric encryption is unpractically slow). This is how HTTPS works, for example.

  how should it be used to protect data communication between client and server side computing?

Use HTTPS. At the time, there really isn't an alternative for this. (well, you could use third party services such as OpenID). You definitely need asymmetric encryption, and you should definitely not write your own.

Misc

either always use camelCase or always snake_case, don't mix them without reason.
key256Bits500Iterations is quite descriptive, but I think key would be just fine as well, and easier to read (and what if you change it to 600 iterations? Either your name would be wrong, or you would need to change it).
encrypt doesn't just encrypt, it also changes the form. I would to this in a different function and just let encrypt do the encrypting.
wherever you do the form manipulation, you should also set document.loginForm.password1.value to something else right there.


I was wondering if there was a better way to improve my XNA joystick code? (Vb. Net)

Just on the if statements.  Could you do something like:

    Dim LY As Integer = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y * 100
    Dim LX As Integer = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X * 100

    HScrollLX.Value = LX
    VScrollLY.Value = LY

    SetVelocity(LY);
    SetVelocity(LX,-1);

    // Private method to set the Velocity values
    private sub SetVelocity(position, factor = 1)
        dim v as integer

        if position = 0 then
            MC1.Velocity(0) = 0
            MC1.Velocity(1) = 0
        else
            MC1.Velocity(0) = position
            MC1.Velocity(1) = position * factor
        end if
    end sub


Checking if two binary trees are identical

Your code already does its job well. It can be shortened a bit:

public boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null || q == null) {
        return p == q;
    }

    return p.val == q.val
        && isSameTree(p.left, q.left)
        && isSameTree(p.right, q.right);
}

I flipped the operands of the == operators since having null in the right hand side reads more naturally.

I added spaces after the if and after the commas to follow the common formatting style.


Reading, writing and filtering a CSV file

This is desperate plan and the most annoying, I get rid of 2 for loops and do everything by hand

I will take this question to be 'How can I remove the two inner for loops if possible?'.

First off, you change the row slice from 'the first three' to 'the first four' in your question. And so post all your code. Don't make us guess.
Anyway, this is what I think you want to give us:

import csv

def add_i(row, i):
    if row[0:3] == range(row[0], row[0] +3 * i, i):
        return True

row_dup = []

with open("out_file", "w") as out_file:
    writer =csv.writer(out_file, delimiter=',')
    with open("test1.csv") as csv_file:
        for row in csv.reader(csv_file, delimiter=','):
            row = [int(x) for x in row]

            for i in range (1,11):
                if add_i (row, i) == True:
                    break

                elif row not in (row_dup):
                    row_dup.append(row)
                    writer.writerow(row)

First, we don't want this to be the worst version of cp, and so we will use the for else statement.

for i in range(1,11):
    if add_i(row, i):
        break
else:
    if row not in row_dup:
        # ...

This makes it so that [2, 4, 6] gets removed as well. This is as you would have a bug, so that in add_i, range(2, 5, 1) would return False, and add it to the output.

we can make the for statement, just an if statement. This is as you use range(start, stop, step). I will use i, j and k for start, stop and step respectfully.
We can say that range returns this sort of structure [i, i+k, i+2k, ... i+((j-i)//k)*k]. As you use range(row[0], row[0] + 3*i, i) we know that is [i, i+k, i+2k] where i and k are row[0] and i respectfully.
As this is getting rather complicated. Here is how I would implement it.

def add_i(row, range):
    step = row[1] - row[0]
    if range[0] <= step < range[1]:
        return step == (row[2] - row[1])
    return False

This while not comparing lists uses the logic, as the difference between them all has to be step, and step has to be in the allowed range.

Now that we have gotten rid of one of the two internal for loops, we need to get rid of the other, for this to be what I would deem is the 'correct' answer.
This loop is a list comprehension, and if you have only 3 columns in all the rows, it would be a relatively fast and a really easy conversion. However, I am guessing that is not the case.
And so if we just remove it, we will have to manually convert the columns into numbers. We can just do this in add_i again.

def add_i(row, range):
    r1 = int(row[1])
    step = r1 - int(row[0])
    if range[0] <= step < range[1]:
        return step == (int(row[2]) - r1)
    return False

Edit, I thought I should make a benchmark for sets, and found it was very fast.

row_dup = set()

# ... in the for loop

row_ = ''.join(row)
if not add_i(row, (1, 11)) and row_ not in row_dup:
    row_dup.add(row_)

This allows for very fast look-ups. And only has a ~27% impact on speed. The way that we make it so that we can use sets, is by making the data hash-able. Strings are hash-able, and with the change in the program, where the data in the row is all strings, it allows you to simply str.join it all together.

And so we have an answer with only one for loop.

import csv

def add_i(row, range):
    r1 = int(row[1])
    step = r1 - int(row[0])
    if range[0] <= step < range[1]:
        return step == (int(row[2]) - r1)
    return False

row_dup = set()

with open("out_file", "w") as out_file:
    writer = csv.writer(out_file, delimiter=',')
    with open("test1.csv") as csv_file:
        for row in csv.reader(csv_file, delimiter=','):
            row_ = ''.join(row)
            if not add_i(row, (1, 11)) and row_ not in row_dup:
                row_dup.add(row_)
                writer.writerow(row)

This is roughly O(n). And you can add a list comprehension to allow more steps easily.

def add_i(row, range):
    r0 = int(row[0])
    step = int(row[1]) - r0
    if range[0] <= step < range[1]:
        return row[1:3] == [str(i) for i in range(r0 + step, r0 + 3*step, step)]
    return False

As you seem to want to look over more than just 3 columns, due to your example with four, using a list comprehension is probably the way how you would want to do this.

If you expand on this then you would want to change add_i to only take a row, and be called something like format_test. This way, you are testing if the row follows a format, and if it does not then you add it, if not already added, to the new file. You can also now tell what the main part of the function is doing better, as it is saying, 'if this row passes this test, add it to the out file.'

Also, if you want some benchmarks.
I used 100000 random 3 column csv lines, of numbers up to 10000.

New program with row_dup as type list:

real    3m37.109s
user    3m36.857s
sys     0m0.057s

New program with row_dup as type set:

real    0m0.453s
user    0m0.440s
sys     0m0.010s

New program without row_dup:

real    0m0.357s
user    0m0.350s
sys     0m0.000s

Old program without row_dup:

real    0m1.321s
user    0m1.290s
sys     0m0.010s


C program to print input longer than 10 characters

The magic value 10 is embedded deep in the logic; I would make it an obvious constant (it might one day come from the command-line arguments).

Before overwriting the final \0 with NUL, you will probably want to check that it is actually \n.  If not, then you may have received the start of a line that's more than 1000 characters, and you'll want to print it and all the subsequent inputs until you do receive a \n (note that if you receive 1000 chars and then 5 chars, you can't ignore the 5-char input, because it's actually part of a 1005-char line).  Also, consider when an input line is read as two separate 6-character chunks - your code would discard both, instead of treating them as a single 12-char unit.

Overwriting the final \n with NUL seems to me pointless here, as you add one back on when writing it out.  It's probably better to keep the newline there, and increase your comparison size to take account of it.

Error checking - fgets() can fail, but you treat all failures as end-of-file.  Also, we don't normally write != NULL explicitly; all non-NULL values are true, so reduce the clutter.

The scope of length can be reduced, as it's not used outside the loop.  Except that I'm going to keep track of the length of lines that are split over more than one read, which moves it back again.

Minor style nit: I don't like writing the sizeof operator to look like a function.  It isn't a function, and I prefer it to be distinct.  I know there's a spectrum of opinion on that, so I won't push the point.

It gets surprisingly involved when you take into account partial reads and longer lines:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 1000

const int max_len = 10;

int main(void)
{
    char line[MAX_SIZE];
    int length = 0;
    int is_continuation = 0;

    while (fgets(line + length, (sizeof line) - length, stdin)) {
        length += strlen(line + length);
        /* length includes the final newline */
        if (is_continuation || length >= max_len+1) {
            printf("%s", line);
            is_continuation = line[length-1] != '\n';
            length = 0;
        } else {
            is_continuation = line[length-1] != '\n';
            if (!is_continuation)
                /* reset for next read */
                length = 0;
        }
    }

    /* do we have any remaining input?  It may or may not end in newline */
    if (length) {
        if (is_continuation || length >= max_len + (line[length-1] == '\n')) {
            printf("%s", line);
            length = 0;
            is_continuation = line[length-1] != '\n';
        }
    }

    if (feof(stdin))
        return EXIT_SUCCESS;

    perror("stdin");
    return EXIT_FAILURE;
}


Parsing argv with while-switch construct

This solution does not sit well with me.  It looks like you're doing too much: checking how to take the input, taking input, and then checking whether that input worked all at once.

Before looking at the code, though, it's worth asking whether this is really the interface that you want to provide to the user.  The way you've designed it, it looks like it is meant to be run by a human, as the requests for input will only muddle the output in a script.  Furthermore, spell-checkers are usually non-destructive: running it with the wrong input file or the wrong dictionary file shouldn't lose you any data.

All in all, this makes double-checking with the user whether the dictionary file is correct questionable.  It is also inconsistent: you do validate the input in that case, but don't in the case that both files are provided, so the user has to remember that if he intends to rely on the input being checked.

My first suggestion is thus to change your interface: only prompt for things that are not already provided, and if you detect an error, report it and exit.

Now to the code: you have a few cases where the program can go in an infinite loop.  This happens if the user closes std::cin, or if the user provided two filenames via argv and then at least one failed to open: you'll keep trying to open it and filesOpen will never be true.

Secondly, you're using operator>> in most places, but use std::cin.get() to ask the user whether he's sure.  This will likely break if the user provides one command-line argument and then some file fails to open.

Thirdly, the condition of your loop seems strange to me.  Why use an extra bool that you then set at the very end instead of using break or return to get out of the loop, or, better, checking the condition directly?  You can use a do-while loop if you want to save yourself one check, though I wouldn't bother as the performance effect will be negligible, while the code will be clearer.

As for the switch construct: I'd use a helper function or two instead.  The code is sufficiently small for it to be clear, especially with the comment, but I don't think it wins you anything over two function calls.  In general, the function looks too big to me, but I've already covered that above.

Last and least, mixing std::printf and std::cin is strange.  I can't come up with any technical problems, but mixing two styles without a good reason is generally more trouble than it's worth.


The main thing about the implementation I am unsure about is making the "Instance" private and creating number of static functions to expose the functionality. This means I can call Local.GetString instead of Local.Instance.GetString which is less clunky. I have not seen any singleton implementation which does this so I wonder if there is some problem with it.

I don't think there's a problem with that. Your static methods are only doing things which otherwise the calling code would do.

  I am also using locking but I don't see how to get around that so that is probably fine.

If your code is single-threaded then you don't need locking at all.

If your code is multi-threaded, perhaps you can construct the singleton before the multi-threading starts: for example by calling a static Locale.CreateInstance method in your program's Main (or from Application_Start if your code is ASP.NET).

If your code is multi-threaded then the non-static Locale methods must also be thread-safe: including your Locale._managers dictionary accessors, and your ResourceManager methods. ResourceManager is already documented as a thread-safe class.

An alternative to the explicit lock you implemented is to use the ConcurrentDictionary class instead of Dictionary, specifically its GetOrAdd method, something like:

ResourceManager GetResourceManager(Type resourceType)
{
    Func<Type, ResourceManager> valueFactory =
        resourceType => new ResourceManager(resourceType);
    return managers.GetOrAdd(resourceType, valueFactory);
}

Stylistically, some people recommend auto-declaring variables types as var for example ...

    var valueFactory = resourceType => new ResourceManager(resourceType);

... or simply ...

ResourceManager GetResourceManager(Type resourceType)
{
    return managers.GetOrAdd(resourceType, resourceType => new ResourceManager(resourceType));
}


Recursive download articles and dump to MongoDB

The logic for getting 100 posts is duplicated for the case of the initial load and subsequent loads with an offset. It would be better to refactor in a way to eliminate the duplicated logic:

params = {'number': 100}
offset = 0

while True:
    response = requests.get(url, params=params).json()
    found = response['found']
    posts = response['posts']
    db.posts.insert_many(posts)
    print 'Inserted {number} posts'.format(number=len(posts))
    offset += 100
    if offset >= found:
        break
    print 'We have {left} posts left to go'.format(left=found-offset)
    params['offset'] = offset


Showing the minimum of letters needed for a palindrome

This is an obvious candidate: (there are more lines containing this anti-pattern):

for(j = 0, k = 0; j < strlen(str); j++) {...}

Will result in the strlen being called on every iteration, nmaking the whole thing an O(N*N) operation.

A better way to do the same would be:

size_t len,j,k;

len = strlen(str);
for (j=k=0; j < len;j++) {...}

Next:

char* _remove(char*, int);
elmt* _ncptr(char [], int, elmt*, int );
elmt* _add(elmt* root, elmt* elm);
int _count(elmt* root);
int _last_p(elmt* root);
int __exist (elmt* root, char* str, int h);

Identifiers with leading underscores are reserved for the implementation and / or the library.

In short: don't use them (unless you are implementing the implemnetation or the library, but in that case you would not ask this question, methinks)

Next: the _remove function is terrible. I malloc() one byte too short, calls strlen() at every heartbeat, and ignores the existing string functions.

char *newremove(char *org, size_t pos) {
    size_t len;
    char *new;

    len =  strlen(org)
    new = malloc(1+len);

    if (pos < len) {
      memcpy(new, org, pos);
      memcpy(new+pos,org+pos+1, len-pos);
      }

    else {
      memcpy(new, org, len+1);
      }

return new;

}


Convert string array to string with separator

Before I review your code I want to point out that Java has a String.join() method which does exactly that. Now to your code:

You use StringBuilder, good. You take care of not appending a seperator after the last and not prepending before the first element, also good. You don't handle null values though, it's your decision if you want to handle them separately or just let Java just throw a NPE. For the separator however, a null appends literally null to the String, I'd rather default to "" if separator is null. A way to get rid of the flag:

public String getArrayAsString(String[] stringArray, String separator) {
    if(stringArray == null || stringArray.length == 0) return "";

With this we already ensured that our stringArray has at least one entry. What we can do now is initialize the StringBuilder with the first String:

    StringBuilder finalString = new StringBuilder(stringArray[0]);

Since all strings after the first one need to prepend the separator, we don't need the flag anymore. Unfortunately, we can't use a foreach loop, since we have to start at index 1 as the element at index 0 is already in the StringBuilder:

    for(int i = 1; i < stringArray.length; ++i)
        finalString.append(separator).append(stringArray[i]);

And then just return what we got:

    return finalString.toString();

Whole function:

public String getArrayAsString(String[] stringArray, String separator) {
    if(stringArray == null || stringArray.length == 0) return "";

    StringBuilder finalString = new StringBuilder(stringArray[0]);

    for(int i = 1; i < stringArray.length; ++i)
        finalString.append(separator).append(stringArray[i]);

    return finalString.toString();
}

Edit:

In String.join() the parameters are swapped, so the separator comes first, the array second:

    String[] arr = new String[]{"Hello", "World"};
    System.out.println(String.join(" | ", arr));
    System.out.println(getArrayAsString(arr, " | ")); //Your function

Output:

Hello | World
Hello | World

Working code at ideone.com


Thing I like less is that you're forcing caller to deal with a static method. I appreciate that kind of helpers but they should be an alternative (maybe with default settings) instead of the only way to go. Why?

If you need more parameters (or to reorder them) then you need to change all calling points.
If you add complex parameters (such as a formatter) then calling point will quickly become a mess.
They're viral. If you separate UI from underlying logic and you need to delegate some decisions to different places then you can't pass around an Hex class (where each component/control may fill its own properties) because you have a single method call.
If a static method becomes complex enough then it will also be harder to test.

I'd also change name from Hex to something that describe what your class is doing. HexStringFormatter? HexStringConverter? I'd give two alternatives:

var formatter = new HexStringFormatter();
Console.WriteLine(formatter.ConvertToString(example));

Note that in this simple case it may even be (an helper method here just save few characters, what's for?):

Console.WriteLine(new HexStringFormatter().ConvertToString(example));

A more complex case may be like this:

var formatter = new HexStringFormatter();
formatter.BytesPerLine = 32;
formatter.Content = HexStringFormatterOutput.Ascii
    | HexStringFormatterOutput.Header;

These settings may come from UI, now you can return formatter object to another method for example in charge to read data without knowing where settings come from...

Note that I also introduced an enum instead of multiple boolean properties but it's not mandatory and not even always suggested, it depends case by case (I like the enum because I can save it in one shot without any effort in my configuration files).

Also you may want to make Hex sealed, it's not intended (so far) to be extended.

You may accept IEnumerable<byte> instead of byte[]. Performance impact in WriteBody() with foreach is negligible, and you do not need ToArray() in your example. Not such big gain but it will let you read huge files that does not fit in memory (because you can read them block by block without need to convert to byte[] all the content).

In this regard you may want to change the output of your class. Now you need to build a huge output string, if content will be written to disk then it's a waste of resources. Write output to a TextWriter. Caller will have responsibility to give you a StringWriter if he wants to output to a string. In this case it may be nice to introduce a static helper method for the most common use case. More complex use case may be like this:

using (var output = new StringWriter())
{
    var formatter = new HexStringFormatter();
    formatter.Output = output;
    formatter.BytesPerLine = 32;

    formatter.ConvertToString(example);
    Console.WriteLine(output.ToString());
}

HOWEVER note that HexStringFormatter accepts a TextWriter and Console.Out is a TextWriter! Code will then be simplified to:

var formatter = new HexStringFormatter();
formatter.Output = Console.Out;
formatter.BytesPerLine = 32;

formatter.ConvertToString(example);

What if you need to write it to a text file?

using (var stream = new StreamWriter("path_to_file"))
{
    var formatter = new HexStringFormatter();
    formatter.Output = stream;
    formatter.BytesPerLine = 32;

    formatter.ConvertToString(example);
}

Of course you may want to introduce few helper methods for this (now they can make sense but keep them as simple as possible), something like this:

public static string DumpToString(IEnumerable<byte> data)
{
    using (var output = new StringWriter())
    {
        var formatter = new HexStringFormatter();
        formatter.Output = output;

        formatter.ConvertToString(data);
        return output.ToString();
    }
}

public static void DumpToFile(string path, IEnumerable<byte> data)
{
    using (var output = new StreamWriter(path))
    {
        var formatter = new HexStringFormatter();
        formatter.Output = output;

        formatter.ConvertToString(data);
    }
}

public static void DumpToConsole(IEnumerable<byte> data)
{
    var formatter = new HexStringFormatter();
    formatter.Output = Console.Out;

    formatter.ConvertToString(data);
}

Now your first example will be again like this:

HexStringFormatter.DumpToConsole(
    Enumerable.Range(0, 256).Select(x => (byte)x));

Few other minor things. Your Translate() function should be simplified and made static). Also do not need to get a new encoding for each call, use Encoding.ASCII. b < 32 is clear for most of us but I'd make it explicit. For now let's keep GetString() but see later...

private static string Translate(byte b)
{
    if (IsPrintableCharacter(b))
        return Encoding.ASCII.GetString(new[] { b });

    return "."
}

private static bool IsPrintableCharacter(byte b) => b > 32;

Now let's think...you're working with ASCII and byte is in range [0...255] then you may directly cast it to char (after leave to representation issues you mentioned in your Console codepage settings), you avoid to create so many strings and you do not even need any encoding:

private static char Translate(byte b)
    => IsPrintableCharacter(b) ? (char)b : '.';

Code like i & 0xFF in WriteHeader() is little bit misleading, IMO. If _bytesPerLine contains an invalid value then it should throw ArgumentOutOfRangeException when you set it, it shouldn't be silently ignored. Your code will then be simplified everywhere.

About your main loop, you do not need to save _length field because you already have the input buffer. I'd also try to give names to all those ifs (=introduce bool locals or separate functions) anyway after refactoring to use IEnumerable<byte> it should look much simpler.


Return index of array where sum first passes n

I'm not sure what you mean by "This does the trick but not very efficiently". I don't really see a way to make the algorithm more efficient, as it is just making a single pass over the array and exits early when it gets the answer. If the input is really long, you could convert it to a byte array instead of splitting it to cut down on the casts, but then you would have to nest the loops, add a subtraction to convert the ascii codes to numbers, add multiplications to keep track of multiples of 10, etc. This would likely be a lot slower than the current method unless you were working with strings on the order of kilobytes.

That said, a couple of observations about the code.  I'd personally use a For loop instead of a While loop to prevent you from running outside of the array bounds for inputs where the target number you are looking for is higher than the sum of the complete array.  For example, with the input string of "6-7-7-10-7-6", a target higher than 43 will overrun the array bound and throw an error.  You'll get a similar error if it is passed an empty string (Split will happily give you an array with an upper bound of -1 in that case).

Also note that you are not returning the zero based index, you are returning the one based position of the token in the string.  If this is the desired behavior, I'd rename the function to make it obvious that you can't use the return value to index into the array.

About the only thing that I would do to make this a tiny bit more efficient would be to use a String array instead of a Variant and use explicit casting so the run-time doesn't have to resolve the Variants for you more than once. Even this improvement will likely be unnoticeable on any reasonable sized input (you'll overflow an Integer long before you'd notice the performance increase anyway).

Maybe something like this:

Public Function getPositionFromSum(source As String, target As Integer) As Integer

    Dim sides() As String
    Dim sum As Integer
    Dim index As Integer

    getPositionFromSum = -1    'Or whatever the "not found" condition is.
    sides = Split(source, "-")

    For index = 0 To UBound(sides)
        sum = sum + CInt(sides(index))
        If sum > target Then
            getPositionFromSum = index + 1
            Exit For
        End If
    Next

End Function


Project Euler #11"numbers in a grid" in Rust

Just like most people not actively involved in the language design, I'm still finding my feet with Rust as well, so take what I have to say with a large grain of salt.

You don't need to define your own max function: there is one already in the standard library, in std::cmp to be exact:

pub fn max<T: Ord>(v1: T, v2: T) -> T

This will work for anything that has an impl Ord, which int certainly does.

You can avoid the casts if you simply read everything in as a uint in the first place. In fact, it's probably a good idea to split up the code reading and parsing the file from the code that does the calculation. I'd write it something like:

use std::io;

fn read_grid(path: &str) -> Vec<Vec<uint>> {
    let path = Path::new(path);
    let mut file = io::BufferedReader::new(io::File::open(&path));
    let mut lines = file.lines().map(|x| x.unwrap());
    let mut grid: Vec<Vec<uint>> = vec![];

    for line in lines {
        let option = line.as_slice().split(' ').map(|x| -> Option<uint> from_str(x.trim()));
        grid.push(option.filter(|x| x.is_some()).map(|x| x.unwrap()).collect());
    }
    grid
}

This will also skip over any non-convertible values (that is, anything that from_str(x.trim()) gives None from.

I don't doubt there are still much better ways of writing this, but that's about where I'm at for now.


You can create a fruit with the common properties before the if:

var fruitList = [];
var fruitExpired = GetFruitStatus();
var fruitName = "Mango";
var companyName = "Limited";

var fruit = {
    fruitName: name,
    fruitCompany: companyName
}

if (fruitExpired) {
    fruit.expiredCrate = GetExpiredCrate().ID;
} else {
    fruit.crateId = GetCrate().ID;
}

list.push(fruit);

Also, beware where you put { } in your code, it's not C# and a { after if or else should be on the same line.


Asynchronous model fitting that allows termination in Python

Two minor notes, your terminate function should just use the is_alive test you've already defined.

def is_alive(self):
    return self.proc is not None and self.proc.is_alive()

def terminate(self):
    if self.is_alive():
        self.proc.terminate()
    self.proc = None

Also in time_elapsed you should test if self.start_time is None. That matches directly to the empty value it begins with and communicates the intent better.

def time_elapsed(self):
    if self.start_time is not None:
        return 0


You can avoid loop altogether.

 With Activesheet.UsedRange
     .Value = Application.Trim(.Value)
 End With

Warning: will give error if any cell has more than 255 characters.


Add lines from files to corresponding dictionaries

There are some ways you can improve your code:

Rather than building a dictionary and then manually assigning each value you can assign to l1[0] etc straight away.
Dict['dictio1'] = {'title': "", "name": "", "date": "", "feedback": ""}
Dict['dictio1']["title"] = l1[0]
Dict['dictio1']["name"] = l1[1]
Dict['dictio1']["date"] = l1[2]
Dict['dictio1']["feedback"] = l1[3]

Dict["dictio1"] = {
    "title": l1[0],
    "name": l1[1],
    "date": l1[2],
    "feedback": l1[3],
}

You should use a for loop over the paths and have the with inside it. Only building one dictionary at a time.
for key, path in ...:
    with open(path) as f:
        lines = []
        for line in f:
            if not line.isspace():
                lines.append(line.rstrip())
        Dict[key] = {
            "title": l1[0],
            "name": l1[1],
            "date": l1[2],
            "feedback": l1[3],
        }

We can use a list comprehension to build lines with some sugar.
lines = [line.rstrip() for line in f if not line.isspace()]

Putting this all together we can get:
data = {}
paths = [
    ("dictio1", "C:/Users/user/Desktop/001.txt"),
    ("dictio2", "C:/Users/user/Desktop/002.txt"),
]
for key, path in paths:
    with open(path) as f:
        lines = [line.rstrip() for line in f if not line.isspace()]
        data[key] = {
            "title": lines[0],
            "name": lines[1],
            "date": lines[2],
            "feedback": lines[3],
        }

with open('file.json', 'w') as file_json:
    json.dump(data, file_json, indent=2)

I would recomend you change your JSON structure to remove the outer dictionary and instead use a list. This would make all your code simpler not only building it here but consuming it later.
This would look like:
data = []
paths = [
    "C:/Users/user/Desktop/001.txt",
    "C:/Users/user/Desktop/002.txt",
]
for path in paths:
    with open(path) as f:
        lines = [line.rstrip() for line in f if not line.isspace()]
        data.append({
            "title": lines[0],
            "name": lines[1],
            "date": lines[2],
            "feedback": lines[3],
        })

with open('file.json', 'w') as file_json:
    json.dump(data, file_json, indent=2)


Deleting millions of rows from a MSSQL server table

The performance problem is due to the non-sargable expression YEAR(CREATEDATE).  Applying a function to a column in a WHERE clause prevents efficient use of the index on the column.  Below is an alternative technique, which uses an inclusive start and exclusive end for the datetime range.

Note the use of SET ROWCOUNT is deprecated for DELETE, INSERT and UPDATE statements.  Use TOP instead.

DELETE TOP(10000) table1
FROM dbo.table1
JOIN dbo.table2
    ON table2.DOC_NUMBER = table1.DOC_NUMBER
    AND table2.DOC_YEAR = table1.DOC_YEAR
WHERE
    CREATEDDATE >= '20070101'
    AND CREATEDATE < '20100101';

I'm not sure the purpose of @tmpcount in your script other than perhaps controlling the number of iterations for testing.


Avoid global variable for callback function called by function with no arguments

You can avoid the global by creating a closure around the function to be called by the maps api code. To do this define another function that returns a function. You can pass in the callback here.
The below code is runnable in single file but you will need to split it across pages in your real code.
function createInitMap(callback){
    return () => {
        const mapOptions = {
            center: {lat: 0, lng: 0},
            zoom: 7
        };
        window.map = new google.maps.Map(document.getElementById("map"), mapOptions);

        if (typeof callback !== 'undefined') {
            callback();
        }
    }
}

/*
    In first page
*/
//<script type="text/javascript" src="js/index.js"></script>
let initMap = createInitMap(() => console.log('first callback'));
//<script type="text/javascript" src="js/maps.js"></script>

initMap(); // simulate google maps calling your function

/*
    In second page
*/
//<script type="text/javascript" src="js/index.js"></script>
initMap = createInitMap(() => console.log('second callback'));
//<script type="text/javascript" src="js/maps.js"></script>

initMap();  // simulate google maps calling your function

Ensure the return value of the function is assigned to the global name initMap (It might need to be window.initMap).


Convert characters to octal, binary, and integer

Unnecessary Headers
The #includes for iterator and bitset are not needed, the code compiles fine without them, iterator may be included indirectly through vector.

Adding unnecessary headers can increase compile/build times and may cause other problems in larger more complex programs.

Portability
This program is currently not portable for 2 reasons, the use of the Visual Studio generated #include "stdafx.h" and the use of the non-standard for each loop. It might be better to embed #include "stdafx.h" within ifdef/endif.

#ifdef windows
#include "stdafx.h"
#endif

I compiled this in Visual Studio 2017 on Windows 10 and it actually reported a compile error on the for each loop. The suggested fix was to use a range based for loop.

1>------ Build started: Project: octbinintconv0, Configuration: Debug Win32 ------
1>octbinintconv0.cpp
1>d:\projectsnfwsi\codereview\octbinintconv0\octbinintconv0\octbinintconv0.cpp(18): warning C4244: '+=': conversion from 'double' to 'int', possible loss of data
1>d:\projectsnfwsi\codereview\octbinintconv0\octbinintconv0\octbinintconv0.cpp(40): error C4496: nonstandard extension 'for each' used: replace with ranged-for statement
1>d:\projectsnfwsi\codereview\octbinintconv0\octbinintconv0\octbinintconv0.cpp(55): warning C4018: '<': signed/unsigned mismatch
1>Done building project "octbinintconv0.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

You might want to replace the for each loop with the following code, which uses an iterator and is part of standard C++.

    for (auto c : buffer)
    {
        int x = c - '0';
        std::stringstream opt;
        opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << "\n";

        std::string val = opt.str();

        std::copy(val.begin(), val.end() - 1, std::back_inserter(collection));
    }

Type Mismatches
A good practice is treating warning messages as errors, since they point to potential logic errors. The pow() function returns double and the result is being truncated, it might be better to use a static cast in the code to show that this is intentional.

    decimalNum += (octalNum % 10) * static_cast<int>(pow(8, count));

In this for loop it would be better to define the local variable i as size_t rather than int, in any of the STL container classes the function size() returns size_t.

    for (size_t i = 0; i < bitsize.size(); i++)

Complexity
Creating the function OctalToBinary(int octalNum) was good but there are two more functions that main() can be broken up into, they have even been identified by comments, both of the for loop are good candidates for functions.


Comma Code (project from "Automate the Boring Stuff with Python")

Ludisposed's answer is already a great improvement, however it fails to take into account some cornercases:

It only works with lists of strings.
For lists of length 1, like ["foo"], it returns " and foo" (your code has the same problem).
It raises an IndexError on an empty list.

This code avoids these problems:

def list_to_string(a_list):
    if not a_list:
        return ""
    elif len(a_list) == 1:
        return str(a_list[0])
    else:
        body = ", ".join(map(str, a_list[:-1]))
        return '{0} and {1}'.format(body, a_list[-1])

This does not currently have the Oxford comma, like your code. But you can easily add it as another special case (don't add it when len(a_list) == 2 and add it otherwise). Thanks to @DavidK for pointing this out in the comments.


DisjointSet with O(1) find and O(1) amortised union

Union is \$O(\log n)\$, not \$O(1)\$

Consider a case where 1024 elements are initially added to their own set.  Then do 512 unions of pairwise neighbors to make 512 sets of 2 elements each.  This requires 512 copies in the "addAll" step, because half the elements are moved to a new set.  Then do 256 unions of pairwise neighboring sets to make 256 sets of 4 elements each.  This also requires 512 copies, because again half of all elements are moved to a new set.  Continue to do unions in passes, where each pass you end up with 2x the number of sets as before.  In the end, you will need 10 passes, and each pass will require 512 elements to be moved.

As you can see from the above, with N=1024, you end up with N unions taking N * log N copies, or on average log N copies per union.


A lot of the code in your while loop can be replaced with a for loop using enumerate() and a toggled boolean.

You should be able to replace your code from c = len(lines) (line 21) down through your entire while loop with:

skip = False
for index, line in enumerate(lines):
    if line.startswith("```"):
        skip = not skip
    else:
        if not skip:
            if line.startswith("\t"):
                lines[index] = line.replace("\t", _TAB_2_SPACE)

I can't test this right now, so please let me know if you run in to any problems with this implementation.


Producing a Pandas Data Frame from Long to Wide format Efficiently

Solution in R

In your last code snippet, you're mixing code from tidyverse and data.table packages. I don't consider this to be completely wrong, but I would rather avoid it to increase readability and consistency.

library(magrittr)
library(data.table)
library(bench)

# data copied from OP
dat <- structure(list(Name = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L),
                                       .Label = c("A", "B", "C", "D"),
                                       class = "factor"),
                      Date = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L),
                                       .Label = c("1/1/2018", "1/4/2018"),
                                       class = "factor"),
                      Val1 = 1:7,
                      Val2 = 2:8),
                 class = "data.frame", row.names = 1:7)

dat
#>   Name     Date Val1 Val2
#> 1    A 1/1/2018    1    2
#> 2    B 1/1/2018    2    3
#> 3    C 1/1/2018    3    4
#> 4    D 1/4/2018    4    5
#> 5    A 1/4/2018    5    6
#> 6    B 1/4/2018    6    7
#> 7    C 1/4/2018    7    8
str(dat)
#> 'data.frame':    7 obs. of  4 variables:
#>  $ Name: Factor w/ 4 levels "A","B","C","D": 1 2 3 4 1 2 3
#>  $ Date: Factor w/ 2 levels "1/1/2018","1/4/2018": 1 1 1 2 2 2 2
#>  $ Val1: int  1 2 3 4 5 6 7
#>  $ Val2: int  2 3 4 5 6 7 8

Tidyverse Solution

tidyr::gather(dat, key = "key", value = "value", -Date, -Name) %>%
    tidyr::unite("id", key, Date, sep = ".") %>%
    tidyr::spread(id, value)
#>   Name Val1.1/1/2018 Val1.1/4/2018 Val2.1/1/2018 Val2.1/4/2018
#> 1    A             1             5             2             6
#> 2    B             2             6             3             7
#> 3    C             3             7             4             8
#> 4    D            NA             4            NA             5

data.table Solution

dt <- data.table(dat)
dt_long <- melt(dt, id.vars = c("Name", "Date"))

dcast(dt_long, Name ~ variable + Date)
#>    Name Val1_1/1/2018 Val1_1/4/2018 Val2_1/1/2018 Val2_1/4/2018
#> 1:    A             1             5             2             6
#> 2:    B             2             6             3             7
#> 3:    C             3             7             4             8
#> 4:    D            NA             4            NA             5

Benchmark

As you can see, data.table is already much faster with 1,200 rows.

nrows <- 1.2e4
# nrows <- 1.2e6
dat2 <- expand.grid(Name = LETTERS[1:4],
                    Date = seq(as.Date("2018-01-01"), by = "days", length.out = nrows/4))
dat2$Val1 <- sample(1:8, nrow(dat2), TRUE)
dat2$Val2 <- sample(1:8, nrow(dat2), TRUE)

f1 <- function(dat) {
    tidyr::gather(dat, key = "key", value = "value", -Date, -Name) %>%
        tidyr::unite("id", key, Date, sep = ".") %>%
        tidyr::spread(id, value)
}

f2 <- function(dat) {
    dt <- data.table(dat)
    dt_long <- melt(dt, id.vars = c("Name", "Date"))
    dt_wide <- dcast(dt_long, Name ~ variable + Date)
}

mark(tidyverse = f1(dat2),
     datatable = f2(dat2),
     check = function(x, y) all.equal(x, y, check.attributes = FALSE))
#> Warning: Some expressions had a GC in every iteration; so filtering is
#> disabled.
#> # A tibble: 2 x 10
#>   expression     min    mean  median     max `itr/sec` mem_alloc  n_gc
#>   <chr>      <bch:t> <bch:t> <bch:t> <bch:t>     <dbl> <bch:byt> <dbl>
#> 1 tidyverse  184.4ms 189.7ms 187.9ms 196.7ms      5.27   15.73MB     5
#> 2 datatable   43.1ms  45.9ms  45.4ms  51.7ms     21.8     5.36MB     2
#> # ... with 2 more variables: n_itr <int>, total_time <bch:tm>

Created on 2019-02-26 by the reprex package (v0.2.1)


Converting a double to a std::string without scientific notation

As mentioned in the comments of the other answer, your decimal floating point numbers are stored as binary and rarely have finite representations.

If you simply want code that passes your test I would mention that it is much easier to remove padding from std::fixed than it is to expand the scientific notation.

#include <iostream>
#include <string>
#include <sstream>
#include <limits>
#include <iomanip>
#include <cstdlib>
#include <cassert>
#include <cstddef>

static std::string to_string(double d)
{
    std::ostringstream oss;
    oss.precision(std::numeric_limits<double>::digits10);
    oss << std::fixed << d;
    std::string str = oss.str();

    // Remove padding
    // This must be done in two steps because of numbers like 700.00
    std::size_t pos1 = str.find_last_not_of("0");
    if(pos1 != std::string::npos)
        str.erase(pos1+1);

    std::size_t pos2 = str.find_last_not_of(".");
    if(pos2 != std::string::npos)
        str.erase(pos2+1);

    return str;
}

static void test_string_conversion(const std::string& str)
{
    assert( to_string( atof(str.c_str()) ) == str );
}

int main(void)
{
    test_string_conversion( "1.5203" );
    test_string_conversion( "-1.025" );
    test_string_conversion( "3.1415" );
    test_string_conversion( "-38271" );
    test_string_conversion( "0.8382" );
    test_string_conversion( "-0.8382" );
    test_string_conversion( "7" );
    test_string_conversion( "-3" );
    test_string_conversion( "0.0000024" );
    test_string_conversion( "7300000000" );
}


Splitting a long string based on its graphical presentation

General remarks

Here are some general remarks that could make your code look a little cleaner :

Avoid using ; at the end of an instruction unless you have to put multiple instructions in the same line.
Document the functions properly: The description of the complition parameter of splitToFitSize isn't well formatted.
The correct spelling of complition is completion.
This is subjective and probably nitpicky: Put a space only where needed, one after the closing curly brace of a scope: } else, and none before a punctuation sign:  (size: size, font: font).

Catching the culprits

Sources of slow code:

" \(content)": String interpolation is slow as previously stated here.
self.components(separatedBy: .whitespaces): This has both a time and space complexity of O(n). Better iterate over the story with a String.Index.
DispatchQueue.global(qos: .background) : This is the lowest priority you could give to code and it wastes time by switching from the main thread to a background one, and back.
contents.removeFirst(): This is called in multiple places and repeatedly. Each call is O(n) since all the elements of the contents array shifted (Have a look here). This means that this algotithm shifts the elements of the contents array n + (n-1) + (n-2) + ... + 1 times. Knowing that :
$$n + (n-1) + (n-2) + ... + 1 = \frac{n(n+1)}{2}$$

it makes this algorithm O(n2), with n being the number of elements in contents. To circumvent this use an index that traverses the array.

Alternative implementation

Here is an alternative solution to split a string into a given size using a certain font :

extension String {

    static let blanks: [Character] = [" ", "\n", "\t"]

    func splitToFit (size: CGSize, using font: UIFont) -> [String] {
        var output: [String] = []
        var (fitted, remaining) = fit(self, in: size, using: font)
        var lastCount = fitted.count
        output.append(fitted)

        while remaining != "" {
            (fitted, remaining) = fit(remaining,
                                      in: size,
                                      using: font,
                                      lastCount: lastCount)
            lastCount = fitted.count
            output.append(fitted)
        }

        //Trim white spaces if needed
        //return output.map { $0.trimmingCharacters(in: .whitespacesAndNewlines)}
        return output
    }

    private func fit(
        _ str: String,
        in size: CGSize,
        using font: UIFont,
        lastCount: Int = 0) -> (String, String) {

        if !str.isTruncated(in: size, using: font) {
            return (str, "")
        }

        var low = 0
        var high = str.count - 1
        let lastValidIndex = high
        var substr = ""
        let step = lastCount/10  //Could be adjusted

        if lastCount != 0 {
            high = min(lastCount, lastValidIndex)
            while !str[0..<high].isTruncated(in: size, using: font) {
                low = high
                high = min(high + step, lastValidIndex)
            }
        }

        while low < high - 1 {
            let mid = low + (high - low)/2
            //Or more efficiently
            //let mid = Int((UInt(low) + UInt(high)) >> 1)
            //Have a look here https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html

            substr = str[0..<mid]

            let substrTruncated = substr.isTruncated(in: size, using: font)

            if substrTruncated {
                high = mid
            } else  {
                low = mid
            }
        }

        substr = str[0..<low]

        while !String.blanks.contains(substr.last!) {
            substr.removeLast()
            low -= 1
        }

        let remains = str[low..<str.count]
        return (substr, remains)
    }
}

It calls these other extensions :

extension String {
    func isTruncated(in size: CGSize, using font: UIFont) -> Bool {
        let textSize = (self as NSString)
            .boundingRect(with: CGSize(width: size.width,
                                       height: .greatestFiniteMagnitude),
                          options: .usesLineFragmentOrigin,
                          attributes: [.font: font],
                          context: nil).size

        return ceil(textSize.height) > size.height
    }

    subscript (range: Range<Int>) -> String {
        let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
        let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
        let range = startIndex..<endIndex

        return String(self[range])
    }
}

This code is inspired by this library but twice as fast . Further improvements are possible.

It was tested using the following code:

class ViewController: UIViewController, UIScrollViewDelegate {

    var scrollView: UIScrollView! {
        didSet{
            scrollView.delegate = self
        }
    }

    private let font = UIFont.systemFont(ofSize: 17)

    override func viewDidLoad() {
        super.viewDidLoad()

        let width = view.frame.width
        let height = view.frame.height
        let labelSize = CGSize(width: width - 40.0, height: height - 60.0)
        //Split the story here
        //let start = Date()
        let strings = story.splitToFit(size: labelSize, using: font)
        //let end = Date()
        //print("time =", end.timeIntervalSince(start))

        let scrollViewFrame = CGRect(x: 0,
                                     y: 0,
                                     width: width,
                                     height: height)

        scrollView = UIScrollView(frame: scrollViewFrame)
        scrollView.contentSize = CGSize(width: width * CGFloat(strings.count), height: height)
        scrollView.isPagingEnabled = true

        let colors: [UIColor] = [.red, .green, .blue]

        for i in 0 ..< strings.count {
            let label = UILabel()
            label.numberOfLines = 0
            label.frame = CGRect(origin: CGPoint(x: width * CGFloat(i) + 20.0,
                                                 y: 40.0),
                                 size: labelSize)
            label.backgroundColor = colors[i % 3]
            label.font = font
            label.text = strings[i]
            label.translatesAutoresizingMaskIntoConstraints = false
            scrollView.addSubview(label)
        }

        view.addSubview(scrollView)
    }
}

with story being a 10-paragraph string, 1104 total words, 7402 total characters, generated on this website, it takes 54ms on my local machine to split the story.

If the story is too long, and to avoid blocking the main thread I would recommend adding subviews asynchronously to the UIScrollView as the fitted strings are calculated one by one.


Some thoughts:

Consider making your middleware package into a proper (private?) npm package and consume it as such in the main application. This would also allow better reuse across other applications that may need this behavior.
const log = require('../../logger'); This relative reference seems problematic. I would guess your logger should also be a proper npm package (or in same package as your middleware if this is a custom logger).  At a very minimum, I would think you would want to use path or similar to get to an absolute file reference based on the location of your middleware file to the working directory.
Your methodology for determining 'production' environment seems fragile. Why is it up to your middleware package to have a hard-coded string in it that determines whether production behavior is to be expressed?
The deleteErrorStack() function seems superfluos and actually obfuscates the logic of what is happening in the handleErrors function.  Why not just have this single line of code inside the handleErrors function so intent is much clearer.

For example:

const handleErrors = () => {
  return (err, req, res, next) => {
    const statusCode = getStatusCode(err.statusCode);
    const errorContext = createErrorContext(statusCode);

    if(isProdEnv(req.app.get('env')) {
        delete err.stack;
    }
    res.status(statusCode).json(errorContext);
  };
};

One could possibly argue that the deletion of the stack trace information from err is logic this should exist within your context creation method, as this is really a display concern, not an error handling concern.


Calculating which direction my enemy should face when moving

In my opinion you should first get the axis of the maximum direction via comparison of xDiff with yDiff:

protected FacingDirections CalculateFacingDirection(Vector2 navPos)
{
    Vector2 curPos = transform.position;

    float xDiff = Mathf.Abs(navPos.x - curPos.x);
    float yDiff = Mathf.Abs(navPos.y - curPos.y);

    if (xDiff > yDiff) // we are moving more along X axis
    {
        return navPos.x > curPos.x ? FacingDirections.Left : FacingDirections.Right;
    }
    // we are moving more along Y axis
    return navPos.y > curPos.y ? FacingDirections.Up : FacingDirections.Down;
}


Yes its still the observer pattern (details in my comment on the question).

But there are a few implementation details that are bad for a C++ context.

Good interface for your observer:

class Observer
{
public:
    virtual void notifyBefore() = 0;
    virtual void notifyAfter() = 0;
};

But you should also make the destructor virtual. It is quite probable that these objects will be destroyed via a pointer to the base class. Without a virtual destructor this is undefined behavior.

You have the basics of subject correct.

class Subject
{
public:
    void attachObserver(Observer * observer)
    {
        observers.push_back(observer);
    }

My one problem is here. You are passing a pointer to an observer. Pointers do not express ownership. So it is unclear for future users of your object if you should pass a dynamically allocated object or a a pointer to an automatic object. It becomes clear by reading your class that you are not taking ownership of the pointer and your class always assumes that it is not NULL. So in this case it is probably better to pass it by reference.

If there are cases were ownership can be passed then you should use smart pointers. A quick search on google for smart pointers or ownership semantics should give you lots of references.

    void attachObserver(Observer& observer)
    {
        observers.push_back(&observer);  // Save the address of the observer
                                         // It is the responsibility of the observer
                                         // to make sure it lives long enough or
                                         // detaches itself on destruction.
    }

Implementation:

class ConcreteObserver : public Observer
{
public:
    void notifyBefore()
    {
        std::cout << "You called me before..." << std::endl;
    }

    void notifyAfter()
    {
        std::cout << "You called me after..." << std::endl;
    }
};

In C++11 we added the override keyword. This should be used in case you refactor your class. This will help in finding locations were you have misnamed the functions:

 void notifyAfter() override ....

This is not Java

auto subject = new ConcreteSubject;
subject->attachObserver(new ConcreteObserver);

You should prefer to use automatic objects (that is perfect here). If you are going to use new then you should wrap the result in a smart pointer to make sure the allocation is exception safe.


I think part of your problem is, you aren't taking the recursion far enough.  I would suggest, that the loop be replaced by recursion.  This can be accomplished quite easily by making sure the array is sorted first, and advancing from highest to lowest.  Since this will require extra parameters and the addition of calling the sort function.  Making the recursive function private and using a  public helper overload, will neaten things quite a bit.  Something like this should work:

public class Solution
{

    public static int coinChange(int[] coins, int amount)
    {
        Arrays.sort(coins);
        return coinChange(coins, amount, coins.length - 1, 0);
    }

    private static int coinChange(int[] coins, int amount, int index, int numCoins)
    {
        if (amount == 0)
        {
            return numCoins;
        }
        if (amount < coins[0])
        {
            return -1;
        }
        if (amount >= coins[index])
        {
            int tempCoins = (int) (amount / coins[index]);
            int tempAmount = amount - (tempCoins * coins[index]);
            if (tempAmount == 0 || tempAmount >= coins[0])
            {
                amount = tempAmount;
                numCoins += tempCoins;
            }
        }
        index--;

        return coinChange(coins, amount, index, numCoins);
    }
}

The usage would still be the same(int numCoins = Solution.coinChange(new int[]{1,2,5},11);).

Your description of the problem didn't mention whether the array would be sorted.  If it is guaranteed to be sorted that line can be left out.

You'll notice that there are still 3 states to check for, but that each one is only checked for once per recursion.

I didn't like the idea of making the amount go below 0.  Simply stopping when the amount was either 0 or less than the smallest coin, seems a cleaner way of doing things, to me.


I don't quite see the purpose of your class. You are basically taking an existing class from the .NET Framework and wrapping it up in something that only exposes a fraction of the functionality.

The code also relies on a lot of hard-coded settings. While specifying a specific user-agent might not cause too much concern, always using a specific HTTP proxy will.

You provide the results of the request in two ways. The actual HTML is returned as a string from the method (what if the site returns binary content?), while the cookies are set in a property. It's strange to have a class called Request that contains a property starting with Response. The approach taken by the HttpWebRequest is much cleaner as it returns a whole class that contains all the information of the reply.


Does this usage of AtomicLong look thread-safe?

No way! Use

public void update() {
    long now = System.currentTimeMillis();

    while (true) {
        long stored = lastActivityTime.get();
        if (stored >= now) break;
        if (lastActivityTime.compareAndSet(stored, now)) break;
    }
}

Explanation:

Your code is obviously racy as between the test and the store, the value may change and you may overwrite a bigger value with a smaller one.

For computing the running maximum, I compare stored >= now and if it's true, there's nothing to do. The compareAndSet operation only succeeds (i.e., does anything and returns true), if the stored value hasn't changed in the meantime. Otherwise, I simply retry.

Look at how addAndGet and similar operations work.

An optimizations for really many cores

If there are many cores and the threads have nothing to do but content for our poor AtomicLong, a significant slowdown could occur. There's a simple solution inspired by the LongAdder.

private static final int PADDING = 8; // fight false sharing
private static final int CONCURRENCY = 8; // use 8 counters
private AtomicLongArray lastActivityTimes = new AtomicLongArray(CONCURRENCY * PADDING);

public long getLastActivityTime() {
    long result = Long.MIN_VALUE;
    // the biggest of the values contains the maximum
    for (int i=0; i<CONCURRENCY; ++i) {
        result = Math.max(result, lastActivityTimes.get(i*PADDING);
    }
    return result;
}
public void update() {
    long now = System.currentTimeMillis();
    Random random = ThreadLocalRandom.get();

    while (true) {
        int i = PADDING * random.nextInt(CONCURRENCY);
        long stored = lastActivityTimes.get(i);
        if (stored >= now) break;
        if (lastActivityTimes.compareAndSet(i, stored, now)) break;
    }
}

It's a simple splitting to multiple slots where the result is given by the biggest value. When updating a slot is selected at random. There are better strategies, but this can get pretty complicated and can lead to memory leaks

To avoid false sharing, only every 8th long gets used.


Alone in a Couple implementation in Java

You are using a pretty nice idea here. You store things you've seen once and remove them when you've seen them a second time. To do so you're using a List.

Instead of a List you should be using a Set though. Lists are not optimized for contains checks. Also ArrayList has a pretty expensive remove operation. Let's rewrite the getAloneNum with a Set:

private static int getAloneNum(int[] arr) {
    Set<Integer> alone = new HashSet<>();
    for (int elem : arr) {
        if (alone.contains(elem)) {
            alone.remove(elem);
        } else {
            alone.add(elem);
        }
    }
    return alone.iterator().next();
}

Note that this implementation avoids the following things:

Unnecessary negation in the if-condition
repeated traversal of the container (contains and indexOf traverse the full list)

I also personally prefer to not have  a space before the opening parenthesis, but YMMV :)

As a challenge for java 8 you could try to rewrite this to use as little memory as possible by using a Stream and handling the input as it comes instead of saving it into an array :)


File Writing optimizations - FileOutputStream vs Writers

According to its javadoc:

  FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

See also: https://stackoverflow.com/questions/11371154/outputstreamwriter-vs-filewriter

You could also use a StringBuilder instead of doing manually a string concatenation.

Also, the whole method is sychronized. The message probably does not need to be constructed in the sychronized block. Only concrete write to the Stream/File should be sychronized:

long logtime = System.currentTimeMillis();
// construct string etc

sychronized(this){
    out.write(message.getBytes(StandardCharsets.UTF_8));
}

You could also try to read the code of "real" logging frameworks to get ideas how they work.


Listing all paths through a matrix, stepping right or down only

static public void printPaths (String tempString, int i, int j, int m, int n, char [][] arr, HashSet<String> palindrome) {

You say palindrome? Maybe you shouldn't recycle names from other tasks.

This method should not be public. And should not be called "printWhatever" as it - fortunately - does not print.

arr is an array, nice, but then why did you write "matrix" in your text? Maybe, because of matrix being a more descriptive name? So use it.

The arguments m and n are redundant as they can be obtained from the matrix (and it's improbably more time-consuming than passing them around). Too many arguments make a method hard to use and to read.

So the public method could be

static public Set<String> allPaths(char [][] matrix) {
    Set<String> result = new HashSet<>();
    addAllPathsTo(result, matrix, "", 0, 0);
    return result;
}

with a helper like

static private void addPathsTo(Set<String> result, String tempString, int i, int j, char [][] matrix) {
    String newString = tempString + arr[i][j];
    int m = matrix.length;
    int n = matrix[0].length;
    if (i == m-1 && j == n-1) {
        result.add(newString);
        return;
    }
    //right
    if (j+1 < n) {
        addPathsTo(result, newString, i, j+1, matrix);
    }
    //down
    if (i+1 < m) {
        addPathsTo(result, newString, i+1, j, matrix);
    }
}

The optimization by JS1 makes a lot of sense and could be included. My point was clean up only.


With custom directives you could save the focus in a $scope.focusTarget variable and the resetting of the focus can be done with a focus broadcast that have the instanceId (=focusTarget e.g. 1, 2, ...) and the new icon class so each directive called iconInput will receive the broadcast and check if the passed ID is matching. If it matches it applies the focus and sets the new icon class.

The ID is generated with a counter that is incremented at every controller run of the iconInput directive.

Please have a look at the code below (then it's more clear how it works, it's a bit difficult to describe) or in this jsfiddle.

The first focus is only working in jsfiddle if you open the fiddle in full screen mode. Not sure what's wrong.

angular.module('demoApp', [])
    .directive('iconbar', IconbarDirective)
    .directive('iconInput', IconInputDirective)
 .factory('focus', FocusFactory)
    .controller('mainController', MainController);

function IconbarDirective(focus) {
    return {
        restrict: 'EA',
        transclude: true,
        scope: {
            focusTarget: '@'
        },
        template: '

',
        link: function (scope, element) {
            var icons = element.find('i');
            console.log(icons);
            icons.addClass('iconbar-icon');
            element.find('i').bind('click', function (evt) {
                console.log('clicked', evt.target, this);
                var icon = angular.element(this),
                    iconClasses = icon[0].className.split('ng-scope'), // third is ng-scope
                 target = scope.focusTarget;

                //console.log(iconClasses);
                //console.log(iconClasses[0]);
                focus('focus' + target, iconClasses[0]);
                scope.$apply();
            });
        }
    }
}

function IconInputDirective() {
    var instanceCounter = 0;
    return {
        restrict: 'EA',
        scope: {
            target: '='
        },
        template: '
' +
            '<input type="text" placeholder="enter text..."/>' +
            '
',
        controller: function ($scope) {
            instanceCounter++;
            this.instanceId = instanceCounter;
            console.log('instance no.', instanceCounter);
            $scope.placeholder = function() {
             return $scope.icon || 'fa fa-bars icon-invisible';
            };
        },
        link: function (scope, element, attr, ctrl) {
            var inputBox = element.find('input');
            inputBox.bind('focus', function () {
                // clear other acitve classes
                element.parent().find('input').removeClass('active');
                inputBox.addClass('active');
                scope.target = ctrl.instanceId;
                scope.$apply();
            })
            /*   .bind('blur', function () {
                inputBox.removeClass('active');
            });*/

            // code for focusOn from here http://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field
            scope.$on('focusOn', function (e, name, iconClass) {
                console.log('focuson triggered', name, element[0]);
                if (name === 'focus' + ctrl.instanceId) {
                    console.log('focus now!!', element.find('input')[0]);
                    element.find('input')[0].focus();
                    inputBox.addClass('active');
                    scope.icon = iconClass;
                }
            });
        }
    }
}

function MainController($scope, focus) {
    $scope.focusTarget = 1; // last acitve input box --> sets first focus
    focus('focus' + $scope.focusTarget); // activate focus with-out class
}

function FocusFactory($rootScope, $timeout) {
    return function (name, iconClass) {
        $timeout(function () {
            $rootScope.$broadcast('focusOn', name, iconClass);
        });
    }
}
.iconbar-icon {
  cursor: pointer;
}
.icon-placeholder {
  width: 16px;
  padding: 5px;
}
[iconbar] {
  border: 1px solid;
  padding: 5px;
  margin-bottom: 5px;
}
.active {
  border: 2px solid blue;
}
i {
  padding-right: 5px;
}
.icon-invisible {
  visibility: hidden;
}
/* spacer not working */

.icon-spacer::before,
.icon-blank::before {
  width: 1em;
  content: ' ';
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" />

  <icon-input target="focusTarget"></icon-input>
  <icon-input target="focusTarget"></icon-input>


A good foundation to build on

One nice thing about your code is that it needs no [arccos,arctan,arg,atan2,phase]-like floating point approximations until you already have your convex hull and demand its Euclidean perimeter and another that you got the Graham scan's stack shuffle pretty concise and \$\mathcal O(n)\$ everywhere outside the one and only \$\mathcal O(n \log n)\$ sortBy.

with a glitch

The worst thing to say about your code is that it is only partially correct and easily confusable by collinear EQ triples: Just to give an example proof of failure, instead of the correct 4·4=16.0 perimeter it calculates incorrect 20.5 perimeter for input point sample sequence

0 0
4 0
1 0
2 0
4 4
0 4

and other inelegances calling for a rewrite:

Aesthetically, your lambdas

(\a b -> turn b pivot a)
(\([x, y]) -> Point x y)

make me want to flip your argument order and core data type so that we get

compareFrom o l r=compare((x l-x o)*(y r-y o))((y l-y o)*(x r-x o))

mnemonically returning LT iff from o l looks "lefter than" = "left to" = "less right than" r,  for example compareFrom (0,0) (1,2) (2,1) == LT [to answer your question about the need for data Direction=LEFT|STRAIGHT|RIGHT aliases] and together with a

distanceFrom from to = ((x to-x from)**2+(y to-y from)**2)**(1/2)

handy not only to reduce your over-individualized perimeter to a one-liner

totalDistance ps = sum(zipWith distanceFrom(last ps:init ps)ps)

but also to get your Graham preparation to lambda-free (but oververbosely pointed)

convexHull points =
    let{o = minimum points; -- maximum/By comparing sum would be equally fine
        presorted=sortBy(compareFrom o)(filter(/=o)points);
        collinears=groupBy(((EQ==).).compareFrom o)presorted;
        outmost=map(maximumBy(comparing(distanceFrom o)))collinears;
    }in dropConcavities[o]outmost

so that we can now easily catch all cases in the final convexity scan

dropConcavities (left:lefter) (right:righter:rightest) =
    case compareFrom left right righter of
    LT -> dropConcavities (right:left:lefter) (righter:rightest)
    EQ -> dropConcavities (left:lefter) (righter:rightest)
    GT -> dropConcavities lefter (left:righter:rightest)
dropConcavities output lastInput = lastInput++output

By hitherto restricting myself to abstract x and y accessor methods i can now take the postponed liberal pick of any representation for which i can provide such functions:

import Data.Ord;import Data.List;(x,y)=((!!0),(!!1));
compareFrom o l r=compare((x l-x o)*(y r-y o))((y l-y o)*(x r-x o));
distanceFrom from to = ((x to-x from)**2+(y to-y from)**2)**(1/2);
totalDistance ps = sum(zipWith distanceFrom(last ps:init ps)ps);
convexHull points =
    let{o = minimum points;
        presorted=sortBy(compareFrom o)(filter(/=o)points);
        collinears=groupBy(((EQ==).).compareFrom o)presorted;
        outmost=map(maximumBy(comparing(distanceFrom o)))collinears;
    }in dropConcavities[o]outmost;
dropConcavities (left:lefter) (right:righter:rightest) =
    case compareFrom left right righter of{
    LT -> dropConcavities (right:left:lefter) (righter:rightest);
    EQ -> dropConcavities (left:lefter) (righter:rightest);
    GT -> dropConcavities lefter (left:righter:rightest);}
dropConcavities output lastInput = lastInput++output;
main = interact(show.totalDistance.convexHull.map(map read.words).lines);


Grouping array elements into batches of at most three

If you are not beholden to using reduce, you could chunk your array like this.

let chunked = [];
for (let i = 0; i < items.length; i = i + 3) {
    chunked.push(items.slice(i, i + 3));
}

Just for kicks, I implemented a jsFiddle to understand performance of Array.reduce() (as in original post) compared to for loop I have suggested and was somewhat surprised to find the for loop to be on the order of 50% slower than reduce.

When testing for larger arrays (100K items for example) performance became similar between the two solutions.

Regardless, it is probably very much in the territory of micro-optimization to consider one approach vs. the other based on performance testing alone. I would still prefer the simpler for loop code from an code management standpoint unless I knew I was going to be running this code at very high frequency in my application.  However if the majority of the surrounding application was using more of a functional programming style, I would be happy to use reduce as well.


Security

It's a little odd that you clean the file for the file_exists check, but not for the echoing.

So I can inject test"><script>alert(1);</script>, and if the file testscriptalert1script exists the alert is executed. This isn't an attack (well, at least as long as users can't upload their own custom theme), but still seems odd.

Up to version 5.xx of PHP, it was possible to inject a null byte to bypass file_exists, but that should be caught by your filter, so it shouldn't enable the attack described above, or any other attacks (such as injecting validFile\0" href="evil" foo=" and hoping there are browsers which choose the second href attribute if two are present).

So I didn't find any vulnerabilities, but I still don't like your approach all that much. At the very least I would echo the replaced file name instead of the original. I would actually prefer the approach suggested by @76484 (hardcode and use a switch or use an array and then check if the filename exists in it), because using whitelists is always safer than using blacklists.

tl;dr: I couldn't find a vulnerability, but would still use a different approach.

Misc

your indentations, newlines and spacing seem rather random, which makes your code a bit hard to read.
if you exit in the head, your website will be quite boring.
it should be rel="stylesheet".
choice isn't a good variable name. Something like cssFileName would be much clearer.
you repeat the inclusion of the default CSS file. Either extract that to a function, or just remove the empty check (assuming that .css doesn't exist).
but then you still have the inclusion code for CSS in general three times.

So your code would be cleaner like this (but still using a blacklist instead of a whitelist for security):

<?php
$cssFileName = $_GET['theme'];
$cssFileName = preg_replace('/[^A-Za-z0-9\-]/', '', $cssFileName);

if (empty($cssFileName) || !file_exists("./css/" . $cssFileName . ".css")) {
    $cssFileName = "default";
}

echo '<link rel"stylesheet" type="text/css" href="css/' . $cssFileName . '.css" />';


Complex reporting query suggestion needed for different approach as per latest Tsql format

To start, here is a potential formatting that makes the query less of a tragedy to read:
SELECT TOP 200
    'Recoup', ERH_DOC_DATE, ERH_DOCNO, ERH_RECV_FROM, ERD_BLH_ID,
    BLD_CODE, A.ERD_ALLOWED_AMT, A.ERD_PAID_INS_AMT
FROM TRN_ERA_HEAD, TRN_ERA_DET A, TRN_BILLING_DET
WHERE ERH_STATUS = 'P'
    AND ERH_BOOL_INACTIVE = 0
    AND A.ERD_BOOL_RECALLED = 1
    AND A.ERD_ALLOWED_AMT <> 0
    AND A.ERD_PAID_INS_AMT <> 0
    AND ERH_ID = A.ERD_ERH_ID
    AND A.ERD_BLD_ID = BLD_ID
    AND NOT EXISTS (
        SELECT B.ERD_ID
        FROM TRN_ERA_DET B
        WHERE A.ERD_ERH_ID = B.ERD_ERH_ID
            AND A.ERD_ID <> B.ERD_ID
            AND B.ERD_BLD_ID = A.ERD_BLD_ID
            AND B.ERD_BOOL_RECALLED = 0
            AND A.ERD_ALLOWED_AMT = B.ERD_ALLOWED_AMT
            AND A.ERD_PAID_INS_AMT = B.ERD_PAID_INS_AMT
    )
    AND ERH_DOC_DATE >= '01-01-2021'
    AND ERH_DOC_DATE <= '05-31-2021'
UNION ALL
SELECT TOP 200
    'Payment', EH1.ERH_DOC_DATE, EH1.ERH_DOCNO, EH1.ERH_RECV_FROM,
    ED1.ERD_BLH_ID, BD1.BLD_CODE, ED1.ERD_ALLOWED_AMT, ED1.ERD_PAID_INS_AMT
FROM (
    SELECT
        ERD_ERH_ID ERDERH_ID, ERD_BLH_ID erdblh_id, a.erd_bld_id bld,
        A.ERD_ALLOWED_AMT, A.ERD_PAID_INS_AMT
    FROM TRN_ERA_HEAD, TRN_ERA_DET A,TRN_BILLING_DET
    WHERE ERH_STATUS = 'P'
        AND ERH_BOOL_INACTIVE = 0
        AND A.ERD_BOOL_RECALLED = 1
        AND A.ERD_ALLOWED_AMT <> 0
        AND A.ERD_PAID_INS_AMT <> 0
        AND ERH_ID = A.ERD_ERH_ID
        AND A.ERD_BLD_ID = BLD_ID
        AND NOT EXISTS (
            SELECT B.ERD_ID
            FROM TRN_ERA_DET B
            WHERE A.ERD_ERH_ID = B.ERD_ERH_ID
                AND A.ERD_ID <> B.ERD_ID
                AND B.ERD_BLD_ID = A.ERD_BLD_ID
                AND B.ERD_BOOL_RECALLED = 0
                AND A.ERD_ALLOWED_AMT = B.ERD_ALLOWED_AMT
                AND A.ERD_PAID_INS_AMT = B.ERD_PAID_INS_AMT
        )
        AND ERH_DOC_DATE >= '01-01-2021'
        AND ERH_DOC_DATE <= '05-31-2021'
    ) AS RECOUPS,
    TRN_ERA_HEAD EH1,
    TRN_ERA_DET ED1,
    TRN_BILLING_DET BD1
WHERE RECOUPS.ERDERH_ID < ED1.ERD_ERH_ID
    AND ED1.ERD_BLD_ID = RECOUPS.BLD
    AND EH1.ERH_ID = ED1.ERD_ERH_ID
    AND ED1.ERD_BLD_ID = BD1.BLD_ID
    AND EH1.ERH_TRNTYPE = 'IN'
    AND EH1.ERH_STATUS = 'P'
    AND EH1.ERH_BOOL_INACTIVE = 0
    AND ED1.ERD_BOOL_RECALLED = 0
    AND ED1.ERD_ALLOWED_AMT <> 0
    AND ED1.ERD_PAID_INS_AMT <> 0;

Aside from the valid points that @Squirrel has already raised:

You'll want to change your date literal format to something that is non-locale-dependent; read https://blog.greglow.com/2020/04/27/t-sql-101-67-literal-date-and-time-values-in-sql-server-t-sql/ for instance
Choose a consistent case; right now yours isn't. My personal preference is lowercase-everything (keywords and symbols) to avoid shouting, but even if you upper-case everything it will be more consistent than what you have now.


There is an alternative way using the str functions of pandas.Series, which has the advantage that they are usually faster. In this case you can use pandas.Series.str.replace, which can take a regex to match strings against and a callable to replace them with, which gets passed the regex match object:

def repl(m):
    k = m.group()
    return k + x[k]

df.q.str.replace(r'\[.*\]', repl)
# 0     hey this is [a](1234)
# 1    why dont you [b](2345)
# 2        clas is [c](xyzad)
# Name: q, dtype: object

This uses the fact that your keys to replace seem to follow a pattern, though, and works only as long as you can write a regex to capture it. In that sense your solution is more general.

One thing that you can change in your approach is the check for if i in data. It is superfluous, since str.replace will just ignore it if the string to replace does not appear in the string (it has to search linearly through the whole string to figure that out, but so does i in data).

In addition, instead of iterating over the keys with for i in x.keys():, you can just do for i in x:. But since you also need the value, you can directly do for key, repl in x.items(): data = data.replace(key, repl).


Finding an exact "phrase" with a given string (as typed/in order)

Basically, Alex has already made some good suggestions (especially the bit about using \b). However, your function will fail in certain cases like this one:

//looking for chars like *, +, ? and such
filterExactPhrase("some *markdown* string", "*markdown*");

The string could contain special regex chars (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -), or the delimiter you use:

//this is operator error (regex + markup don't mix)
filterExactPhrase('
foobar
', '
');

Yes, it's evil, but people still seem hellbent on using regex's to consume markup, so your code should either check and throw an exception if it's used to do that, or you should defend against it. The example above will generate an error, because the string
 is concatenated into the regex raw, so you end up with this:

/\b(
)\b/
/\b(</ -> faulty regex
hi>\b/ -> unknown and invalid flags

Another thing to think of is that people, once they find out the function uses a regex, will start passing regular expressions instead of a string to it. Kind of like people entering SQL wildcards in search forms (stuff like foo%).

filterExactPhrase("some string with words and 123 numbers", "[\w\d]+");

So how do you go about this? simple: preg_quote filters the input for you, and escapes whatever chars need escaping. Basically, all I'm trying to say is change this:

$numFound = preg_match_all("/\b(" . $phrase . ")\b/", $input);

to this:

$escaped = preg_quote($phrase, '/');//second param is the delimiter
$numFound = preg_match_all("/\b(" . $phrase . ")\b/", $input);

Now chars like + or * are escaped properly, and so are the delimiters.

The other thing I'd suggest is to remove the print_r from your function/method. I realize that it's probably there for debugging purposes, but still: a function/method does one thing. In this case its job is to process a piece of string, and find exact matches of another string. Whether or not that data should be shown (displayed, echoed or printed or whatever) is not a call this method should make. It's not aware of output buffers, headers that might be set later on, so it shouldn't forcibly generate output.

For all you know, I might want to call this method, store the data somewhere, and send something entirely different to the output stream. In short: a function/method should return data, not print/echo it
This dogma doesn't apply for methods in a renderer component or view class, of course. But it holds true for data-processing code units


ReactJS paginated component with React Router

Your code looks quite reasonable. There are only a few small things I notice:

Indent the JSX in App a bit more: ScrollToTop is a child of Router, so it should be indented further, not on the same level as Router. (It doesn't really make a difference here, but it's good to be consistent, and could be an improvement if that section ever got more complicated)

Avoid let, prefer const - ESLint rule here.

Or, in the case of oneBasedNewPage, consider defining the argument with that name instead of creating a new variable - and maybe call it oneIndexed, not oneBased:
const handleChange = (
  event: React.MouseEvent<HTMLButtonElement> | null,
  oneIndexedNewPage: number
) => {

URLSearchParams does not differentiate between numbers and strings.
urlParams.set("page", oneBasedNewPage.toString());

can be
urlParams.set("page", oneIndexedNewPage);

if you wish.

Consider if using Math.min might be clearer than the conditional operator:
function getPageNumber() {
  const newPage = parseInt(urlParams.get("page")) || DEFAULT_PAGE;
  return Math.min(newPage, MAX_PAGE_COUNT);
}