There are a couple things in this method that can be refactored to remove a lot of duplicate code:

Firstly, you have this if statement:

if held_item.find_all('option')[1:]:
    ...
else:
    ...

What this is really checking for is if there is more than 1 option found. So, instead of having to write nearly identical code to handle the cases of 0 options or at least 1 option, we can simply store the find_all result and modify it based on a quick length check:

options = held_item.find_all('option')
if len(options) > 1:
    options.pop(0)

for option in options:
    append_dict(selection_container, option)

    # If there is a non-zero amount of spaces, there will be at least
    # 2 partitions when split.
    if option.text.count(' '):
        stock_info = {'message': reduce(lambda x, y: x + ' ' + y, option.text.split(' ')[1:])[1:-1],
                      'status': 'pre-order'}
    problem_dict.update({'stock': stock_info})

Now, take a look at this line of code:

stock_info = {
    'message': reduce(lambda x, y: x + ' ' + y, m.text.split(' ')[1:])[1:-1],
    'status': 'pre-order'
}

I have two points to make about this line of code:

As a quick disclaimer about this first point:

  The line is still compliant with PEP8, so this is just a personal preference.

With that out of the way, I try to never to put an opening {/(/[ at the end of a line unless I have to. Also, I never put the closing }/)/] on a line by itself. So I would format the line like this:

stock_info = {'message': reduce(lambda x, y: x + ' ' + y, m.text.split(' ')[1:])[1:-1],
              'status': 'pre-order'}

My second point about this line of code is about how you create message. They way you use reduce is not quite necessary. From what I can tell, you want to take everything after the first space, then everything of that section except the first and last characters. This can be easily done using the split function:

stock_info = {'message': m.split(' ', 1)[-1][1:-1] ...

Or you can use list splicing:

# Below is reduced version of:
#    m[m.index(' ') + 1:][1:-1]
stock_info = {'message': m[m.index(' ') + 2:-1] ...

Past these two points, there isn't much to improve the algorithm from what information you gave. If you wanted to reduce the number of lines, you could write the first for loop as a list comprehension:

holder = [moselect.find_all('div')[1:]
          for moselect in base_page.find_all('div', attrs={'class': 'Moselect'})
          if moselect.find('div', attrs={'id': 'noSize'})]

Style-wise, you could improve a few of your variable names (m, holder, and selection_container specifically) as some of them are either ambiguous or slightly misleading.

Here is your code with my suggestions implemented:

def get_info():
    problem_dict = {}
    selection_container = []
    holder = [moselect.find_all('div')[1:]
              for moselect in base_page.find_all('div', attrs={'class': 'Moselect'})
              if moselect.find('div', attrs={'id': 'noSize'})]

    for held_item in holder[0]:
        options = held_item.find_all('option')
        if len(options) > 1:
            options.pop(0)

        for option in options:
            append_dict(selection_container, option)

            # If there is a non-zero amount of spaces, there will be at least
            # 2 partitions when split.
            if option.text.count(' '):
                stock_info = {'message': {'message': m[m.index(' ') + 2:-1],
                              'status': 'pre-order'}
            problem_dict.update({'stock': stock_info})

problem_dict.update(dict(selections=selection_container))
return problem_dict


Validate the set accessors in a simple Triangle class

Assuming you'll have other shapes that would have the same requirement, one option you have is to have a class Side inside the class Shape, and put the validation in there.  Now every shape can declare as many sides as needed and each will be validated.  Some thing like this should work:

private class Side
{
    double length;
    public double Length
   {
        get{return length;}
        set
        {
            if(value > 0)
            {
                 length = value;
            }
            else
            {
                 throw new ArgumentException("Value must be greater than 0");
            }
         }
    }
    Side(double _length)
    {
        Length = _length;
    }
}

In regards to the height, instead of having it passed to the constructor, calculate the height from the length of the sides, Heron's formula should work.


http://php.net/array_diff

  Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

// Set the keys matching to the $rowTwo array
$row['release'] = $row['Trelease'];
$row['date'] = $row['dateTime'];

// Unset the original values as we no longer need these
unset($row['Trelease'], $row['dateTime']);

// Compare them:
$difference = array_diff($row, $rowTwo);
$needUpdate = count($difference)!==0;


collections.deque

Why not use a collections.deque with a max_len?

from collections import deque

for submission in reddit.subreddit("funny").stream.submissions():
    queue = deque(max_len=10)

    if submission.id not in queue:
        if "foo" in title:
            submission.reply("Bar!")
            queue.append(submission.id)


Check the response of an API for correctness

Towards better performance and code organization

The list of required fields is better defined as const at top level:

const requiredFields = ["code", "name", "pricings"];

There are 2 negative outcomes that can be combined and checked at once:
1) if the response is not of Array type, 2) if it's empty array. The Consolidate conditional expression technique is applied.

if (!Array.isArray(resp) || !resp.length) {
    return false;
}

Instead of getting list of keys for each object in response array with var keys = Object.keys(obj) - the more efficient and faster way is to just apply obj.hasOwnProperty(el) to check if an object obj has required field el as a key.
All the rest "movements" in the initial approach are redundant and eliminated.

The final optimized approach:

function checkResponseApi(resp, mustHave) {
    if (!Array.isArray(resp) || !resp.length) {
     return false;
    }
    return resp.every(obj => {
        return mustHave.every(el => obj.hasOwnProperty(el))
    });
}

let arr = [
    {"code": "X", "name": "Product A", "pricings": []},
    {"code": "Y", "name": "Product B", "pricings": []},
    {"code": "Z", "name": "Product C", "pricings": []}
];
const requiredFields = ["code", "name", "pricings"];

if (checkResponseApi(arr, requiredFields)) {
    console.log('Ok')
} else {
    console.log('Bad response')
}


Searching all object property values inside Array.prototype.filter callback

The method console.assert is a non-standard feature and it may not work across different user's browsers as each browser may have a different implementation, or may not have implemented it at all.

Read more at the red box at the top of this Mozilla Developer Network article.

I'd say you are better off using console.log because most browsers implement that, and use the same base implementation.

var keys = Object.keys(item);
for(var i = 0, len = keys.length; i < len; i++){

This is slightly re-inventing the wheel.

JavaScript already has a type of loop called for/in loop. It's syntax is this:

for(var key in object) {

}

Where key is a variable that will iterate through all the properties/keys of object. You could then access the value of that key/property by using

object[key]

withing the loop.

Instead of hard-coding the array items as the array that your function is checking, write over Array.prototype with this as a new method.

Then, you can refer to the array to check as this.

Here is roughly what I mean:

Array.prototype.findObjectByPropertyName(value, ignoreCase) {
    var result = this.filter(...);
    ...
}

Then, if you wanted to use this function on items, you would simply call (for example):

items.findObjectByPropertyName('blah', true);

if(ignoreCase && typeof propertyValue === 'string' && typeof value === 'string')
     match = propertyValue.toLowerCase() === value.toLowerCase();
 else
     match = propertyValue === value;

This is a debatable topic; many will say that you should always have {}s no matter how short the code inside the block will be.

I believe they say this because it greatly improves the readability of the organization of your code because all the code that is associated with, for example, that if statement is clearly seen in between the {}s.


Observer pattern implementation in JavaScript

You could add multiple event handlers for each Watcher instead of initializing a global one.

watchWindow: {
    addWatcher: function (settings) {
        $window.on(settings.event, function (e) {
            settings.callback(e.type === 'scroll' ? $window.scrollTop() : $window.width());
        })
    },
    removeWatcher: function(settings) {
        $window.off(settings.event, settings.callback);
    }
}

In this example you would be using the same settings object to add and remove event handlers, but you could of course keep your map of handlers and generated id's if you prefer.


You could a number of different things. For instance, using ranges and a couple of Array methods, I get this:

class DoubleSeries
  def self.generate_sequences(seq1_start, seq2_start, seq1_step, seq2_step, iterations)
    seq1_end = seq1_start + iterations * seq1_step
    seq2_end = seq2_start + iterations * seq2_step
    seq1 = (seq1_start..seq1_end).step(seq1_step)
    seq2 = (seq2_start..seq2_end).step(seq1_step)
    seq1.zip(seq2)
  end
end

There's still some nasty repetition going on. I might suggest simply skipping all this in favor of a generate_sequence method, that only returns a single sequence. Then you can use that plus Array#zip to generate double, triple, or whatever sequences:

def generate_sequence(start, step, iterations)
  limit = start + iterations * step
  (start..limit).step(step).to_a
end

double_seq = generate_sequence(a, b, c).zip(generate_sequence(x, y, z))


Set Label content and make it disappear after 5 seconds

I would use a timer.

On callback, you set the content of your label to empty. You just have to restart the timer on every button click.

I think it simplifies a lot the code.


Generate the alphabet and select only specific letters

This may get hard, but you requested it... ;o)

Your program fails the SOLID principle (at least) in this ways:

Single responsibility principle

You mix the "business logic" with the user interface (UI).

The getModifiedArray method does the separation of the values and displays the result. Along the way it also fails to do what its name expresses.

Open/closed principle

Your class hierarchy is questionable.

OCP is about future changes, so imagine you want to enhance this program so that the user can select the number of characters to process.

SoC does not allow to put a int maxChars = new Scanner(System.in).nextInt(); into your Characters class.

So you have to either create a setter Metthod in    Characters which extends the interface of CharactersParity too (violates Interface seggaration), or you create a parameterized constructor which forces you to create the same constructor in CharactersParity too.

The better way would be that CharactersParity does not inherit from Characters but gets a Charactersobject as constructor parameter to use:

class CharactersParity  {
   private final Characters characters;

   CharactersParity(Characters characters){
     this.characters = characters;
   }

public void getModifiedArray(String arg) {
    String arg2 = arg.trim().toLowerCase();

    switch (arg2) {
    case "even": {
        for (char c : characters.getArray()) {

    // ....

Liskov substitution principle

IMHO
not applicable .

Interface segregation principle

The declaration of method getModifiedArray() in class Characters is not needed. It makes the interface of   class Characters wider as is should be.

I guess the aim was to force other AnythingCharacters classes to have this method.
In that case this method should be in a separate interface class:

public interface CharacterArrayModifier {
   void getModifiedArray(String arg);
}
class CharactersParity implements  CharacterArrayModifier{
   private final Characters characters;

   CharactersParity(Characters characters){
     this.characters = characters;
   }

@Override
public void getModifiedArray(String arg) {
// ...

Dependency inversion principle

Your class  CharactersParity  has 2 dependencies: Systen.out and  Characters.

You get the first via static access and the second is bound via inheritance.

DI suggests to gather the dependencies outside the class needing it and injecting them into the using class. The using class stores them in internal variables.

This injection can be done in three ways:

direct assignment
The dependency object is directly assigned to the variable in the using object.
setter injection
the using object has a setter method to receive the dependency.
constructor injection
the using object gets  the dependency as constructor parameter (as shown above).

IMHO the priority in usage should be 3, 1, 2.

The main advantage of "constructor injection" is that the dependency cannot be null by accident, (i.e. you simply did not type the assignment). The compiler forces you to pass a value. If this value is null then it is your intention...

As I indicated you program as some improper naming, but I think it is enough for now...


CancellationToken and Reactive Extensions

I need to cancel a subscription

If you're actually subscribing to the source using Subscribe(), then that has overloads that accept a CancellationToken, you might want to consider using that.

Observable.Create<object>(observer => token.Register(() => observer.OnNext(null)));

It took me a while to figure out that this doesn't cause a memory leak. I thought that since you call Register(), but never use the returned IDisposable to unregister, the registrations will stay there even when they are no longer needed. But that's not true, because the IDisposable is actually returned to Create(), which will Dispose() it when it's no longer needed.

I think this is confusing enough that it warrants a comment explaining the situation.

Also, the common way to express the void type in generics in Rx is the Unit type, not object:

Observable.Create<Unit>(observer => token.Register(() => observer.OnNext(Unit.Default)));

This is longer than your code, but I think it's also clearer.


Shell script: is it doing what I think it's doing

You should protect the URL with double quotes to prevent the shell from parsing the =, ?, and & as being special instead of just plain old characters.

Also, as a minor nitpick, you should use fgrep because grep will treat the . characters as being 'match any character' and not as a literal .. fgrep treats the whole string it's searching for (except for \n) as literal. But this is unlikely to cause you problems in practice.

The programmer in me shudders at this approach because so many things could potentially go wrong. In practice, they almost certainly won't. But I've learned to never, ever write programs as if the things I think should never happen never will. Because, in practice, they almost all do eventually.

For example, if you ever try to do two different fetches with different parameters at the same time, one will mysteriously not happen.

Also, if some random person happens to have put that URL on the command line for something, that will cause the script to not do anything until whatever command it is finishes.

As I said, these may or may not be serious problems. But I would be aware of them.


Reducing Inventory Quantity When Order Is Being Processed

Are you sure that you need two queries for this?
E.g. you could do something like this:
UPDATE Product
SET    Quantity = Quantity - @usedQuantity
WHERE  Id = @productId
  AND  Quantity >= @usedQuantity

Try to execute that and if it doesn't affect 1 row - you don't have enough quantity for the line item.
The drawback for your current logic is that you no longer get the InventoryNumber for when there's an error. I think there are two reasons why this is a better approach anyway:

You now execute 1 query per line item on the happy path.
I think you have UI logic intermingled here - this code should just deal with ProductId. If you want to display something else, that's on the UI code to do.

Other points:
The (bool, string) return type is not idiomatic C#. I don't mind this pattern but am aware I am not in the majority with that opinion. In C#, an exception would probably be expected here. The other option is to create some kind of Result class, there are many examples of this around. E.g. https://github.com/altmann/FluentResults. It's still not recognized by most C# developers though.
_InvoiceRepository.DbConnection - this is not a good place to get configuration from. An IConnectionProvider interface that is used by all the data access may be a better option. Without more code, it's hard to tell.
// if it was successful, commit the transaction - don't comment like this. Anyone reading your code can understand if (success) Commit(). Comments are for why not what.
It looks like you're trying to keep one return statement and that is causing more conditionals with if (success) around the place. I am a big proponent of returning early but I know not everyone agrees. If you only want a single return, you need to at least factor out methods to get rid of the spaghetti.
errorProductNumber = "Error saving invoice"; - That's not a product number. I'm almost sure that you're displaying this string somewhere. Keep the UI concerns out of the infrastructure code.
This seemingly innocuous pattern is a big problem on more established code bases:
invoice.InvoiceStatus = "COMPLETE";
if (!await UpdateInvoiceAsync(invoice))

You have baked in what a complete invoice looks like in an arbitrary place in the code! What if you need to add a CompletedBy or CompletedDate? You have to find all these places and update them. You also have a magic string - it needs to be a constant. Consider instead:
invoice.Complete();
if (!await UpdateInvoiceAsync(invoice))

Now if you add a CompletedBy, you do it in that method and add a parameter. The compiler then ensures you haven't forgotten to update any places. You now have an appropriate place to introduce a constant for the magic string too:
public void Complete()
{
    // You can also add a guard to prevent invalid completion.
    if (!CanCompleteInvoice)
        throw new BusinessConstraintVoilatedException();

    this.InvoiceStatus = COMPLETED_STATUS; // <- name your constants however you like.
}

Overall this method does too much and is too long. You want each method to be scannable, pseudocode:
public async Task<(bool, string)> CompleteInvoice(
    Invoice invoice,
    List<InvoiceLineItem> lineItems)
{
    // Precondition checks omitted

    using (var conn = _InvoiceRepository.DbConnection)
    {
        conn.Open();
        using (var trans = conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead))
        {
            foreach (var lineItem in lineItems)
            {
                var lineItemResult = UpdateLineItem(lineItem, ...);
                // ... on error, do something
            }
            UpdateInvoiceAsync(invoice);
        }
    }
}


jQuery grid-system - handing different row widths

Things I pondered:

What's with the underscores everywhere?
Why not use regular jQuery convention and use this instead of element in your each iterator?
What's the use-case for this? A regular user will never see the console, so logging to it doesn't help anyone.
Even if someone is watching the console, what's the point of warning them when the row is just summarily removed? At least give the user a chance to fix the problem. It's worse if you're not looking at the console - then stuff is just gone with no explanation.
And the warning, "You have too many columns", isn't really truthful. The problem is that the columns - even if it's just 1 - are too wide. You code isn't checking how many there are.
But mostly: Why use percentages? Just compare widths directly. Saves you a whole lot of trouble (and code)

This seems clearer to me:

function validateRowWidth() {
  $('.row').each(function (index) {
    var row = $(this), // use `this`
        widthSum = 0;

    // sum up the (direct descendant) column widths
    row.children('[class*="size-"]').each(function () {
      widthSum += $(this).outerWidth(true); // 1 line is all you need here
    });

    // compare and warn if need be
    if(widthSum > row.width()) {
      // alert is not a great choice, but it's better than console.log,
      // if this is user-facing. Explain the problem, and propose solutions.
      alert("Row " + index + " is too wide. Remove one or more columns or make them narrower.");
    }
  });
}


Eloquent Javascript exercise: find average age from ancestors array per century

Incorrect calculation of average

average([1, 2, 3, 4]) is \$\dfrac{1+2+3+4}{4}=2.5\$.

However, due to the way you call reduce() in getAverageAgePerCentury():

averageAgePerCentury[agePerCentury.century] = [average(averageAgePerCentury[agePerCentury.century].concat(agePerCentury.age))];

… you would actually calculate average([average([average([average([1]), 2]), 3]), 4]), which would produce a result of 3.125 — weighted in favour of the later entries.

Doing too much

A root cause of the bug, I think, is that getAverageAgePerCentury() is doing a lot of work.  It creates a map of centuries to the age of people who died in that century, and calculates the average of those values.

I would define two utility functions, inspired by Lodash's _.mapValues() and _.groupBy().

/**
 * Creates a new object in which all of the original obj's values are
 * transformed by callback(value).
 */
function mapValues(obj, callback) {
    return Object.keys(obj).reduce(function(result, key) {
        result[key] = callback(obj[key]);
        return result;
    }, {});
}

/**
 * Given an array of objects, creates a new object in which all objects where
 * attrExtractor(obj) having the same value are grouped together in an array.
 */
function groupBy(objs, attrExtractor) {
    return objs.reduce(function(result, obj) {
        var attr = attrExtractor(obj);
        if (attr in result) {
            result[attr].push(obj);
        } else {
            result[attr] = [obj];
        }
        return result;
    }, {});
}

Then, the rest of the solution looks simpler.

function average(array) {
    return array.reduce(function(a, b) { return a + b }) / array.length;
}

function averageAgePerCentury(ancestry) {
    function deathCentury(person) { return Math.ceil(person.died / 100) }
    function deathAge(person) { return person.died - person.born }

    return  mapValues(
                mapValues(
                    groupBy(ancestry, deathCentury),
                    function(persons) { return persons.map(deathAge) }
                ),
                average
            );
}

Note that I've renamed getAverageAgePerCentury().  A "getter" function should retrieve something that already exists.  Here, you're doing a calculation.  You call Math.sin(x), not Math.getSin(x), so the same naming principle applies here.


A simple project of getting Mars Rover images from NASA API and displaying them in JSON format

Here are a few things I found:
General practises

Using packages is great. But if you are just going to have one class/file in each package, then you probably don't need it. You could just have all your files in the challenge directory.

If you really needed to use packages, storing a data file in the package is not a great idea. Packages are meant for code. So your cache.json would probably be more suitable elsewhere. You could just have the cache file inside the challenge directory, or create a data directory inside challenge to contain it.

Providing a requirements.txt file is great. It is an easy way for someone to download you code and just be able to download its dependencies.

Files should end with an empty line. See this question.

Code style

If your docstrings are just one line, its fine to have have them as such:

def my_function():
  '''Some docs about my_function'''
  ...

However, if your docstring is longer than one line, its better to write it as:
def my_function():
  '''This is a oneliner description about my_function

  This is further information about it

  Foo

  Bar
  '''
  ...

It seems you are using this latter way of writing docs for you classes, but not for you methods. See NasaClient#generate_responde_data. For further information about docstrings, you can refer to PEP-257.
For further information regarding style, in python there is PEP-8, a general guide about it.
pathlib
Since python 3.4, we have pathlib available in the standard library, which makes the handling of paths more pythonic.
For example, you could change:
import os
absolute_path = os.path.dirname(os.path.abspath(__file__))
file_path = absolute_path + '/cache.json'
...
with open(FileCache.file_path, 'r') as file_reader:
...

in FileCache, with:
from pathlib import Path
absolute_path = Path(__file__).resolve().parent
file_path = absolute_path / 'cache.json'
...
with FileCache.file_path.open() as file_reader:
...

The usage of this library also gets rid of the os dependency if you are only using it for os.path
Handling exceptions / errors
In HttpClient, if the responde status code is not OK, you are returning a string containg an exception message.
That is probably not the best of ideas. Being able to tell, dinamycally, whether a returned value is as expected or not by examining the contents of a string is (which you actually don't even do in your code) is expensive and unnecessary.
You could either use None, or throw an actual exception:
...
def get_response(url):
  response = requests.get(url)
  if response.status_code == 200:
    return response
  else:
    return None
  # If you want to get fancy, you could use the ternary operator here:
  # return response if response.status_code == 200 else None
...
#Then when using get_response:
my_response = get_response()
if my_reponse:
  do_something(my_response)
else:
  handle_not_OK_reponse()

using exceptions:
class NotOKResponseException(Exception):
  pass
...
class HttpClient:
  def get_response(url):
    response = requests.get(url)
    if response.status_code == 200:
      return response
    else:
      raise NotOKResponseException()
...
#Then when using get_response:
try:
  my_response = get_response()
  do_something(my_response)
except NotOkResponseException:
  handle_not_OK_reponse()

Code design (Edit)
Regarding the comment:

The gateway method to actually run the code was 'print_response()' which should actually print the response but it also calls the NasaClient to generate the response. Is that a good design?

That is not the best of designs.
After reading what the OutputGenerator#print_response method does, its probably best to name it something like retrieve_printable_data, which indicates its behaviour more accurately.
Also, it does not seem right to me that the NasaClient stores the data in the cache file for the OutputGenerator to read it. There are two reasons I can currently think of:

NasaClient is already responsible for reading and writing the cache using FileCache. Therefore, to isolate this responsibility, just have NasaClient#generate_response_data return the actual data. That way, the cache is transparent to OutputGenerator.

OutputGenerator is just using the FileCache given to it through its constructor. Now, if you wished to change the cache to an in-memory cache, that would make the logic even more complex, as now whoever is constructing the instances not only has to know that OutputGenerator and NasaClient need a FileCache, but also that they need to have the same instance.


Don't throw RuntimeException: they are not specific, and hence difficult to catch.  (Otherwise, you might as well drop the null checks and let it fail naturally with NullPointerException, which is also a kind of RuntimeException.) You should make your own exception subclass, or use java.util.NoSuchElementException.

It would also make sense to support an isEmpty() method, to give the user a fair chance to avoid the exception.

Two spaces per level of indentation is too narrow and unconventional for my taste, and could also encourage excessive nesting.  Four or eight spaces would be acceptable.


I assume WordUtils and StringUtils are Apache Commons?  If so, it would be helpful for us for you to link to their online documentation/source.

The first thing to do when optimizing is to make sure you're optimizing the right thing.  You might find ways to shave off a bit of running time in this method, but if this method is only responsible for 1% of the total running time then that's not very good use of your effort.

The thing that strikes me is all of the safety for weird conditions.  I can pretty much guarantee you that your replaceAll calls are the slowest things.  Maybe upstream code should be ensuring that the title is of the correct form to begin with, the strings are trimmed, and there are no double spaces.


Python vs. Java Runtime on Euler 22 - Name Scores

Broadly speaking try creating less objects. ;)

You can

read the entire file as a series of lines or as a string with FileUtils.
iterate through each character rather than building an array which you iterate.
as the program is so short, try using -client which has shorter start time.

To maximise the performance

long start = System.nanoTime();
long sum = 0;
int runs = 10000;
for (int r = 0; r < runs; r++) {
    FileChannel channel = new FileInputStream("names.txt").getChannel();
    ByteBuffer bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    TLongArrayList values = new TLongArrayList();

    long wordId = 0;
    int shift = 63;
    while (true) {
        int b = bb.remaining() < 1 ? ',' : bb.get();
        if (b == ',') {
            values.add(wordId);
            wordId = 0;
            shift = 63;
            if (bb.remaining() < 1) break;

        } else if (b >= 'A' && b <= 'Z') {
            shift -= 5;
            long n = b - 'A' + 1;
            wordId = (wordId | (n << shift)) + n;

        } else if (b != '"') {
            throw new AssertionError("Unexpected ch '" + (char) b + "'");
        }
    }

    values.sort();

    sum = 0;
    for (int i = 0; i < values.size(); i++) {
        long wordSum = values.get(i) & ((1 << 8) - 1);
        sum += (i + 1) * wordSum;
    }
}
long time = System.nanoTime() - start;
System.out.printf("%d took %.3f ms%n", sum, time / 1e6);

prints

XXXXXXXXX took 27.817 ms

Its pretty obtuse, but works around the fact its not warmed up.

You can tell this is the case because if you repeat the code in a loop 10000 times, the time taken is only 8318 ms or 0.83 ms per run.


i++ or ++i?

Using i++ is fine here, but also read this discussion:

https://stackoverflow.com/questions/4261708/i-or-i-in-for-loops

fgets(message, 128, stdin);

How about fget(message, sizeof(message), stdin) -- makes it easier to change the size of the message buffer.

int main(int argc, char * keyWord[])

Most people are used to seeing:

int main(int argc, char* argv[])

int alphaCheck(char * argv[])

How about:

int alphaCheck(char *str) {
  for ( ;*str; ++str) {
    if (!isalpha(*str)) {
      ...
    }
  }
  return 0;   // You don't have this return.
}

First of all, this makes alphaCheck usable on any string, not just argv[1]. Also you avoid computing the length of the string. Moreover, this is the idiomatic way to iterate over a null-terminated string in C.

Finally - make sure you always return a value since you've declared this function returns an int.

for (i = 0, j = strlen(keyWord[1]); i < j; i++) {

You are modifying cipher[i] but are you checking that i < 64? What if keyWord[1] has length > 64?

keyWord[1]

You reference this array element many times in the program. Perhaps you should assign a meaningful variable name to it, e.g.:

char* secret = keyWord[1];

It will make you program more readable.

printf("%c\n", message[i]);

Do you want to always print a \n here? I would think you only want to print an extra \n at the end of the message.

the main loop

You main loop has this structure:

for each character c in the message:
  let e = encrypt c using the secret key
  printf("%c", e)
  advance pointers, counters, etc.
printf("\n")

so it would be nice if the code could match this as much as possible.

How about:

int i;
for (char *p = message, i = 0; *p; ++p, ++i) {
  char e = ...encrypt (*p) using secret, strlen(secret) and i...
  printf("%c", e);
}
printf("\n");

Now there is only one place where the encrypted character is printed out - instead of three difference places.

You can implement this via a helper function:

char encrypt(char* secret, int secret_len, char c, int i) {
  // return how c is encrypted when at position i in the message.
  if (isupper(c)) {
    return ...
  } else if (islower(c)) {
    return ...
  } else {
    return c;
  }
}

Hint: The expression i % secret_len might come in handy here.


Drop-down for populating a list of cities

View Model

Looks fine to me, although I'd recommend that if all your DTO classes are to be appended with 'DTO' you instead put them inside a namespace named 'DTO' and leave the 'DTO' characters off the class names entirely.

Controller

Use var when the Right Hand Side (RHS) is obvious.

Also, I don't like the indentation in your LINQ statement. It makes it difficult to discern between LINQ and constructor.

There is no point in calling ToList so much. AddRange is going to enumerate the whole collection anyway, so you don't actually need any ToList calls at all.

var Loc = new Models.LocationDTO();
var locCtx = new EF.LocationEntities();

public Action Result Index() {
    using(locCtx) {
        var locResults = (from q in locCtx.usp_GetAllCities()
                             Select new Models.CityDTO
                             {
                                 CityId = q.Id,
                                 CityName = q.Name
                             });
        loc.Cities = locResults;
    }

    var citiesList = new List<Models.CityDTO>();
    var city = new Models.CityDTO()
    {
        CityId = "-1",
        CityName = "Select City"
    };
    citiesList.Add(city);
    citiesList.AddRange(Loc.Cities);

    ViewBag.CitiesDropDown = citiesList;
    return view(loc);
}

View

You make a call to Cities.SingleOrDefault(). SingleOrDefault() can return a null value if your City class' default operator returns null (which is the err default behaviour). If this happens, accessing CityId will fail.

//View

@{
    List<TestApp.Models.CityDTO> citiesList = ViewBag.CitiesDropDown;
    var cityItems = new SelectList(citiesList, "CityId", "CityName");
}
<div>
    Cities: @Html.DropDownListFor(x => x.Cities.SingleOrDefault().CityID, @cityItems)
</div>


I'm not sufficiently familiar with PDO to say more on your database access than that you don't seem to have any injection vulnerabilities. However, there are a few things which I would do differently.

Salt entropy

There are two things which strike me as odd about your salt generation. Firstly, using a base-77 encoding. If you configure your database correctly then you can use the full 8 bits of each byte of salt. That's more efficient, avoids possible bugs with generating a number in the wrong range (how sure are you that strlen($CharStr) === 78?), and is closer to the assumptions made when analysing salted hashing.

Secondly, while mt_rand is better than rand it's not a cryptographic PRNG. The best portable secure PRNG in PHP is openssl_random_pseudo_bytes; if you're not planning to deploy to Windows then you could also get good entropy from /dev/random.

Hash

SHA is not generally recommended as a hash for passwords. The current conventional wisdom is that you want password hashing to be slow, and should use either bcrypt or scrypt. If you insist on SHA then you should use it as a component of PBKDF2.

Account existence oracle

There are two schools of thought on telling people "That username doesn't exist". The usability argument is that it's preferable to tell someone that they got their username wrong. The security argument is that you should always say "Either your username doesn't exist or you got your password wrong" to prevent people identifying accounts which do exist and then trying to brute-force their passwords. (Anti-brute-forcing techniques is a separate issue which I'm not going to address in detail).

If you favour the security argument over the usability argument then you need to avoid telling people indirectly that the username doesn't exist. That means that if $GetSalt -> rowCount() === 0 you should still do a hashing operation to avoid a quicker page load which leaks information.

Minor style points

if($GetSalt -> rowCount() == 0)
    ...
elseif($GetSalt->rowCount()>0)

I see three things wrong here:

What other possibilities are there? Shouldn't that elseif just be an else?
Why == instead of ===?
Pick a style for use of whitespace and stick with it.


If you are targetting styles for more than one element, then consider using class instead of id.
Block elements cannot be inside inline elements.
 can't be inside
 is a self-closing tag. No need for a  though you need to end it with />
Put some padding on your containers. They look awful when they all stick to the edge.
I have read somewhere that increasing the size on hover is awful CSS. Consider putting focus by changing the background color, or changing the font color or putting an outline in a subtle way.
Constrain the slider by putting overflow:hidden on the container. That way you don't have that horrible scrollbar at the bottom.
Use transform instead of margin. As far as I know, the new CSS3 properties are hardware accelerated (or were those just the 3D), so they're smoother.
Also, transform's values are relative to the element itself and not the parent. While 100% margin (top or bottom) is equal to the parent container, 100% transform is the height (for y) and width (for x) of the element. This is useful especially when the slider is longer than the container.

Too long to list down what I did so here's the code instead:

HTML:

                @Something
                3m

content

CSS:

#controller {
    box-sizing: border-box;
    background-color: #06C;
    position: absolute;
    width: 100%;
    overflow:hidden;
}
#controller:hover #ticker {
    -webkit-animation-play-state: paused
}
#ticker {
    white-space: nowrap;
    -webkit-animation: move_eye 6s linear 0s infinite normal;
}
@-webkit-keyframes move_eye {
    from {
        -webkit-transform: translate(100%,0)
    }
    to {
        -webkit-transform: translate(-100%,0)
    }
    90% {
    }
}
.text {
    display:inline-block;
}
.tweet {
    box-sizing: border-box;
    background-color: #EEE;
    display: inline-block;
    border-radius:5px;
    padding: 5px 10px;;
    vertical-align: top;
    margin: 5px 2px;
    height: 100%;
}
.tweet:hover .extra_info {
    display: inline;
}
.extra_info {
    display: none;
}
img {
    display:inline-block;
    height: 30px;
}


Tail-recursive call vs looping for a Poker app

GC.KeepAlive(Updates);

Do you really need to do this? Objects are not collected as long there is a valid reference to them meaning that Updates should always be avaiable if you are not replacing the reference. If you are replacing the reference it means that you are not keeping you object alive long enough for the current game which sounds leaky.

Bot1 = (Bot)RotateTurns(Bot1, Bot1.EnumCasted);

RotateTurns should be an instance method on Bot and should not be present on the current scope. And once again you are replacing the object reference.
The bots should be alive at least as long as a game instance.

It would be better to keep a list of all bots so you could iterate on them.

foreach(var bot in _bots){
    await bot.RotateTurns();
}

if (!_restart)
{
    continue;
}
break;

The !_restart condition could be placed on the while. Also consider to keep this a method variable instead of a field.

while(!_restart)


Calculate FFT from windowed time-based signal

The easy way to plot something with a logarithmic scale would be to just take the logarithm of the variable.

logspectrum = log(spectrum);
The source of some files is available when you type edit function name, example:

edit unique

However, not all Matlab source is available, so unfortunately you cannot customize everything this easily.


Creating every possible combination until a code word is found

You should learn about separating concerns. Currently your functions have two concerns, finding the right word and timing how long it takes. You can take out this part by writing a decorator, that allows timing any function you decorate it with.

Next, your bruteforce_by_precomputed and your dictionary_attack are really the same function, just with a different dictionary behind it. You could just let the function accept it as an argument. And let it accept the word do decrypt as well, while we are at it. Normally I would also move the reading of the file here, but since you might want to decrypt more than one word, it could be a good idea to read the files only once.

I would add a maximum length for the infinitely_increasing_brute and just call it brute_force. No point in waiting for the heat death of the universe just to crack that one password...

You should close the files you open. One easy way to do that is to use with.

You should put your main running code under a if __name__ == "__main__ guard. This allows you to easily import the functions defined here in another script, without executing the encryption itself.

You should have a look at the string module, it has many pre-defined sets of characters, including string.ascii_lowercase, string.punctuation and string.printable.

It is not exactly clear if your code file contains only a single word. I modified it so that it can contain many words, separated by newlines.

Putting this together, your code becomes:

import itertools
from time import clock
from string import ascii_lowercase, ascii_uppercase, digits, punctuation

printable = ascii_lowercase + ascii_uppercase + digits

def timeit(func):
    def wrapper(*args, **kwargs):
        starting_time = clock()
        result = func(*args, **kwargs)
        ending_time = clock()
        print('Duration: {}'.format(ending_time - starting_time))
        return result
    return wrapper

@timeit
def dictionary_attack(encrypted, dictionary):
    for attempt in dictionary:
        if attempt == encrypted:
            return attempt

@timeit
def increasing_brute(encrypted, max_len=10):
    for length in range(1, max_len + 1):
        for brute_attempt in itertools.product(printable, repeat=length):
            attempt = ''.join(brute_attempt)
            if attempt == encrypted:
                return attempt

@timeit
def custom_brute(encrypted, length):
    for brute_attempt in itertools.product(printable, repeat=length):
        attempt = ''.join(brute_attempt)
        if attempt == code:
            return attempt

if __name__ == "__main__":
    with open("C:\\Users\\User\\Desktop\\dictionary.txt") as dictionary:
        dictionary_words = dictionary.read().splitlines()
    with open("C:\\Users\\User\\Desktop\\precompute.txt") as precomputed:
        precomputed_words = precomputed.read().splitlines()
    with open("C:\\Users\\User\\Desktop\\code.txt") as code:
        for encrypted in code:
            word = dictionary_attack(encrypted, precomputed_words)
            if word is not None:
                print "The word is", word
                continue
            word = dictionary_attack(encrypted, dictionary_words)
            if word is not None:
                print "The word is", word
                continue
            word = custom_brute(encrypted, int(input("what length to force?")))
            if word is not None:
                print "The word is", word
                continue
            word = increasing_brute(encrpyted)
            if word is not None:
                print "The word is", word
                continue

This could be improved further by making the attack functions generators that yield attempts and a single attack function that performs the comparison using a sequence of functions:

def dictionary_attack(encrypted, dictionary):
    for attempt in dictionary:
        yield attempt

def increasing_brute(encrypted, max_len=10):
    for length in range(1, max_len + 1):
        for brute_attempt in itertools.product(printable, repeat=length):
            yield ''.join(brute_attempt)

def custom_brute(encrypted, *args):
    length = int(input("what length to force?"))
    for brute_attempt in itertools.product(printable, repeat=length):
        yield ''.join(brute_attempt)

@timeit
def attack(encrypted, attack_funcs, attack_args):
    for func, args in zip(attack_funcs, attack_args):
        for attempt in func(encrypted, *args):
            if attempt == encrypted:
                return attempt

if __name__ == "__main__":
    with open("C:\\Users\\User\\Desktop\\dictionary.txt") as dictionary:
        dictionary_words = dictionary.read().splitlines()
    with open("C:\\Users\\User\\Desktop\\precompute.txt") as precomputed:
        precomputed_words = precomputed.read().splitlines()

    attack_funcs = dictionary_attack, dictionary_attack, custom_brute, increasing_brute
    attack_args = [precomputed_words], [dictionary_words], [10], []
    with open("C:\\Users\\User\\Desktop\\code.txt") as code:
        for encrypted in code:
            word = attack(encrypted, attack_funcs, attack_args)


Comparing similar types that don't share any interface

You can shorten the syntax a bit and increase readability by using the is or == operators instead of ReferenceEquals:

public new bool Equals(object x, object y)
{
    if (ReferenceEquals(x, y)) return true;
    if (x is null || y is null) return false;
    {
        if (x is Tx tx && y is Ty ty && Equals(tx, ty)) return true;
    }
    {
        if (x is Ty ty && y is Tx tx && Equals(tx, ty)) return true;
    }
    return false;
}

The extra braces to make the variables local to their body is clever, however I cant exactly say I like it, it's very easy to consider the first braces to be part of the if statement above them and it can be made much more readable too if you extract it to a method:

public new bool Equals(object x, object y)
{
    if (ReferenceEquals(x, y)) return true;
    if (x is null || y is null) return false;
    return CompareObjects(x, y) || CompareObjects(y, x);
}

protected bool CompareObjects(object x, object y)
{
    return x is Tx tx && y is Ty ty && Equals(tx, ty);
}

You can also define 2 generic type arguments for the CompareObjects methods, to make it more explicit, that you're swapping the types.

private bool Equals(Tx x, Ty y)

Feels weird and out of place in my opinion, you're checking if the values of x and y are null, but you've already done so in public new bool Equals(object x, object y) and since it's a private method, that doesn't make much sense, removing this check makes it a simple call to _equals, which makes the whole method redundant, you are better off making it protected virtual, or just delete it all together

protected virtual bool Equals(Tx x, Ty y)
{
    return x != null && y != null && _equals(x, y);
}

You also lack null checks for the delegates in the Create method, but I assume you've omitted those for simplicity/


This is a bit difficult to answer, because you did not share code sample that fully type-checks (and so it is hard to make sure the answer is correct). However, I think you're very close. When refactoring two similar functions, you just need to abstract out the bits that differ.

In your case, there are two places:

One is the function that is used to retrieve the data (either getPrices or getVolumes)
Second is the projection that is used when triggering the event (either item or item.Price)

If you take these two operations as functions, then you can write the following:

open System

type IID =
  abstract member ID : int64

let Publish (dataRetriever:TimeSpan -> list<#IID>) valueSelector time ID (polling:float) =
  let sync = System.Threading.SynchronizationContext.Current
  let obs = new Event<int>()
  let raiseEvent (value:int) = sync.Post((fun _ -> obs.Trigger(value)), null)
  let interval = TimeSpan.FromSeconds(polling)
  let rec loop nextTime= async {
    // Generate next value (on the GUI thread)
    dataRetriever nextTime
    |> List.filter (fun item -> item.ID = ID)
    |> List.iter (fun item -> raiseEvent (valueSelector item))
    // Wait some short time
    do! Async.Sleep(1000)
    // Continue looping
    do! loop (nextTime.Add(interval)) }
  loop time |> Async.Start
  obs.Publish

The type annotation TimeSpan -> list<#IID> is interesting. It says that the argument is a function that returns a list of some values that implement the IID interface - but it turns this type into a generic type argument that is then passed to the other function (valueSelector), so when you use the function, the compiler knows that the argument of valueSelector has the same type as the thing that you obtain from dataRetriever. The annotation allows you to write item.ID in the filtering function.

The two functions can now be defined as follows:

let Prices = Publish getPrices (fun price -> price.Price)
let Volumes = Publish getVolumes id


This is a problem that's well suited to elementwise aggregation. Consider the following:

move_zeroes (L) ->
    case L of
       [0 | T] -> move_zeroes(T) ++ [0];
       [El | T] -> [El] ++ move_zeroes(T);
       _Else -> L
    end.

I am only blindly guessing at the syntax here, but this should clarify how one would write this without using lists:filter twice. It additionally avoids the helper function you created there, which seems to not serve a purpose ...


Alternative to setInterval and setTimeout

Update 4/23/2014:
Okay then, off to your updated code. Nothing much I can do here now. Here are some generic code optimization tips:

Name stuff verbosely. It's one issue I find with others' code. They tend to name it like t for time, or l for length. Unless it's something implied, like i,j and k for counters (and we do see loops), please name them verbosely.

Don't ever worry about long code. That's what minifiers are for. Name them verbosely, structure them properly. Don't even bother using the "comma-separated vars". Minifiers do that.

Ternaries tend to be messy and unreadable. If possible, use if-else. Again, minifiers also convert them to ternaries to be shorter.

As for possible bottlenecks, splice is an overhead because it resizes the array, shifting the contents around. It's much avoided like unshift and shift for the same reason. I don't know if keeping a "hole" in the array is a performance benefit either, so let's leave it as is.

A general performance tip is just to avoid creating objects inside the loops. If it can't be avoided, just make sure you free them up when done (free references).

So far, that's about it. I'll leave the fine-tuning to you.
Previous answer:

Normally i don't write functions inside functions, but in this case it's prolly a good solution. What about memory leaks if i create hundreds of this timebased functions?

That wouldn't be an issue. Besides, how many functions do you think the FB homepage, or any site for that matter, creates? What you should be wary about, though, is when your timers create functions on every iteration. That's what you should look out for. Along the lines of this:
function tick(){
  requestAnimationFrame(tick);

  // Oh...
  var aFunctionMadeOnEachTick = function(){...};
  aFunctionMadeOnEachTick();
}

Although some JS engines are smart enough to figure this out and pull out the function, I have seen performance decreases when doing this in some of my projects.

Is there a better solution to clear those functions?

I was thinking about something along the lines of a common function that can be referenced by each API function to generate a runner. This way, we have one function sitting internally waiting to be called, instead of one created each call.
;(function (ns) {

  // An array of references/ids/booleans/whatever that can be used to clear off running timers
  var timers = [];

  // The common function
  // Haven't figured out how the cb and delay gets called on the next tick, but
  // this should be a good template to think about.
  function runningFn(cb,delay) {
    if(iShouldStillRun) requestAnimationFrame(runningFn);
    if(Date.now() > something) execute();
  }

  // Your API functions
  ns.setTimeOut    = function (callback, delay) {
    runningFn(callback,delay);
  }
  ns.setInterval   = function (callback, delay) {...}
  ns.clearInterval = function (callback, delay) {...}
  ns.clearTimeout  = function (callback, delay) {...}

}(this.Timers = this.Timers || {}));

For heavy animations and multiple intervals,timeouts i was thinking to activate a single requestAnimationFrame loop which check for intervals and timeouts inside a previously stored array...

The last time I checked, looping through an array with 700+ items caused stuttering in the UI. Also, by the nature of timers, they can actually be delayed by these operations. Again, JS is single-threaded, and timers also live in that thread. If JS is busy churning, it can delay async tasks and that includes timers.
rAF at a glance
One thing about rAF is that it's built for animation. It strives to give you a 60fps. However, when it can't, it isn't any different from setInterval and setTimeout. Also, it depends on browser implementation. Some browsers throttle timers according to different situations, like unfocused windows/tabs.
Let's start cherry-picking
Now here are some interesting things about your implementation:

You have an internal function in each instance of a timer. Looks like the root of your worries.
But you also return an object for each instance for the clear. Why not store some sort of reference to running timers, and create another global function that clears them?
Like you found out, 60fps is 16ms per draw. However, timers are as fast as 4ms.


I think your answer is perfectly valid and much better than the editorial solution.

I only have two suggestions to improve it further:

variable name i is commonly used for array indexes. Using it instead for array values can confuse the reader of the code.
return is not needed - Ruby functions will implicitly return the value of the last evaluated expression.


Optimal method for writing bytes to file

Given the care and effort that has been put into performance within the JVM and Java standard libraries, it is a virtual certainty that the second implementation will be faster.

However, does it really matter? Worrying about optimization is generally only useful if the system performance is inadequate. It's far more important to worry about functionality and readability first. Performance issues can be tackled (if they exist) when the system is nearing completion and it is possible to get actual performance data on where the bottlenecks are.

See the Wikipedia article on Program Optimization - especially the "When to optimize" section


Memory management for matrices built with dynamic arrays

At first, you should give your program some structure.

Start by indenting all the lines consistently. Ideally, let a program do this automatically. Search for indenter or beautifier.

Then, define a class called Matrix, give it a proper constructor and destructor. This could already help with the memory leak.

Or if you don't like classes, at least define an allocation and a deallocation function for a matrix. But then, it's almost a class anyway.

Finally, fix the syntax errors in your code so that it compiles at least.

Make the code in main so simple to read that you can explain it to a layman. That is, no explicit memory allocation, no details, just the high level view. All the rest of the code needs to go to separate functions.


Push bus lines, not edges
I feel like your breadth first search could be improved if instead of pushing single edges onto your queue, you pushed a whole bus line.  After all, the distance you are finding is the number of bus lines traversed, not the number of edges.  So a pseudocode algorithm would be:
foreach (busline b connected to vertex 0) {
    visited_busline[b] = true;
    q.push(b, 1);  // 1 = distance
}
visited_vertex[0] = true;

while (q.notEmpty()) {
    busline, distance = q.pop();

    foreach (vertex v in busline) {
        if (v == target) {
            return distance;
        }
        if (visited_vertex[v]) {
            continue;
        }
        visited_vertex[v] = true;
        foreach (busline b connected to v) {
            if (!visited_busline[b]) {
                visited_busline[b] = true;
                q.push(b, distance+1);
            }
        }
    }
}

Then all that is left it to parse the original input so that each vertex v contains a list of bus lines that it is connected to.
Typo
This code didn't compile for me:

    if(e.d > mini)
        continue;

I believe that at some point, you changed mini to shortest_path.  Also, in this line, I believe that you can use >= which can help a little in reducing your search depth by 1 level:
    if(e.d >= shortest_path)
        continue;


You have a logical bug in the code. Imagine all jobs are finished and then shutdown is called. You'll never leave the notifier.wait(...).

Also, if a job exists but shutdown is called you quit instantly without doing it - I do not think that this is a good idea. I think you should finish all jobs prior to quitting. Make a special hard reset routine for the immediate exit. Though, it probably requires usage of exceptions.

Also, consider what will happen if an exception is called inside the function f. In the thread pool one of the threads will die and kill the whole program - most likely. It is not good. It should somehow forward the error to the caller. To this end I have thread pool functionality divided - made a supplementary class for user that wraps whatever additional functionality is needed.

Technical issues:

std::bind(f, args...) should be std::bind(f, std::forward<Args>(args)...) to ensure perfect forwarding as otherwise you might end up with unnecessary copying of data.
numThreads should be defaulted to std::thread::hardware_concurrency and I believe and uint8_t is getting too small for some of the latest processors. Additionally the ThreadPool should have the functionality to tell to its user how many threads it has.
I am not too fond of std::future - it is somewhat incomplete as Executors TS is still incomplete. Normally I'd expect that user would want to call the push task several times to complete a single operation. In which, case you generate multiple std::future<void>. It would be better to somehow to make it into a single wait instead of several. But I think I might be nitpicking - honestly I'd wait for Executor TS near completion and try to implement or get from somewhere something with the same interface as long as Executor TS is unavailable.
The declarations

ThreadPool(const ThreadPool& other) = delete;
void operator=(const ThreadPool& other) = delete;

are redundant as the class already has a std::mutex that makes the whole class non-copyable and non-movable. Yeah, it isn't important.


Replacing DataContract serialization with Binary one in Azure Service Fabric

You should probably remove empty braces inside attributes. [OnSerializing()] => [OnSerializing].
This loop is very hard to read due to how you use offsets.

foreach (var property in GetType()
        .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
        .Where(p => p.CanRead && p.CanWrite))
        property.SetValue(this, property.GetValue(obj));

Mainly because it is impossible to tell at first glace where foreach statement ends and loop body begins. Use offsets to separate them:

foreach (var property in GetType()
                        .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                        .Where(p => p.CanRead && p.CanWrite))
    property.SetValue(this, property.GetValue(obj));

Or just add { } braces (that's what I would do).
State is probably not the best name for a property, its too generic. Maybe SerializedState or BinaryData would do a better job at explaining its purpose.
It would be nice to have some control over which properties are deserialized. You know, similar to how you can use XmlIgnore attribute to skip a property during xml (de-)serialization.
Unless what you do should be completely obvious to anyone working with Azure, you should add some basic documentation. I am not familiar with Azure, and to me it is unclear what problem you are trying to solve, why do you solve it using inheritance as opposed to using separate non-abstract binary serializer or wtf Recursive property is used for. You might want to explain some of those things in your code using xml-documentation.


This looks pretty good to me.  I am not that good at threads myself, so I won't comment on the thread safety, but these are a few things I noticed.

This is fine as it is, but you might want to consider making this a ternary:

if (Services.Count != 0)
{
    SetNextSerAndSend();
}
else
{
    CheckAndSetServices();
}

Here it is in ternary form:

Services.Count == 0 ? CheckAndSetServices() : SetNextSerAndSend();

I'm not sure how this would affect the performance of your code, or whether it is important that the variable stay the same, but it is good to always keep your variables in as tight a scope as possible:

private void SendTask()
{
    SendMessage msg;
    while (true)
    {
        msg = MessageSendQueue.GetItem(-1);
        String rtrn = PushData(msg);
    }
}

This could possibly become:

private void SendTask()
{
    while (true)
    {
        SendMessage msg = MessageSendQueue.GetItem(-1);
        String rtrn = PushData(msg);
    }
}

The same principle can be applied to ReceiveTask.


I'd suggest not rolling your own implementation; just use strtok_r properly and save yourself some time. For memory allocation, you can either use the offsets into the string in-place, or use strndup to get copies of each token as you find it.


When instancing generic collections, it' best to use the diamond operator to let the compiler figure out the generic arguments. This lets you define in a single place (type definition, not constructor) for easier future modification.

sequenceList[index] = new LinkedList<>();
When using an Object, always declare its type as the highest class in its type hierarchy (up to interface if possible).

You're not using LinkedList's specific methods, so:

List<Integer>[] sequenceList = new List[n];

Javadoc!
Use proper Objects:

Make Solution a real instance created one in main (no real job should be performed in main). Then you can make lastAns and n fields of Solution because in the problem statement it is made to be a state of the Solution, so you don't need to pass those around every time
You could Wrap your Lists in a Sequence internal class of Solution. Internal means it will be able to access the lastAns field of the Solution instance etc.

It's a bit weird to lazily initialize the sequences. You don't win much, but you put an ugly if in your code. If there is no risk having a huge but sparse array, I would drop this.
Don't one-line ifs, and always use brackets
I'm usually against calling variables x, y etc. On this case it's defined in the problem so it's ok.

Updated code:

public class Solution {
    private int n;
    private int q;
    private int lastAns = 0;
    public Solution(int size, int numberOfQuestions) {
        n = size;
        q = numberOfQuestions;
    }
    public int getIndex(int x) {
        return (x ^ lastAns) % n;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Solution solution = new Solution(in.nextInt(), in.nextInt());
        solution.solve(in);
    }
    public void solve(Scanner in) {
        List<Integer>[] sequenceList = new List[n];
        while(q-- != 0) {
            int queryType = in.nextInt();
            int x = in.nextInt();
            int y = in.nextInt();
            int index = getIndex(x);
            if(queryType == 1) {
                if(sequenceList[index] == null) {
                    sequenceList[index] = new LinkedList<Integer>();
                }
                sequenceList[index].add(y);
            } else if(queryType == 2) {
                lastAns = sequenceList[index].get(y % sequenceList[index].size());
                System.out.println(lastAns);
            }
        }
    }
}


Do you mean write code that would repeat the multiple if/else statements? cause that would be the right idea and make your code more DRY.

The first thing to take a look at is your data structure. As it is, you have hard-coded a handful of ticker properties that would make iteration difficult. You could use a for/in loop to go through the properties of your object, but we know we don't want the description or id in the string. Better to put all tickers in an array. That way it'll be easy to create a string with as many (or little) tickers as you want.

{
    description: "GOOG AAPL TSLA"
    id: 42
    tickers: ["GOOG", "AAPL", "TSLA"]
    timespan: "1mo"
}

It's now easy to iterate over the tickers and construct a string out of them. Since we always start with ticker_<n> as the beginning, we can construct that inside our loop, using the index to count which ticker # we are on.

For the function:

function createUrl(viewObject){
    // use .map to add "ticker_<n>=<value>" to each of the tickers,
    // then join with "&" for the query.
    var urlString = viewObject.tickers
        .map(function(ticker, index){
             // prepend the first query with its own '&'
            var and = index === 0 ? "&" : "";

            //create a 1-indexed count of the tickers.
            var tickerNum = index + 1;
            return and + "ticker_" + tickerNum + "=" + ticker;
        })
        .join('&'); //<--separate each query with "&"

    // for timespan, you don't need to make a seperate `time` variable,
    // this can be done in one line.
    if(viewObject.timespan) urlString += "&timespan=" + viewObject.timespan;

    console.log('/dashboard'+urlString);
    return '/dashboard'+urlString;
}


Locate a number in an array with a special ordering

I suspect that the better solution is to compute the column index directly, without the if-else conditions. You can do this by using integer division, and modulo. Consider the following computation breakdown:

% declare an int32 value 2
itwo = int32(2)
% compute the position of the column with the value 1
onecol = idivide(len + 1, itwo)
% compute how far away the desired value is from the 1 column
distance = idivide(z, itwo)
% compute the direction of the desired value from the 1 column (-1 is left (odd numbers), +1 is right (even numbers))
direction = 1 - 2 * mod(z, itwo)

You can string this together as a 1-liner:

column = idivide(len + 1, itwo) + idivide(z, itwo) * (1 - 2 * mod(z, itwo))

You can also put it in a function should you choose. I have put together this example here:

https://goo.gl/Oenp85 (and updated for int32 conversion here: https://goo.gl/NgJJhN

Note that it has been a long time since I played with MATLAB.

indexOfVal = @(mat, val) idivide(numel(mat) + 1, int32(2)) + idivide(val, int32(2)) * (1 - 2 * mod(val, int32(2)));

x = [9 7 5 3 1 2 4 6 8];

result1 = indexOfVal(x, 9)
result2 = indexOfVal(x, 7)
result3 = indexOfVal(x, 5)
result4 = indexOfVal(x, 3)
result5 = indexOfVal(x, 1)
result6 = indexOfVal(x, 2)
result7 = indexOfVal(x, 4)
result8 = indexOfVal(x, 6)
result9 = indexOfVal(x, 8)

Produces:

result1 =  1
result2 =  2
result3 =  3
result4 =  4
result5 =  5
result6 =  6
result7 =  7
result8 =  8
result9 =  9


Hexadecimal to string without C++ standard library functions

As both the others have said use std::string if you are going to dynamically allocate space. Its not going to be worse than your code;if your compiler implements the small string optimizations its actually goinf to do better than your code as no dynamic memory will be used.

unsigned count(unsigned n)

Well we know that unsigned have a particular size sizeof(unsigned). So we know that the max size of the array is sizeof(unsigned)*CHAR_BITS/4. On most systems this will be 8 on some it will be 16. But neither of these numbers is huge why not always use the maximum size (it will save you the time of calculating an exact size.

You can also get away with no dynamic memory allocation by having a static array in the function (not thread safe but it does not look like that is your issue).

Others have suggested replacing the n /= 16; by n >> 4;. DON'T do that (unless you think it expresses intent better). It hides the intent of the code. The code is supposed to express the intent in the most natural way possible. It is the job of the compiler to see that this can be optimized to a shift by 4 and I am dead sure the compiler will generate the most efficient code.


Converting embedded JSON into flat table

I don't know anything about tkinter, so I'm just going to look at your flatten function.

I'm going to start with some overarching comments. When checking for the type of something, use  isinstance instead of type(x) is some_type. Secondly, when you have a trivial loop of the form

list_ = []
for x in iterable:
    list_.append(function(x))

You almost always want to turn it into a list comprehension

list_ = [function(x) for x in iterable]

You have an unnecessary dict.copy which is definitely going to slow things down if you start having very large files.

You can get rid of the for i in range(len(data)) and just use for item in data.

I don't like that out isn't a local variable/parameter, and I find it a bit hacky that it is modified inside of flatten2 without being passed as a parameter.  I think a better idea is to use an input parameter. This might also help speed things up, as Python accesses locals faster than nonlocals.

Now you also have a minor correctness issue - you only handle dict and list, but what if there were a tuple inside? Some user defined type that quacks like a dict? Admittedly if you're parsing json that is unlikely, but this would be a fairly useful general utility to flatten all sorts of nested mappings.  There are all sorts of ways to handle this, but the easiest might be to ask forgiveness instead of permission

try:
    for key, value in x.items():
        # your dict stuff here
except (ValueError, AttributeError): # oh this doesn't support unpacking/the items() method
    for item in x: # treat it like a list

Not necessarily a perfect solution, but worth considering.

I doubt this is going to help a ton with speed. Short of parallelising this (and I don't think Python would do that effectively with either threads or processes) I'm not seeing a good solution.

One last minor thing - if you have a large and deeply nested json file this might choke with a recursion error. You could fix that by using a list or a queue and keep adding items to it as they're discovered.  Something like this (sketched, may not work right away) might work

to_flatten = [(item, '') for item in y]
for item, name in to_flatten:
    if isinstance(item, dict):
       for key, value in item.items():
            if key == "name":
                to_flatten.append((item["value"], name + item[key] + '_'))
            else:
                to_flatten.append((item[key], name + key + '_'))
    elif isinstance(x, (list, tuple)):
       for member in item:
           to_flatten.append((member, name + '_'))
    else:
        result_dict[name[:-1]] = item

This may also help with speed - I honestly don't know.

One last note - like with most languages, string concatenation is slow in Python. In CPython, the peephole optimizer does some magic with just 2 strings (I wish I could find the source for this) but doesn't for more than that. And according to PEP8,

  For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython ... In performance sensitive parts of the library, the ''.join() form should be used instead.

(emphasis and code-formatting added)

You might be able to get a speedup by changing your string concatenation method.

to_flatten.append((item["value"], ''.join([name, item[key], '_'])))


Moving instance variable from partial to helper

Is _header.html.erb part of the layout? If so, i would advice you to move this logic to helper, if not all the controllers would need to set the @towns instance variable.

module ApplicationHelper
  def town_names
    Town.all.collect(&:name)
  end
end

And in your view call the town_names. I think you want each name to be in an li element. I have changed the code accordingly.

<% town_names.each do |name| %>

<%= link_to name, '#', id: "logo" %>

   <% end %>


Printing the last two digits of an exponential calculation

document your code. In the code.
Python got it right with docstrings:
The laziest copying of a function includes its docstring, ready for introspection.
document what everything is there for wherever not blatantly obvious.
This would include the problem description - if it was in the source code, one might notice that the statements use an abs() where the description never mentions it.
let a tool help you to follow the Style Guide for Python Code.
your naming is OK (with the exception of result - there should be digits of power or modulus of power)
your binaryToDec() is too weird to mention - just try to describe what it does accomplish, and how.
read the requirement specification carefully. If possible, fix in writing how to check requirements are met.
You mention that your implementation is not the fastest way to do [modular exponentiation]: is there an upper limit on execution time? Rank among course-mates?
The way the exponent is specified looks constructed to head you to use one particular way to implement exponentiation.
know your python library. Mast commented the existence of a built-in - for conversion of strings to numbers using a non-default base, more likely than not.

How not to do more than hardly avoidable (/be "fast"):
For starters, only the last d digits of a number have any influence on the last d digits of its integral powers represented using the same base b.
Moreover, those last d digits become cyclic with b**d an integral multiple of cycle length - just watch out for things like 2**100.


How best to keep track of an unknown number of objects?

I'm not an Objective-C guy but, I do know that if you used some sort of hash table structure and could define a hashcode for these objects, that you'd be able to pull them out much faster.

You said at times you "need to find one", I would assume you would know enough about it to be able to generate its hashcode and check your table for it in O(1) time.


Find max number of items that can fit in a given max-width

I find your code clear enough, but you could improve it a little bit, so you only do the add operation once:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;
  let count = 0;
  for (let i = 0; i < elements.length; i++) {
    accWidth += elements[i].width
    if (accWidth <= maxWidth) {
      count++;
    } else {
      break;
    }
  }
  return count;
}

Further you could reverse the conditional statement:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;
  let count = 0;
  for (let i = 0; i < elements.length; i++) {
    accWidth += elements[i].width
    if (accWidth > maxWidth) {
      break;
    }

    count++;
  }
  return count;
}

In a more condensed version you could make the count variable also be the index:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;

  for (var count = 0; count < elements.length; count++) {
    if ((accWidth += elements[count].width) > maxWidth) {
      break;
    }
  }
  return count;
}

Be aware that count must be declared as var count = 0 not let count = 0


I honestly don't see anything particularly wrong with that Linq query, but there are a number of other things you should consider:

Converting the query to a List<T> forces immediate evaluation of the query and requires the allocation of an single, contiguous portion of memory to store the results. If there are several thousand records, this can be fairly costly. If you later filter / re-order / group this list, it must be done in memory, which is usually much slower than allowing the database to filter / re-order / group the results. Generally, you should try to put off evaluating results until as late as possible.
Even if you're not doing any further processing on the list, it may not be necessary to actually store the result set as a List<T>. You really should only use a List<T> when you need to be able to add or remove items from the result set dynamically. If you only need to be able to access elements in the result set by index (particularly in O(n) time), I'd recommend using an array instead (with ToArray). If all you need to do is iterate through the result set one item at a time, I'd strongly recommend using an IEnumerable<T> instead (with AsEnumerable). This way, your application doesn't need to pull all items in at once, and it doesn't have to allocate a single, contiguous portion of memory to store them.
If you've done all you can to speed up the C# code, and it still runs slowly, you should look at optimizing the database—your code can't run any faster than the back-end database, after all. Perhaps you need to add an index to the item_parent column (and probably a foreign key as well).

If you've setup a proper navigation property you could write your query a bit more cleanly, although I doubt this would run any faster, since this will still translate to an INNER JOIN in SQL:

List<myItem> items =
    (from x in db.myItems
     where !x.tblParent.hidden
     orderby x.name
     select x)
    .ToList();

Or in fluent syntax:

List<myItem> items = db.myItems
    .Where(x => !x.tblParent.hidden)
    .OrderBy(x => x.name)
    .ToList();


Thread.MemoryBarrier()
What do you expect the call to Thread.MemoryBarrier() will help your code ?
What does Thread.MemoryBarrier do ? It prevents that the compiler and the hardware subtly transform a program’s memory operations.
So basically for your code it ensures that then following instructions will be executed in the order they are written.

var sync = new Control();
sync.Handle.GetHashCode(); // ensure handle is created
_sync = sync;

Thread safety
To answer "Is this code thread safe ?", you first need to set your definition of thread safety aka what does thread safety means for you. See also what-is-this-thing-you-call-thread-safe
General

the code is lacking a EndInvoke() which should be integrated.

you are misusing a Control to access the main (ui) thread of an application.

wouldn't a SynchronizationContext be a better fit here ?
See also: https://stackoverflow.com/a/20300351/2655508


Asyncronous unit test refactoring in Objective-C

It looks like you can extract the method bodies entirely. Warning: I typed this code into a web browser, not an IDE:

- (NSDictionary *)invokeClassBBlockRunnerWithExpectedObject: (id)object expectedError: (NSError *)error {
    [mockClassA setObject: object];
    [mockClassA setError: error];
    [mockClassA setRunCompletionBlockImmediately: YES];

    __block NSError *actualError = nil;
    __block id actualObject = nil;

    [classB fireClassAsBlockThenDoThisBlock: ^(id object, NSError *error) {
        actualObject = object;
        actualError = error;
    }];

    NSMutableDictionary *results = [NSMutableDictionary dictionary];
    if (actualObject) [results setObject: actualObject forKey: @"Object"];
    if (actualError) [results setObject: actualError forKey: @"Error"];
    return results;
}

- (void)testBlockMethodOne {
    NSError *expectedError = [NSError errorWithDomain: @"An Error" code: 42 userInfo: nil];
    NSDictionary *results = [self invokeClassBBlockRunnerWithObject: nil error: expectedError];

    STAssertNil([results objectForKey: @"Object"], @"Shouldn't get an object when an error occurs");
    STAssertEqualObjects(expectedError, [results objectForKey: @"Error"], @"Should get the error I expected");
}

- (void)testBlockMethodTwo {
    id expectedObject = [[NSObject alloc] init];
    NSDictionary *results = [self invokeClassBBlockRunnerWithObject: expectedObject error: nil];

    // you get the idea
}


We can avoid the excessive indentation by returning early.
Instead of checking for validity:
if (username.length() >= MIN_NAME_LENGTH)
{
    ... additional nested checks...
}

we reverse the check and return as soon as possible:
if (username.length < MIN_NAME_LENGTH)
    return false; // done!

So overall we'd get something like:
if (username.length() < MIN_NAME_LENGTH || username.length() > MAX_NAME_LENGTH)
    return false;

if (username.empty() || !std::isalpha(static_cast<unsigned char>(username.front()))) // paranoia: avoid crashing with empty username
    return false;

if (std::find_if(username.begin(), username.end(), isNotValid) != username.end())
    return false;

return true;

Note that isalpha is in the std:: namespace in C++. Technically we should also cast to unsigned char when calling the function. (We could wrap that in a function of our own).


Triangle categorizer -- completely refactored and re-written

A few simple comments:

Spelling:

Triangles are either Isosceles, Equilateral, or Scalene

Also instead of using string literals, replace them with macros like so:

#define EQUILATERAL "equilateral"
#define ISOSCELES "isosceles"
#define SCALENE "scalene"

I commend you on using long names in c, as many c-programmers use 1-2 letter names for things. I might suggest adding comments to complex code, such as mentioning the fact that you are using triangle inequality in your is_valid_triangle function

I would also suggest extending this program to work with non-integers, such as long longs, doubles and the like. In addition, it may be more helpful to a user to pass in coordinates instead of side lengths. That would also allow you to not check if a triangle is valid or not, as technically all 3 point pairs form a triangle (even if it is degenerate).


What is the best way to make this code dry?

I think a good way to reduce the WET code here is to consolidate and generalize the core functionality to a single function, and tweak the arguments going into it accordingly. I left the get_api_key function alone and focused on the other ones as they are the most similar. See below:
def add_template_2(hostname, api_key, template_name, name):
    return add(hostname, api_key, template_name, name)

def add_template_stack_2(hostname, api_key, stack_name, template_name):
    return add(hostname, api_key, stack_name, template_name)

def add_variable_2(template_name, var_name, netmask, hostname, api_key):
    return add(hostname, api_key, template_name, netmask, var_name)

def add(hostname, api_key, xpath_name, element, xpath_var=None):
    url = f'https://{hostname}/api'

    if xpath_var:
        xpath = f"entry[@name='{xpath_name}']/variable/entry[@name='{xpath_var}']"
        ret_val = xpath_var
    else:
        xpath = f"entry[@name='{xpath_name}']"
        ret_val = xpath_name

    values = {'type': 'config',
        'action': 'set',
        'xpath': xpath,
        'element': f"<tag>{element}</tag>",
        'key': api_key
        }
    requests.post(url, params=values, verify=False, proxies=proxies)
    return(ret_val)


From a short review;

locationIsUnoccupied and createGameInfoWindow are mysterious, where are they defined?
newMarker ? gameMarkers.push(newMarker) : null; should trigger jshint, I would just go for the if statement
I would structure all the code and functions in to MVC (model view controller)

So GAME_ICON_URL becomes model.GAME_ICON_URL
So createGameInfoWindow becomes ui.createGameInfoWindow
So locationIsUnoccupied becomes model.locationIsUnoccupied

This could make your code look like;
// Initialising map and markers
export function handleApiLoaded(model, ui, controller){
  ui.infoWindow = new google.maps.InfoWindow({});

  model.gameMarkers = [];
  for (const game of games) {
    addGameMarker(game, model, ui, controller);
  }

  //Not sure the below would still make sense?
  model.setGameMarkers(gameMarkers);
  ui.setInfoWindow(ui.infoWindow);
};

// Create marker object for game
export function addGameMarker(game, model, ui, controller){

  const [lat, lng] = [parseFloat(game.latitude), parseFloat(game.longitude)];

  if (model.locationIsUnoccupied(lat, lng, model.gameMarkers)) {
    var icon = {
      url: model.GAME_ICON_URL,
      //Why 30 and 45, a comment would be good here
      scaledSize: new google.maps.Size(30, 45),
    };

    var marker = new google.maps.Marker({
      position: {
        lat: lat,
        lng: lng,
      },
      icon: icon,
      map: model.map,
    });

    marker.addListener("click", () => {
      ui.infoWindow.close();
      //Maybe `map` should be part of `ui`, deep thoughts to be had..
      model.map.panTo(marker.getPosition());
      ui.handleMarkerClick(marker, map);
      ui.infoWindow.setContent(createGameInfoWindow(game));
      ui.infoWindow.open(map, marker);
    });

    model.gameMarkers.push(marker);
  }
};


You can skip the check for the end of one of the strings. If the other string ends before the one that you check the length for, the comparison of the characters will catch the difference:

int compare(char *str1, char *str2) {
  while (*str1 && *str1 == *str2) {
    str1++;
    str2++;
  }
  return *str1 - *str2;
}

You can write the same using a for statement if you want it shorter (and less readable):

int compare(char *str1, char *str2) {
  for (;*str1 && *str1 == *str2; str2++) str1++;
  return *str1 - *str2;
}

Just for the sake of it, you can make is shorter (mis)using recursion, but that is a rather terrible solution:

int compare(char *str1, char *str2) {
  return (*str1 && *str1 == *str2) ? compare(++str1, ++str2) : *str1 - *str2;
}


First of all, bad naming.

Try prefixing everything with stack,  this makes it a bit more useful as a library where you won't name clash

stack_count
stack_top
stack_push
stack_pop
stack_is_empty

etc

A lot of stack implementations now don't let pop both return a value and change the stack.  It goes against CQS (Command Query Separation). Instead, just use top to get the the top of the stack, and pop simply removes one if one exists.

Your reallocs need to be tested to see if they work, if not, handle the situation nicely rather than the havoc that currently will happen.

Don't use fputs().  A stack should have no dependencies on a "UI"

you should have a stack_destroy  which free's up your stack memory.

Bad things will happen if your capacity increment is 1.

Having a multiplier as a capacity increment will make for a super expensive stack for larger amounts of memory.

Changing your elementcount-- then ++ again in peek is just weird.  Just change all this:

p->elementCount--;
int topValue = p->elementData[p->elementCount];
p->elementCount++;
return topValue;

to

return p->elementData[p->elementCount-1]


Advent Of Code 2017 Day 4 (part 2) in Functional Programming (FP)

I don't see much that I would change about this code. I recently discovered that the spread syntax can be used to split a string into an array so that could be used to eliminate calling the split() function.

Instead of

const sortWords = words => words.map(word =>  word.split('').sort().join(''));

use the spread syntax:

const sortWords = words => words.map(word =>  [...word].sort().join(''));

In this reduction:

const countDuplicate = words => words.reduce((acc, word) => {
  return Object.assign(acc, {[word]: (acc[word] || 0) + 1});
}, {});

I presume that the only reason you used brackets with a return statement is because it would be too long for a single line. You could avoid those by pulling out the arrow function to a separate line:

const countWord = (acc, word) => Object.assign(acc, {[word]: (acc[word] || 0) + 1});
const countDuplicate = words => words.reduce(countWord, {});

I know that is only one line shorter but at least there is no need for the brackets and return statement.


Time limit exceeded on finding out the GCD and LCM of a Python list

It is a really bad idea to use  a variable named l. I is hard to distinguish it from 1.
All these functions using xrange are inefficient

the lcd function can be efficiently calculated by

from fractions import gcd
def lcd(a,b):
    return(a*b/gcd(a,b))

the count function is

count(l,g)=divisor_count(g/l)

where divisor_count is the number-of-divisors function

If the number n has the prime factor decomposition

$$n=p_1^{e_1}\cdot p_2^{e_2}\cdots p_k^{e_k}$$
then we have

$$ \text{divisor_count}(n)=(e_1+1)\cdot(e_2+1)\cdots(e_k+1)$$

This can be calculated in the following way:

def divisor_count(n):
    cnt=1
    i=2
    while i*i<=n:
        e=0
        while n%i==0:
            n//=i
            e+=1
        cnt*=e+1
        i+=1
    if n>1:
        cnt*=2
    return(cnt)

This divisor_count function runs in
$$O(\sqrt{n})$$
time, the xrange implementation uses
$$O(n)$$
time.


I genuinely hope you don't take offence by this, but this implementation is so insane that it's frankly impressive.
Since you have delete_flag = "*kill_*.flag", calling os.path.split on it is pointless. Perhaps you're substituting that with something else that has a path, but if you are, why isn't it parametrized?
Do a tuple-unpack here:
                    content = f.read().split(";")
                    payload = {
                        "name": content[0].strip(),
                        "link": content[1].strip(),
                        "id": content[2].strip()
                    }

should just be
name, link, id = (part.strip() for part in f.read().split(';'))

Putting these in a payload dict is actively harmful. You only ever use these as variables later. About the most generous I can be here is to guess that there's actually more code in your application that you haven't shown which relies on the payload for some other network or serialized file operation, but if that's the case the whole question is invalid.
AutomaticCreate implements PatternMatchingEventHandler - so then why are you reinstantiating it here?
        observer.schedule(AutomaticCreate()

You already instantiated it here:
AutomaticCreate().main()

Keep the second instantiation, and replace the first instantiation with a reference to self.
The following is a strange and non-standard way of calling a base constructor:
    watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]],  # ...

Just use super().
Rework your class to be a context manager, where __enter__ calls self.observer.start(), and __exit__ calls self.observer.stop(). Then, use your class instance in a with at the top level and delete your main() method.


Adding/changing ID3 tags to media files with "artist - title" format

Here are some things I see that may help you improve your code.

Add error checking

In your changeTag routine, a segfault can occur if there is no file. Add this just after the FileRef line:

if(!file.isNull() && file.tag()) {

Separate concerns

The code would be a little more clear if the changeTag routine was split into two parts. In particular, one could extract artist and title, and the other could apply those. It may also be reasonable to make extractFiles return the vector of errors rather than having it emit those errors to std::cout.  The calling program might be able to do something different with those, such as if it were a GUI.

Use command line parameters

Instead of prompting for a directory name, it would be better to have that as a command line parameter.  That would also simplify the control structure of your program as mentioned in the next comment.

Try to consolidate loop exit conditions at the top

Prefer a for loop with the actual exit condition to a while(true) loop.  Because the reader is forced to search for the loop terminating condition, it's more effort to understand the latter construct.  This code, for example could be structured like this:

int main() {
    std::string dir;
    std::cout << "Directory: Enter 'x' to close: ";
    for (std::cin >> dir; dir != "x"; std::cin >> dir) {
        extractFiles(dir);
    }
}

This also eliminates a break statement.  A break can also contribute to difficulties understanding a loop because again, the programmer reading the code has to search for them.

Consider the user

It might be nice to have an option for a "dry run" of the program.  That is, have it print what it would have done without actually altering any files.  This would help the user have confidence that the program was doing only and exactly what was intended.


Find element that has been removed from a shuffled array

When you don't know how long a built-in function call will take, then the TimeComplexity page on the Python wiki comes to the rescue. This tells us that both item in list and list.remove(item) take time proportional to the length of the list.

So although current in arr2 and result.remove(current) are single expressions in Python, in fact each of them has a loop hidden inside it, and this makes the overall runtime \$Θ(n^2)\$.

If you're having trouble with the analysis, there's no substitute for actually running the code and timing how long it takes on different inputs! This is really easy to do, for example, you might write:

from random import randrange
from timeit import timeit

def test(n):
    """Time finder on lists of length n."""
    a = list(range(n))
    b = list(a)
    del b[randrange(n)]
    return timeit(lambda:finder(a, b), number=1)

and then:

>>> for i in range(5):
...     n = 10000 * 2 ** i
...     print(n, test(n))
...
10000 0.020456696045584977
20000 0.07089142000768334
40000 0.361092661973089
80000 1.5187797680264339
160000 6.356738713919185

You can see that when \$n\$ doubles, the runtime increases by around four times, which is what we expect for an \$Θ(n^2)\$ algorithm. Here's a plot showing a least-squares fit of the measurements collected above to the function \$t = an^2\$, and you can see that the fit is pretty good:


Exception handling with expression lambda in Presenter class

To avoid a discussion in comments I'll go ahead and make my comments an answer.

I think this a much better than your original way. Instead of catching Exception in your DAL, you're allowing all exceptions to propagate up until you can properly handle them. Catching Exception can be a bad thing and is generally considered a bad practice. The problem is that whenever a critical exception such as OutOfMemoryException is thrown, you swallow it and throw a new exception with a message of "Bank account is empty" if I remember correctly. It's just not right because you were hiding what actually went wrong. Your stacktrace would show the exception being thrown from the wrong place and it wouldn't have a meaningful message.

But that was the past and this is the present. You're handling the exceptions where they should be handled and you're not catching Exception. Those were my only real concerns.

The only thing I don't really like (note it's not actually a problem with your example) is that you handle all exceptions in one method. If one method in your presenter does file IO and another does sql stuff - you'd have to include catches for both types of exceptions in one place. What if your presenter is big and can possibly catch dozens of different exceptions? Is this a problem for you? I don't think so because all you're really doing is displaying the exception message through your MessagingService. I would only see it as a problem if you had to uniquely react to exceptions.


So far it's looking quite good, but I have a few comments:

Which file to load?

private static final File file = new File("config.yaml");

In my opinion it would be better to pass the File to load in to the constructor of this Config class, for flexibility. Now perhaps you only need to load a specific file, but in the future you might want to support multiple files. Who says that you always want to load config.yaml? Sometimes you might want to try different configurations, and instead of making backups of your config file and renaming files like crazy, you could instead load config-withsomespecials.yaml

private final File file;
public Config(File file) {
    this.file = file;
}

Speaking of flexibility, your setDefaults class works fine for your server, but you could make your Config class an abstract class, setDefaults as an abstract method and use a ServerConfig as a subclass in which you override this method:

// In your `Config` class:
protected abstract void setDefaults();

// In your `ServerConfig` class:
@Override
protected void setDefaults() {
    config.clear();

    config.put(SERVER_NAME,     "Server");
    config.put(MOTD,            "Welcome to the server!");
    config.put(SERVER_PORT,     21020);
}

These are only suggestions, if you don't want to make it that flexible, that's up to you.

<personal-opinion> As for the choice of using YAML.... it isn't exactly my favorite format. Let me guess, you're a Minecraft / Bukkit player? The Minecraft / Bukkit world is about the only place I've come across this format. If you have the ability to choose, I would personally recommend using Jackson, which is primarily used for JSON, although it has support for XML and even support for YAML. Jackson is wildly used, very flexible, and I think it is more well-documented than Snakeyaml.</personal-opinion>