PHP library that can use different authentication mechanisms

I would lay it out something like this:

interface AuthenticableInterface
{
    public function getName(): string;

    /**
     * Based on auth type, return the right format of credentials to be sent to the server
     *
     * @param Authenticable $credentials
     * @return mixed
     */
    public function encodedCredentials(): string;
}

class AbstractAuthenticable implements AuthenticableInterface
{
    protected $name = 'PLAIN';
    protected $options;

    public function __construct(Options $options)
    {
        $this->options = $options;
    }

    abstract public function encodedCredentials(): string;

    public function getName(): string
    {
        return $this->name;
    }
}

class Plain extends AbstractAuthenticable{

    public function encodedCredentials(): string
    {
        $credentials = "\x00{$this->options->getUsername()}\x00{$this->options->getPassword()}";
        return XML::quote(base64_encode($credentials));
    }

}

I kept the interface, a lot of people get confused between using abstract and interface.  I should add that the interface is inherited through the extending of the abstract class, so there is no need to declare (implement) it again.

Interfaces basically just outline the classes API (application program interface, or I like to say public interface), Abstract classes do the same thing (basically) as an interface but you can have concrete implementation of common functionality within the class.  Interface doesn't allow you to implement any functionality.

By keeping the interface you could in theory create a Authenticable that uses a base other then the Abstract class.  This is useful especially when type casting.

class foo{
     public function __construct(AuthenticableInterface $Authenticable){
          //...
     }
}

So instead of hinting the Abstract class or the Concrete class you can type hint the interface which can be satisfied even when using a completely different base class.  In this case it may not be strictly necessary to carry the interface but it does give you that little bit of extra flexibility for the hierarchy.

A good example of the above would be to make a token based login for something like REST where you don't have a username and password, and so that class could be quite different then the base class that uses a user and a password.

Another example I can think of is if you have a hierarchy in your user system, such as a Parent and Subusers, or Admins and non-admins.  You may want something like a passwordless Login As functionality that relies more on the user's role and relationship to decide if it should authenticate.  Something like a button you just click to login as one of your associated subusers etc.  We use subusers a lot in our user systems.

Rather or not you should decouple the username and password depends really on how you want to pass that data.  Obviously username and password are going to be really important so it may be worth adding them as function arguments.  But as I mentioned above you may create authentication that does not use a username and password.

I would say the biggest argument for it is, then the password and username is not "hidden" or buried in some kind of BLOB or array data. But on the same token (pun intended) you may have some classes that don't need them.  So the biggest disadvantage is then requiring it as part of the class, which may break the single interface design.

For example consider this interface and class:

interface Authenticable
{
    public function setPassword(string $password);
}

class LoginAs
{
     //public function setPassword(string $password);
}

So you can see setting a password for "LoginAs" doesn't really make sense and this would stretch what we can do with our interface.  By having them as options they are not exposed to the interface because they are wrapped in another object.

I'll end by saying if you keep them in the options you will want to do some more robust error checking such as this:

public function encodedCredentials(): string
{
    $credentials = "\x00{$this->options->getUsername()}\x00{$this->options->getPassword()}";
    return XML::quote(base64_encode($credentials));
}

I modified your getUsername function in Options. I like to set them up this way.

class options{

     public function getUsername($default=null){
           if(isset($this->username)) return $this->username;

           if(!is_null($default))  return $default;

           throw new OptionException("Option {$username} is not set");
     }
}

By doing this we can control what we get back when its not set.  By setting a default other than null, when default is not set we throw an error.  Typically I do this using the magic __call method etc..  Basically I showed this to show how you can implement some error checking on those values.  Obviously you could check this in each encodedCredentials() but you can also bake it into the options class so it happens when we try to get an options etc...

Hope that helps!


Converting props to data is a bad idea if it is not a copy of the prop because you might end up in a situation where your parent changes your prop and your component changes your data and then which is right? The component manipulating props is not good. Instead decide which is externally sourced (from parent) and which is internally manipulated, and then assign each to either prop or data.

Since your code in particular doesn't actually manipulate the data or props you are simply better off if you remove the data key completely, just leave it with props and you can access the values in precisely the same way using this.totalStarsData for example. You can clearly see that having a props key and manually entering the same info into data is ugly code anyway.

Having that global variable is unhelpful in my opinion, and probably bad practice since it goes against the decoupling of the component. Why not make it another prop with a default value of false?


The date field is assumed to be the last day of the given month.

This seems to suggest that you would want to convert 201502 to 2015 Feb 28,
as that's the last day of 2015 Feb.
Your code converts to 2015 Feb 01, I hope that's what you really meant.

Your validation is too weak:

if (intDate < 100000 || intDate > 999999) {
    log.warn("Unable to parse int date {}", intDate);
    return null;
}

So, 999999 is a valid date? The method will convert that to 10007-03-01.

What about 201599? The method will convert that to 2023-03-01. Not so great.

I'd suggest to do the validation after converting to intYear and intMonth.
It will be easier to follow and more logical.

Why does the method take an Integer?
It doesn't make sense, and it makes the method prone to NullPointerException.
(The code will throw when reaching intDate < 100000 in the if condition.)

The conversion to month would be more readable with a modulo:

    int intMonth = intDate % 100;

And the way you set the month is incorrect,
as the second value of result.set is supposed to be a constant like Calendar.JANUARY.
The correct way:

    result.set(Calendar.YEAR, intYear);
    result.set(Calendar.MONTH, intMonth - 1);
    result.set(Calendar.DAY_OF_MONTH, 1);


You don't need to actually build a whole list of the digits. It's unnecessary memory consumption. You can pass a generator to max.
use python's -= syntax when subtracting from a variable.
The break is unnecessary as it's covered by the while condition

Final code:

n=int(input())
count=0

while n:
    n -= max(int(i) for i in str(n))
    count += 1

print (count)

This code would be fairly difficult to improve much further for efficiency. You could really penny pinch performance on the generator by building a generator that will stop iteration after it encounters a 9, as it knows it cannot ever get a number bigger than that. You could also use modulo and integer division logic to extract digits to avoid having to go from int -> str -> int.

Okay. This is now straying pretty far from the original question, but I liked the challenge and @Mast in the comments expired me by mentioning memoization.

To utilize memoization the problem needed to be formulated in a recursive way where I can store the result of intermediate calls to avoid re-computation of things already computed. The strategy was to define the recursive function "compute_count(previous_max, rest)", where previous_max is initially called with 0, and rest as the entire number.

The idea is that a max, num pair uniquely identifies a solution, so every time we end up with the same max, num pair we can use the precomputed result. Formulating the problem in this way led to writing a fairly complicated function, but on the example you provided in the comments it returns instantly. The memoization table ends up with 293 entries, so it's well within your 256MB limit.

Anyway, here's the final code:

memoization_table = {}

def compute_count(previous_max, rest):
    global memoization_table
    original_rest = rest

    if (previous_max, rest) in memoization_table:
        return memoization_table[(previous_max, rest)]

    num_digits = len(str(rest))

    if num_digits == 1:
        memoization_table[(previous_max, original_rest)] = 1, min(0, rest-previous_max)
        return 1, min(0, rest-previous_max)

    sum_count = 0
    while rest > 0:
        s = str(rest).zfill(num_digits)
        new_max = max(previous_max, int(s[0]))
        new_rest = int(s[1:])
        count, leftover = compute_count(new_max, new_rest)

        sum_count += count
        rest -= new_rest
        rest += leftover

    memoization_table[(previous_max, original_rest)] = sum_count, rest
    return sum_count, rest

print(compute_count(0, 1278564645)[0])
print(len(memoization_table))

I imported the length of the memoization table just to see the memory implications of the solution, and it turned out to be very reasonable. Obviously remove this from any submitted solutions.

Here's the output of the run:

$ python compute_count.py
154026551
293

Example:

For calculating 24, these are the function calls made:

compute_count(0,24)
compute_count(2,4)
compute_count(2,0)
compute_count(1,8)
compute_count(1,0)
compute_count(0,9)

To calculate compute_count(0, 24):

get new previous_max, which is the max of 0 and 2.
do a compute_count on 2,4. Since this is a single digit number, it's our base case, and we return that we can get to 0 with a single move (as is the case with all single digit numbers).
Since we did a compute_count(2,4) which told us it did a single computation, we need to subtract the number computed for (4) from our running number (24). This gives us a remainder of 20, and a running count of 1.
The new previous_max is still 2, as our remainder is 20.
do a compute_count on 2,0. This one is a special case. Getting from 0 to 0 should technically take no moves, but we have additional logic for these cases because the previous max is 2. Which means this isn't really a single digit number, and I need to return the "leftover" which is -2 so the caller can account for the underflow of the subtraction. So this function returns a count of 1, and a leftover of -2
Since we passed 0 to compute_count, we subtract 0 from our 20 which keeps us at 20. But because a leftover of -2 was returned, we also have to add that to our 20 which gives us a total of 18 for this iteration.
The above process continues in kind until our remaining is 0 or less and we've summed all the counts.


Verifying if a string can be created with the letters of another string

Your logic seems hard to follow.  Why spread str2 to array, which you then read into a Set, only to turn around and make the Set into an array, which you then iterate, comparing each letter’s count in each string by splitting them repeatedly?
You see how long and convoluted that sentence was? The last line of code there is kind of the same, dense and hard to follow.
The problem should be solved by counting characters for str1 into map keyed by each letter. You then iterate through str2 and decrement those counters. If any counter goes to -1 you have false condition.  This approach means each letter in passed string only needs to be visited once making performance linear to the combined length of the strings in operational complexity.  Your current solution has exponential complexity.


Check WiFi Connectivity and internet connectivity in Background thread - with a return value

Your implementation of isNetworkConnected does not make much sense for the following reasons:

You create a new, private ExecutorService each time the method runs. The intention behind Executors is that they're created once and then used over a longer time span to execute multiple (short) tasks. This should save you from having to create a new Thread for each task, because the executor manages a number of threads which get re-used for multiple tasks in succession.
You don't need that FutureTask<Boolean>. The usual idiom of the ExecutorService is like:

Callable myCallable = new CheckConnection(...);
Future future = service.submit( myCallable );
...
Boolean result = future.get();
It does not make any sense to submit a (single) task to an executor and then start waiting for completion immediately. This will block exactly as if there was no Executor involved at all. In your case, you could just write Boolean result = new CheckConnection(...).call(); with the same effect w.r.t. concurrency.

Suggestion

Don't run your checking code and wait for the result. Better have your checking code run in the background periodically (e.g. in a dedicated Thread or a ScheduledExecutorService) and have that code post its result back to any interested party.

You can use a Handler to send a message from a background thread to the UI thread. For example, send one message each time the connectivity state changes.


After creating a socket make it non-blocking. Then call connect(). If connect returns 0 then the connection has been established and you can use it already. If it retuned -1 and errno is equal to EINPROGRESS then you need to wait until it becomes write-ready using select() or poll(). When it becomes write-ready use getsockopt(sock, SOL_SOCKET, SO_ERROR, ...) to tell if the connection has failed or succeeded. The example code for using non-blocking connect is here:

http://developerweb.net/viewtopic.php?id=3196

But this sample shows waiting on single socket only. You need to wait on a bunch of them at the same time. So have a table of socket connections with some fixed size, e.g. 32:

#define MAX_CONNECT 32

struct socket_info {
    int sock;    /* the socket */
    int ready;   /* initialize to 0 when filling the table, set to 1 when the connection has established or failed */
    int error;   /* set to errno got with getsockopt() for failed connections, set to 0 if connection succeeded */
    sockaddr_in addr;
};

struct socket_info pending_connect[MAX_CONNECT];

First fill this table in a loop calling socket/connect. Then wait in another loop with select until all of the sockets become ready. Set appropriate flags in the table as the sockets become ready.

After the select loop you have info about 32 ports. Print it. Close the sockets. Then proceed with a next bunch of 32 ports.

This approach could be further optimised. You could close a socket as soon as you get info about it, print that info, and immediately open another socket in its place in the table. This will be faster but perhaps this also requires more careful coding.


Simple Haskell calculator, using Maybe for error handling

I'd further suggest to split compute into two parts:

Getting the right operation from a given character:

op :: Char -> Maybe (Double -> Double -> Double)
op '*' = Just (*)
op '/' = Just (/)
op '+' = Just (+)
op '-' = Just (-)
op _   = Nothing

This accepts a character, and either produces a function corresponding to the character, or Nothing.
Applying the operation on values, taking into account all possible Maybes:

compute' :: Maybe Char -> Maybe Double -> Maybe Double -> Maybe Double
compute' c x y = (c >>= op) <*> x <*> y

Here c >>= op results into Maybe (Double -> Double -> Double), where the result is Nothing if the character is Nothing or if it doesn't match any supported operation. And then we use twice <*> from Control.Applicative, which, specialized for Maybe, applies Maybe (a -> b) to Maybe a yelding Maybe b.


Some other improvements:

Check ExternalValueContainer.Value synchronously first. If it already exist then you can return early, and there is no reason to await anything. (Note eurotrash's point about thread safety).
If value is never set, getValueTask never returns. Instead of waiting for delayTask separately, you should check the timeout inside getValueTask's body and return once timeout is exceeded.

In general I feel like proper unit tests should not use delays and should not rely on them. Not only because those 5s delays quickly add up if you run this method multiple times, but also because the behavior of unit tests becomes unpredictable. The same test can fail on one machine and pass on another, simply because on one machine GetStringValueOrNull() timed out, while on the other - it did not. IMHO you should take it as signal, that you design is flawed and should be changed. If you own ExternalValueContainer, then you should probably modify its API so consumer can wait for the value (using async methods, events, observables or any other suitable tool). If you do not own ExternalValueContainer then you should wrap it in non-static service and mock this service in your tests.


Maintaining session timeout globally in java spring configuration

Quite a number of points for this short piece of code:

As the properties file will probably not change at runtime, loading it every single time a session gets created is a total waste. See whether you can cache the session timeout in a static variable.
If the value is not set, the default "no value found" will lead to a number format exception. Better use a sensible parseable default.
Similar context: by setting the value to a non-parseable string, you can kill the server with a misconfiguration.
"sessionTimeout" should not be named "cookieName"
Separation of concerns: a method should do one thing. This is a mixup of reading the program configuration and using the determined value to set the timeout.
Error handling: printStackTrace does not accomplish anything. Do something real (e.g. log an error for the server admin, shutdown, whatever.) If you decide to continue the process in case of an I/O exception, set a sensible default on the session.


Deleting duplicate elements from a single-linked list in C++11

Currently your code is broken (it just happens to work accidentally).
  for (auto p = head->next, prev = head; p; p = p->next) {
    if (<Test>) {
      <Stuff>
      Node* temp {p};    // So p and temp both point at the same block of memory
      delete temp;       // You delete the memory pointed at by temp.
                         // This is the same effect as deleting p.
                         // This memory now belongs to the system and not
                         // your code. Access anything within this memory
                         // block is "undefined behavior".

                         // When you loop back to the `for` and
                         // execute `p = p->next` you are now
                         // invoking undefined behavior.

The term "undefined behavior" basically means the standard does not define what can happen and any hardware/compiler can do anything it likes as it result it can blow up or could look like it is working perfectly.
The reason the standard does not specify is to allow each implementation to pick the most efficient thing possible for them (you can specify the most efficient thing).
The block you have given back may be on a page that has been returned to the OS. The memory management could re-use parts of that block for its own internal buffers (to make allocation/deallocation efficient). The content of this block could have any value in it or it could be completely removed from the memory available to your processes. The least worst that could happen is probably a segfault and your application crashes. The real worst is that your application gets a random pointer and seems to work normally (but in reality it is trashes memory all through your application making it really hard to debug). Even much worse is that it happens to actually work in your tests then breaks when you push to production.
Fixed code
  std::unordered_map<int, bool> map {{head->data, true}};

  for (auto p = head->next, prev = head; p;) {
      if (map[p->data]) {
          prev->next = p->next;
          Node* temp {p};
          p = p->next;         // Move p before you delete its memory
          delete temp;         // Now you delete temp (which points at the old value)
      }
      else
      {
          map[p->data] = true;
          prev = p;
          p = p->next          // Don't forget you need to move p in both branches.
      }
  }

Bracing style.
This is horrible (IMO)
} else {

It is also not a common bracing style used in C++ os better avoided. The two main common styles are
if (<test>) {
}
else {
}

// or

if (<test>)
{
}
else
{
}

Questions

Is there a better way to delete a Node than by creating a temporary variable temp and deleting that.

No. Because you need to use the next member before deleting. So you have moved your pointer. So you need the temp value to record where you where so that you can delete it.

I actually tried deleting p directly and it worked.  I find this surprising because after I delete p I would expect p->next to be a segmentation fault.

It could be a segfault or it could work as expected. The memory does not belong to you so you can't know what is there anymore. But the standard does not require the code to do anything special with the memory so it could just contain the values it used to have before you called delete.

Is this a compiler-specific trickery or is it a safe practice?

Its definitely not safe to even read this memory. It is just happens to work. But if you change anything it may stop working. Compiler flags/ Compiler/ OS Version/ OS/ Hardware. Any or none of these things could trigger a change in behavior.

I'm a little confused about passing pointers by reference. If I don't pass head by reference in insert, it doesn't work; but passing them by copy to remove_duplicates works (that is, the second call to print_node doesn't print the original list).

The remove_duplicates() only works as long as you don't try and remove the value of the head node. But because the head is never a duplicate it will work.
A reference is a variable alias. ie. It is another name for a variable that already exists. So by changing the value of the reference you actually change the originals value.
int  head  = 6;
int& otherHead = head;   // otherHead is an alias for head.
                         // If I change the value of otherHead then
                         // I change the value of head.

otherHead = 12;          // head is now 12.

So in the insert() function you are passing head by reference (it becomes another name for the variable you passed as the parameter).
void insert(int& otherValue)
{
    otherValue = 15;  // otherValue is an alternative name for the parameter
                      // that was passed to this function.
}
int main()
{
    int value = 5;
    insert(value);
    std::cout << value;  // prints 15
}

So in your function:
void insert(Node*& head, const int data) {
  head = new Node {data, head};
  ^^^^  // This is an alias for another variable.
        // So we are changing the value of that other variable.
}

If we don't use a reference:
void broken_insert(Node* head, const int data) {
  head = new Node {data, head};
  ^^^^  // This is a local variable (a copy of the original)
        // We change head here. But it does not change the original variable.
}
int main()
{
    Node* data = nullptr;
    broken_insert(data, 12);
    std::cout << data << "\n"; // Still prints nullptr
}                              // as broken_insert only changed the local
                               // variable head it has nothing to do with
                               // the variable data.


Convert rating value to visible stars using fontawesome icons

I recently implemented this same thing, here's what I used. Main difference: Let the for loop do the math for you. By the end of the first loop, if there is half a star it will be in the i variable. Use an array to buffer your string (or create DOM objects instead, don't use += to build a string).

document.getElementById("stars").innerHTML = getStars(3.6);

function getStars(rating) {

  // Round to nearest half
  rating = Math.round(rating * 2) / 2;
  let output = [];

  // Append all the filled whole stars
  for (var i = rating; i >= 1; i--)
    output.push('&nbsp;');

  // If there is a half a star, append it
  if (i == .5) output.push('&nbsp;');

  // Fill the empty stars
  for (let i = (5 - rating); i >= 1; i--)
    output.push('&nbsp;');

  return output.join('');

}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

Rating:


Method has same erasure: How should I go about refactoring?

I strongly suspect that you have the wrong problem -- this feels like UtilClass.getNextAvailableNumberAsInteger is implemented incorrectly.  It's also not clear why you want to use the same method name when the argument has a completely different meaning.

That said... my recommendation would be to create a new function object.

class NumberGenerator {
    private List<MyObject> objects = null;
    private List<String> unavailableNumbers = null ;

    public NumberGenerator withObjects(List<MyObject> objects) {
        this.objects = objects;
        return this;
    }

    public NumberGenerator withUnavailableNumbers(List<String> unavailableNumbers) {
        this.unavailableNumbers = unavailableNumbers;
        return this;
    }

    public int getNext() {
        return UtilClass.getNextAvailableNumberAsInteger(objects, unavailableNumbers);
    }

    // OPTIONAL
    public static NumberGenerator newInstance () {
        return new NumberGenerator();
    }
}

Then your clients can use the NumberGenerator to get what they need, without having to worry about the details

int nextNumber = NumberGenerator.newInstance().withUnableNumbers(otherNumbers).getNext();

Other comments: it looks really odd that your "other unavailable numbers" are stored in a collection of String.  It looks somewhat odd that you are using a collection of MyObject to produce integers as well.  Why do the collections need to be List, as opposed to Collection or Iterable?

    if (objects.get(0) instanceof MyObject)

That's an awful idea; you're rooked if the array you are passed is empty.  If it's true that an empty list means you don't care what kind of list it is, that very strongly suggests that the entire interface is broken.

List<MyObject> objectList = new ArrayList<MyObject>();

If the list isn't supposed to by modified by the function, then you might be better off using Collections.EMPTY_LIST; it would help clarify your intent.


It's neat, though I feel like there's a bit too much array manipulation going on.

Your friend for this, I'd argue, is the each_cons method, short for "each consecutive". Then you don't need the zip, though you do need to pad the beginning of the array.

Here's my take:

def brainturing_printer_generator(text)
  ords = [0] + text.chars.map(&:ord)
  ords.each_cons(2).map do |previous, current|
    delta = current - previous
    line = (delta < 0 ? "-" : "+") * delta.abs
    "#{line}."
  end.join("\n")
end


Give me parameterized SQL or give me death!
Seriously. Use prepared statements! Don't use mysqli_query as that makes your code vulnerable to SQL Injection. By using prepared statements, you won't need the mysqli_real_escape_string calls anymore.

This code looks nasty:
$result1 = mysqli_query($con, $sql);
if (!$result1 || mysqli_query($con, $sql)) {
    die('Invalid query: ' . mysqli_error());
}

First you perform the query. If the query fails (i.e. it returns a false-ish value), you die, but if the query works then you call the query again. And if the second query is successful, then you call die.
THAT MAKES NO SENSE!

This code can't possibly be working:
$dblink = "SELECT * FROM users WHERE (username= '" . $username . "')";
$dblink->bind_param('username', $username);

And again, don't concatenate SQL queries! Use prepared statements!

Use better variable names!
What is $result1 and what is $result2? Describe what the result is for in the variable name.

You have a whole bunch of empty blocks, such as this:
if ($emailLength >= 3 && $emailLength <= 42) {

} else {

$errorMessage = $errorMessage . "Email must be between 3 and 42 characters" . "
";

}

Also work on your indentation. Fixing the indentation, the if-logic and the string concatenation, and I suggest that you write your HTML tags with lowercase, this can be:
if ($emailLength < 3 || $emailLength > 42) {
    $errorMessage .= "Email must be between 3 and 42 characters
";
}


Speeding up Project Euler 43 - sub-string divisibility

You can make a few quick improvements without altering the algorithm significantly:

Remove one of the redundant calls to timer().
Store the list of primes instead of calculating it for every call to follows_property.
Convert the digits to strings in the list passed to permutations so you can simplify the calculation of num.
Run through all permutations instead of 9-tuples and remove the Counter and missing parts.

These are minor changes, but they clean up the code a bit. I also renamed ans to sum to clarify what it holds. They also cut the running time by more than half.

from itertools import permutations
from primes import primes_upto
from collections import Counter
from timeit import default_timer as timer

divisors = primes_upto(17)

def follows_property(n):
    for k in range(7):
        if int(n[k+1:(k+4)]) % divisors[k] != 0:
            return False
    return True

sum = 0
start = timer()

for combo in permutations([str(x) for x in range(10)]):
    num = ''.join(combo)
    if follows_property(num):
        sum += int(num)

elapsed_time = (timer() - start) * 1000 # s --> ms

print("Found %d in %r ms." % (sum, elapsed_time))


Edited simple Blackjack game in Python 3.4

My first tip would be to get rid of the Game class. It serves no value. Rather, it should be a method, appropriately named main. If you want a few tips for determining whether to write a class or not, here are a some instances where you should avoid classes:

If the class only contains two methods, __init__, and another.
If the class never refers to self. (Credit to @jonrsharpe)

Secondly, those comments underneath your function declarations should be docstrings. A typical function docstring would look something like this,

def my_func(args):
    """
    A detailed description of the function
    and its arguments.
    """

The below statement in Game.__init__ is not needed, and does nothing. It can be removed.

else:
    pass

You have some odd naming in places. For example, logic could be renamed to check_for_soft_17 or something along those lines, and total could be renamed to determine_winner.
The two for loops underneath the VAL = [] could be shortened to generator expressions. Here's how that would be done.

VAL = [[a + 2] * 4 for a in range(9)] + [[10] * 4 for _ in range(3)]

Preferably, the variable a in the above example should also be renamed to something a little more descriptive, and you should apply some of those "magic numbers" to variables as well.
As mentioned by @Josay, you're using globals in a lot of your functions. Rather than assigning a value to a global, try returning a value instead. It makes things a whole lot easier to manage.

Anyways, that's about all I can think of. If there's anything else that you want me to cover, just mention it in the comments, and I'll see what I can do. I hope this helps!


The code for the two cases (sorting by name and sorting by price) have nearly nothing in common.  You may be better off writing two functions.  Even if you really like this interface, it might make sense to have the master function to call a sort-by-name function or a sort-by-price function to do the work.

I have no idea what aux.cat = malloc(sizeof *(aux.cat)) is for.  You never really store anything in the .cat member.  Furthermore, after all the swapping done in the sorting process, the aux.cat at the end of the function is not the same aux.cat that you started out with.  That's a memory leak.

Your sort algorithm is selection sort, which takes O(n2) time.  There are more efficient algorithms that work in O(n log n) time.

Your sort() function always returns 0.  You might as well make it a void function and not return any value.

For efficiency and brevity, you would be better off using sorting routines built into the C library.  All you have to do to use those routines is to define a comparator function, which tells the sorting function how to order any pair of books.

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

static int compare_books_by_name_asc(const void *a, const void *b) {
    const book *book_a = (const book *)a,
               *book_b = (const book *)b;
    return strcmp(book_a->fname, book_b->fname);
}

static int compare_books_by_name_desc(const void *a, const void *b) {
    return compare_books_by_name_asc(b, a);
}

static int compare_books_by_price_asc(const void *a, const void *b) {
    int price_a = ((const book *)a)->cat->price,
        price_b = ((const book *)b)->cat->price;
    return price_a < price_b ? -1 :
           price_a > price_b ? +1 : 0;
}

static int compare_books_by_price_desc(const void *a, const void *b) {
    return compare_books_by_price_asc(b, a);
}

void sort(book *books, int num_books, char mode, char sortBy) {
    int (*comparator)(const void *, const void *);
    if (sortBy == 'n') {   /* Sort by name */
        comparator = (mode == 'a') ? compare_books_by_name_asc
                                   : compare_books_by_name_desc;
    } else {               /* Sort by price */
        comparator = (mode == 'a') ? compare_books_by_price_asc
                                   : compare_books_by_price_desc;
    }
    qsort(books, num_books, sizeof(*books), comparator);
}


I would like to go beyond just making the code prettier, and change the method that you are using. Instead of looping through the arrays looking for matches, you can put the synonyms in a hashed list. That will give you a performance close to O(1) for each lookup, instead of O(n).

Example in C#:

public class Synonymiser {

  private Dictionary<string, string> _synonyms = new Dictionary<string, string>();

  public Synonymiser AddWord(string word, params string[] synonyms) {
    foreach (string synonym in synonyms) {
      _synonyms.Add(synonym.ToUpper(), word);
    }
    return this;
  }

  public string NormaliseString(string inStr){
    string replacement;
    return String.Join(
      " ",
      inStr.Split(' ')
      .Select(w => _synonyms.TryGetValue(w.ToUpper(), out replacement) ? replacement : w)
    );
  }

}

Usage:

Synonymiser s =
  new Synonymiser()
  .AddWord("one", "two", "three", "four", "five")
  .AddWord("six", "seven", "eight");

Console.WriteLine(s.NormaliseString("one two seven bulb"));

Output:

one one six bulb


Populate inorder successor for all nodes

I think this equivalent, but simpler. It removes the need for the TreeNodeHolder class by returning a TreeNode<T>.

public void populateInorderSuccessor() {
  populate(root, null);
}

private TreeNode<T> populate(TreeNode<T> root, TreeNode<T> successor) {
  if (root == null) {
    return successor;
  }

  root.next = populate(root.right, successor);
  return populate(root.left, root);
}

PopulateInorderSuccessor is not a good name for a class. Let's change it to BinaryTree.

Tree construction can be simplified:

public BinaryTree(T[] items) {
  this.root = create(items, 0);
}

private TreeNode<T> create(T[] items, int i) {
  if (i >= items.length || items[i] == null) {
    return null;
  }

  TreeNode<T> root = new TreeNode<T>(items[i]);
  root.left = create(items, 2 * i + 1);
  root.right = create(items, 2 * i + 2);
  return root;
}

I find that helper methods setLeft and setRight on TreeNode can make tree code a bit cleaner, in general. It's not of much advantage here, but just for reference:

public TreeNode<T> setLeft(TreeNode<T> left) {
  this.left = left;
  return this;
}

public TreeNode<T> setRight(TreeNode<T> right) {
  this.right = right;
  return this;
}

This way we can write

private TreeNode<T> create(T[] items, int i) {
  if (i >= items.length || items[i] == null) {
    return null;
  }

  return new TreeNode<T>(items[i])
    .setLeft(create(items, 2 * i + 1))
    .setRight(create(items, 2 * i + 2));
}

Putting it all together, we get something like this

import java.util.ArrayList;
import java.util.List;

public class BinaryTree<T> {
  private TreeNode<T> root;

  public BinaryTree(T[] items) {
    this.root = create(items, 0);
  }

  private TreeNode<T> create(T[] items, int i) {
    if (i >= items.length || items[i] == null) {
      return null;
    }

    return new TreeNode<T>(items[i])
      .setLeft(create(items, 2 * i + 1))
      .setRight(create(items, 2 * i + 2));
  }

  public void populateInorderSuccessor() {
    populate(root, null);
  }

  private TreeNode<T> populate(TreeNode<T> root, TreeNode<T> successor) {
    if (root == null) {
      return successor;
    }

    root.next = populate(root.right, successor);
    return populate(root.left, root);
  }

  public List<T> toInOrderList() {
    TreeNode<T> node = root;
    while (node.left != null) {
      node = node.left;
    }

    final List<T> list = new ArrayList<>();
    while (node != null) {
      list.add(node.item);
      node = node.next;
    }
    return list;
  }

  private static class TreeNode<T> {
    private TreeNode<T> left;
    private T item;
    private TreeNode<T> right;
    private TreeNode<T> next;

    TreeNode(T item) {
      this.item = item;
    }

    public TreeNode<T> setLeft(TreeNode<T> left) {
      this.left = left;
      return this;
    }

    public TreeNode<T> setRight(TreeNode<T> right) {
      this.right = right;
      return this;
    }
  }
}


set

You build a dictionary to take advantage of the fast \$O(1)\$ membership test of the keys, but you never use the value (that is always 1), so you could just use a set that has the same \$O(1)\$ membership test but no values.

Returning the result

It is standard practice to return the results, not print them. If a result is returned, the user of the function may decide to do anything with it, including printing it. If you just print the result, no further re-use is possible.

Avoid globals when unnecessary

Globals may be changed anytime, from anywhere in your program. If you modify a global once wrongly by accident the whole program goes bogus. Just return the dict from insert_to_dictionary (I would call it abundant_sums because types should be in names and it is more descriptive.)

Use the built-ins

sum = 0
for i in range(1, 28123, 1):
    if i not in dict:
        print i
        sum += i
print sum

Becomes:

return sum(i for i in range(1, 28123, 1) if i not in set_)

I also avoided printing long lists of numbers because is not required (just the final answer is required).


Extract the largest value for each day from a matrix

A few notes:  (I implemented this in Octave, so there may be differences between my code and a proper Matlab implementation, but there shouldn't be).

First we care about only unique dates, right?  So lets grab
indices for their groupings.  I'm assuming this original data is
stored in the matrix A.

[X, y, z] = unique(A(:, 4))

Now z is the only value I used from this output, so you could
ignore the other returns by putting ~ in their place.
Second, let's split out data up based on these groups.  We can use
the function accumarray() to accomplish this nicely.  If we
pass in the function handle @max to it, it'll even find the max
within these groups.

B = accumarray(z, A(:, 1), [], @max)

There is some trick to get each row corresponding to that maximum value based on the z parameter, but after investigating this for a few hours I still haven't figured it out and have given up.  You could try using find() to get these rows instead, using z to make sure we are grabbing the right values.


Seed std::mt19937 from std::random_device

Well, first off, why do you use a std::vector for a comparatively small sequence of known length? A raw array or std::array suffice and avoids any dynamic allocation.

Next, avoid needless magic numbers. Use std::mt19937::state_size instead of manually specifying 624.

Why do you use a lambda? A simple std::ref(source) suffices.

The seeding itself looks perfectly fine and there's no actual error anywhere in your code.
template<class T = std::mt19937, std::size_t N = T::state_size * sizeof(typename T::result_type)>
auto ProperlySeededRandomEngine () -> typename std::enable_if<N, T>::type {
    std::random_device source;
    std::random_device::result_type random_data[(N - 1) / sizeof(source()) + 1];
    std::generate(std::begin(random_data), std::end(random_data), std::ref(source));
    std::seed_seq seeds(std::begin(random_data), std::end(random_data));
    return T(seeds);
}

You could avoid the need for random_data by using counting and transforming iterators as detailed in "Sequence iterator? Isn't there one in boost?".
This is not simpler, but maybe more efficient:
template<class T = std::mt19937, std::size_t N = T::state_size * sizeof(typename T::result_type)>
T ProperlySeededRandomEngine () {
    std::random_device source;
    auto make_iter = [&](std::size_t n) {
    return boost::make_transform_iterator(
        boost::counting_iterator<std::size_t>(n), [&](size_t){return source();});
    };
    std::seed_seq seeds(make_iter(0), make_iter((N - 1) / sizeof(source()) + 1));
    return T(seeds);
}

On coliru


You code is extremly hard to read. But I belive this is what you are looking for:

function FindText(FileName: TFilename; const Delimit1, Delimit2: string): string;
var
  Buffer: TStringList;
  PD1, PD2: Integer;
begin
  Buffer := TStringList.Create;
  try
    Buffer.LoadFromFile(FileName);

    PD1 := Pos(Delimit1, Buffer.Text) + Length(Delimit1);
    PD2 := Pos(Delimit2, Buffer.Text);

    Result := Copy(Buffer.Text, PD1, PD2 - PD1);
  finally
    FreeAndNil(Buffer);
  end;
end;


Scraping news articles from various pages

Use interface instead of class with single method
Each concrete implementation should be a singletone
Each concrete implementation should contain only logic and accept your current news in crowler() method: do not recreate a strategy instance for each news.


Inefficient binary search? Hackerrank - Climbing the Leaderboard

As @hoffmale correctly pointed out, the Hackerrank code to read in the input files on the larger tests was causing a problem. More specifically it didn't have enough memory to read in the array. So I increased the size of the reader  and the writer (just in case). I also made a change to my binary search to ensure end would not be out of bounds on scores.

reader := bufio.NewReaderSize(os.Stdin, 1024*1024*3)

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
    "strings"
)

func removeDuplicates(a []int) []int {
    r := []int{}
    seen := map[int]int{}
    for _, val := range a {
        if _, ok := seen[val]; !ok {
            r = append(r, val)
            seen[val] = val
        }
    }
    return r
}

func getMidPoint(start, end int) int {
    i := end - start
    if i%2 == 0 {
        return i/2 + start
    }
    return (i+1)/2 + start
}

func binarySearch(scores []int, v int, i int) int {
    var mid int
    var end int

    start := 0
    if i >= len(scores) {
        end = len(scores) - 1
    } else {
        end = i
    }

    for true {
        if end-start == 1 {
            // fmt.Printf("1 - v: %d start: %d end %d\n", v, start, end)
            if v < scores[end] {
                return end + 2
            } else if v < scores[start] {
                return start + 2
            }
            return 1
        }
        if end == 0 {
            return 1
        }

        mid = getMidPoint(start, end)

        if v > scores[mid] {
            end = mid
        } else if v < scores[mid] {
            start = mid
        } else {
            // v == scores[mid]
            // fmt.Printf("2 - v: %d start: %d end %d\n", v, start, end)
            return mid + 1
        }
    }
    return end
}

// attempt 3 - binary search
func climbingLeaderboard(originalScores []int, alice []int) []int {

    r := make([]int, len(alice))

    //create scores and remove dups
    scores := removeDuplicates(originalScores)
    i := len(scores)

    for a, v := range alice {
        // fmt.Printf("1 - i: %d a: %d alice[a]: %d\n", i, a, alice[a])
        i = binarySearch(scores, v, i-1)
        r[a] = i
    }

    return r
}

func main() {
    reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024*3)

    stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
    checkError(err)

    defer stdout.Close()

    writer := bufio.NewWriterSize(stdout, 1024 * 1024*3)

    scoresCount, err := strconv.ParseInt(readLine(reader), 10, 64)
    checkError(err)

    scoresTemp := strings.Split(readLine(reader), " ")

    var scores []int

    for i := 0; i < int(scoresCount); i++ {
        scoresItemTemp, err := strconv.ParseInt(scoresTemp[i], 10, 64)
        checkError(err)
        scoresItem := int(scoresItemTemp)
        scores = append(scores, scoresItem)
    }

    aliceCount, err := strconv.ParseInt(readLine(reader), 10, 64)
    checkError(err)

    aliceTemp := strings.Split(readLine(reader), " ")

    var alice []int

    for i := 0; i < int(aliceCount); i++ {
        aliceItemTemp, err := strconv.ParseInt(aliceTemp[i], 10, 64)
        checkError(err)
        aliceItem := int(aliceItemTemp)
        alice = append(alice, aliceItem)
    }

    result := climbingLeaderboard(scores, alice)

    for i, resultItem := range result {
        fmt.Fprintf(writer, "%d", resultItem)

        if i != len(result) - 1 {
            fmt.Fprintf(writer, "\n")
        }
    }

    fmt.Fprintf(writer, "\n")

    writer.Flush()
}

func readLine(reader *bufio.Reader) string {
    str, _, err := reader.ReadLine()
    if err == io.EOF {
        return ""
    }

    return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
    if err != nil {
        // fmt.Println("Error: " + err.Error())
        panic(err)
    }
}


Query string substitutions for links on a page

The code you provide is inefficient in two ways:

Unnecessary loops. It loops through a.rewrite anchor each time for one querystring match. It could be optimized into one loop;
Repeated calculation on regular expression matches. regexS is executed for each gup function and it could be reduced into one calculation.

The solutions are:

Fetch the window.location.href data into one variable which could be referred to later;
Integrate the two (or more) loops into one and finish all the replacement in one loop.

Here the optimized code goes:

//First you fetch the query string as key-value pairs in the window.location.href, this equals your gup function.

//This code, fetch the ?key1=value1&key2=value2 pair into an javaScript Object {'key1': 'value1', 'key2':'value2'}
var queryString = {};
var queryStringPattern = new RegExp("([^?=&]+)(=([^&]*))?", "g");
window.location.href.replace(
    queryStringPattern,
    function($0, $1, $2, $3) { queryString[$1] = $3; }
);

//Second you collect all the anchor with class rewrite and execute the replacement.

$("a.rewrite").each(function () {
  this.href.replace(
    queryStringPattern,
    function ($0, $1, $2, $3) {
      return queryString[$1] ? $1 +  "=" + queryString[$1] : $1 + '=' + $3;
    }
  )
});


Sorting a list of phone numbers by teleconference provider and location

Your first attempt

That seems to be a correct implementation, but the same array meeting.phoneNumbers
is filtered repeatedly, which is not very efficient. You could improve it by
traversing the array once and assign each phone number to one of the four arrays:

func sortParsedNumbers(meeting: Meeting) -> [String] {

    var unknownProviderNumbers: [String] = []
    var incorrectProviderNumbers: [String] = []
    var correctProviderNumbers: [String] = []
    var matchingLocationNumbers: [String] = []

    let userCountry = getUserLocation()
    for phoneNumber in meeting.phoneNumbers {
        // ... append `phoneNumber` to one of the four arrays ...
    }

    return matchingLocationNumbers + correctProviderNumbers + incorrectProviderNumbers + unknownProviderNumbers
}

But this does not scale well if more sorting criteria are added.
Which leads us to

Your second attempt

There are two problems. First, you sort the arrays with comparison functions like this:

meeting.phoneNumbers.sorted { element, _ in
    someBooleanPredicate(element)
}

But the sorted(by:)
method requires that the given predicate is a "strict weak ordering over the elements",
in particular that

areInIncreasingOrder(a, a) is always false. (Irreflexivity)

and that condition is violated in your code.

Second, you chain multiple sorted(by:) calls. But the sorted() method
is not stable, which means that the later sort can destroy the result of the
previous sorts.

For both reasons, your code may give correct results, but you cannot rely on it.

So (unless you have a stable sort method, which the Swift standard library does not
yet provide), a multi-level sort must be done with a single call to sorted(by:).

Let's start with an example: Assume that you have a Person type with firstName
and lastName properties, then

persons.sort(by: { (lhs, rhs) in
    if lhs.lastName != rhs.lastName {
        return lhs.lastName < rhs.lastName
    }
    return lhs.firstName < rhs.firstName
})

would be a correct way of sorting an array with respect to the last name first,
and with respect to the first name second. This can be simplified to

persons.sort(by: { (lhs, rhs) in
    return (lhs.firstName, lhs.lastName) < (rhs.firstName, rhs.lastName)
})

because the compiler automatically creates a < operator for tuples of
comparable elements, implementing the lexicographical order.

In your case we have two criteria as well: provider and location. First we need some
type to describe and compare the desired sorting order for both criteria.
That could be just an Int, but an integer-based enum describes the intention more clearly:

enum ProviderStatus: Int, Comparable {
    case known
    case unknown
    case correct

    static func <(lhs: ProviderStatus, rhs: ProviderStatus) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }
}

enum LocationStatus: Int, Comparable {
    case notMatching
    case matching

    static func <(lhs: LocationStatus, rhs: LocationStatus) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }
}

Then you can compute a tuple describing the sorting order for each phone
number, and sort the numbers accordingly:

func sortParsedNumbers(meeting: Meeting) -> [String] {

    let userCountry = getUserLocation()

    func sortOrder(phoneNumber: String) -> (ProviderStatus, LocationStatus) {
        let providerStatus = ...
        let locationStatus = ...
        return (providerStatus, locationStatus)
    }

    return meeting.phoneNumbers.sorted(by: { (lhs, rhs) in
        sortOrder(phoneNumber: lhs) < sortOrder(phoneNumber: rhs)
    })
}

Adding more sorting criteria is straightforward with this approach.

A possible disadvantage is that sortOrder() can be called multiple times for the
same phone number during the sorting process. That can be avoided at the expense
of additional storage:

    return meeting.phoneNumbers
     .map { ($0, sortOrder(phoneNumber: $0))}
     .sorted { $1.1 > $0.1 }
     .map { $0.0 }

The return expression maps each phone number to a (number, sortOrder) pair,
sorts the pairs according to the sort order, and finally extracts the phone number
again. This guarantees that the sortOrder() function is called only once
for each phone number.


Foreign Key

Your foreign key is typed to List. I recommend using a HashSet to prevent adding the same entities twice to you navigation properties. I also recommend instantiating it, too, so that you don't get null reference exceptions on new Users that haven't been loaded from EF.

public virtual ICollection<Note> Notes { get; set; } = new HashSet<Note>()

Additionally, you can take advantage of EF Code First Conventions to not require the foreign key id fields or primary key id fields at all, and have EF imply them for you. This will lead to your entities most closely resembling your domain model, instead of DTOs.

public class User
{
    [MaxLength(20)]
    public string UserName { get; set; }

    public virtual ICollection<Note> Notes { get; set; } = new HashSet<Note>();
}

public class Note
{
    [MaxLength(30)]
    public string Title { get; set; }

    [MaxLength(200)]
    public string Content { get; set; }

    public virtual User User { get; set; }
}

public class NotesContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Note> Notes { get; set; }
}

Structure

There isn't a ton wrong with your code being structured as it is. Anything extra would really be redundancy at this stage, but then it isn't very large at this stage.

The following are recommendations that don't make sense in a trivial project like this, but once you start involving substantial logic, they will be a huge benefit.

Put your logic in a class that makes sense

Program is doing too much, move your DB logic into a Notes or Users class. For command line apps, I prefer to use Program to bridge the chasm between the screaming maw of stringly-typed CMD world and the beautiful, shining crystal palaces of your OOP domain.

I like to use a Service Object for this.

That DbContext Issue

The approach of using a whole db context per operation would be an efficiency issue but you appear to be aware of that.

However, performance aside, I'd recommend against this for a number of reasons.

These methods creating their own db contexts is a violation of the Single Responsibility Principle. It shouldn't matter what DB store you've got in there or when it's saved. Leave that to the consumer of those methods. On top of that, you cannot swap out what DbContext is used in the case of testing.

Secondly the static methods are permanently affecting state. It is very difficult to test these methods without first creating an entire database.

To fix this, you should inject this DbContext dependency.

Lastly, there's a lot of duplication in the boilerplate of creating a DbContext, so we can extract that out to a single method. With it in a single method, it frees you to be more open to altering db code too, allowing you to implement transactions, for example, in the future.

Don't pass ids around, pass the entities

Now that Program is acting as a barrier between the nasty, stringly-typed command line frontier and the beautiful, pure objects domain, let's make that actual domain use pure objects.

You've got these lovely types for a reason, benefit from the type checker and get extra correctness by passing the whole entity between your functions.

Recommendation

(assuming the EF model recommendation earlier)

class NoteService
{
    readonly NotesContext db;

    public NoteService(NotesContext context)
    {
        db = context;
    }

    public Note CreateNote(User user, string title, string content) => new Note { User = user, Title = title, Content = content };

    public void AddNote(Note note) => db.Notes.Add(note);

    public Note GetNote(int id) => db.Notes.Find(id);

    public void RemoveNote(Note note) => db.Notes.Remove(note);

    public void ClearNotes() => db.Notes.RemoveRange(db.Notes);
}

class UserService
{
    readonly NotesContext db;

    public UserService(NotesContext context)
    {
        db = context;
    }

    public User CreateUser(string userName) => new User() { UserName = userName };

    public void AddUser(User user) => db.Users.Add(user);

    public User GetUser(int id) => db.Users.Find(id);

    public void RemoveUser(User user) => db.Users.Remove(user);

    public void ClearUsers() => db.Users.RemoveRange(db.Users);
}

class Program
{
    private static void ExecuteAgainstDatabase(Action<NotesContext> action)
    {
        using (var db = new NotesContext())
        {
            action(db);
            db.SaveChanges();
        }
    }

    private static void ExecuteForUsers(Action<UserService> action) => ExecuteAgainstDatabase(db => action(new UserService(db)));

    private static void ExecuteForNotes(Action<NoteService> action) => ExecuteAgainstDatabase(db => action(new NoteService(db)));

    private static void AddUser(string userName) => ExecuteForUsers(us => us.AddUser(us.CreateUser(userName)));

    private static void RemoveUser(int userId) => ExecuteForUsers(us => us.RemoveUser(us.GetUser(userId)));

    private static void ClearUsers() => ExecuteForUsers(us => us.ClearUsers());

    private static void AddNote(int userId, string title, string content)
    {
        ExecuteAgainstDatabase(db =>
        {
            var noteService = new NoteService(db);
            var userService = new UserService(db);

            var user = userService.GetUser(userId);

            noteService.AddNote(noteService.CreateNote(user, title, context));
        });
    }

    private static void RemoveNote(int noteId) => ExecuteForNotes(ns => ns.RemoveNote(ns.GetNote(noteId)));

    private static void ClearNotes() => ExecuteForNotes(ns => ns.ClearNotes());
}


Concatenating rows in CSV files and removing old CSV files

Clear

List Comprehension

It's an unneeded habit in Python to pre-declare your variables.  Instead of

myList = []
for x in otherList:
    myList.append(foo(x))

you can use list comprehension,

myList = [foo(x) for x in otherList]
# identical: myList = map(foo, otherList)

Clarity

for f in files:
    file_ints.append(int(f[:8])) #converts file names to ints from datenumber

The comment explains that f[:8] returns the date number of the file but how that happens is a mystery to me.  Why don't you just use os.path.getctime?

file_ints = [os.path.getctime(f) for f in files]

This next bit is confusing.

# makes a valid file path from of the lowest value datenumber
del_file = raw_dir + str(min(file_ints)) + '.csv'

If only makes sense if your files' naming convention is based on their ctime.  You aren't defining that naming convention here.  Don't rely on external rules. Your file_ints line up with your file_paths so just use

del_file = file_paths(min(file_ints))

You might consider maintaining the alignment by zipping the two together like this

path_mtime = zip(file_paths, file_ints)

Assumptions

Do you get the files daily?  Is the script guaranteed to be run daily?  If both of these are ever false then your clearing will be out of sync.  You are not deleting every file older than 14 days, you are deleting the oldest file if there are more than 14.  It could be 15 days old, it could be 3 day's old.

Instead, iterate over all files and delete anything older than 14 days.

for path, ctime in zip(file_paths, file_ints):
    if is_too_old(ctime): # implement externally.  use time module to get today.
       os.remove(path)

You are also assuming all files in this directory are .csv.  I don't know the nature of the directory but it could be possible that some jerk comes and drops a .txt or .xls in your directory.  os.listDir will also return any subfolders that you might have.  You might not have them but if you did you surely don't want to remove them. Using glob might be the safer bet.  It will also return the full path so you don't need the intermediate files variable.

file_paths = glob.glob(os.path.join(raw_dir, "*.csv"))

This is optional though. It might be more than fair to assume what is or isn't in your folder.

Results

import glob

def clear(raw_dir):
    """ remove any raw csv files that are older than 14 business days. Data itself
    is not lost because it has been archived in the full csv"""
    file_paths = glob.glob(os.path.join(raw_dir, "*.csv"))
    # Optional early exit assuming you get no less than 14 files a day.
    # if len(file_paths ) <= 14:
    #     return
    file_ints = [os.path.getctime(f) for f in file_paths]
    for path, ctime in zip(file_paths, file_ints):
        if is_too_old(ctime): # implement externally.  Use time module to get today.
           os.remove(path)
           print path + ' was deleted in clean up'

Merge

You declare this variable, and then never use it,

archive_file = archive_dir + date + '.csv'

the same value is used at the end,

shutil.copyfile(today_dir + 'TODAY.CSV', archive_dir + date + '.csv')

but I say drop the declaration and leave the end as is, except please use os.path.join

Order

The main issue with this procedure is the order you perform events.  Currently, it is

open output file
read input files
write output file.

It should be,

read input files
open output file
write output file.

reading before you create the output file will simplify the read to,

rows = []
files = os.listdir(raw_dir)
for fi in files:
    if fnmatch.fnmatch(fi, '*.csv'):
         rows.append(open(os.path.join(raw_dir, fi)).readlines())

using glob will make it simpler,

rows = \
    [open(fi).readlines() for fi in glob.glob(os.path.join(raw_dir, "*.csv")]

Clarity

I have no idea why you are transposing your rows.

iter = izip_longest(*rows)

Each row is the list of lines of a file so

rows = [[line1_file1, line2_file1, ...], [line1_file2, line2_file2, ...], ...]

then you transpose that, so you get

iter = [[line1_file1, line1_file2, ...], [line2_file1, line2_file2, ...]]

So then each line of your output is a join of the non-null lines of your files.
Are you sure that's what you want?  I could help you more but I don't understand the process you are going through.  Your output file looks like it could be

line1_file1 line1_file2 line1_file3
line2_file1 line2_file2 line2_file3
line3_file1 line3_file3
line4_file3

Point is it's confusing and there should be some explanation.

Results

def merge(raw_dir, today_dir, archive_dir, date):
    """Read through all .CSVs in RAW directory and merge rows into Today's "full" CSV
    """
    rows = \
        [open(fi).readlines() for fi in glob.glob(os.path.join(raw_dir, "*.csv")]
    merged_file = os.path.join(today_dir, 'TODAY.CSV')
    archive_file = os.path.join(archive_dir, date + '.csv')
    with open(merged_file, 'w') as f_obj:
        # whatever is going on here...
        for row in izip_longest(*rows):
            f_obj.write('   '.join([field.strip() for field in row if field is not None]) + '\n')
        shutil.copyfile(merged_file, archive_file)


Overall Observations
The function main() is too complex and should be broken up into multiple functions, if you do this you might notice that you are recreating your segtree struct for every query when it only needs to be created once and then each query should be applied to that structure.
Recursion is expensive in terms of resources it might be better to find iterative solutions.
The code is difficult to read and that may be why I am the first person answering.
Avoid using #include <bits/stdc++.h>
The header bits/stdc++.h is not part of the C++ programming standard and includes the whole world, this program needs only 2 C++ headers
#include <iostream>
#include <vector>

I realize that the programming challenge probably provided this for you, but that doesn't mean you should keep it if you know the proper includes.
Avoid using namespace std;
If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.
Variable Names
While you are using the variable names from the programming challenge, these variables names are not very descriptive and could cause you or someone who might be maintaining this code in a professional environment to make errors in the code.
Horizontal Spacing
One of the standard conventions in programming is to leave a space between an operator and an operand in any statement, this makes the code easier to read, examples:
        if(rx-lx==1){sums[x]+=v;return;}

versus
        if (rx - lx == 1) { sums[x] += v; return; }

        int m=(lx+rx)/2;

versus
        int m = (lx + rx) / 2;

Vertical Spacing
        if(rx-lx==1){sums[x]+=v;return;}
        int m=(lx+rx)/2;

versus
        if (rx - lx == 1)
        {
            sums[x] += v;
            return;
        }

        int m = (lx + rx) / 2;

As mentioned above, it isn't really clear what the variables m, rx and lx are, especially m.
Unused #define
The code contains:
#define ll long long

This is unused in the scope of the program and should be removed. There are at least 2 ways in C++ that don't require #define, one is a typedef and another is a using statement. While macros will continue to be supported in C++ to remain backwards compatible with C, the trend is to not use macros when possible.
##Magic Numbers
There are Magic Numbers throughout the program function (40, 2, 1), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
An enum could be used for the query type.


There's no way to tell this in a friendly manner: your indentation is abysmal.

Let's fix that up first. Note that there's plenty left to improve, like giving your operators some space, but I'll leave that as an exercise for yourself. Keep in mind space is cheap and readability is very important in code. If you can add readability by using some extra newlines or space, do it. But only if it helps. Don't throw them needlessly around just for the sake of it.

#include <iostream>
using namespace std;

int main(){
    int i=0, n, x, k;
    cin>>n;
    if(n>100) {
        cout<<"f("<<n<<")=";
        n=n-10;
    }
    else {
        cout<<"f("<<n<<")=";
        while(n<=100){
            loop:
                x=0;
                k=0;
                i++;
                n+=11;
                while(x<=i){
                    x++;
                    cout<<"f(";
                }
                cout<<n;
                while(k<=i){
                    k++;
                    cout<<")";
                }
                cout<<"=";
                if(n>100){
                    x=0;
                    k=0;
                    i=i-1;
                    n=n-10;
                    while(x<=i){
                        x++;
                        cout<<"f(";
                    }
                    cout<<n;
                    while(k<=i){
                        k++;
                        cout<<")";
                }
                cout<<"=";
            }
            if(n>100){
                x=0;
                k=0;
                i=i-1;
                n=n-10;
                if(i>=0){
                    while(x<=i){
                        x++;
                        cout<<"f(";
                    }
                    cout<<n;
                    while(k<=i){
                        k++;
                        cout<<")";
                    }
                    cout<<"=";
                    goto loop;
                }
                break;
            }
        }
    }
    cout<<n;
 }

Much better, but plenty left to improve.

Namespaces

using namespace std; is considered bad practice. Short code is not a requirement in C++, clear code is preferred. It's a thing commonly taught to new C++ programmers because it's 'easier', but it will royally bite you in the behind when conflicts arise.

goto

I'm not going to re-iterate how evil goto is, but please take a look at this well-written answer by 200_success. Basically, one should only use it in C++ if you know exactly what you're doing and there's no better alternative. There usually is a better alternative!

Be consistent!

x++ is usually reserved for for loops. Doing it in while loops indicates you're using the wrong tool for the job. You use x++, x += 1 and x = x + 1 or the negative version of it all over the place. There usually is no reason to write i = i -1, i -= 1 will do.

But the worst of it is:

Your code is simply incomprehensible. It takes too long to understand what it does and all the re-declaring of variables makes it hard to track what's going on. One-letter variables are usually not a good idea, iterators in for loops are an acceptable exception.

You have 6 while loops in your main function. 6!. I'd expect at least 3 different functions to keep this readable, with sensible returns passing the data along and there can't be a good reason to have this many while loops.

So?

Write down what you want to do as a flow-chart. Simplify it as much as possible. Implement that. The result will be half as complicated and twice as readable, at least. What you currently have is the result of a design flaw. I'm afraid a re-design, with this answer in the back of your head, is the only sensible solution here.


I can see three problems with this approach:

1) Calling runResourceT at each step releases all the scarse resources allocated by the original conduit. This is not what you want, since a conduit can depend on the availability of those resources until the point where it terminates.

2) You cannot call close after push returns Finished. This is explicitly stated in the documentation of PreparedConduit.

3) You need to call close on the conduit when the upstream pipe terminates. Unfortunately, I think this is impossible to do with vanilla pipes. That's why I am currently experimenting with what I call "guarded pipes". You can find them here, together with some other utilities ported over from conduits.

Using guarded pipes, you can write something like:

c2p :: Resource m => Conduit a m b -> Pipe a b (ResourceT m) ()
c2p c = do
  PreparedConduit push close <- lift $ prepareConduit c
  loop push close
  where
    loop push close = do
      input <- tryAwait
      case input of
        Nothing -> do
          output <- lift $ close
          mapM_ yield output
        Just input -> do
          stepResult <- lift $ push input
          case stepResult of
            Producing output -> do
              mapM_ yield output
              loop push close
            Finished _ output ->
              mapM_ yield output

You can try it, for example, with:

main = runResourceT . runPipe $
  fileProducer "sample.txt.gz" >+> c2p CZ.ungzip >+> fileConsumer "sample.txt"

where fileProducer and fileConsumer are also contained in the above pipes-extra package.


In general, it is bad practice to perform string substitutions in multiple passes, feeding the output back of one substitution into another round of substitutions.  (Here is an example of how multiple-pass substitutions can lead to incorrect results.)  In this case, it happens to be safe, since none of the outputs overlap with any of the patterns, but I would still recommend a different approach.  Fortunately, Ruby makes it easy to do multiple substitutions the right way, with #gsub(pattern, hash).

return is implicit in Ruby.  The last expression evaluated is automatically returned, and everything is an expression.

The standard is to use two spaces of indentation, not three.

def lisp(input)
  input.downcase.gsub(/er|[lrs]/,
    'er' => 'uh',
    'l'  => 'w',
    'r'  => 'w',
    's'  => 'th',
  ).capitalize
end


Create two vehicles, move them on a grid based on user input

Use functions
Having code at the top-level of a module is bad practice as it impairs both reusability and testing: as soon as the module is imported, the code gets executed which is not necessarily what you want.
Instead you should use functions and wrap the remaining top-level code in an if __name__ == '__main__': statement.
Having functions would also mean that you need to stop relying on global variables such as GRID_MAX_X, GRID_MAX_Y, first_vehicle_x or first_vehicle_y. Which is a good thing as currently they make your code tightly coupled. Instead, you should pass those values of interest as parameters to objects or functions.
Bug
Requirements state that:

Vehicles are sent sequentially. If the second vehicle attempts to move to the occupied spot of the first vehicle, the command will be skipped. If any move command makes any of the vehicles move out of the grid, that command will be skipped as well.

You effectively skip the command if the second vehicule tries to move to the position of the first one, but you don't skip it if the move would put the vehicule out of the boundaries of the map. Instead you make the vehicule glide along that boundary.
Also note that you can easily compare the position of the two vehicules using tuple equality (new_x, new_y) != vehicule_one_position and check that a number is within bounds using extended comparisons: 0 <= new_x <= grid_max_x.
Indexables
Strings are iterables and indexables, no need to split them in a list or a tuple. I would however encapsulate changing directions in its own class to better separate concerns and avoid a small amount of repetitions.
eval
There is one saying that eval is evil. It has its uses, but never in such simple cases. Instead, you should know that you can reference functions and methods just by their name so you can build the commands dictionnary in the Vehicule class using
{
    'L': self.turn_left,
    'R': self.turn_right,
    'M': self.move,
}

And be able to do commands[command]() directly, without the need for eval.
Use @property
For simpler data extraction, @property methods can help format them and appear as a simple attribute access. This help make a cleaner design.
Proposed improvements
class Directions:
    """Circular buffer of possible directions"""
    DIRECTIONS = 'NESW'

    def __init__(self, start):
        self.index = self.DIRECTIONS.index(start)

    def next(self):
        self.index = (self.index + 1) % len(self.DIRECTIONS)

    def previous(self):
        self.index = (self.index - 1) % len(self.DIRECTIONS)

    @property
    def current(self):
        return self.DIRECTIONS[self.index]

class Vehicle():
    MOVEMENT = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W':(-1, 0)}

    def __init__(self, x, y, facing, grid, obstacle):
        self.x = x
        self.y = y
        self.facing = Directions(facing)
        self.grid_width, self.grid_height = grid
        self.obstacle = obstacle

    @property
    def direction(self):
        return self.facing.current

    @property
    def position(self):
        return (self.x, self.y)

    def parse_commands(self, commands):
        action = {
            'L': self.facing.previous,
            'R': self.facing.next,
            'M': self.move,
        }
        for command in commands:
            action[command]()

    def move(self):
        offset_x, offset_y = self.MOVEMENT[self.facing.current]
        x = self.x + offset_x
        y = self.y + offset_y

        if (x, y) != self.obstacle and 0 <= x <= self.grid_width and 0 <= y <= self.grid_height:
            self.x = x
            self.y = y

def setup_and_move_vehicule(grid, obstacle):
    x, y, facing = raw_input().split()
    vehicule = Vehicule(int(x), int(y), facing, grid, obstacle)
    vehicule.parse_commands(raw_input().strip())
    return vehicule.position, vehicule.direction

def main():
    grid = map(int, raw_input().split())
    v1_pos, v1_dir = setup_and_move_vehicule(grid, None)
    v2_pos, v2_dir = setup_and_move_vehicule(grid, v1_pos)
    print v1_pos[0], v1_pos[1], v1_dir
    print v2_pos[0], v2_pos[1], v2_dir

if __name__ == '__main__':
    main()


Batch file-download script - is it necessary to re-phrase commands?

I don't think there's a better way to format your %DATE% variable. And be careful, because I think this won't work in all locales. I had this problem a few years ago, and I remember that there was no good solution to format dates using native commands. I had to make a simple dateformat utility myself to generate date formats easily and in a locale independent way.

Just a small thing, I recommend NOT to put the trailing \ in the %ARCHIVE% variable. So instead of this:

SET ARCHIVE=%PATH%\Archives\%date%\
DIR %PATH% /B > %ARCHIVE%log-%date%.txt

MOVE %PATH%\Upload.zip %ARCHIVE%Upload-%date%.zip

Write like this:

SET ARCHIVE=%PATH%\Archives\%date%
DIR %PATH% /B > %ARCHIVE%\log-%date%.txt

MOVE %PATH%\Upload.zip %ARCHIVE%\Upload-%date%.zip

This may be a matter of taste, but I like to see explicitly that it's a directory there, not just a prefix.

Another formatting tip about this:

MOVE %PATH%\index.txt %ARCHIVE%\index-%date%.txt ||(
MOVE %PATH%\error_files\index.txt %ARCHIVE%\index-%date%.txt
)

I find it easier to read when the commands inside (...) are indented, like this:

MOVE %PATH%\index.txt %ARCHIVE%\index-%date%.txt || (
    MOVE %PATH%\error_files\index.txt %ARCHIVE%\index-%date%.txt
)


Find index of lowest unique integer in each line of the file

First off, your usage of alter can easily be replaced by insertWith:

counts :: [(Int, Int)] -> IntMap [Int]
counts = foldr f empty
  where f (i,v) = insertWith (const (i:)) v [i]

You could also use fromListWith, which is neater but less efficient due to the need to concatenate lists:

counts :: [(Int, Int)] -> IntMap [Int]
counts = fromListWith (flip (++)) . map (\(i,v) -> (v,[i]))

Second, you could shorten g quite a bit as well using a view:

g a = case minView $ filter ((== 1) . length) a of
        Nothing      -> 0
        Just ([i],_) -> i

Which is also probably slightly less efficient, as it will construct at least a thunk for the rest of the IntMap.

Concerning different approaches - you could make a recursive function that removes all duplicates:

import Data.List
import Data.Ord

dedup :: [(Int,Int)] -> [(Int,Int)]
dedup [] = []
dedup ((i,v):ps)
  | null dups = (i,v):dedup ps
  | otherwise = dedup ndups
  where (dups, ndups) = partition ((==v) . snd) ps

minUnique :: [Int] -> Int
minUnique l
  | null ddups = 0
  | otherwise  = fst $ minimumBy (comparing snd) $ ddups
  where ddups = dedup $ zip [1..] l

Once more this trades for a bit of efficiency, as the traversal in partition makes it O(n²). Not sure whether that can be helped though without involving more complex data structures.


Is this an appropriate approach to "tweak" a color to a similar lighter/darker color?

I think that your algorithm is overly simplistic.  To illustrate its problems, try running the Stack Snippet in this answer, in which I have translated your TweakColor() function into JavaScript for demonstration purposes.

It has three significant flaws, in my opinion:

It is subject to jarring discontinuities when switching from darkening to lightening mode and vice versa.

For example, with Diff=127, try changing the input color from rgb(234,150,0) to rgb(233,150,0).  The output color jumps from maroon to creamy yellow.
It doesn't preserve the hue, which is what most people would consider to be the most important attribute of a color.

In the example above, with rgb(234,150,0) as the input color, as Diff increases from 0, we see the output change from orange to red.  I would expect any tweaking to result in another color that is still recognizably "orange".  If you start from the neighboring rgb(233,150,0), then the color changes to yellow as Diff increases from 0.
Its behavior is hard to characterize.

For example, starting with rgb(255,130,0), and increasing Diff from 0, we see that the output fades from orange to black.  In contrast, starting with rgb(255,125,0), it fades from orange to white.

As another example, starting with rgb(0,80,160) and increasing Diff from 0, we see true blue turning towards cyan as blue is clamped at 255, then trending towards white as green is clamped at 255.

The inconsistency makes no sense to the user.

The remedy is to map the RGB input to a color wheel — I suggest using the hue-saturation-value color model.  Define the tweak to be a hue-preserving transformation.  My suggestion is to vary just the value, but you could also vary saturation instead.

function TweakColor(const AColor: TRGBColor; const ADiff: Integer): TRGBColor;
var
  HSV: THSVColor;
  V, VAdj: Single;
begin
  HSV := RGBToHSV(AColor);
  V := GetVValue(HSV);
  VAdj := (ADiff / 128) * (V - 0.5);
  Result := HSVToRGB(HSV(GetHValue(HSV), GetSValue(HSV), V - VAdj));
end;

/* Your original function, translated into JavaScript */
function tweakColor(aColor, aDiff) {
  function intRange(value, min, max) {
    return value < min ? min
         : value > max ? max
                       : value;
  }
  var r = aColor.r,
      g = aColor.g,
      b = aColor.b;
  var d = (r + g + b) / 3;
  var dir = (d >= (256 / 2)) ? -aDiff : aDiff;
  r = intRange(r + dir, 0, 255);
  g = intRange(g + dir, 0, 255);
  b = intRange(b + dir, 0, 255);
  return new RGBColor(r, g, b);
}

function newTweakColor(aColor, aDiff) {
  var hsv = aColor.toHSV();
  var vAdj = (aDiff / 128) * (hsv.v - 0.5);
  return (new HSVColor(hsv.h, hsv.s, hsv.v - vAdj)).toRGB();
}

function RGBColor(r, g, b) {
  this.r = r; this.g = g; this.b = b;
}

RGBColor.prototype.toString = function() {
  return 'rgb(' + Math.round(this.r) + ',' + Math.round(this.g) + ',' + Math.round(this.b) + ')';
};

/* Based on formulas from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm */
RGBColor.prototype.toHSV = function toHSV() {
  var r = this.r / 255,
      g = this.g / 255,
      b = this.b / 255;
  var cMax = Math.max(r, g, b),
      cMin = Math.min(r, g, b);
  var Δ = cMax - cMin;
  var hue = 60 * ( (cMax == r) ? ((g - b) / Δ) % 6
                 : (cMax == g) ? ((b - r) / Δ) + 2
                               : ((r - g) / Δ) + 4 );
  var sat = cMax == 0 ? 0 : Δ / cMax;
  var val = cMax;
  return new HSVColor((hue + 360) % 360, sat, val);
}

function HSVColor(h, s, v) {
  this.h = h; this.s = s; this.v = v;
}

HSVColor.prototype.toString = function() {
  return 'hsl(' + Math.round(this.h) + ',' + Math.round(100 * this.s) + '%,' + Math.round(100 * this.v) + '%)';
};

/* http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSV */
HSVColor.prototype.toRGB = function toRGB() {
  var c = this.v * this.s;
  var h = this.h / 60;
  var x = c * (1 - Math.abs(h % 2 - 1));
  var r1 = (h < 1 || h >= 5) ? c
         : (h < 2 || h >= 4) ? x : 0;
  var g1 = (h >= 1 && h < 3) ? c
         : (h >= 0 && h < 4) ? x : 0;
  var b1 = (h >= 3 && h < 5) ? c
         : (h >= 2 && h < 6) ? x : 0;
  var m = this.v - c;
  return new RGBColor(Math.round(255 * (r1 + m)),
                      Math.round(255 * (g1 + m)),
                      Math.round(255 * (b1 + m)));
};

var ColorTweakerCtrl = function ColorTweakerCtrl($scope) {
  $scope.inColor  = new RGBColor(234, 150, 0);
  $scope.diff = 127;

  $scope.tweak = function tweak() {
    $scope.inColor.r = Math.round($scope.inColor.r);
    $scope.inColor.g = Math.round($scope.inColor.g);
    $scope.inColor.b = Math.round($scope.inColor.b);
    $scope.diff = Math.round($scope.diff);
    $scope.outColor = tweakColor($scope.inColor, $scope.diff);
    $scope.newColor = newTweakColor($scope.inColor, $scope.diff);
  };
  $scope.tweak();
};
fieldset {
  display: inline-block;
  width: 25%;
}
fieldset#tweak {
  display: block;
  width: 100%;
  border-width: 0;
}
label {
  display: block;
}
.swatch {
  border: 1px solid grey;
  width: 100%;
  height: 1em;
}
input[type=range] {
  width: 40%;
}

  <form ng-controller="ColorTweakerCtrl">
    <fieldset id="tweak">
      Diff
        <input ng-model="diff" type="range" min="0" max="255" ng-change="tweak()">
        <input ng-model="diff" type="number" min="0" max="255" ng-change="tweak()">

    </fieldset>

    <fieldset>
      <legend>Input Color</legend>

      R
        <input ng-model="inColor.r" type="range" min="0" max="255" ng-change="tweak()">
        <input ng-model="inColor.r" type="number" min="0" max="255" ng-change="tweak()">

      G
        <input ng-model="inColor.g" type="range" min="0" max="255" ng-change="tweak()">
        <input ng-model="inColor.g" type="number" min="0" max="255" ng-change="tweak()">

      B
        <input ng-model="inColor.b" type="range" min="0" max="255" ng-change="tweak()">
        <input ng-model="inColor.b" type="number" min="0" max="255" ng-change="tweak()">

    </fieldset>

    <fieldset>
      <legend>Output (Yours)</legend>

      R
        <input ng-model="outColor.r" type="range" min="0" max="255" disabled>
        <input ng-model="outColor.r" type="number" min="0" max="255" disabled>

      G
        <input ng-model="outColor.g" type="range" min="0" max="255" disabled>
        <input ng-model="outColor.g" type="number" min="0" max="255" disabled>

      B
        <input ng-model="outColor.b" type="range" min="0" max="255" disabled>
        <input ng-model="outColor.b" type="number" min="0" max="255" disabled>

    </fieldset>

    <fieldset>
      <legend>Output (Suggested)</legend>

      R
        <input ng-model="newColor.r" type="range" min="0" max="255" disabled>
        <input ng-model="newColor.r" type="number" min="0" max="255" disabled>

      G
        <input ng-model="newColor.g" type="range" min="0" max="255" disabled>
        <input ng-model="newColor.g" type="number" min="0" max="255" disabled>

      B
        <input ng-model="newColor.b" type="range" min="0" max="255" disabled>
        <input ng-model="newColor.b" type="number" min="0" max="255" disabled>

    </fieldset>
  </form>


As you say, there are only a limited possibilities for a Score, which I would call GameScore to be more precise. This calls for an enum.

public enum GameScore {
    S0000(0, 0), S1500(15, 0), S3000(30, 0), ...;

    private static final GameScore[] SWIN = { S1500, ... };
    private static final GameScore[] RWIN = { S0015, ... };
    private static final String[] NAME = { "Love-All", ... };

    ...

    public GameScore serverWins() {
        return SWIN[ordinal()];
    }

    public GameScore returnerWins() {
        return RWIN[ordinal()];
    }

    public String getDisplayText() {
        return NAME[ordinal()];
    }
}

That's all. All in one class, ready for testing.

By the way, in Java all method names start with a lowercase letter, not an uppercase. (That would be C# or Ada.)

Using an enum and predefined string literals has the benefit of generating zero memory allocations at runtime.


You can shorten that code by not converting the values directly, but rather use common intermediate representation. E.g. you could convert the incoming number first to celsius (not matter what source and destinations are) and then convert the intermediate representation to the target:

double inputTemperature = ... ;
double outputTemperature;
String inputUnit = ... ;
String outputUnit = ... ;
// input conversion if necessary
if (inputUnit.equals("fahrenheit")) {
    inputTemperature = fahrenheitToCelsius(inputTemperature);
}
if (inputUnit.equals("kelvin")) {
    inputTemperature = kelvinToCelsius(inputTemperature);
}
// output conversion:
if (outputUnit.equals("fahrenheit")) {
    inputTemperature = celsiusToFahrenheit(inputTemperature);
}
if (outputUnit.equals("kelvin")) {
    inputTemperature = celsiusToKelven(inputTemperature);
}

So only 4 if statements rather than 9.

P.S.: Please review https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java


There is more efficient and idiomatic ways of implementing merge sort, yet I will assume your style. I have embedded my comments directly in your code whenever I have something to say:

#include <iostream>
#include <vector>
#include <algorithm>

template <typename T>
void merge(const std::vector<T>& left_vector,
           const std::vector<T>& right_vector,
           std::vector<T>& merged_vector)
{
    /*
    auto i = left.begin();
    auto j = right.begin();
    auto k = merged.begin();
    */
    // Better names + names for end iterators in order not to call end() on each
    // iteration:
    auto left      = left_vector.begin();
    auto right     = right_vector.begin();
    auto merged    = merged_vector.begin();
    auto left_end  = left_vector.end();
    auto right_end = right_vector.end();

    /*
    while (i != left.end() && j != right.end())
    {
        *k = (*i < *j) ? *i : *j;
        if (*i < *j) ++i;
        else ++j;
        ++k;
    }*/
    // Would be more efficient since you compare only once per iteration:
    while (left != left_end && right != right_end)
    {
        if (*right < *left)
        {
            *merged = *right;
            ++right;
        }
        else
        {
            *merged = *left;
            ++left;
        }

        ++merged;
    }

    /*
    while (j != right.end())
    {
        *k = *j; ++k; ++j;
    }
    while (i != left.end())
    {
        *k = *i; ++k; ++i;
    }*/
    // Here you could use std::copy. Only one of these two calls will have an
    // effect, since either left < left_end or right < right_end:
    std::copy(left, left_end, merged);
    std::copy(right, right_end, merged);
}

template <typename T>
void merge_sort(std::vector<T>& A)
{
    if (A.size() <= 1) return;
    size_t mid = A.size() / 2;
    std::vector<T> left(A.begin(), A.begin() + mid);
    std::vector<T> right(A.begin() + mid, A.end());
    merge_sort(left);
    merge_sort(right);
    merge(left,right, A);
}

int main()
{
    std::vector<int> input = {19, 14, 17, 16, 12, 9, 15, 1, 2, 11, 7, 3, 10, 14};
    std::vector<int> sorted = {1, 2, 3, 7, 9, 10, 11, 12, 14, 14, 15, 16, 17, 19};
    /*
    merge_sort(input);
    bool success = true;
    merge_sort(input);
    for (size_t i = 0; i < input.size(); ++i) if ( input[i] != sorted[i] ) success = false;
    std::cout << "Merge sort " << (success ? "passed\n" : "failed\n");
     */
    // You can write better:
    merge_sort(input);
    std::cout << "Merge sort passed: "
              << std::boolalpha
              << std::equal(input.begin(),
                            input.end(),
                            sorted.begin(),
                            sorted.end())
              << std::endl;
}

Hope that helps.


I'd be inclined to make a simple fixed array instead of a std::vector for funcs:

const std::function<void(int i)> funcs[] {
    [](int i) { std::cout << i << "\n"; },
    [](int ) { std::cout << "fizz\n";  },
    [](int ) { std::cout << "buzz\n";  },
    [](int ) { std::cout << "fizzbuzz\n"; }
};

This is useful because it eliminates the overhead of memory allocations for a std::vector and the calls for constructor and destructor.  As an embedded systems guy, I tend to think about whether code can be in ROM rather than RAM, and whether work can be done at compile-time rather than run-time.

Note, too that I've omitted the variable name for the last three lambdas.  There's no real difference except that it prevents the compiler from generating a warning about "unused parameter i" in those three lines.

Also, I think you're overthinking the lambda.  The test lambda isn't really necessary at all since you can call it like this:

funcs[ (i % 3 == 0) + 2 * (i % 5 == 0) ](i);

So (without xrange.h, although one could use that also) it would look like this:

#include <iostream>
#include <functional>

int main() {
    const std::function<void(int i)> funcs[] {
        [](int i) { std::cout << i << "\n"; },
        [](int ) { std::cout << "fizz\n";  },
        [](int ) { std::cout << "buzz\n";  },
        [](int ) { std::cout << "fizzbuzz\n"; }
    };

    for (int i=1; i <= 100; ++i)
        funcs[ (i % 3 == 0) + 2 * (i % 5 == 0) ](i);
}


At its heart, this is a stack problem.  You can get O(n) worst-case performance and O(n) space complexity by simply iterating the string in place, pushing opening brackets onto a stack and when encountering a closing bracket, popping the last item off stack to compare against.

You need to end up with an empty stack, and you can never have a case where you try to read out of an empty stack.  This in addition, of course to making sure items you are comparing out of the stack match appropriately.  So, there are three failure scenarios.

The solution I present might technically be optimized by hard-coding the opening and closing bracket values into conditionals and such, but I find this solution more flexible and easier to maintain from a code standpoint, as you have decoupled the bracket "configuration" from the code logic.

var balanced = '({[test string](test [string])})';
var unbalanced = '{()}]';
var empty = '';

var bracketConfig = [
    { left: '{', right: '}' },
    { left: '[', right: ']' },
    { left: '(', right: ')' }
];

function isBalanced(subject, bracketConfig) {
    // not shown - perhaps validate subject as string and error out if failing

    // build bracket arrays from config
    var openingChars = [];
    var closingChars = [];
    bracketConfig.forEach( (item) => {
        openingChars.push(item.left);
        closingChars.push(item.right);
    });

    var stack = [];
    for (var i = 0, len = subject.length; i < len; i++) {
        var char = subject[i];
        var openIdx = openingChars.indexOf(char);
        var closeIdx = closingChars.indexOf(char);
        if (openIdx > -1) {
            stack.push(openIdx);
        } else if (closeIdx > -1) {
            if (stack.length === 0) return 0;
            lastIdx = stack.pop();
            if(lastIdx !== closeIdx) return 0;
        }
    }

    if (stack.length !== 0) return 0;
    return 1;
}

// run tests
console.log(isBalanced(balanced, bracketConfig));
console.log(isBalanced(unbalanced, bracketConfig));
console.log(isBalanced(empty, bracketConfig));

JSFiddle of this example

My guess is that, for your interview, they were really looking to see that you could identify this as a stack problem and come up with a reasonable implementation.


What if I wanted every 7 number to also add fizz, so 105 would be fizzbuzzfizz? You can't do that in your code, since you are using the string as the (unique) key and the number as the value. Instead, use the number as the key and the string as the value.

While it will work in most cases, the order of properties in an object is not guaranteed. I would change this to either use an array of object or a map.

What if you wanted just the result form a single number? Or make a function that found the first number that gives fizzbuzz? Right now you are printing the result, so you can't do anything else with it. Make a separate function to get the result, which you can also use for other things.

function fizzBuzz(divisors = new Map([[3,'fizz'],[5,'buzz']]), maxNumber = 100) {
  for (var num = 1; num <= maxNumber; num++) {
    console.log(fizzValue(divisors, num));
  }
}

function fizzValue(divisors, num) {
  var str = "";
  divisors.forEach((value, key) => {
   str += num % key == 0 ? value : '';
  });
  return (str ? str : num);
}

fizzBuzz();