Just a few points

You're missing a & in your if conditional. Right now you're doing a bitwise AND, rather than a logical AND (which would be &&).
I'd say you should always use curly braces, even for one-liners. JS accepts one-liners just fine, but as a code-hygiene thing it's better to have braces there, I think.
You could rewrite the reg exp to remove everything that isn't a numerical digit (instead of only removing dashes). I don't know if that's what you need, but if it is

wd.value = wd.value.replace(/[^\d]/g, ""); // remove all non-digit characters

You also could use a little more reg exp to make sure you remove all leading zeros (even if you say there's only going to be 1). Incidentally, this allows you to skip the "starts with zero" check, and only have the getCCC() != "" check. Point is, you can do a replace for leading zeros specifically, rather than "blindly" chopping something off of the string.

function prepareTelNo() {
    var wd = document.getElementById('numbertodial');
    wd.value = wd.value.replace(/-/g, ''); // strip - from the tel. no.

    // Cut off leading zeros if a country code is set
    if(getCCC() != "") {
        wd.value = wd.value.replace(/^0+/, ""); // cuts off all leading zeros
    }
}

If you really, truly only want to remove 1 leading zero rather than all of them, use /^0/ (without the plus sign) as the reg exp pattern.


Authenticating user/password against Active Directory using ASP.NET Identity

SignInAsync is an async method, and you most likely want to wait for it to complete before returning the SignInStatus. In order to await it, we must declare the method with the async keyword. This also means we can simplify the return statements:

public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    if (Membership.Provider.ValidateUser(userName, password))
    {
        var user = UserManager.FindByName(userName);
        if (user == null)
        {
            return SignInStatus.Failure;
        }

        await base.SignInAsync(user, isPersistent, shouldLockout);
        return SignInStatus.Success;
    }

    return SignInStatus.Failure;
}


Your code is hard to read, and a few test cases would be nice to know what this should handle. For example, do you want to allow multiple lines? Do you want to replace things that are not "amp", like &gt;? Are you sure this will correctly sanitize your inputs?

It seems to me that you only want to replace & (ampersand + space) by &amp;.

This version works:

for any kind of whitespace
across multiple lines:

$s = preg_replace('/&(\s)/m', '/&amp;$1/', $s);


Project Euler #4 - finding the largest palindrome from the product of two n-digit numbers

Javascript numbers are stored in IEE754 format that can precisely represent numbers up to 2^53 - 1 (9007199254740991), so it's impossible to use the built-in Javascript arithmetic to get actual digits for a lot of two 8-digit number products (for example, 94,906,266 * 94,906,266 exceeds the abovementioned maximum).

There are several BigNumber libraries for JavaScript, but I'll only give an answer for the case of 7 digits and less. A brute-force enumeration with a couple of optimization is quite fast for n<7 compared to the original OP code that took 1370 ms for 3 digits and 3+ minutes for 4 digits.

function largestPalindromeOfTwoFactors(len1, len2) {
    // calculate number range for n digits:  10^(n-1)..10^n-1 (e.g. 10-99)

    // 'a' (outer loop) will be the largest multiplicand
    var maxA = Math.pow(10, Math.max(len1, len2)) - 1 |0;
    var minA = (maxA + 1) / 10 |0;

    // 'b' (inner loop) will be the smallest multiplicand
    var maxB = Math.pow(10, Math.min(len1, len2)) - 1 |0;
    var minB = (maxB + 1) / 10 |0;

    var maxMul = 0, maxMulA, maxMulB;

    for (var a = maxA; a >= minA; a--) {
        // in case len1==len2 only process 'b' smaller than current 'a'
        // as the larger numbers were already checked when used for 'a'
        for (var b = Math.min(a, maxB); b >= minB; b--) {
            var mul = a * b;
            if (mul <= maxMul) {
                // no need to continue, we'll never exceed maxMul with a smaller 'b'
                break;
            }
            var mulStr = mul.toString();
            for (var i = mulStr.length-1, j=0; i>=j && mulStr[i] == mulStr[j]; i--, j++) {}
            if (i <= j) {
                maxMul = mul, maxMulA = a, maxMulB = b;
                // 'a' smaller than current 'b' won't produce a bigger product
                minA = Math.max(minA, b);
            }
        }
    }
    // retain the order of input parameters' magnitudes: 2,3 -> 99, 951
    return [maxMul, len1 < len2 ? maxMulB : maxMulA, len1 < len2 ? maxMulA : maxMulB];
}

Test run:

for (var i=1; i<=7; i++) {
    var start = Date.now();
    console.log('%o in %d ms', largestPalindromeOfTwoFactors(i, i), Date.now() - start);
}

  [9, 9, 1] in 0 ms
  [9009, 99, 91] in 0 ms
  [906609, 993, 913] in 2 ms
  [99000099, 9999, 9901] in 1 ms
  [9966006699, 99979, 99681] in 551 ms
  [999000000999, 999999, 999001] in 171 ms
  [99956644665999, 9998017, 9997647] in 162363 ms <<<<<< ughhhh

Notes:

There are much better algorithms.
090 isn't a number, 90 is, so the former and the likes are not palindromes.


Dictionary lookup of non-nullable struct into nullable destination

General

I think I would question the value of this extension method. You've already got the same information from the existing TryGetValue method:

Could the key be found?
What is the value?

If at all possible, I'd recommend trying to modify the calling code not to need this extension:

DateTime triedNearestDateUtc;
var nearestDateUtc = nearestDatesUtc.TryGetValue(company, out triedNearestDateUtc)
    ? (DateTime?)triedNearestDateUtc
    : null;

or even do away with the nullable entirely:

DateTime triedNearestDateUtc;
if (nearestDatesUtc.TryGetValue(company, out triedNearestDateUtc))
{
    // Do something with value
}
else
{
    // Do something without value
}

If there are multiple possible sources for your value (which your if (!nearestDatesUtc.TryGetValue(...)) suggests), try:

DateTime nearestDateUtc;
var foundNearestDateUtc = nearestDatesUtc.TryGetValue(company, out nearestDateUtc);

if (!foundNearestDateUtc)
{
    foundNearestDateUtc = otherDatesUtc.TryGetValue(company, out nearestDateUtc);
}

if (!foundNearestDateUtc)
{
    nearestDateUtc = DateTime.Now;
}

Or break that part into its own method:

private DateTime FindNearestDateUtc(string company)
{
    DateTime nearestDateUtc;

    if (nearestDatesUtc.TryGetValue(company, out nearestDateUtc))
    {
        return nearestDateUtc;
    }

    if (otherDatesUtc.TryGetValue(company, out nearestDateUtc))
    {
        return nearestDateUtc;
    }

    return DateTime.Now;
}

But this is all a bit speculative on what you're using it for. Onto the bits you've actually put in your question:

DateTime

The DateTime type is a tricky customer - it tries to be all things to all people. I understand if it'd be a lot of effort and upheaval to move away from this type now, but I'd strongly recommend NodaTime as an alternative - it forces you to think clearly about exactly what kind of date and time structures you mean, and helps to prevent subtle bugs down the line.

Some interesting reading (if you find this sort of thing interesting) on the subject: Jon Skeet on DateTime

Signature

The main reason for having the bool return value as well as the out parameter is that default(DateTime) could be a valid return value. With a signature like DateTime TryGetValue(string key), you have no way of knowing whether 0001-01-01T00:00:00 was the value or the default "I don't have a value" value.

In your case, you seem to be using a null DateTime? to indicate "I don't have a value" and a "real" DateTime? to indicate the result. There's no ambiguity here, so there's no reason you can't just return the value on its own.

This also has a nice side effect of making the body of the method a bit shorter and simpler:

    TValue result;
    if (that.TryGetValue(key, out result))
    {
        return result;
    }
    else
    {
        return null;
    }

or

    TValue result;
    return that.TryGetValue(key, out result) ? (TValue?)result : null;

Naming

I'd probably give the method a rename because it behaves differently from the normal TryGetValue: Try... methods conventionally have a bool return and an out result parameter.
that isn't a good name for a variable - it doesn't tell you anything about what it is or does.

public static TValue? GetValueOrNull<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary,
    TKey key) where TValue : struct
{
    ...
}

Result

I'd go with the ternary operator over the if ... else version and end up with:

public static TValue? GetValueOrNull<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary,
    TKey key) where TValue : struct
{
    TValue result;
    return dictionary.TryGetValue(key, out result) ? (TValue?)result : null;
}


Reduce the number of rotations

For each "ring" you rotate, the number of rotations you can do before you reach the original position again is: \$2*(rows + columns) - 4\$, where rows and columns are the number of rows and columns for the ring.  So you can reduce the number of rotations like this:

sizeOfRing = 2*(r-sr + c-sc) - 4;
rotationsForThisRing = totalRotations % sizeOfRing;

You will of course need to modify your program to use a variable number of rotations per ring.


consecutive_find function for returning a consecutive range of elements

Your function does not work correctly. The bug is in the lines:

    marker = std::find_if_not(lead, last,
                              [&lead] (value_type const& x) { return x == *lead; });

Say you call the function with the following code:

std::vector<int> v{1, 2, 2, 2, 3};
auto it = consecutive_find(v.begin(), v.end(), 3);

In the function, you start with:

marker -> 1
last   -> 1

Then, in the first statement of the outer while block, you execute:

    lead = std::next(marker);

Now,

last   -> 2

You break out of the first inner while block with count set to 1, Then you execute

    marker = std::find_if_not(lead, last,
                              [&lead] (value_type const& x) { return x == *lead; });

When this line is finished executing,

marker -> 3

and you completely missed the correct return value.

You can change those lines to simply:

    marker = lead;

and the function works fine.

Here's a sample program and its output:

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

template <class Iter>
Iter consecutive_find(Iter first, Iter last, std::size_t n)
{
    Iter marker(first), lead(first);
    std::size_t count(1);

    while (lead != last)
    {
        lead = std::next(marker);
        while ((lead != last) && (*marker == *lead)) { ++count; ++lead; }
        if (count == n)
        {
            if ((lead == last) || !(*lead == *marker))
                return marker;
        }
        marker = lead;
        count = 1;
    }
    return marker;
}

void test1()
{
   std::vector<int> v{1, 2, 2, 2, 3};
   auto it = consecutive_find(v.begin(), v.end(), 3);
   for (int i = 0; i < 3 && it != v.end(); ++i, ++it )
   {
      std::cout << *it << " ";
   }
   std::cout << std::endl;
}

int main()
{
   test1();
}

Output:

2 2 2


To many accumulators, paths and graph, you just need one.
One for loop to many, you can do everything with one loop.
open with no close is a no no. Sure you could aruge that the codebase is small and you will just run the function once and then terminate... But it's good practice to always close your file handlers. Instead of using open() and close() you shuold just use with open(filename, 'r') as f:, because with clause take care of close() for you.
Route is not use anywhere else so no need for it.
You are doing del paths[-1] twice so you will actually remove one vaild path.
The for loop is stupidly complex for such a simple problem. I dont even know where to start in my quest of understading it.

graph[node][path[0]] doesn't do what you say it does; it makes a dict of dict, and not a list of tuples in a dict as you specified. eg. the code returns {birmingham : {'manchester': 84, 'bristol': 85}} instead of {birmingham : [('manchester', 84), ('bristol', 85)]}.
So theres a lot of if else statements in the loop to solve the problem of: "what to do when the dict/list isn't instantiated" . This can be done in a simpler way with dict.setdefault(), this function basically checks if the dict has an list (dict or whatever you want) as a child, and if it dosen't it will instantiate it for you.

I dont think that's a graph because not everything in that dataset is connected to eachother, its more like a set of graphs.

def new_sol(filename):
    graph = {}
    with open(filename, 'r') as f:
        for line in f:
            city1, city2, distance = line.lower().split()
            if distance == "input":
                break
            #what you say you want
            graph.setdefault(city1, []).append((city2,int(distance)))
            graph.setdefault(city2, []).append((city1,int(distance)))
            #same as your code
            #graph.setdefault(city1, {})[city2] = int(distance)
            #graph.setdefault(city2, {})[city1] = int(distance)
    return graph
if __name__ == "__main__":
    print(new_sol("test.txt"))

Time analysis

You wanted to optimize the code, so lets us do an time analysis to see if there is some thing we can optimize in our algorithms, or if the optimaztion is just in the implementaion.

askers code

read line: \$O(N)\$
put line in arr: \$O(1)\$
iterate over paths: \$O(N)\$
put the diffrent directions in a dict \$O(2)\$

\$O(N*1+N*2) = O(N*3) = O(N)\$

proposed code

read line: \$O(N)\$
put line in arr/dict: \$O(2*(1+1))\$, \$(1+1)\$ comes from lookup/insertion + insertion

\$O(N*4) = O(N)\$

So from a algorithmic standpoint both your code and my code preforme equally well, and that is the fastst we can do it.
From an implentaion standpoint my code is a bit faster but as \$N\$ goes toward infinity it dosent really matter.


Correctness

How should these names be ordered?

SMITH, ARIEL B.
SMITH, ZINNIA X.
SMITHSON, HARRIET

The way your code works, you smash all the components of each name together, like "SMITHZINNIAX" and "SMITHSONHARRIET", resulting in Harriet Smithson coming before Zinnia Smith.  Thus, you'll end up Ms. Smithson ordered between the two Smiths, violating the expectation that all employees with the last name Smith be listed together.

Therefore, you should be comparing by lName first, proceeding to compare by fName only to break ties.
If one of the employees has no name (lName, fName, and midInitial are all empty strings after trimming), then this compareTo() method will report it as being equal to all other employees!

Performance

That's a huge amount of string manipulation to do a comparison!  That's a bad idea, because if you want to sort a list of employees, you will likely end up doing many of these comparisons, and each comparison will be much slower than it should be.

You should be able to implement this compareTo() method without any string concatenation or trimming.

Design

Why do you need to .trim() any of these name components?  Is your data unclean?  Why are initial and trailing spaces being stored in any of these fields?  Such spaces would not be considered a legitimate meaningful part of a name, so why aren't they either rejected or sanitized in the constructor or setter methods?
Unlike numbers or strings, which have an inherent natural ordering, there is no obvious reason why employees should be ordered according to their names.  What if you want to sort a list of employees by their salary instead?  Instead of writing this Employee.compareTo() method, consider moving this code out into a Comparator class instead:

import java.util.Comparator;

public class Employee {
    public String getLastName() { … }
    public String getFirstName() { … }
    public String getMidInitial() { … }

    public static final Comparator<Employee> COMPARE_BY_NAME = new Comparator<Employee>() {
        @Override
        public int compare(Employee a, Employee b) {
            int cmp;
            if (0 != (cmp = a.getLastName().compareTo(b.getLastName()))) {
                return cmp;
            }
            if (0 != (cmp = a.getFirstName().compareTo(b.getFirstName()))) {
                return cmp;
            }
            return a.getMidInitial().compareTo(b.getMidInitial());
        }
    };
}

Since Java 8, you can also write:

public class Employee {
     …

    public static final Comparator<Employee> COMPARE_BY_NAME =
        Comparator.comparing(Employee::getLastName)
                  .thenComparing(Employee::getFirstName)
                  .thenComparing(Employee::getMidInitial);
    }
}


Restructuring data received from JSON call

A much more maintainable solution would be using templates, like Handlebars. This is to primarily avoid HTML in the JS, which can get messy in the long run:

Assuming your data looks like:

{
  media : [
    {"displayName" : "", "hours" : ""},
    ...
  ]
}

Add this to your page. This will be your template. It will not render since it's inside

Then your JS, short and lean.

// Get the template and compile it to a renderer function;
var template = $('#template-chatinfo');
var templateRenderer = Handlebars.compile(template);

// You might want to cache chatInfo
var chatInfo = $('#chatInfo');

// Pull out the url for easy reading and editing
var url = "/services/chatInfo.json?user=manual" + mediaTypes + locationTypes;

$.getJSON(url, function(data) {
  // Render the data and append
  var renderedData = templateRenderer(data);
  $("
").html(renderedData).appendTo(chatInfo);
});


Determine if input word can be created from a list of letters

Imports

In general, imports should be listed at the top of the script, not inside function definitions.  So instead of this:

def validate_word(words, letters):
    from collections import Counter
    ...

Write:

from collections import Counter

def validate_word(words, letters):
    ...

Variable names

In Python, variable names should be snake_case.  Words beginning with upper case letters are reserved from classes, like Counter, so Count should be called count.

Test Code

user_word and letters are declared far from the code that uses them.  They should be declared near where they are used, so at the bottom of the script, and ideally inside a __name__ == '__main__' guard:

from collections import Counter

def validate_word(word, letters):
    ...

if __name__ == '__main__':
    user_word = 'BANANA'
    letters = ['N', 'B', 'N', 'A', 'A', 'P', 'M', 'S', 'A']
    print(validate_word(user_word, letters))

A String is a List of Characters

The Counter class accepts an iterable for its construction argument, such as the list of letters you want to count.  But a string is also an iterable list of characters, so instead of a list, you could simply pass in a string, and it would work just as well:

if __name__ == '__main__':
    user_word = 'BANANA'
    letters = 'NBNAAPMSA'
    print(validate_word(user_word, letters))

Counters

You are counting up the counts of letters you are allowed to use.  Why not count up the count of letters in the user_word?

>>> Counter('NBNAAPMSA')
Counter({'A': 3, 'N': 2, 'B': 1, 'P': 1, 'M': 1, 'S': 1})
>>> Counter('BANANA')
Counter({'A': 3, 'N': 2, 'B': 1})

Then instead of looping over the letters of the user word, and subtracting 1 from the letter count, you could compare the letter counts directly.

Or ... you could subtract one from the other ...

>>> counts = Counter('NBNAAPMSA')
>>> counts.subtract('BANANA')
>>> counts
Counter({'P': 1, 'M': 1, 'S': 1, 'N': 0, 'B': 0, 'A': 0})
>>>

As long as all values in the counter are non-negative, the word is valid.

>>> all(count >= 0 for count in counts.values())
True

From this, a simpler function can be created.  Left to student.


Search for longest substring in alphabetical order in a given string

You don't have to split a string into an Array, you can work on a String directly.

Note that I have removed you inline onclick handler. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript

How your ES3 code probably should have looked

var main = document.getElementById('main');
main.style.visibility = 'visible';
var enterString = document.getElementById('enterString');
// test string azcbobobegghakl, should yield beggh
function findSubStr() {
  var string = enterString.value;
  var lastSub = '';
  var longestSub = '';
  for (var index = 0; index < string.length; index += 1) {
    var character = string.charAt(index);
    if (character >= lastSub.slice(-1)) {
      lastSub += character;
      if (lastSub.length > longestSub.length) {
        longestSub = lastSub;
      }
    } else {
      lastSub = character;
    }
  }
  if (main.firstChild) {
    main.firstChild.nodeValue = longestSub;
  } else {
    main.appendChild(document.createTextNode(longestSub));
  }
  return false;
}

document.getElementById('search').onclick = findSubStr;
#start {
  top: 25%;
  left: 40%;
  position: absolute;
}
#main {
  top: 50%;
  left: 45%;
  font-size: 1.5em;
  position: absolute;
  visibility: hidden;
}
#enterString {
  color: gray;
}

  <input id="enterString" placeholder="Please enter string">
  <button id="search">Sub-String Search</button>

How it could have looked in ES5

var forEach = Function.prototype.call.bind(Array.prototype.forEach);
var main = document.getElementById('main');
main.style.visibility = 'visible';
var enterString = document.getElementById('enterString');
// test string azcbobobegghakl, should yield beggh
function findSubStr() {
  var lastSub = '';
  var longestSub = '';
  forEach(enterString.value, function(character) {
    if (character >= lastSub.slice(-1)) {
      lastSub += character;
      if (lastSub.length > longestSub.length) {
        longestSub = lastSub;
      }
    } else {
      lastSub = character;
    }
  });
  main.textContent = longestSub;
}

document.getElementById('search').addEventListener('click', findSubStr, false);
#start {
  top: 25%;
  left: 40%;
  position: absolute;
}
#main {
  top: 50%;
  left: 45%;
  font-size: 1.5em;
  position: absolute;
  visibility: hidden;
}
#enterString {
  color: gray;
}

  <input id="enterString" placeholder="Please enter string">
  <button id="search">Sub-String Search</button>

How it could have looked in ES6

const main = document.getElementById('main');
main.style.visibility = 'visible';
const enterString = document.getElementById('enterString');
// test string azcbobobegghakl, should yield beggh
function findSubStr() {
  let lastSub = '';
  let longestSub = '';
  for (let character of enterString.value) {
    if (character >= lastSub.slice(-1)) {
      lastSub += character;
      if (lastSub.length > longestSub.length) {
        longestSub = lastSub;
      }
    } else {
      lastSub = character;
    }
  }
  main.textContent = longestSub;
}

document.getElementById('search').addEventListener('click', findSubStr, false);
#start {
  top: 25%;
  left: 40%;
  position: absolute;
}
#main {
  top: 50%;
  left: 45%;
  font-size: 1.5em;
  position: absolute;
  visibility: hidden;
}
#enterString {
  color: gray;
}

  <input id="enterString" placeholder="Please enter string">
  <button id="search">Sub-String Search</button>

There are surely other ways that you could have tackled this, but essentially there is nothing wrong with your approach.

If you have any particular questions about the changes/code posted, then just comment and I will expand in the areas that most need it.


How should I refactor my image uploader script?

I'd do it something like this. Comments are sprinkled throughout:

#!/usr/bin/env ruby

require 'httparty'
require 'json'
require 'clipboard'

Use constants instead of globals:

CLIENT_ID     = 'xxxxxxxxxxx'
CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
TOKEN_FILE    = '.imgur_token'

Move strings that are subject to change to the top of the file for easy access:

AUTHORIZE_URL = "https://api.imgur.com/oauth2/authorize?client_id=#{ CLIENT_ID }&response_type=pin"
TOKEN_URL = 'https://api.imgur.com/oauth2/token'

def auth_app

I prefer to see separate strings being printed on individual lines, rather than split them with , and let puts do it. It helps the code reflect what the output will be:

  puts 'Follow the link to allow the application access to your account and enter the pin:'
  puts AUTHORIZE_URL

  print 'Pin: '
  pin = STDIN.gets.chomp

I know it's common/popular in Ruby to not use parenthesis to delimit parameters to methods, but I always use them. It visually separates the parameters from the method name, and also forces the correct parsing in ambiguous cases when blocks are also passed in.

Also, I prefer to see the parameters on separate lines from opening/closing braces and brackets when there is more than a trivial array or hash. Again, it's a readability thing:

  response = HTTParty.post(
    TOKEN_URL,
    :body => {
      'client_id'     => CLIENT_ID,
      'client_secret' => CLIENT_SECRET,
      'grant_type'    => 'pin',
      'pin'           => pin
    }
  )

I reversed the order of the test for clarity and simplicity. Rather than test for nil, I test for the "positive" condition, which is a simpler test:

  if response['access_token']
    tokens = {
      'access_token'  => response['access_token'],
      'refresh_token' => response['refresh_token']
    }
    File.write(TOKEN_FILE, tokens.to_json)
  else
    puts 'Authorization failed'
  end
  tokens
end

def refresh_token(refresh_token)

  response = HTTParty.post(
    TOKEN_URL,
    :body => {
      'refresh_token' => refresh_token,
      'client_id'     => CLIENT_ID,
      'client_secret' => CLIENT_SECRET,
      'grant_type'    => 'refresh_token'
    }
  )

  response['access_token']
end

def upload_image(access_token)

  response = HTTParty.post 'https://api.imgur.com/3/upload.json',
  :headers => { 'Authorization' => "Bearer #{access_token}" },
  :body    => { 'image' => Base64.encode64(File.read('imgur.png')) }

  response['data']['link']
end

abort('scrot not found') unless system('scrot -s imgur.png')

if File.exists?(TOKEN_FILE)
  tokens = JSON.parse(File.read(TOKEN_FILE))
else
  tokens = auth_app
end

I do NOT like seeing an assignment inside the conditional test. It's confusing and an error-in-waiting in the future if someone things you meant to do an equality check and "corrects" the code:

link = upload_image(tokens['access_token'])

Again, I reversed the test:

if (!link)
  tokens['access_token'] = refresh_token(tokens['refresh_token'])
  link = upload_image(tokens['access_token'])
  File.write(TOKEN_FILE, tokens.to_json)
end

I reversed the test and assign a message to a string so I can fall through and use a single system invocation:

if link
  response_msg = 'notify-send Upload error'
else
  Clipboard.copy link
  response_msg = 'notify-send Upload complete'
end
system(response_msg)

File.delete('imgur.png')

In general I think your code is pretty good, with just a few tweaks that I'd do. I'd rather write my code as clearly and cleanly as I can, even for trivial stuff, because I never know when I'll need to revisit it. Sometimes I have to tweak something a year or two later, so being able to comprehend what the heck I was thinking quickly is important.


Do not use strlen() in for loops. strlen() walks over the string every time you call it.


Groovy method optimization to build > tokens

Yes, it can be simplified further. I divided the process into three steps and added comments and assertions to make it easier to see how it works.

// Simulate converting a CSV file into a list.
def csv =
'''LEDES98BI V2
LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL
1|20150301|INV-Error_Test1|22
2|20150301|INV-Error_Test1|24
3|20150301|INV-Error_Test2|26
4|20150301|INV-Error_Test2|28'''.split(/\n/)

assert csv == [
    'LEDES98BI V2',
    'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
    '1|20150301|INV-Error_Test1|22',
    '2|20150301|INV-Error_Test1|24',
    '3|20150301|INV-Error_Test2|26',
    '4|20150301|INV-Error_Test2|28']

/*
 * Ignore the first two csv lines and create a list of lists.
 * The inner lists represent the fields of each record.
 */
def invoices = csv[2..-1].collect { it.tokenize('|') }

assert invoices == [
    ['1', '20150301', 'INV-Error_Test1', '22'],
    ['2', '20150301', 'INV-Error_Test1', '24'],
    ['3', '20150301', 'INV-Error_Test2', '26'],
    ['4', '20150301', 'INV-Error_Test2', '28']]

/*
 * Create a Map by grouping each record by its invoice number.
 */
invoices = invoices.groupBy { it[2] }

assert invoices == [
    'INV-Error_Test1':[
        ['1', '20150301', 'INV-Error_Test1', '22'],
        ['2', '20150301', 'INV-Error_Test1', '24']
    ],
    'INV-Error_Test2':[
        ['3', '20150301', 'INV-Error_Test2', '26'],
        ['4', '20150301', 'INV-Error_Test2', '28']
    ]
]

Here's the same program in a condensed form to give you an idea of just how concisely this can be done:

'''LEDES98BI V2
LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL
1|20150301|INV-Error_Test1|22
2|20150301|INV-Error_Test1|24
3|20150301|INV-Error_Test2|26
4|20150301|INV-Error_Test2|28'''
    .split(/\n/)[2..-1]
    .collect { it.tokenize('|') }
    .groupBy { it[2] }


Merging nested tables into a single table

Suspicious code

The variable insideText seems to be used before it's defined.
Is that a global variable? Avoid global variables as much as possible.

This else block seems pointless:

else {
    var insideText = channelTableHeaders.text();
}

Something's suspicious here:

$('table#' + newTableName).html($('
'));

Note that ids must be unique in the document. So the table prefix there is redundant.

Readability

For better readability, put spaces around operators, for example instead of this;

var firstRow = $('
'+newTableName+'
');
$('#'+oldTableName+' .budget-inner-table').each(function() {

Get into the habit to write like this:

var firstRow = $('
' + newTableName + '
');
$('#' + oldTableName + ' .budget-inner-table').each(function() {

The ternary operator can be very useful sometimes.
But this expression is too complex and hard to read:

className = ((insideText.indexOf('-') > 0) ? /- (.*)/.exec(insideText)[1]: insideText.replace(/ /g, '-')).toLowerCase();

It would be better to expand this to its equivalent using if-else:

if (insideText.indexOf('-') > 0) {
    className = /- (.*)/.exec(insideText)[1];
} else {
    className = insideText.replace(/ /g, '-').toLowerCase();
}

Helper methods

You are using this kind of code in at least two places:

... = insideText.replace(/ /g, '-').toLowerCase();
... = headerText.replace(/ /g, '-').toLowerCase()

It would be good to introduce a helper function for this, for example:

function slugify(text) {
    return text.replace(/ /g, '-').toLowerCase();
}

... = slugify(insideText);
... = slugify(headerText);

Misc

Code like this can be simplified:

if (condition) {
    return;
} else {
    // do something
}

Like this:

if (condition) {
    return;
}

// do something


You're misunderstanding how the static keyword works.

The first time it is encountered for a specific variable in the method it defines the $inst variable as null, then checks to see if it is null (it is :p) and then sets it to a new object of that class.

The second time, the static definition isn't used because the static variable has already been defined. It then checks to see if it is null, it isn't, it has already been set to a new object of the class, so it skips the if and returns the object.


Nice implementation.

Here are a couple suggestions

collections.defaultdict

Intead of hashTable[i] = hashTable.get(i, 0) + 1, use collections.defaultdict

charcount = defaultdict(int)

for char in inputStr:
    charcount[char] += 1
actualCharactersInInput = len(inputStr) - charcount[' ']

collections.Counter

Or better yet, use a Counter:

charcount = collections.Counter(inputStr)
actualCharactersInInput = len(inputStr) - charcount[' ']

other

if actualCharactersInInput % 2:
    # odd number of chars
    return sum(count%2 for count in charcount.values()) == 1
else:
    # even number of chars
    return not any(count % 2 for count in charcount.values())


A big ng-repeat to display the progress of builds

If it is performance you are after, the scroll till you drop directive by Angular UI may help.

A common mistake is to throw too many array members inside your DOM via ng-repeat, but you are already limiting your input...

You may consider using custom filter instead and making sure it is fast.


Checking if a Stack is sorted in ascending order

Advice 1

if (s.size() == 1 || s.isEmpty()) {
    return isSorted;
}

You can write more succinctly

if (s.size() < 2) {
    return true;
}

Advice 2

boolean isSorted = true;
if (s.size() == 1 || s.isEmpty()) {
    return isSorted;
}

I suggest you write instead:

if (s.size() == 1 || s.isEmpty()) {
    return true;
}
boolean isSorted = true;

This is a micro-optimization.

Advice 3

Making it generic is not hard. You could demand a type parameter E which extends a Comparable<? super E>

Alternative implementation

I had this in mind:

public static <E extends Comparable<? super E>>
    boolean isSortedV2(Stack<E> stack) {
    if (stack.size() < 2) {
        return true;
    }

    Stack<E> aux = new Stack<>();
    aux.push(stack.pop());

    while (!stack.isEmpty() && stack.peek().compareTo(aux.peek()) >= 0) {
        aux.push(stack.pop());
    }

    boolean sorted = stack.isEmpty();

    // Restore the input stack:
    while (!aux.isEmpty()) {
        stack.push(aux.pop());
    }

    return sorted;
}


Make the tree from a database into a tree of Java

OR-mapping

You fall into the object-relational impedance problem.

RawNode seems to be the same as Node but they are totally different in purpose. This doesn't even change if you use an OR-Mapper like Hibernate.

The following definitions assume you do not want to have an anemic domain model.

RawNode (mapping object)

It provides a concrete representation what came from the database. It is a datastructure only with no logic. It abstracts from the raw resultset where you access columns via column names or indices.

A RawNode is used as a datastructure to communicate with the database through the DAOs in both ways. A RawNode object is a value object. It has no assertion to consistency. You may check the values for consistency (e.g. Java Validation API) and get a list of constraint violations. But the current state of the object may be inconsistent. OR-Mapper can do validations but as they are not able to enforce business rules I would not rely on this.

Equality of these type of objects should be checked either be on all values or on none.

Node (business object)

Equality of a business object is checked on a global unique id.

This is a real business object. It has the assertion to be immutable in the current version. If the non unique values are different but the id is the same you have a different version of the business object. But it is the same object. A business object is ALWAYS consistent in respect to the information it provides. If it is not this is an error. Business objects enforce business rules and consistency when you try to make a change. They will process validation and structural checks to keep the whole system consistent.

Useful assertions

As you remap the business object to the mapping object in the DAO you can be sure that the communication object is consistent as the business object was consistent.

As you remap an unmodified mapping object from the database to a business object you can assume consistency.

Your code

Avoid continue

multiple return, break and continue are not refactring-friendly. They make it hard to extract methods if you want to sub divide a method.

What kind of exception do you expect?

You have all transient datastructure available. Do you expect a NullPointerException because a parent that was defined could not be found? If that is the case you should fix the algorithm that produces that inconsistency and not try to straighten it for further algorithms. The decision to fix the data is depending on your influence on the data holder of course.

Extract methods

Extract the following responsibilities into separate methods:
 1. Build Nodes without parents and children from RawNodes
 2. Build a temporaray map with Node by Id
 3. Set parent child relationship


C String Processing -- magnet link example

Your code is nicely written and you have checked for errors well.  It
is perhaps a little over-commented, many of the comments explaining
the obvious (and hence being just 'noise').

String handling in C is messy and there are always many ways of
achieving the same thing.  There's nothing really wrong with using
snprintf although it can be less efficient than using strcat and
friends.  Since you are using snprintf I'll concentrate on
how you use it and ignore any alternatives.  Someone else might like
to comment on them.

You first append the command line parameter:

if (20 + strlen(argv[1]) >= SIZE)
    die(1, "buffer overflow detected");

bufEnd = buf + snprintf(buf, SIZE, "magnet:?xt=urn:btih:%s", argv[1]);

In this you have traversed argv[1] twice, once in the strlen call
and then again in snprintf.  You could avoid one of these:

const char *limit = buf + sizeof buf;
char *in = buf;

in += snprintf(in, limit-in, "magnet:?xt=urn:btih:%s", argv[1]);
if (in >= limit) {
    die(1, "buffer overflow detected");
}

This is more efficient and also avoids embedding the magic number 20
(embedded constants are usually best avoided).  It uses the fact the
snprintf returns the number of bytes needed for the string it wanted
to print but doesn't overflow the buffer.  So if it returns a number
greater than or equal to the space available , you know there was an
overflow.  I also changed bufEnd to in, used limit to mark the
end of the buffer and added braces around the call to die

Within your while loop you also traverse each string twice.  The
same technique as above can be used to avoid this.  Also your check
for blank lines does not trap lines that contains white-space as well
as a \n.  For that you might use:

const char *s = line + strspn(line, " \t\r\n");
if (*s == '\0')
    continue;


Perl hash mapping SVG elements to content elements

First a general code review, not specific to your “is there a more reliable way”. Later, I will show a superiour solution. But first, a lengthy rant.

I see you have a very unique coding style. This is not good: Every piece of code has two audiences: The computer, and a maintainer. Everybody can write code a computer understands, but writing for humans is an art. Do the maintainer a favour and write understandable, easy code – it could be you! In fact, your coding style slightly reminds me of the horrors of the “perlish coding style” which is neither perlish, nor recommendable, although completely logical. See here for an example. Do not imitate! Your single-space indent isn't recommendable either.

You have a knack for single letter variable names. Heck, you even have a comment explaining what each variable means: my ($t, $d) = @_; # Element, stack. This is completely and utterly silly, just name them my ($element, $stack) already. Code ought to be self-documenting.

Otherwise, comments explaining what you are doing is suspiciously absent.

When opening a file, always include the reason for failure $! in the error message, or use automatic error handling with the autodie pragma.

UTF-8 is not the default encoding for HTML documents. If your document is guaranteed to be encoded in UTF-8, then opening the file with such a layer is the correct thing. Otherwise, you can pass the filename to the parse_file method. You should check if the return value of parse_file is defined. If not, you'll find a reason for failure in $!.

You can shorten the :encoding(UTF-8) layer as :uft8. Technically, they are slightly different. Most importantly, the latter is more relaxed.

I see how you used a recursive solution for your misnomed list sub, which traverses the document. You should comment this more thoroughly – it took me a moment to realize that if (ref $t), then it is a tag, possibly with childs, otherwise a text node.

You have two stacks: @t and $d. Why do you carry one around as an argument, but not the other? Your code is actually quite hard to grok, because different branches in the tree append elements to the same $d arrayref. If I understand your code correctly, then a tree like

   html
    / \
head   body
       / \
    div   div
    / \   /|\
  h1   p p p p
           |
          em

would produce the flattening $d = [qw/html head body div h1 p div p p em p/].

[type type type] Now I see I don't understand the code correctly – you always pop the last element of the stack after traversing into childs. As each child also pops one element of the stack, each node removes itself. I think this is utterly silly, and it would be better to pass each recursion a copy of the stack. Otherwise, comment this shit! Recursion has the advantage that it is easier to reason about code. You loose this advantage when you use mutable variables.

Another problem is that your search is too wide. First, you want the HTML element. Then only the body. Then all divs. Then another one. Then a definition  list or another div. However, you search the whole tree. This is wasteful.

You have a magic number in that code: 5. Which is wrong, because your regexes can only match starting at positions 6 tags deep! Oh, and all those regexes could be combined into one, which would be more efficient. You can also anchor the match at the beginning of the string with the ^ or \A operators, which lets the regex fail faster. You also might want to assert that your path ends with a = (or, if you heed the advice of the next paragraph, with the end of the string $ or \z).

You combine the element path and the text value by concatenating them with an = in between. Later, you use captures to fiddle that value out again. I would rather use an two-element arrayref.

But why even have the @t stack? If you look closely, you'll see that there is a lot repeated code, e.g. regexes in the else path of list, and the if(1) later. You could just do the processing right there, and save that memory.

Why is there an if(1)? If you, for some reason, want to enter a new scope, just use a plain block:

my $x = 1; { my $x = 2 } say $x; # 1

This is Ok on the statement level. On the expression level, you can use a do {BLOCK} to include more complex calculations. This evaluates to the result of the last statement in the block.

Here is a refactoring of your code. It tries to fix many issues mentioned above.

# tested, works
use strict; use warnings; use 5.016;
use autodie;
use Data::Dump;
use HTML::TreeBuilder;

open my $fh, "<:utf8", "svgSpecification.html";
my $tree_builder = HTML::TreeBuilder->new;
my $document = $tree_builder->parse_file($fh) or die $!;

my (%elements, $element);
my $state = 0;
# state = 0: want element
# state = 1: want dt "Content model"
# state = 2: want value

find($document, {
  body => { div => { div => {
    div => { span => sub {
      return unless $state == 0;
      $element = shift->as_trimmed_text =~ s/\pP//gr;
      $state++;
    }},
    dl => {
      dt => sub {
        my $content = shift->as_trimmed_text;
        if ($state == 1 and $content =~ /Content model:/) {
          $state++;
        } elsif ($content =~ /Attributes:/) {
          $state = 0;
        }
      },
      dd => { ul => { li => {
        span => { a => { span => sub {
          return unless $state == 2;
          push @{ $elements{$element} }, shift->as_trimmed_text =~ s/\pP//gr;
        }}},
        a => { span => sub {
          return unless $state == 2;
          push @{ $elements{$element} }, shift->as_trimmed_text =~ s/\pP//gr;
        }},
      }}},
    },
  }}},
});

dd \%elements;

sub find {
  my ($tag, $path) = @_;
  for my $child ($tag->content_list) {
    next unless ref $child; # skip text contents
    next unless my $nextpath = $path->{$child->tag};
    if (ref($nextpath) eq 'CODE') {
      $nextpath->($child);
    } else {
      find($child, $nextpath);
    }
  }
}

As you see, the actual recursion logic is decoupled from your data extraction. The find function is guided by a hashes-of-hashes data structure, which keeps the search space minimal. The formerly implicit state machine is now documented and quite explicit. No unneccessary regexes are used.

One problem with my solution is that the data structure is extremely verbose. I used unusual formatting to battle insanely deep intendation, and it does have a slightly DSL-esque feeling. However, automatic formatting will destroy this.

Of course, such recursion is absolutely silly in this day and age. Modules like Mojo::DOM and Web::Query allow us to use CSS selectors, which makes this a breeze.

# tested, works
use strict; use warnings; use 5.016;
use Data::Dump;
use File::Slurp;
use Mojo::DOM;

my $contents = read_file "svgSpecification.html", { binmode => ":utf8" };
my $dom = Mojo::DOM->new($contents) or die "Can't parse input";

my %elems;

for my $summary ($dom->find('.element-summary')->each) {

  my $name = $summary->at('.element-summary-name')->all_text;
  $name =~ s/[\pP\s]//g; # remove all punctuation and spaces

  # Getting the correct section is tricky, as it is only identified by text.
  # We get around this by filtering manually for the correct text,
  # then continuing with the next sibling node
  my ($child_headline) = grep { $_->all_text =~ /Content model/ } $summary->find('dt')->each;
  next unless $child_headline;

  my @childs = map { $_->all_text =~ s/[\pP\s]//gr } $child_headline->next->find('.element-name')->each;
  push @{ $elems{$name} }, @childs;
}

dd \%elems;

Both of these solutions have the same speed. The 2nd solution will also put elements without childs into the hash, while the first solution ignores them. My scripts were tested with the SVG 1.1 spec on a single page.


Avoid using list as the variable name, because it is a
function in Python.
You don't need to manipulate the list, such
as list.pop() and    list.reverse(). It is inefficient. You can
determine the updated search range with index.
When target is assigned a value not within list, there will be IndexError: list index out of range. It means you didn't handle the case well.

Modified code:

search_list = [1,15,37,53,29,22,31,90,14,6,37,40]
target = 37
start = 0
end = len(search_list)-1
search_list.sort()
print('The sorted list:',search_list)
while start<=end:
    n = int((end + start)/2)
    if target < search_list[n]: # the target is small
        end = n-1
    elif target > search_list[n]: # the target is large
        start = n+1
    elif target == search_list[n]: # the target is found
        print('The item {} has been found at the index {} in the sorted list.'.format(target,n))
        break
else:
    print('The item is not found.')


Not as clean as it could be, some code duplication, and there's also some state mutation in your addMovie function.
Issues

movies.push(movie); mutates the current state object.
checkForDuplicate isn't a clear name, i.e. checking for duplicates is clear, but what is the return value?
Using isMovieDuplicate as the negation of the result from checkForDuplicate is completely counter-intuitive and confusing.
When adding data to current state and computing the next state, a functional state update should really be used.
Ternary logic could be reduced/simplified.
Handle side-effect of persisting to local storage in the component as an "effect" of updating the movies state.

Suggestions

Use a functional state update and shallow copy of current state in order to not mutate current state and correctly enqueue state updates.
Change checkForDuplicate to checkIsDuplicate to make it more clear the return value is likely a boolean (by isXXX naming convention) and will be true if it is a duplicate.
Remove isMovieDuplicate and use checkIsDuplicate directly in conditional test.
Remove the ternary. Assume duplicate failure, only update if not a duplicate and adding to movie array.
Use an useEffect hook to persist to localStorage (and eventually to DB).

Code
const addMovie = (movie: IMovie) => {
  let message = 'is already added to your watchlist.';
  let variant = 'warning';

  if (!checkIsDuplicate(movies, movie)) {
    setMovies(movies => sortMovieList([...movies, movie]));
    message = 'has been added to your watchlist.';
    variant = 'success';
  }

  displaySnackbar(`${movie.original_title} ${message}`, { variant });
};

useEffect(() => {
  addMovieToLocalStorage(movies);
}, [movies]);


Please stop using new and delete.

This is like reading old C code. Modern C++ rarely uses new and practically never uses delete (unless you are building stuff at a very low level). You should be using containers or smart pointers (always question the use of new and if you see a delete you are not using the facilities of the language).

curl_pool(const std::string &root_cert, int size) : m_size(size) {
    m_handles = new CURL*[m_size];
}

virtual ~curl_pool() {
    delete m_handles;
      // Also note this should have been `delete [] m_handles;`
}

This breaks separation of concerns. You are doing memory management and business logic in the same object.

Also because you don't follow the rule of three. Your code is broken and will likely cause crashes.

The best way to fix this is to change m_handles into a vector.

std::vector<CURL*>     m_handles;

Let the vector handle the memory management. You can handle the business logic. PS. You still need to implement the rule of three.

Your connection is dangerious:

    void release() {
        m_pool.m_queue.push(m_index);
    }

What happens if I call release multiple times? I should not be able to break the code from the outside of the interface. Once you have released the handle you should make sure that a subsequent release does nothing and getting a CURL* should return nullptr.

Note I: Calling release() once will break the code. As the object will subsequently be destroyed and call release again.

Note II: Because your object is copyable. Passing it as a parameter will also break the code. As a copy is made and both the original and the new version will eventually be destroyed.

Looks like this should be a movable but not copyable object.


Improving the efficiency of my FizzBuzz algorithm

Your problem is not really a fizz-buzz problem at all, it is a sum-of-sequence problems, and is commonly based/equivalent to the first "Project Euler" challenge

Note: your code has a bug, you are supposed to sum values that are a multiple of either 3, or 5, but you are summing only the multiples of both 3 and 5 (i.e. 15) that are less than the number...

There is an algorithmic/mathematical solution to this which completely removes the need for the iteration at all.

Consider the sum of all the multiples of 3 less than n....:

3 + 6 + 9 + .... + t

where t < n.

The sum of that sequence is called the sum of the Arithmetic Progression.

if you change the sequence to be:

(1 x 3) + (2 x 3) + (3 x 3) + .... + (m * 3)

then you can factor out the 3's, and have:

3 * (1 + 2 + 3 + .... + m)

Now, the '1 + 2 + 3 + .... + m` sequence is what's called a triangular number:

*
* *
* * *
....

* * * .... *

which you can visualize as being half the area of a rectangle, where one side of the rectangle is m, and the other side is m + 1

What is the size of m, well, it is the number of 3 multiples there are:

m = (n - 1) / 3

And, your arithmetic progression sum becomes:

count3s = (n - 1) / 3
sum3s = 3 * count3s * (count3s + 1) / 2

Similarly, the sum of 5's less than n are:

count5s = (n - 1) / 5
sum5s = 5 * count5s * (count5s + 1) / 2

So, the sum of all 3 and 5 multiples less than n is easy, but there's a probem.... if we add the two sums together, it will count the multiples of 15 twice.....

so, the sum of one 15's series is:

count15s = (n - 1) / 15
sum15s = 15 * count15s * (count15s + 1) / 2

if we subtract that, you get the actual sum....

In ruby terms, this can all be reduced to a simple function, and then simple arithmetic... (see ideone ):

def sum_series(base, limit)
    count = (limit - 1) / base
    sum = base * (count * (count + 1)) / 2
end

def fizz_buzz_sum(number)
  sum_series(3, number) + sum_series(5, number) - sum_series(15, number)
end


Keeping Linq's readability (e.g. over goto statements) without sacrificing performance

Focus on optimizing the innermost loop. That's where the performance is lost. In particular try to minimize the number of indirect calls (virtual method, interface and delegate calls).

Your LINQ code has ~60 of those. My variant 1 reduces them to ~20, and my variant 2 to only a handful.

Variant 1:

Very close to linq, but using Array.TrueForAll. About twice as fast are pure linq:

public int Solution_ArrayLinqVersion()
{
    var dividers = Enumerable.Range(1, 20).ToArray();

    int solution = Enumerable
                    .Range(1, int.MaxValue)
                    .First(candidate
                      => Array.TrueForAll(dividers, divider => candidate%divider==0));

    return solution;
}

Variant 2:

Use a loop for the division testing(inner loop) and linq for the outer loop. Almost as fast as no LINQ:

int LinqOutLoopInner()
{
    return Enumerable
        .Range(1, int.MaxValue)
        .First(IsDivisibleBy1to20);
}

static bool IsDivisibleBy1to20(int candidate)
{
    for (int j = 1; j <= 20; j++)
    {
        if (candidate % j != 0)
            return false;
    }
    return true;
}


Dependency injecting or manually instantiating structs in others with go

Version 1 wins hands down.

Because, as you say yourself, go isn't an OO language, you kind of have to treat your entry point (e.g. main func) as your injection point. The main function loads up the global config (usually from flags and/or environment variables), and then passes them on the the various components you'll use (or packages if you like).

Go is a great language to write tests in quickly. If I see code like the second snippet:

func Start() {
    c := config.New()
    // do stuff with c
}

I will rewrite it. The config value is created in that function, so it's safe to assume that this function will need to check the config values. How am I going to reliably unit-test the package, if I can't pass in all possible combinations of config?

Sure, I could write a ton of code setting/unsetting environment variables, and call this Start function over and over again, but am I really unit-testing the code then? Surely, if the config package is broken, then all other tests become unreliable to say the least. What about a change to the config package? How awful it'd be to rewrite all the tests just to make sure the changes to the config are reflected there, too? It's going to be a PITA, and an enormous waste of time and resources.

PS: code like config.NewConfig() will also get rewritten by a lot of gophers. This is referred to as stuttering code (read this).

I now I'm getting config, because I'm using the config package. The function name New is enough information, surely. config.NewConfig reads like "from config, get me new config" as opposed to "hey, config, give me a new value".
This might be personal preference, but I generally find it better to use the function Get for config, rather than New. Config is, IMO, an immutable set of data, not something that does something, not something that needs constructing, it needs to be fetched/loaded. For that reason, I'd write config.Get() and that func would looks something like this:

package config

// Conf - global config struct
type Conf struct {
    App // config per package
}

// App - config specific to the App package
type App struct {
    Locale string
}

func Get() (*Conf, error) {
    // get values, return...
}


Here's what I would start with:

import sys
import re
import urllib2
import webbrowser

from bs4 import BeautifulSoup

def get_episodes(url):
    print '[*] Working...'

    soup = BeautifulSoup(urllib2.urlopen(url))
    links = {}

    for table in soup.find_all('table', width='100%'):
        for a in table.find_all('a', target='_blank'):
            for li in table.find_all('li', class_='current-rating'):
                match = re.search(r'Version (\d+)', a.get_text())

                if match:
                    number = match.group(1)
                    links[number] = 'http://www.1channel.ch' + a['href']

                    print '({}) - {}\n'.format(number, li.get_text())

    return links

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print '1channel.py -show episode#'
        sys.exit()
    elif sys.argv[1] == '-breakingbad':
        url = 'tv-4128-Breaking-Bad/season-4-episode-'
    elif sys.argv[1] == '-walkingdead':
        url = 'tv-2490619-The-Walking-Dead/season-3-episode-'
    elif sys.argv[1] == '-poi':
        url = 'tv-2727923-Person-of-Interest/season-2-episode-'
    else:
        sys.exit()

    try:
        episodes = get_episodes('http://www.1channel.ch/' + url + sys.argv[2])
    except urllib2.HTTPError:
        print '- HTTP Error!'
        sys.exit(0)
    except urllib2.URLError:
        print '- Connection Faliure!'
        sys.exit(0)

    number = int(raw_input('>>> '))

    if number in episodes:
        webbrowser.open(episodes[number])
    else:
        print 'Episode does not exist!'
        sys.exit(0)

Keep functions simple and (generally) single-purpose. Have them do one simple task.
Keep your code DRY. If you catch yourself writing the same code over and over, make a function for the general case and just fill in the variables.
BeautifulSoup4 uses underscores instead of camel case, so findAll becomes find_all.

I haven't tested this code either, but it should work.


Your code is very procedural, with branching and variables and things we see in code... and bad queries. SQL likes sets/tables.

You're lucky your fiscal quarters line up with the "normal calendar" - every company I worked for had different periods for their fiscal calendar.

Since I worked with a data warehouse, one of the first things I do when I come on board in a company where I need to work with time data, is look at their databases to see if they have a table somewhere that contains their fiscal calendars. And if they don't have one, I simply create it:

create table dbo.FiscalCalendars (
     _Id int not null identity(1,1)
    ,_DateInserted datetime not null
    ,_DateUpdated datetime null
    ,CalendarDate date not null
    ,CalendarDayOfWeek int not null
    ,CalendarDayOfMonth int not null
    ,CalendarDayOfYear int not null
    ,CalendarWeekOfYear int not null
    ,CalendarMonthOfYear int not null
    ,CalendarYear int not null
    ,FiscalDayOfWeek int not null
    ,FiscalDayOfMonth int not null
    ,FiscalDayOfQuarter int not null
    ,FiscalDayOfYear int not null
    ,FiscalWeekOfMonth int not null
    ,FiscalWeekOfQuarter int not null
    ,FiscalWeekOfYear int not null
    ,FiscalMonthOfQuarter int not null
    ,FiscalMonthOfYear int not null
    ,FiscalQuarterOfYear int not null
    ,FiscalYear int not null
    ,constraint PK_FiscalCalendars primary key clustered (_Id asc)
    ,constraint NK_FiscalCalendars unique (CalendarDate)
);

With a table that stores everything you've always wanted to know about every date you ever need to know anything about, selecting the last 4 quarters becomes... simple:

declare @referenceDate as date;
set @referenceDate = getdate();

with quarters as (
    select
         t.FiscalYear
        ,t.FiscalQuarterOfYear
        ,min(t.CalendarDate) StartDate
        ,max(t.CalendarDate) EndDate
    from dbo.FiscalCalendars t
    group by
         t.FiscalYear
        ,t.FiscalQuarterOfYear
)
select top 4
     q.FiscalYear
    ,q.FiscalQuarterOfYear
    ,q.StartDate
    ,q.EndDate
from quarters q
where q.StartDate <= @referenceDate
order by
     q.EndDate desc

The hardest part is ...populating that time table, not querying it.

Now, to make the above return a column for each quarter, you'll need to pivot it. But if you're working (and thinking) in sets (LINQ works off IEnumerable<T> after all), you won't need to do this.

Speaking of LINQ... assuming you have the time table mapped to FiscalCalendar entities, you could query it like this:

var referenceDate = DateTime.Today;
var quarters = context.FiscalCalendars
                      .GroupBy(t => new { t.FiscalYear, t.FiscalQuarterOfYear })
                      .Select(g => new {
                                         FiscalYear = g.Key.FiscalYear,
                                         FiscalQuarterOfYear = g.Key.FiscalQuarterOfYear,
                                         StartDate = g.Min(q => q.CalendarDate),
                                         EndDate = g.Max(q => q.CalendarDate)
                                        })
                      .Where(q => q.StartDate <= referenceDate))
                      .OrderByDescending(q => q.EndDate)
                      //.Skip(1) // skip current quarter?
                      .Take(4);

That would give you an IQueryable<T> where T is an anonymous type with int FiscalYear, int FiscalQuarterOfYear, DateTime StartDate and DateTime EndDate properties.


Get a value from a list in Sharepoint 2010

Naming conventions:

As per the Microsoft guidelines, use PascalCase for method names. Read more here: Capitalization Conventions. Your method names will become GetValueFromList and CleanValue.

Object Initialization and Format String:

Use the String.Format method to build your string, don't use concatenation. The building of your CAML query will be:

var spQuery = new SPQuery
{
    Query = String.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", matchColumnName , valueToMatch)
};

More reading on Object and Collection Initializers.

Get SharePoint list:

Don't blindly use web.Lists["listName"], it depends on the number of lists you have in your environment what call you should use.

Using web.Lists["listName"], SharePoint will look for all lists in the current web-object and fetch all metadata from them. Then it compares the name you provided and return the correct list.

And SPWeb.GetList("url/to/list") will make a call to the DB for each list for which info is needed.

If you have a lot of lists (thousands), use the second method, otherwise the first will normally score better. Also, this depends on the performance of your hardware. But in general, I tend to avoid the indexer (using the second method or even web.TryGetList("listTitle")).

The foreach loop:

You have this piece of code:

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}

Why have a loop if you will return on the first item? If you only want to return the first entry, use the SPQuery.RowLimit property and set it to 1:

var spQuery = new SPQuery
{
    Query = String.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", matchColumnName , valueToMatch),
    RowLimit = 1
};

Following code:

SPListItemCollection results = oList.GetItems(oQuery);

if (results.Count == 0)
    return "";

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}
return "";

will now look like this:

var results = list.GetItems(spQuery);
if (results.Count == 0)
    return "";

var item = results[0];
return CleanValue(item[returnColumnName].ToString());

Or in one return statement:

return results.Count > 0 ? CleanValue(item[returnColumnName].ToString()) : String.Empty;

Nitpicking:

Variable names:

theList should be replaced by listName or listTitle.
Avoid adding the o before the names, use spList and spQuery instead.


Is this an acceptable implementation of the Adapter pattern?

This is not an implementation of the Adapter pattern.

What is the Adapter pattern trying to solve?

Lets' say I have :

public interface UKPlug {

    int getPin1();

    int getPin2();

    int getPin3();
}

public class UKSocketImpl {

    public void plugin(UKPlug plug) {

        if (plug.getPin1() == -plug.getPin2() && plug.getPin3() == 0) {
            System.out.println(plug.toString() + " -> UKSocket");
        }

    }
}

A UK socket, that accepts UKPlugs. The socket is the client in this scenario, which makes use of an interface (UKPlug)

Now I want to plug in my device, but it has a USPlug :

import java.math.BigInteger;

public class USPlugImpl {

    public BigInteger getPin1() {
        return BigInteger.TEN;
    }

    public BigInteger getPin2() {
        return BigInteger.TEN.negate();
    }

    @Override
    public String toString() {
        return "USPlug";
    }
}

This is where we can write an Adapter class to adapt our Adaptee (USPlugImpl) :

package adapter.improved;

public class USUKAdapter implements UKPlug {

    private final USPlugImpl plug;

    public USUKAdapter(USPlugImpl plug) {
        this.plug = plug;
    }

    @Override
    public int getPin1() {
        return plug.getPin1().intValue();
    }

    @Override
    public int getPin2() {
        return plug.getPin2().intValue();
    }

    @Override
    public int getPin3() {
        return 0;
    }

    @Override
    public String toString() {
        return plug.toString() + " adapted to UKPlug";
    }
}

This is what the Adapter class does :

it implements the needed interface
it does so by delegating to methods of the Adaptee instance (the USPlug), or by supplying some default behaviour.
Both the USPlug as the UKSocket are unaware of the use of an Adapter.

example use :

private void plugIn(UKSocketImpl ukSocket, USPlugImpl usPlug) {
    ukSocket.plugin(new USUKAdapter(usPlug));
}

How do your Adapter classes differ?

They implement an interface, but not one that is used by the Client
The UKPlug and USPlug classes have a reference to an adapter. What if these were classes from a 3rd party library, and you couldn't add members to them? That's what the Adapter pattern solves.

Final style note : don't use '_' in method names.


Interactive complete Brainfuck Interpreter

All in all this looks good to me. I would make 2 changes

bracket_map

The code to assemble this map can be more clear in it's own function.

+ and -

v = data[data_index] - 1
if v < 0:
    v = 255
data[data_index] = v

can be easily replaced by

data[data_index] = (data[data_index] - 1) % 256

Same goes for the + operation


Python - use a list of names to find exact match in pandas column containing emails

It sounds like the thing you're trying to do is somewhat insane. With 40k first names to search for, false positives are inevitable. At the same time, with only 40k names, false negatives are also inevitable. People's names are untidy; hopefully you have plans to accommodate. Even when you get correct matches for a "first" and "last" name, as your example email shows, there's no guarantee that they'll be the first and last names of the same person.
Maybe someone with experience in natural-language-processing AI would be able to solve your problem in a robust way. More likely you've resigned yourself to a solution that simply isn't robust. You still pretty definitely need case-sensitivity and "whole word" matching.
I'm not convinced by the example you give of a false positive. The pandas function you're using is regex-based. r'tero' does not match 't er o'; it does match 'interoperability'. With name lists as long as you're using, it seems more likely that you over-looked some other match in the email in question. I would kinda expect just a few of the names to be responsible for the majority of false-positives; outputting the matched text will help you identify them.

Case-sensitive regex matching should be the default.
I think \b...\b as a regex pattern will give the kind of "whole word" matching you need.
pandas.extract will do the capturing.

Given the size of your datasets, you may be a bit concerned with the performance. Or you may not, it's up to you.
I haven't tested this at all:
# Import datasets and create lists/variables
import pandas as pd
from pandas import ExcelWriter
from typing import Iterable

# Document, sheet, and column names:
names_source_file = 'names.xlsx'
first_names_sheet = 'Alle Navne'
first_names_column = 'Names'
last_names_sheet = 'Frie Efternavne'
last_names_column = 'Frie Efternavne'
subject_file = 'Entreprise Beskeder.xlsx'
subject_sheet = 'dataark'
subject_column = 'Besked'
output_first_name = 'Navner'
output_last_name = 'Efternavner'
output_file = 'PythonExport.xlsx'

# Build (very large!) search patterns:
first_names_df = pd.read_excel(names_file, sheet_name=first_names_sheet)
first_names: Iterable[str] = namesdf[first_names_column]
first_names_regex = '''\b{}\b'''.format('|'.join(first_names))
last_names_df = pd.read_excel(names_file, sheet_name=last_names_sheet)
last_names: Iterable[str] = lastnamesdf[last_names_column]
last_names_regex = '''\b{}\b'''.format('|'.join(last_names))

# Import dataset and drop NULLS:
data_frame = pd.read_excel(subject_file, sheet_name=subject_sheet)
data_frame[subject_column].dropna(inplace=True)

# Add columns for found first and last names:
data_frame[output_first_name] = data_frame[subject_column].str.extract(
    first_names_regex,
    expand=False
)
data_frame[output_last_name] = data_frame[subject_column].str.extract(
    last_names_regex,
    expand=False
)

# Save the result
writer = ExcelWriter(output_file)
df.to_excel(writer)
writer.save()

One obvious problem that I still haven't talked about is that there may be multiple name matches in a given subject. Assuming that you care about multiple matches, you can probably do something with extractall.


Text representation for numbers with python

rewrite the function a little bit cleaner

A way to achieve it, would be to divide your code into simpler functions, for instance:

lst = [0] * 3
for i in xrange(3):
    div = 10 ** (2 - i)
    lst[i] = num / div
    num %= div

Could be a simple function call:

lst = split_decimals(num)

(btw the name lst is not a very explicit...)

  Maybe decrease a number of branches somehow

To clean your branching, I would advise to make a function that treats one part of the problem: numbers between 1 and 99, with a function under_hundred_as_word for instance.

Better variable names might also help the reader to understand your code.

After some further refactoring, this is what I came with:

units = [
    'zero', 'one', 'two', 'three',
    'four', 'five', 'six',
    'seven', 'eight', 'nine',
]
tens = [
    '', '', 'twenty', 'thirty', 'forty',
    'fifty', 'sixty', 'seventy',
    'eighty', 'ninety',
]

hundred_exceptions = {
        10: 'ten',
        11: 'eleven',
        12: 'twelve',
        13: 'thirteen',
        15: 'fifteen',
        18: 'eighteen',
}

def under_hundred_as_word(num):
    assert 0 < num < 100

    unit = num % 10
    ten = num / 10
    if ten == 0:
        return units[unit]
    elif ten == 1:
        if num in hundred_exceptions:
            return hundred_exceptions[num]
        else:
            return units[unit] + 'teen'
    else:
        if unit:
            return tens[ten] + '-' + units[unit]
        else:
            return tens[ten]

def make_word(num):
    assert 0 < num <= 1000
    if num == 1000:
        return 'one thousand'

    parts = []

    # two last digits
    if num % 100:
        parts.insert(0, under_hundred_as_word(num % 100))

    # hundred digit
    hundreds = (num / 100) % 10
    if hundreds:
        hundreds = units[hundreds] + ' hundred'
        parts.insert(0, hundreds)

    return ' and '.join(parts)

for x in xrange(1, 1000 + 1):
    print x, make_word(x)

It can be easily modified to print numbers greater than 1000.


one of the great things about Clojure is the ability to seperate code into concerns and then compose them. This really helps spot reusable parts and lets you build code in smaller independently testable parts.

the parts I see are:

given a sequence of number produce the next one

partition-all the seq into groups of consecutive numbers
for each group of consecutive numbers say how many there are (map say list-o-groups)
flatten the result into one list. but really you should use mapcat in the previous step and skip this step.

apply the the result to the same function (the iterate function)
take as many of these as you need


$('#slider_1').click( function change_slider(){

You don't have to name the function when you pass it to an event handler.

$('#slider_1').click( function() {

An anonymous function is sufficient.

$('#slider_1').addClass('current_tab').siblings('.current_tab').removeClass('current_tab')

This seems to be missing a ; at the end.

But neither of those is what you asked:

var change_slider = function() {
  $(this).addClass('current_tab').siblings('.current_tab').removeClass('current_tab');
  $('#cart_'+$(this).attr('id')).show().siblings().hide();
  $('#cart_'+$(this).attr('id')).addClass('current').siblings('.current').removeClass('current');
  numItems = $('.current .cart_slide').length;
  sliderwidth = numItems * swidth;
  $('.cart_slides').css({'left': 0, 'width': sliderwidth});
  numloop = numItems-1;
  last_slide = sliderwidth - swidth;
  i=0;
};

$('#slider_1').click( change_slider );
$('#slider_2').click( change_slider );
$('#slider_3').click( change_slider );
$('#slider_4').click( change_slider );
$('#slider_5').click( change_slider );
$('#slider_6').click( change_slider );

The basic idea is that we assign an anonymous function to a variable and then pass that to the various click handlers.  In order to make this work, we make use of the fact that when the function is called, it knows what object called it:  this.

  $(this).addClass('current_tab').siblings('.current_tab').removeClass('current_tab');
  $('#cart_'+$(this).attr('id')).show().siblings().hide();
  $('#cart_'+$(this).attr('id')).addClass('current').siblings('.current').removeClass('current');

In the first line, we can access our slider object directly.  The cart_slider is a little more complicated, so we rely on the fact that it just adds a prefix to the id of the slider object.  We get the id by calling $(this).attr('id') and use string concatenation to form the id of the cart_slider.

Note:  I haven't tried to run this.  Apologies in advance if I missed the syntax somewhere.


Max difference between two array elements

TestData

I don't know if the test data is given to you, but it is not the most useful for verifying the such that larger element appears after the smaller number condition.  Since 100 is the last value, any code that finds 100 as the largest number and subtracts the lowest number will find the correct answer.  If the test data was

int arr[] = {100, 2, 6, 3, 80};

it would be a better test.  The correct answer is now 78 because we ignore the 100 as it is before the 2.

NOTE: For the above data, the current code returns -2147483547 as the difference because we find 100 at the 0th element and never find a min value so the max difference is 100 - INT_MAX.

The code as written is \$O(n)\$ as when considering such things we don't worry about multiples of N, so iterating through the list twice \$O(2n)\$ is, for complexity comparisons, the same as \$O(n)\$.

The bad news is that the algorithm is flawed.

Find the largest number,
Find the largest difference between the largest number and all the numbers before it

fails if the largest number is first (as above), but also if there is a larger difference after the largest number

int arr[] = {50, 60, 100, 10, 70};

the code as written returns 50 but the correct answer 60 (70 - 10).

The following should give the correct answer.

#include <stdio.h>

int maxDiff(int* arr, int len);

int main(void)
{
    int arr[] = { 50, 60, 100, 10, 70 };
    int len = sizeof(arr) / sizeof(int);
    int max_diff = maxDiff(arr, len);
    printf(" max diff is %d \n ", max_diff);
}

int maxDiff(int* arr, int len)
{
    if (arr == NULL || len == 0)
    {
        return -1;
    }
    int prev = arr[0];
    int maxDiff = 0;
    for (int i = 1; i < len; ++i)
    {
        if (arr[i] > prev)
        {
            int newDiff = arr[i] - prev;
            if (newDiff > maxDiff)
            {
                maxDiff = newDiff;
            }
        }
        else
        {
            prev = arr[i];
        }
    }
    return maxDiff;
}


application = webapp.WSGIApplication([  ('/page/([0-9]+)', PageHandler), ])

I'd put the list of urls as a global constant, I think that would make it easier to read.

  class PageHandler(BaseHandler):
      def get(self, file_id):
        page = Page.get_by_id(long(file_id))
        if not page:

If you are checking against None here, I'd  use if page is None:

  self.error(404)
  return

I'd use else instead of returning here

self.render_template(file_id+'.html', {
    'body': page.body,
})


Script to pick random answers for a vocabulary quiz

You can skip animations from elements using JQuery stop. This method is appled to a Jquery selector, and it will stop the animation running on it.

So using it, you can force to finish all the animations related to the question container after firing the click


This won't solve the long run times of your code if the issue is the EntireRow.Delete method.  I assume you still want those rows deleted and stackoverflow would be the place to get a workaround or solution.

That being said your code should be reviewed.

Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

Never use Select unless you are making some macro to find a range for the user. Use Rows("1:1").Insert ....  Making these concatenations should be priority #1 after recording a macro.  Also you are not declaring the parent of Rows.  ActiveSheet is implicitly the parent but Rows is already nested in a With statment.  Just put the period .Rows("1:1")... to make it explicit.

With ActiveSheet

As you said, this is being called as a sub function.  If your project grows to include more sheets, assuming ActiveSheet is the sheet you want to manipulate won't be safe.  Any Sub not meant to be an outermost Sub should not use ActiveSheet, ActiveBook, ActiveCell, or Selection.  Sheets, books, and ranges should be passed as an argument.

This variable isn't being used. Delete it.

Dim rng As Range

You get the last row by going to the bottom of the sheet and iterating up until you find the bottom of your data.

lastRow = .Cells(.Rows.Count, 2).End(xlUp).Row

Instead get the bottom of the range containing data:

lastRow = .UsedRange.Rows.Count

Now there is the general steps that your macro takes.  It operates like user interaction, which is usually not the best way to approach it.  The steps you take:

AutoFilter the range

only rows with columns "C" and "F" are visible

Delete all visible rows in the range

It makes perfect sense in a user interface side but from a programming side is unnecessarily indirect.  Rows to delete are marked by remaining visible and then deleted.  What if something else has marked rows as invisible?  I would suggest iterating over all rows in the range and deleting those that should be.

Public Sub DeleteRows()
    ' ActiveSheet or Range("B2:F" & lastRow) should be passed
    Dim sheet as Worksheet
    set sheet = ActiveSheet

    Dim lastRow As Long
    lastRow = sheet.UsedRange.Rows.Count

    Dim table as Range
    set table = sheet.Range("B2:F" & lastRow)

    Dim l as Long
    For l = lastRow to 1 step -1

        If ShouldBeDeleted(table.rows(l)) Then

            table.rows(l).EntireRow.Delete shift:=xlUp

        End If

    Next l

    ' These should be in the outside Sub
    sheet.Range("1:1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    MsgBox Format(Time - start, "hh:mm:ss")

End Sub
Function ShouldBeDeleted(row_range as Range) as Boolean

    ShouldBeDeleted = (row_range.cells(1, 2) = 0 And row_range.cells(1, 5) = 0)

End Function

Pulling bits out like ShouldBeDeleted might seem verbose but there is a better name for it.  There is something special about those rows, and I would rename the function IsX where X describes what those rows are.  Also, columns "C" and "F" seem to be special for your worksheet.  If they are so, declare them as constants

Const IMPORTANT_COL_1 As String = "C"
Const IMPORTANT_COL_2 As String = "F"

Sorting Optimizations

If sorting the rows of the table is allowed and 0 is the minimum then you could sort the table and only iterate over the rows that you need to delete.

Public Sub DeleteRows(table as Range)

    Dim lastRow As Long
    lastRow = table.Rows.Count

    With table.Parent.Sort

        .SortFields.Clear
        .SortFields.Add key:=table.Range(IMPORTANT_COL_1 & ":" & IMPORTANT_COL_1)
        .SortFields.Add key:=table.Range(IMPORTANT_COL_2 & ":" & IMPORTANT_COL_2)
        .SetRange table
        .Apply

    End With

    Dim botRow as Long
    botRow = 1

    While ShouldBeDeleted(table.rows(botRow))
        botRow = botRow + 1
    Wend

    table.range("1:" & botRow).Delete shift:=xlUP

End Sub


You're not always using var in what I think of as a good way. We should only use the keyword when it's obvious what type the variable is. Consider this line.

Task<bool>[] tasks = new Task<bool>[sites.Count()];

It's completely obvious what tasks is because you're newing it up right there on that line. There's no reason not to simplify by using var.

But here, you have the opposite problem.

var response = client.Execute(request);

It is not obvious what the return type is, so you shouldn't be using var.


Efficiency and length of functions when perfomring similar tasks to classes and IDs

Use toggleClass instead of:

if ($(this).hasClass('active')) {
    $(this).removeClass();
// When in initial state, add active class
} else {
    $(this).addClass('active');
}

You can map the event handlers for multiple classes:

['about', 'contact', ...].map(cls => {$(`.${cls} a`).click(...)}


Unit test for a CreateUser() method using JustMock lite

I think you are not testing everything. The API should create a user but the only thing you assert is the ActionResult

Assert.AreEqual(actionResult.RouteValues["Action"], "Index");

So the method runs and the result is correct. But has it actually created a new user and add it to the repository? How about this operation?

var opStatus = _UserRepository.AddUser(newUser);

IMO you should also check the repository to see whether the API correctly added the new user to it. I don't know what interfaces the UserRepository might implement but for this

var UserRepository = Mock.Create<IUserRepository>();

assertions like these ones could be appropriate (just examples) or anything else that makes sense for the repository.

Assert.AreEqual(1, UserRepository.Count);
Assert.AreEqual(referenceUser, UserRepository.GetUser(abc));

What if someone had a problem with the repository and commented it out and actually forgot to add #if DEBUG or made any other changes ignoring the status-code?

public ActionResult Create(UserViewModel item)
{
    if (ModelState.IsValid)
    {
        var newUser = Mapper.Map<UserViewModel, User>(item);
        //Populates file name and content type to newUser
        UserHelper.PopulateFile(item.File, newUser);

        newUser.UserId = (int)_membershipService.GetUser().ProviderUserKey;

        // I temporarily disabled the repository because I didn't work for me.
        //var opStatus = _UserRepository.AddUser(newUser);
        //if (!opStatus.Status)
        //    throw new System.Web.Http.HttpResponseException(new   HttpResponseMessage(HttpStatusCode.InternalServerError));

        return RedirectToAction("Index");
    }
    else
        return View(item);
}

The test would still pass but the result would be wrong.


Debounce function that limits the rate a callback is triggered. Which implementation is better, and why?

I think the solution with the timeout variable is far more clear, and avoids arithmetic operations. However, your implementation has some odd behaviours. That is, using debounce with a high frequency will postpone the callback indefinitely.
const debounce = (func, interval) => {
    let timeout = null;
    return ()=>{
        if (timeout) return undefined;
        timeout = setTimeout( ()=>timeout=null, interval)
        return func();
    }
}

As an alternative, I propose this. Using this code, the timeout is only set when an actual function call occurs.


Redirecting all pages under a certain directory to a single file

It seems you're looking for a negative lookahead:
path starting with /dir/ and not followed by new$:

RedirectMatch 301 ^/dir/(?!new$) http://example.com/dir/new


Do not put the sentinel characters in every iteration. Set them before the loop, and after a successful reallocation.
Also, (*line)[*capacity - 2] = 0; is redundant. Indeed, if (*line)[*capacity - 1] remains 1 we don't care, and if it turns to 0 then (*line)[*capacity - 2] has been overwritten anyway.

goto is totally unwarranted. break works very well.

Do not handle fgets failures inside the loop. Break immediately.

Using position as an index, rather than the pointer, seems cleaner. Consider
  fgets(*line + position, *capacity - position, stream)

etc.


bcode = []
stack = []
regs = []
sp = 0
bcd = []

Global variables like this are frowned upon. To be pythonic you should really put them a in a class or something.

'''
Instructions
'''
OP_EOP = 0
OP_EOI = 1
OP_PUSH = 2
OP_PRINT = 3

def load_program(f2o):

f2o? What in the world is that?

    f = open(f2o, "r")
    f2 = f.read()

My recollection of RPython is that it doesn't support this pattern. Are you sure it works in RPython?

    f2 = f2.replace("\n"," ")
    bcode = f2.split(" ")
    i = 0
    for item in bcode:
        item = int(item, 16)
        bcd.append(item)
        i += 1

What are you ding with i? You count it, but don't do anything with the value that you count.

    return bcd

# VM action functions
def do_EOP():
    print "End of Program"

def do_PUSH(ba, b, ip):

ba? b? pick variables names that let me know what they represent.

    i = 2
    loop = 1
    cb = len(b)

None of these last three lines do anything. They set variables local to the function when then gets thrown away.

    stack.insert(0, ba)

For a stack, we usually use the end of the list as the top of stack. That way you can simply append() and pop() the list. Its rather inefficient to insert at the begining.

def do_PRINT(stack):
    stk = stack[0].split(" ")
    for item in stk:
        print unichr(int(item))

def execute_program(b):
    ip = 0
    sp = 0
    loop = 1

Use True and False for true/false.

    cb = len(b)
    while (loop):

You don't need the ( or )

        if ip < cb:
            bc = b[ip]
            if bc == OP_PUSH:
                if bc != OP_EOI:

Are you expecting bc to change between those two lines?

                    ba = str(b[ip + 1])

You read the next piece of bytecode to push it, but you don't skip increment ip to account for it.

                    do_PUSH(ba, b, ip)

            elif bc == OP_PRINT:
                do_PRINT(stack)
            ip += 1
        else:
            loop = 0

def run_program(f):
    b = load_program(f)
    execute_program(b)

def main(argv):
    run_program(argv[1])
    return 0

def target(*args):
    return main, None

if __name__ == '__main__':
    import sys
    main(sys.argv)

The biggest issue with your code is that you have a lot of code that can't possibly do anything useful. Reading me leaves me to wonder if you just haven't cleaned up your code or are confused about the code actually works.


Sort files in a given folders and provide as a list

Docstrings

You should include a docstring at the beginning of every function, class, and module you write. This will allow documentation to identify what your code is supposed to do. This also helps other readers understand how your code works. I see that you already have a couple for your functions, but stay consistent.

Parameter Names

Parameter names should be descriptive enough to be able to tell what should be passed. While l might be obvious to some programmers as an iterable, to others it might not. Since you're passing a list, renaming it to list_ (to avoid using reserved word list) makes it more obvious what you're passing, and accepting.

Constant Variables

When you have a constant in your program, it should be UPPER_CASE to identify it as such.

Code Reduction

You want as little code as possible in your program. So, instead of:

def subject_list_fastafiles():
    """ Method Docstring """
    subject_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))])
    return subject_fastafiles

def query_list_fastafiles():
    """ Method Docstring """
    query_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(query_path) if os.path.isfile(os.path.join(query_path, fastafile))])
    return query_fastafiles

def filter_files_ending_with_one(sorted_files):
    """ Method Docstring """
    files_end_with_one = [name for name in subject_fastafiles if name[-1].isdigit() and not name[-2].isdigit() == 1]
    return files_end_with_one

You can simply return the function call, instead of assigning it to a variable and returning the variable, like so:

def subject_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(SUBJECT_PATH) if os.path.isfile(os.path.join(SUBJECT_PATH, fastafile))])

def query_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(QUERY_PATH) if os.path.isfile(os.path.join(QUERY_PATH, fastafile))])

def filter_files_ending_with_one():
    """
    The function filters the files end with 1
    """
    return [name for name in SUBJECT_FASTAFILES if name[-1].isdigit() and not name[-2].isdigit() == 1]

Main Guard

This is an excerpt from this fabulous StackOverflow answer.

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed.  Functions and classes that are defined are, well, defined, but none of their code gets run.  Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block.  __name__ is a built-in variable which evaluates to the name of the current module.  However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__".  Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won't get run as the condition is not met.

Updated Code

"""
Module Docstring (A description of your program goes here)
"""

import os
import re

SUBJECT_PATH = "/Users/catuf/Desktop/subject_fastafiles/"
QUERY_PATH = "/Users/catuf/Desktop/query_fastafiles"

def sorted_nicely(list_):
    """
    Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(list_, key=alphanum_key)

def subject_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(SUBJECT_PATH) if os.path.isfile(os.path.join(SUBJECT_PATH, fastafile))])

def query_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(QUERY_PATH) if os.path.isfile(os.path.join(QUERY_PATH, fastafile))])

def filter_files_ending_with_one():
    """
    The function filters the files end with 1
    """
    return [name for name in SUBJECT_FASTAFILES if name[-1].isdigit() and not name[-2].isdigit() == 1]

if __name__ == '__main__':

    SUBJECT_FASTAFILES = subject_list_fastafiles()
    QUERY_FASTAFILES = query_list_fastafiles()
    SUBJECT_FILES_ENDING_WITH_ONE = filter_files_ending_with_one()


This kind of trace logging could conceivably be solved with an Aspect.

Aspect oriented programming allows you to add boilerplate-style code to your program without actually writing the boilerplate inline. You could, for example, add an aspect than logged a method name and parameters every time a program entered a method, and then logged the method name and return value every time a method returned.

Of course, you don't necessarily want to log every method. Instead, most aspect frameworks allow you to indicate which code you want the boilerplate added to.

I don't know enough about C# to recommend a specific aspect-oriented framework to use, or appropriate syntax for you. Sorry.


I think your approach is fine, and it's easy to understand. I have just a few improvement ideas:

A more natural ordering of the method parameters might be: source, token, length, filler
Instead of Integer, int should be enough and shorter
Move the closure in collect to its own method
Do you really need the static final String declaration? Why not use simply def?
Do you really need the type declarations in the signature? You could omit them, and it will be still quite clear
The brackets around the multiplication are unnecessary in

line + (filler * (length - line.size()))

Suggested implementation

Putting the above suggestions together:

def adjustLineLength = { line, length, filler ->
    if (line.size() > length) {
        line.substring(0, length)
    } else if (line.size() < length) {
        line + filler * (length - line.size())
    } else {
        line
    }
}

def adjustTextLength = { source, token, length, filler ->
    source
    .tokenize(token)
    .collect { adjustLineLength(it, length, filler) }
    .join(token)
}


A graph representation of Adjacent Matrix in Python

Use third party libraries if possible

Almost anytime you want to do something, you probably want to use someone else's code to do it.  In this case, whenever you're working with graphs in Python, you probably want to use NetworkX.

Then your code is as simple as this (requires scipy):

import networkx as nx

g = nx.Graph([(1, 2), (2, 3), (1, 3)])
print nx.adjacency_matrix(g)
g.add_edge(3, 3)
print nx.adjacency_matrix(g)

Friendlier interface

It seems unnecessarily cumbersome to have to explicitly initialize an empty Graph this way: g = Graph([]).  I think a better implementation would be something like

class Graph(object):

    def __init__(self, edge_list=None):
        self.edge_list = edge_list if edge_list is not None else []

Similarly, I think the parameters for add_edge could use work. For one, it isn't a list of edges that you're passing it - it is a single edge, encoded as a list/tuple/collection of some kind.  I also find it a little annoying that I have to create a tuple/list/whatever to actually add the edge to the graph - I'd rather just pass in the two end-points.  I'd prefer something like this:

def add_edge(self, first, second):
    self.edge_list.append((first, second))

Encoding your graph

At this point, however, I have to ask why you're representing your graph as a list of edges - to me, the most intuitive way to think of a graph (and how I've implemented one in the past) is to use a dictionary - to use your example, I'd probably encode it like this

{
    1: {2, 3},
    2: {1, 3},
    3: {1, 2}
}

Then, instead of searching through an entire list to find a given edge, you just have to perform a quick dictionary lookup for one of the endpoints, and then a theoretically smaller iteration over a (hopefully) shorter list.  I've also seen versions that use nested dictionaries very effectively.

Your adj_mtx function

Note - I didn't change anything about the encoding here, I just used your implementation.

You could clean this up a bit.  You don't need to initialize v where you do. It would also be easier if you kept the nodes in a set and added them whenever you added an edge.

In general, prefer xrange in Python 2, although that makes compatibility trickier - I generally use a library like six to handle things like that, although if you don't need everything you can write your own file (good name is usually compatibility.py) that has only the changes you need.

Instead of nested comprehensions, just do [0] * v.  Also, if you don't care about a variable (such as x or y) use _ to identify it.

You can split up iteration variables in a for loop - for src, dest in self.edge_list is cleaner than for e in self.edge_list: src, dest = e.

Overall you could use more descriptive names in this function.  I'd probably write it something like this:

def adj_mtx(self):
    count = len(self.nodes)

    matrix = [[0]*count for _ in range(count)]
    for src, dest in self.edge_list:
        src -= 1
        dest -= 1
        matrix[src][dest] = 1

    return matrix

Additionally, it seems like adj_mtx should just be called adjacency_matrix, and I would rather it be a property (potentially with caching) than a function.  Imagine something like this:

class Graph(object):
    _adjacency_matrix = None

    def __init__(self, edge_list=None):
        self.edge_list = edge_list if edge_list is not None else []
        self.nodes = set()
        self.cache_valid = False

    def add_edge(self, first, second):
        edge = first, second
        self.edge_list.append(edge)
        self.nodes.update(edge)
        self.cache_valid = False

    @property
    def adjacency_matrix(self):
        if not self.cache_valid:
            count = len(self.nodes)

            matrix = [[0]*count for _ in range(count)]
            for src, dest in self.edge_list:
                src -= 1
                dest -= 1
                matrix[src][dest] = 1

            self._adjacency_matrix = matrix
            self.cache_valid = True

        return self._adjacency_matrix

    def clear_cache(self):
        self.cache_valid = False
        self._adjacency_matrix = None

Note that if someone adds edges to the list manually, or does other weird things, then the caching won't work.


Thanks to @wondra for the help. I rewrote the function without the getpixel and just loaded the pixels using the image.load() method. This caused the execution time to reduce down to 3.09 seconds.

Rewritten function:

def fitness_new(new):
    fitness = 0

    new_data = new.load()

    for x in range(0, width):
        for y in range(0, height):
            r1, g1, b1 = optimal_data[x, y]
            r2, g2, b2 = new_data[x, y]

            deltaRed = abs(r1 - r2)
            deltaGreen = abs(g1 - g2)
            deltaBlue = abs(b1 - b2)

            pixelFitness = pixelFitness = math.sqrt(deltaRed ** 2 + deltaGreen ** 2 + deltaBlue ** 2)

            fitness += pixelFitness

    return fitness

optimal_data is preloaded as a global variable instead of being passed as an argument, because it is accessed elsewhere. I know this is probably not the most ideal method.