First pass on your code:

Don't panic. For example, your WriteHostsFile function should return error instead of bool.
Don't create a special struct for a string set. Just use map[string]bool and exploit zero values =) Don't be afraid to use map[string]map[string]bool to represent your hosts.

Your Add function go away, but fyi: you are making it return a bool and never using it.

Your pop function could be simplified and inlined. Just use ip, parts = parts[0], parts[1:].
Check for nil value using foo == nil instead of len(foo) == 0.
strings.Split(line, " ") only works if things are separated with spaces — but indentations are a perfectly valid separator for /etc/hosts =)
If your lines aren't too long (and you can probably assume lines from /etc/hosts are going to be smaller than 65k chars), use bufio.Scanner to read a file line by line. See this SO answer for a full example and a discussion of caveats.

Your GetLines function should probably be inlined, but fyi: you're silently discarding its argument.

You probably want to use flags for the input and output paths, and output on stdout by default (maybe have a flag to override /etc/hosts). Outputting to a file named hosts in the current directory is pretty unexpected.
Instead of for k := range hosts and then calling hosts[k], you can use directly for k, h := range hosts and use h.
You don't want to write into a file line by line — what if you're overwriting the original file and your binary fails in the middle? You probably want to have WriteHostsFile write into a bytes.Buffer and write everything at once at the end.
All your functions are exported (they start with an uppercase letter), but this is not a library; so you shouldn't export anything: they should all start with a lowercase letter.
Your algorithm is not deterministic, because you're iterating over the elements of a map in WriteHostsFile: it might be unexpected to see the file modified if all hosts are already correctly grouped. Sorting the hosts by key; or by first appearance in the original file, would solve this.

Cheers!


I'm no expert, but what the heck, here's a review comment:
# needs to be 16-byte aligned before the next function call so do two pushes
pushq $0
pushq %rax

This comment is good, but I would rephrase it. Two eight-byte pushes makes 16 bytes and doesn't change the stack alignment. Therefore I infer that one of these pushes is significant and the other one is insignificant — but your comment doesn't tell me which is which! So you might say instead
# one extra push to preserve 16-byte stack alignment
pushq $0

# push the result of `exp`
pushq %rax

You could make the generated code smaller by eliminating the insignificant constant $0:
# push the result of `exp`, plus one extra push to preserve 16-byte stack alignment
pushq %rax
pushq %rax

Now the reader doesn't even need to figure out which push is the significant one, because both pushes do the same thing!

But why is preserving 16-byte alignment on calls important? That's not a requirement of the machine. You seem to be trying to follow some specific ABI, like maybe for interoperability with C or C++. Your external documentation should be clearer about what ABI you're trying to follow.
And then, if you are trying to interoperate with C code, you could improve your code by indicating which of its labels are meant as external entrypoints and which ones are just internal local labels. It seems like you intend exp to be called from other code — it's an entrypoint — but e.g. exp_op is not callable, and exp_ret is technically callable but just acts as a no-op. You might mark them somehow as "local implementation details, not for external consumption."
Yeah, you technically already do this by exporting .globl _start and not .globl exp — but there's still a big difference between the callable function exp and the local label exp_op which is not reflected in your naming scheme. If I were doing this, I'd add .globl exp and I'd rename exp_op, exp_ret to something like Lexp1, Lexp2 or L1_looptop, L2_loopend.


I'll start off by saying this is actually really good.
There are a few minor PEP8 errors:

In after_login you call Request. the argument url shouldn't have a space on the right side of the equals.
Another thing in Request. The argument callback needs at least one more indent.
However you should either aligned with opening delimiter or use hanging indents.
And so you should change this to either of:

yield Request(url=baseurl + page + "?id=1",
              callback=self.action)

yield Request(
    url=baseurl + page + "?id=1",
    callback=self.action)

Variables and functions should be named in snake_case.
pagelist should be page_list, pageurl page_url, etc.

Whilst not being a PEP8 error you may want to change page_list to say pages.
This is as multiple pages are probably a list, and sounds more fluid.

I say the above as consistency is the best way to allow others to easily read your work.
But they are quite minor.

Personally I'd move the baseurl out of the class and make it a constant.
This allows you to easily change the url, say the company you're scraping change their company/domain name or their top-level domain.
I'd also move other system settings, 'UserNameHere', 'PasswordHere', 'http://www.example.com'.
I may even say that pagelist should be moved out too.

Now for comments on your business logic, as parse and after_login are very short 3 line functions,
there's honestly not much to say about them.
action however has a few problems:

response.url is a string and so you shouldn't cast it to one.
This confused me as I it made me think response.url would be something that isn't a string.
You seem to be getting the response as an instance of TextResponse, which contains selector.
This also contains the shortcut xpath which is equivalent to selector.xpath.
Which allows you to reduce the size of that large command.
Unfortunately scrapy doesn't document extract_first, but looking at the source they use Parsel.
The documentation on extract_first was also kinda lacking, so I read the source code again, and it seems like they always return strings or None.
So you probably don't need the str around extract_first if you set default to an empty string.
You don't define pagename unless page is not None.
But you go on to use it regardless.
This is wrong, and can lead to errors.
There are two ways to come at this, either silently fail.
Or raise an exception, where NameError: name 'pagename' is not defined is not a good error.
Finally it's strange to see yield rather than return, you're only going to ever return one thing.
And so unless it's a requirement imposed by scrapy I'd change it to return.

And so if I were to improve it, leaving yield and failing silently, I'd end with:

BASE_URL = 'http://www.example.com'
USER_NAME = 'UserNameHere'
PASSWORD = 'PasswordHere'
PAGES = ['page1.aspx', 'page2.aspx', 'page3.aspx', 'page4.aspx']

class ShareSpider(scrapy.Spider):
    name = "sharespider"
    start_urls = [BASE_URL + '/public/login.aspx']

    def parse(self, response):
        yield scrapy.FormRequest.from_response(
            response,
            formxpath='//form[@id="login"]',
            formdata={
                'UserName': USER_NAME,
                'Password': PASSWORD,
                'Action':'1',
            },
            callback=self.after_login)

    def after_login(self, response):
        base_url = BASE_URL + '/public/'
        for page in PAGES:
            yield Request(
                url=base_url + page + "?id=1",
                callback=self.action)

    def action(self, response):
        page = re.search('public/(.*)id=1', response.url)
        if page:
            page_name = page.group(1)
            title = response.xpath('//title/text()').extract_first('').strip()
            item = PageItem()
            item['pagename'] = page_name
            item['description'] = title
            yield item


Without changing the global structure of your code, here are a few things that could make it better.

NB: I will try to cover as much as I can, skipping objects and if-reduction, as it has already been covered in another answer

Docstrings

You use regular comments at the beginning of your functions. Their purpose is to indicate what the function does, therefore they should be docstrings. The difference is that it is stored in the __doc__ special variable.

def get_number(level):
    """selects a random number in range depending on difficulty selected"""
    if level == "e":
        # rest of the function

About get_number

You could use a dictionary of levels to make it shorter and easier to understand. Also more flexible when you want to change levels later, or add new levels.

levels = {'e': 20, 'm': 100, 'h': 1000}

The content of the function is then something like:

if level != "e" and level != "m" and level != "h":
    print ("Invalid input!")
    get_number()
else:
    number = random.randint(1, levels[level])
return number

Or even better, try and catch a KeyError that is raised when the key does not exist. Final get_number function:

levels = {'e': 20, 'm': 100, 'h': 1000}

def get_number(level):
    """selects a random number in range depending on difficulty selected"""
    try:
        number = random.randint(1, levels[level])
    except KeyError:
        print ("Invalid input!")
        get_number()
    return number

About guess_number

Golden rule : never rely on a user input (you can read about it here for example). As we've seen before, the user does not always enter what you asked for, and this can cause your game to crash. Fortunately, using try/except can solve this problem. I've kept the use of the levels dictionary here.

def guess_number(level):
    """function that prompts the user to guess within range
    depending on chosen difficulty"""
    try:
        guess = int(input("Guess a number between 1 and "+str(levels[level])+":\n"))
    except KeyError:
        print('This should never have happened. "level" is not part of the levels')
    except (ValueError, NameError, SyntaxError):
        print('Invalid input\n')
        guess = guess_number(level)
    return guess

Naming arguments

Sometimes functions can be obscure, it can be helpful for others (and future you) to name arguments, as Python allows nicely.

if level == "e":
    com_guesses = round(random.normalvariate(mu=3.7, sigma=1.1))

This makes it way easier to understand.

Magic numbers

Speaking of the line of code just above, 3.7 and 1.1 seem to come out of nowhere. Two solutions to get this straight:

Create constants (not my favorite)

For instance,

EASY_MU = 3.7
EASY_SIGMA = 1.1
MEDIUM_MU = 5.8
# ...

and the line becomes much more understandable

if level == "e":
    com_guesses = round(random.normalvariate(mu=EASY_MU, sigma=EASY_SIGMA))

Use dictionaries (again)

We could improve the levels dictionary to make it contain what we want for later.

levels = {'e': {'size': 20, 'mu': 3.7, 'sigma': 1.1},
          'm': {'size': 100, 'mu': 5.8, 'sigma': 1.319},
          'h': {'size': 1000, 'mu': 8.99, 'sigma': 1.37474}
          }

Then the whole method becomes way more readable

def com_num_guesses(level):
    """function to get the number of guesses taken by the computer"""
    try:
        com_guesses = round(random.normalvariate(mu=levels[level]['mu'], sigma=levels[level]['sigma']))
    except KeyError:
        print('This should never have happened. "level" is not part of the levels')
    print("The computer guessed the number in {0} guesses! Can you beat that?".format(com_guesses))
    return com_guesses

Also note that in get_number and guess_number, we will now have calls to levels[level]['size'] since the dictionary has changed.

Lauching

It is recommended to encapsulate your mainloop function within an if __name__ == '__main__' condition. That way, it will not get run if this module is imported by someone else. More information on that here.

if __name__ == '__main__':
    mainloop()

Global remarks

You used a lot of recursive calls. This is OK, since the number of calls remains small (once per user mistake). But I personally have a preference for while True loops that break as soon as the user input is correct. It uses less memory.

This answer is already quite long, and I've given you pieces of information to improve your code, not revolutionized the whole structure, that's why I didn't copy the whole code at the end.


I'm quite surprised that the messageETCS regex actually works.
Probably the best and fast way it's to use a parser (ex: https://github.com/picoe/Eto.Parse).

To improve performances, read and process the file chunk by chunck, or line by line if those are lines


Not sure what is behind the requirement of 5 seconds, but from the top level (please comment to answer the items marked as warnings):

public sealed class Batcher
    {
        private readonly object _syncLock = new object();
        private readonly Timer _timer;
        private bool _timerSet = false;
        private volatile int _callCount = 0;
        private const int ExecuteImmediatelyCallCount = 3;
        private readonly ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
        private readonly List<Order> _orders = new List<Order>();

        public Batcher()
        {
            _timer = new Timer(Batch, null, Timeout.Infinite, Timeout.Infinite);
        }
#warning What is the "orders" parameter for
        public void  TryBatch(IEnumerable<Order> orders)
        {
#warning don't see a point to lock this operation
            lock (_syncLock)
            {
                _orders.AddRange(orders);
                if(!_timerSet)
                {
                    _timerSet = true;
                    _timer.Change(5000, Timeout.Infinite);
                }
                _callCount ++;
            }
#warning not thread safe
            if(_callCount >= ExecuteImmediatelyCallCount)
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
                Batch(null);
            }
#warning what is this for?
            _manualResetEvent.WaitOne();
        }

        private void Batch(object state)
        {
            lock (_syncLock)
            {
                if(_orders.Count > 0)
                {
#warning not thread safe
                    RemoteService.Send(_orders);
                    _orders.Clear();
                    _manualResetEvent.Reset();
                }
                _callCount = 0;
            }
        }
    )


Write MD5 hashes to file for all files in a directory tree

Four things:

You should put global constants in CAPITAL_LETTERS, according to PEP8.
I would make the file_name for the checksums a constant
You never close the files you iterate over.
In general, doing all writes at the same time is faster.

So for 2, 3 & 4, maybe use:

for root, subdirs, files in os.walk(SRC_DIR):
    checksums = []
    for file in files:
        with open(os.path.join(root, file), 'rb') as _file:
            checksums.append([root, file, hashlib.md5(_file.read()).hexdigest()])
    writer.writerows(checksums)

This will perform one write per subdir, which should be faster than a write after every file. If you have a lot of files this will take more memory, which should be slightly mitigated by doing a write for each subdir. You can even pull the checksums list outside of the os.walk loop to have only one (possibly giant) write.

Otherwise, clear and readable code!


Finding numbers with odd frequency in an array

Undeclared variables You aren't declaring your newObj variable or your key variable. This will either implicitly create properties on the global object, or throw an error in strict mode. Both should be avoided. Always declare your variables (with const, or let when const isn't usable) before using them for the first time. Eg, change newObj={}; to const newObj = {};.
Algorithm complexity Your current approach is pretty computationally expensive. .indexOf will iterate through all elements of the array until it finds a match, or until it reaches the end of the array. .filter will iterate through all elements of an array. With an .indexOf inside a .filter, the computational complexity is O(n ^ 2). (For example, given an array of 30 items, you can expect to have to carry out 900 times more operations than an array with only 1 item, worst-case.) That's not very good.
Inside the forEach, you again iterate over every element of the array, resulting in another operation of O(n ^ 2) complexity.
To reduce the overall complexity of the whole findOdd function to O(n), iterate over the input array only once, and inside the loop, either create a property on the object, or increment the existing property. (See snippet below for a demo.)
Variable names You have variable names A and newObj. At a glance, these are not very informative. Better to give them names that represent what they contain so you can understand them at a glance, such as inputNumbers and occurrencesByNumber. Also, the variable named key isn't actually a key - it's an array of keys. Better to make it plural: keys.
Semicolons Sometimes you're using semicolons, sometimes you aren't. Unless you're an expert, I'd recommend using semicolons, else you may occasionally run into hard-to-understand errors due to Automatic Semicolon Insertion. I'd highly a linter (not just for semicolons, but for many ways to prompt you to correct potential bugs before they turn into errors, and to enforce a consistent code style)
Iterating over an object You collect the keys using Object.keys, then you iterate over the value at each key by accessing the property of the object: newObj[cur]. If you want to iterate over keys and values at once, you can consider using Object.entries instead.
.find or .filter? If the objective is to

then finally finding the keys with odd frequencies.

then
return parseInt(key[0])

is not the right approach, since it'll return only the first element of the array. If you want only one match to be returned, use .find above instead of .filter, so that it ends as soon as a match is found. If you want more than one match to be found, return the array of keys/entries, mapped to numbers.
Demo implementing these fixes:

const findOdd = (inputNumbers) => {
  const occurrencesByNumber = {};
  for (const number of inputNumbers) {
    occurrencesByNumber[number] = (occurrencesByNumber[number] || 0) + 1;
  }
  return Object.entries(occurrencesByNumber)
    .filter(([, occurrences]) => occurrences % 2 === 1)
    .map(([numberKey]) => Number(numberKey));
};

console.log(findOdd([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]));
console.log(findOdd([1, 1, 2]));
console.log(findOdd([0, 1, 2]));


Python logging: show variable name without specifying it explicitly

This is good for narrowing down dirty fixes. I used to do this, but don't think it's the correct solution to the problem. Instead if you make smaller functions that are less complicated, and you have a test suite to test these functions, you should reduce the amount of bugs that you have, and not need this. The only time I used something like this, other than when I was debugging, was for a school project that was anal about logging.

You're correct, this isn't very DRY. To make it dry however would be best with a decorator, and inspect.signature.
This way, you can use the standard decorator sugar, to allow for easily toggleable debugging on the functions.
This for example could be:

@log(logger, debug=False)
def fn(arg1, arg2):
    ...

@log(logger, debug=True)
def fn(arg1, arg2):
    ...

The difference being that the second turns debugging on, where the former doesn't. It won't show anything.
Doing this, you can also include default arguments and types to every function, without any extra effort.
To do this could be with:

from inspect import signature, Parameter
import logging

logger = logging.getLogger(__name__)
DEBUG = True

def log(logger_=None, debug=False):
    debug = DEBUG and debug
    if logger_ is None:
        logger_ = logger
    def wrapper(fn):
        sig = signature(fn)
        formats = {}
        for name, param in sig.parameters.items():
            fmt = '{}() {}'.format(fn.__name__, name)
            if param.annotation is not Parameter.empty:
                fmt += ': {0.__name__}'.format(param.annotation)
            if param.default is not Parameter.empty:
                fmt += '={!r}'.format(param.default)
            fmt += ' -> {value}'
            formats[name] = fmt
        def inner(*args, **kwargs):
            if debug:
                ba = sig.bind(*args, **kwargs)
                ba.apply_defaults()
                for key, value in ba.arguments.items():
                    logger_.debug(formats[key].format(value=value))
            return fn(*args, **kwargs)
        return inner
    return wrapper

@log(debug=True)
def execute(system_command, **kwargs):
    process = subprocess.run(
        shlex.split(system_command),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        **kwargs)
    if process.returncode != 0:
        logger.info(process.stdout.strip())
        logger.error(process.stderr.strip())
    return process

@log(debug=True)
def test(a: int, b:str='b'):
    return a, b

test(1)
# Displays:
# test() a: int -> 1
# test() b: str='b' -> b

Also I'd not be surprised if there is a somewhat large performance difference, with and without the occurrence of @log. Which should be something to keep in mind.


You are mixing C with C++. I know these contests like speed, but it is usually unnecessary.
1. Prefer streams over scanf.
This means you can change this code:
    scanf("%d %d", &numMarbles, &numQueries);

Into this:
    std::cin >> numMarbles >> numQueries ;

2. Use the C++11 auto keyword when possible.
You have a C++11 tag, so I assume you have C++11 available.
You can change this:
std::vector<int>::const_iterator itr = std::lower_bound(marbles.begin(), marbles.end(),aMarble);

To this:
auto itr = std::lower_bound(marbles.begin(), marbles.end(),aMarble);

3. Make sure the iterator does not point past the end when you dereference it.
In this line: if(*itr == aMarble), you dereference the iterator. If aMarble is not in marbles, then std::lower_bound() will return marbles.end(). It is undefined behavior to dereference marbles.end(). Always check for this condition.
So change this line:
if(*itr == aMarble)

To this:
if (iter != marbles.end () && *itr == aMarble)

4. Prefer pre-increment over post-increment.
You have:
case1++;

In the case an int, it doesn't really matter. Your compiler will optimize this correctly. But if you had a complicated object, then you would be creating an unnecessary copy here. So:
++case1;

Would be a better habit to get into.
5. Encapsulate input and output with an Object.
You could create an object that represents a single unit of input. Something like this:
struct Input
{
    int nMarbles ;
    int nQueries ;
    static int caseNumber ;

    std::vector <int> marbles ;
    std::vector <int> queries ;

    Input () ;
    void Clear () ;

    friend auto operator>> (std::istream &is, Input &input) -> std::istream& ;
    friend auto operator<< (std::ostream &os, const Input &input) -> std::ostream& ;
};

Then you could implement the member and friend functions like this:
int Input::caseNumber = 0 ;

Input::Input () : nMarbles (), nQueries ()
{
}

void Input::Clear ()
{
    nMarbles = 0 ;
    nQueries = 0 ;
    marbles.clear () ;
    queries.clear () ;
}

auto operator>> (std::istream& is, Input &input) -> std::istream&
{
    ++Input::caseNumber ;

    is >> input.nMarbles >> input.nQueries ;

    if (input.nMarbles == 0 && input.nQueries == 0) {
        is.setstate (std::ios::failbit) ;
        return is ;
    }

    auto begin = std::istream_iterator <int> (is) ;
    std::copy_n (begin, input.nMarbles, std::back_inserter (input.marbles)) ;

    begin = std::istream_iterator <int> (is) ;
    std::copy_n (begin, input.nQueries, std::back_inserter (input.queries)) ;

    return is ;
}

auto operator<< (std::ostream &os, Input &input) -> std::ostream&
{
    os << "CASE# " << Input::caseNumber << ":" "\n" ;

    auto &marbles = input.marbles ;

    std::sort (std::begin (marbles), std::end (marbles)) ;

    for (int query : input.queries) {
        auto iter = std::lower_bound (std::begin (marbles), std::end (marbles), query) ;

        if (iter != std::end (marbles) && *iter == query) {
            os << query << " found at " << (std::distance (std::begin (marbles), iter) + 1) << "\n" ;
        }

        else {
            os << query << " not found" "\n" ;
        }
    }

    return os ;
}

Then your driver would look like this:
int main ()
{
    Input input ;

    while (std::cin >> input) {
        std::cout << input ;
        input.Clear () ;
    }

    return 0 ;
}

With the above code, I got an accepted answer with a runtime of 0.212 units on your website. So streams are more than fast enough for this particular challenge.


Chrome extension -- replace words on a page from a large dictionary

Your logic currently does a lot more work that it needs to do.

First, you are iterating every element in DOM and then iterating on every child element of those (which is actually duplicate work, since all nested tags would already be present in elements). This is especially problematic in that you are really only interested in text nodes.  So, your first order of business, is to get only those nodes you care about.

Perhaps check out this Stack Overflow post on this topic. I personally like the TreeWalker approach in the accepted answer.

Now that you have a good flattened representation of these text nodes, you can just iterate through and directly modify them.

// build word map
var wordMap = {
   'match value': 'replace value',
   // etc.
}

// build single regex
var regex = new RegExp(Object.keys(wordMap).join("|"),"gi");

// get text nodes
var textNodes = ...; // derive similar to linked SO question above.

// iterate text nodes and modify in place
for (var i = 0, len = textNodes.length; i < len; i++) {
    textNodes[i].nodeValue = textNodes[i].nodeValue.replace(regex, function(match) {
        return wordMap[match];
    });
}

This example above would have you modifying the nodes in place rather than having to do any DOM replacements.

You could also potentially have some savings by dumping the regex approach to string search altogether in favor of simply iterating through the string a single character at a time comparing against key/property values in your word map, to see if any replacement strings are potentially starting or continuing.  You would like need to build a trie structure to give efficient lookup against your dictionary. This is certainly more complex from an implementation standpoint, but could be an optimization you need to make if you find the regex approach is just not operating fast enough for you.

You might find this interesting reading on tries in javascript - http://ejohn.org/blog/javascript-trie-performance-analysis/


Idiomatic way to write proper F# (x)unit + fsunit tests?

I think that regardless of a language you're using the most idiomatic way would be to take advantage of InlineData attribute

It would look roughly like this

[<Theory>]
[<InlineData("DSXLAD46", "expectedbic1")>]
[<InlineData("KAOLADZOAQC", "expectedbic2")>]
let ``Bics should be valid with SEPA-compliant countries`` input output =
    let result = validateAndFormat input
     match result with
        | Ok s ->
            Assert.Equal(s, output)
        | Error _ -> Assert.True(false) //looks like there is no Assert.Fail() in xunit


Iterating over global keymap, removing all bindings to super keys

Apart from using dolist as mentioned by @brfennpocock it looks mostly
fine.

system-type is a symbol though, so you can compare it with eq
instead of string-equal (unless I missed a reason to use that here).

Also the single if can also be when for consistency.

(defun global-unset-all-super-key ()
"Will unset any single key in global keymap that has the super modifier."
(dolist (km (current-global-map))
    (let ((maybe-event (and (listp (car km)) (caar km))))
    (when (and (eventp maybe-event)
                (memq 'super (event-modifiers maybe-event)))
        (global-unset-key (vector maybe-event))))))

For init.el if you have more functions also consider the
autoload
facilities, but that's not necessary for just this bit of code (actually
I'd probably put it all in init.el to be honest even though a separate
file like this is somewhat cleaner).


Generic getting single value from DB in C#

Something smells hinky having this class inherit from something called Page. Like it's mixing UI and data concerns where it shouldn't. What does Page give this class?
C# convention is to use language aliases object and string over the CLR types Object and String, respectively.
Also along the lines of convention, the word is "database", not "data base" and therefore the class should not be named DataBase, but rather Database.
You have two particular dependencies in this class: a connection string and a logger. I'd recommend inverting those dependencies and injecting them into the class at time of construction.
Better yet, there are other dependencies, SqlConnection and SqlCommand being created in the GetValue method. These may best be refactored into another class injected into this one.
Class member variables should always be private. If you need them exposed to the outside, or subclasses, use properties to control access.
Use var where possible.

So, here's a cut at that:

IDatabaseAdapter interface:

public interface IDatabaseAdapter
{
    IDbConnection GetConnection();

    IDbCommand GetCommand(IDbConnection connection, string query);
}

DatabaseAdapter implementation:

public class DatabaseAdapter : IDatabaseAdapter
{
    private readonly string _ConnectionString;

    public DatabaseAdapter(string connectionString)
    {
        this._ConnectionString = connectionString;
    }

    public IDbConnection GetConnection()
    {
        return new SqlConnection(this._ConnectionString);
    }

    public IDbCommand GetCommand(IDbConnection connection, string query)
    {
        var command = new SqlCommand(query, connection as SqlConnection);

        connection.Open();
        return command;
    }
}

Database class:

public class Database
{
    private readonly ILog _Log;

    private readonly IDatabaseAdapter _DatabaseAdapter;

    public Database(ILog log, IDatabaseAdapter databaseAdapter)
    {
        this._Log = log;
        this._DatabaseAdapter = databaseAdapter;
    }

    public string ConnectionString
    {
        get
        {
            return this.ConnectionString;
        }
    }

    protected ILog Log
    {
        get
        {
            return this._Log;
        }
    }

    public T GetValue<T>(string query)
        where T : IComparable, IConvertible, IEquatable<T>
    {
        var value = this.GetValue(query);

        return Convert.IsDBNull(value) ? GetDefaultValue<T>() : (T)Convert.ChangeType(value, typeof(T));
    }

    public static T GetDefaultValue<T>()
        where T : IComparable, IConvertible, IEquatable<T>
    {
        return typeof(T) == typeof(string) ? (T)(object)string.Empty : default(T);
    }

    private object GetValue(string query)
    {
        try
        {
            using (var connection = this._DatabaseAdapter.GetConnection())
            using (var command = this._DatabaseAdapter.GetCommand(connection, query))
            {
                return command.ExecuteScalar();
            }
        }
        catch (Exception e)
        {
            this.LogQueryError(query, e);
            return DBNull.Value;
        }
    }

    protected void LogQueryError(string query, Exception e)
    {
        this._Log.Error(string.Format("Error while executing Query ({0}): {1}", query, e.Message));
    }
}

Sample calling code:

internal static class Program
{
    private static readonly DataBase _Database = new DataBase(
        LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType),
        new DatabaseAdapter(ConfigurationManager.ConnectionStrings["abc"].ConnectionString));

    private static void Main()
    {

    }
}

As a final note, you'll likely want to check for null or empty strings in constructors and raise appropriate exceptions then to keep the state of the objects well-known.


Critique of FilterInputStream and FilterOutputStream classes

It looks like you have covered the bases quite well. There are some things I would like to suggest, and the first one is the most important:

  The performance of Input/Output Streams that read/write 1 byte at a time is really, really bad. You should also override the bulk read(...)/write(...) methods.

Now, when you get around to doing the bulk methods, you will have some challenges with getting the byte manipulation right, but that's another problem.... ;-)

Now in your decrypt routine you have:

int b = super.read();
return (b != -1 ? b ^ XOR_KEY : b);

I don't like this. The reason is that it has too much negative logic..... and even though it relates b to a constant -1 you return b instead of -1. Consider the following alternative:

return b == -1 ? -1 : b ^ XOR_KEY;

I know it is a minor nit-pick, but it does make a difference.

On that note, you had better make sure that XOR_KEY is always positive... a negative XOR_KEY will cause the result to be negative, and break all sorts of InputStream readers.

Now, you say the key should be as long as the message... that's not true. Even some of the best algorithms use 2048-bit keys (256 bytes). and many of them use much less (16 bytes...).

Additionally, you hint that you know that storing the key the way you do is incorrect ... It should be passed in as a constructed value or something, and not hard-coded as a static variable.

What you have is more than 'adequate', it is neat, and appears to be fully accurate... but, in order to be good, or great, it needs to do the bulk-operations...


1. Introduction

Your goal (if I understand correctly, of generating all the execution paths in a state transition graph for a Java thread and then using those execution paths to test the code) seems unrealistic to me.

Even in an acyclic graph (or with the condition that you must not revisit a state) there may be exponentially many paths. In a graph with cycles (like any realistic state transition graph) there are infinitely many paths.

You cannot afford the time to generate all these path, let alone the time to run the test cases based on the paths: the best you can hope for is to intelligently (or randomly) sample the space of paths.

2. Detailed review

There are no docstrings. What do your functions do, what data structures do they act on, and how do I call them?
The singular of leaves is leaf in English (not leave).
Your program has code at the top level of the module. This makes it inconvenient to test the code from the interactive interpreter: each time you reload the module, the program runs. It would be better to put the top-level code into a function and call this function inside the guard if __name__ == '__main__':.
Your program relies on a global variable graphPaths. This makes it inconvenient to test the program repeatedly, as you have to ensure that this variable is reinitialized each time you want to run the test case. Instead of passing gname and appending to graphPaths[gname] inside findPaths, it would be better to pass the list as an argument to findPaths.
But it would be even better not to append paths to a list, but instead to generate them one at a time using Python's yield instruction. That would allow you to interleave the generation of the paths with their further processing, and would avoid attempting to store exponentially many paths in memory.
There's a global variable seenNodes which is not used.
There's no point in writing:

for endNode in gdict.iterkeys():

when you could achieve the same thing by writing:

for endNode in gdict:

This also has the advantage of being portable to Python 3.
The lines:

if not gdict:
    return []

are unnecessary. You can't call findPaths unless you can give it a vertex for the leave argument, which means that the graph must be non-empty.
The argument leave to findPaths is poorly named. On the first call to the function it is (what you call) a leaf, but thereafter it can be any vertex.
The leave argument to findPaths is always the first element of the argument path. So why not get it from there and avoid repeating yourself?
Your algorithm searches backwards through the graph from its sinks. This is inconvenient because in order to prepare the list temp of vertices that might appear on the path before the current vertex, you have to search the whole graph. It would be simpler to search forwards because then you could look up the neighbours directly.
Your choice of graph data structure is not one of the standard representations such as adjacency list (a map from a vertex to a list or set of its neighbouring vertices). It looks to me as though your representation is "map from vertex to map from neighbouring vertex to the empty map". Why did you choose this representation?

Instead of the representation:

{0: {1: {}}, 1: {2: {}, 3: {}}, 2: {3: {}}, 3: {4: {}}, 4: {5: {}}, 5: {6: {}}, 6: {7: {}}, 7: {6: {}, 5: {}, 8: {}}, 8: {}}

I would use:

{0: [1], 1: [2, 3], 2: [3], 3: [4], 4: [5], 5: [6], 6: [7], 7: [6, 5, 8], 8: []}

or the similar alternative with sets instead of lists.
Your test case is very small: it only has two paths. This means that it does not really exercise the code. See §4 below for some more thorough test cases.

3. Revised code

def paths(graph, v):
    """Generate the maximal cycle-free paths in graph starting at v.
    graph must be a mapping from vertices to collections of
    neighbouring vertices.

    >>> g = {1: [2, 3], 2: [3, 4], 3: [1], 4: []}
    >>> sorted(paths(g, 1))
    [[1, 2, 3], [1, 2, 4], [1, 3]]
    >>> sorted(paths(g, 3))
    [[3, 1, 2, 4]]

    """
    path = [v]                  # path traversed so far
    seen = {v}                  # set of vertices in path
    def search():
        dead_end = True
        for neighbour in graph[path[-1]]:
            if neighbour not in seen:
                dead_end = False
                seen.add(neighbour)
                path.append(neighbour)
                yield from search()
                path.pop()
                seen.remove(neighbour)
        if dead_end:
            yield list(path)
    yield from search()

Notes:

This uses the yield from statement and so requires Python 3.3 or later. If you have to use an earlier Python, you can rewrite yield from search() as:

for p in search():
    yield p

seen is a collection containing the same vertices as path, but in a set for efficient computation of neighbour not in seen. It would be nice to be able to use a single data structure here (an ordered set), but Python does not provide one. We might consider using the keys of an OrderedDict or Raymond Hettinger's ordered set recipe.
This implementation maintains the search state on the Python call stack (the current position in the iteration over the neighbouring vertices, and the value of dead_end) and so a large graph could exceed the recursion limit. In this case you could increase sys.setrecursionlimit, or maintain your own stack (for example, using the stack of iterators pattern).

4. Test cases

from itertools import chain, permutations
from unittest import TestCase

class PathTest(TestCase):
    def test_complete(self):
        # The maximal paths in a complete graph are the permutations
        # of the vertices.
        n = 8
        vertices = list(range(n))
        g = {v: vertices for v in vertices}
        found = sorted(chain.from_iterable(paths(g, i) for i in vertices))
        expected = map(list, permutations(vertices))
        for p, q in zip(found, expected):
            self.assertEqual(p, q)

    def test_binary(self):
        # Two alternatives at each of n places yields 2 ** n paths.
        n = 10
        g = {n * 2: [], n * 2 + 1: []}
        g.update({i: [i + 2, i + 3] for i in range(0, 2 * n, 2)})
        g.update({i: [i + 1, i + 2] for i in range(1, 2 * n, 2)})
        found = sorted(paths(g, 0))
        def expected():
            for i in range(2 ** n):
                p = []
                for j in reversed(range(0, 2 * n + 2, 2)):
                    p.append(j + i % 2)
                    i //= 2
                yield p[::-1]
        for p, q in zip(found, expected()):
            self.assertEqual(p, q)


Generic function with same logic but different input structure

You could create a more general function which simple compares two values.
Like:

hasDifference(oldValue: number, newValue: number, offset?: number): boolean {
  const offsetToUse: number = offset === undefined ? this.EPSILON : offset;

  return Math.abs(oldValue - newValue) > offsetToUse;
}


Extract and divide algorithm implementation in Elixir

(untested)

defmodule ExtractAndDivide do
  def extract_and_divide(x) when x < 10, do: x
  def extract_and_divide(x) do
    head = div x, 10
    tail = rem x, 10
    up_or_down = rem tail, 2
    go_up_or_down(head, tail, up_or_down)
  end
  defp go_up_or_down(head, tail, up_or_down) when up_or_down == 0 do
    extract_and_divide(head * 2 + 1)
  end
  defp go_up_or_down(head, tail, _up_or_down_is_one) do
    extract_and_divide(div(head, tail) + rem(head, tail))
  end
end

The idea with having multiple conditional function clauses is twofold: it reduces nesting (and thus should increase readability), and - quite powerful - it allows to to easily test individual conditional parts. Whether to make the recursive call to extract_and_divide by piping the calculation through the function invocation or directly (like I did purely to show the alternative) is largely a matter of taste.

(note: skipped/circumvented potential nitpicking around naming and whether up_or_down shouldn't be a boolean; I just wanted to illustrate the pattern of doing logic by using multiple function heads)


In the following code, I tried two modifications.

I slightly modified the way tests are performed, in order to minimize them a little bit

I used iterators, like this :auto p_str = base_string.begin() + right;

with the idea to avoid a redirection here:
count_map[*p_str++]--;

instead of
count_map[base_string[right++]]--;

At the end, we cannot be sure how much the speed has been improved. A benchmark is needed (by LeetCode?). We can only be sure that the code is more difficult to read!
#include <iostream>
#include <string>
#include <vector>
#include <cassert>

std::string minWindow(std::string base_string, std::string target) {
    std::vector<int> count_map(128, 0);
    int n = base_string.length();

    for (auto character : target)
        count_map[character]++;

    int left = 0, right = 0;
    int min_left = 0, min_right = n+1;
    int target_length = target.size();

    while (right < n) {
        auto p_str = base_string.begin() + right;
        while (target_length > 0 && p_str != base_string.end()) {
            if (count_map[*p_str++]-- > 0)
                target_length--;
        }
        right = p_str - base_string.begin();

        if (target_length == 0 && right - left < min_right)
                min_right = right - left;

        p_str = base_string.begin() + left;
        while (target_length == 0) {
            if (count_map[*p_str++]++ == 0) {
                left = p_str - base_string.begin() - 1;
                if (right - left < min_right)
                    min_right = right - (min_left = left);
                target_length++;
            }
        }
        left = p_str - base_string.begin();
    }
    if (target_length == 0 && (right - left < min_right))
        min_right = right - (min_left = left);

    return min_right == n ? "" : base_string.substr(min_left, min_right);
}

int main() {
    std::string s = "XXXABYYCTTTABYC";
    std::string target = "CBA";
    std::cout << minWindow (s, target) << "\n";

}


Powershell search millions of files as fast as possible

First, you don't need to call Get-Date for every file. Just call it once at the beginning:

$t = (Get-Date).AddMinutes(-15)

Get-ChildItem -Path $path -Recurse |
    Select Name, PSIsContainer, Directory, LastWriteTime, Length |
    where {($_.LastWriteTime -gt $t)}

That's saves about 10% (as measured by Measure-Command).

Secondly, you don't need to call Select-Object for each file either. Just change the processing order:

$t = (Get-Date).AddMinutes(-15)

Get-ChildItem -Path $path -Recurse |
    where {($_.LastWriteTime -gt $t)} |
    Select Name, PSIsContainer, Directory, LastWriteTime, Length

Thirdly, try increasing the buffer size using the OutBuffer parameter:

$t = (Get-Date).AddMinutes(-15)

Get-ChildItem -Path $path -Recurse -OutBuffer 1000 |
    where {($_.LastWriteTime -gt $t)} |
    Select Name, PSIsContainer, Directory, LastWriteTime, Length

I've used 1000, but you can experiment with the value.

Those three changes reduced the running time to under one half on my system.


The OnPaint Method

I would refactor your OnPaint method a little to use more descriptive variable names, and store the new values added to the Rectangle in another variable, just to make things more maintainable. (And perhaps a little quicker, as well.)

Start with:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Graphics graphics = e.Graphics;
    Rectangle rc = this.ClientRectangle;
    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    Font font = new Font("Arial", rc.Height * 0.65f, FontStyle.Bold, GraphicsUnit.Pixel);
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;

    using (var background = new SolidBrush(Background))
    using (var foreground = new Pen(Foreground, 2.0f))
    using (var text = new SolidBrush(Foreground))
    {
        graphics.FillEllipse(background, rc.Left + 1.5f, rc.Top + 1.5f, rc.Width - 4.0f, rc.Height - 4.0f);
        graphics.DrawEllipse(foreground, rc.Left + 1.5f, rc.Top + 1.5f, rc.Width - 4.0f, rc.Height - 4.0f);
        graphics.DrawString(((char)Operator).ToString(), font, text, rc, sf);
    }
}

And work towards:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Graphics graphics = e.Graphics;
    Rectangle controlBounds = this.ClientRectangle;
    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    Font operatorFont = new Font("Arial", controlBounds.Height * 0.65f, FontStyle.Bold, GraphicsUnit.Pixel);
    StringFormat stringFormatter = new StringFormat();
    stringFormatter.Alignment = StringAlignment.Center;
    stringFormatter.LineAlignment = StringAlignment.Center;

    RectangleF outsideBounds = new RectangleF(controlBounds.Left + 1.5f, controlBounds.Top + 1.5f, controlBounds.Width - 4.0f, controlBounds.Height - 4.0f);

    using (var backgroundBrush = new SolidBrush(Background))
    using (var foregroundPen = new Pen(Foreground, 2.0f))
    using (var textBrush = new SolidBrush(Foreground))
    {
        graphics.FillEllipse(backgroundBrush, outsideBounds);
        graphics.DrawEllipse(foregroundPen, outsideBounds);
        graphics.DrawString(((char)Operator).ToString(), operatorFont, textBrush, controlBounds, stringFormatter);
    }
}

This should help maintainability in the future. Yes, things are much more verbosely named, but variable/parameter/method name lengths only affect compilation performance, not run-time.

Qualifying Names

I would also consider fully-qualifying the names of the member variables of the class. I.e. this.Operator instead of Operator. Yes, it makes it much more verbose again, but it's also clearly expressing exactly where things are coming from. The idea is to be able to skim the code and know it immediately. (Not that you can't do that with the original, but it does remove ambiguities.)

If we make that last change as well, we end up with:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Graphics graphics = e.Graphics;
    Rectangle controlBounds = this.ClientRectangle;
    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    Font operatorFont = new Font("Arial", controlBounds.Height * 0.65f, FontStyle.Bold, GraphicsUnit.Pixel);
    StringFormat stringFormatter = new StringFormat();
    stringFormatter.Alignment = StringAlignment.Center;
    stringFormatter.LineAlignment = StringAlignment.Center;

    RectangleF outsideBounds = new RectangleF(controlBounds.Left + 1.5f, controlBounds.Top + 1.5f, controlBounds.Width - 4.0f, controlBounds.Height - 4.0f);

    using (var backgroundBrush = new SolidBrush(this.Background))
    using (var foregroundPen = new Pen(this.Foreground, 2.0f))
    using (var textBrush = new SolidBrush(this.Foreground))
    {
        graphics.FillEllipse(backgroundBrush, outsideBounds);
        graphics.DrawEllipse(foregroundPen, outsideBounds);
        graphics.DrawString(((char)this.Operator).ToString(), operatorFont, textBrush, controlBounds, stringFormatter);
    }
}

Comments on 'Magic Values'

You should also consider specifying what some of the floating values are set in the manner they are for via comments. I.e. on the using (var foreground = new Pen(Foreground, 2.0f)) line it would not hurt to add a comment indicating why the width of the Pen is 2.0f. This is merely to help remind yourself in the future for if (when) you come back to the code.

Hardcoded 'Magic Values'

You should also consider adding a custom RectangleF TextPadding property that defaults to new RectangleF(1.5f, 1.5f, 4.0f, 4.0f) to remove those hard-coded values. This will also increase extensibility and reuse-ability greatly for the future. (We want to reuse this class in another programme, don't we?)

You could then write an extension method to add two rectangles together or similar. This bit is up to you, but it could definitely ease maintainability and reuse-ability.

Field Naming

I also, personally, would not name the private Operators field op. Generally speaking, fields should be the camelCase variant of the property they back (operator in your case). Though, personally, I don't use that idea, and instead I use the backing field name as equivalent to the property name but prefixed with an underscore (_Operator in your case). Both these options are open, and generally increase meaningfulness.

All of these suggestions are mostly for consistency and conventions so that if you have to go back into the code two years from now, it's very easy to follow. These are based on my personal flavours of writing code, and are no way concrete.

Take them all as you would like. :)


How can this simple coroutine implementation be improved?

Things you did well on:

Overall, this looks like a pretty decent little bit of code.  It looks like some research went into this
I like the comments.  Everywhere I was confused on something, there was a comment to clarify.  You also didn't go overboard with them!

Things you could improve on:

Preprocessor:

Group all of your #defines at the top of your code, just after your #imports.  Otherwise you will have to jump around your code to find them.

Initialization:

typedef your structs.

struct {
  jmp_buf jmp;
  void *stack;
  long stack_sz;
} coroutines[MAX_COROS];

The typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
You can initialize some variables right away.

int stack_sz;
stack_sz = coroutines[coro_pid].stack_sz;

int stack_sz = coroutines[coro_pid].stack_sz;

Syntax:

You use print() where it is unneeded.

printf("starting the scheduler...\n");

You can use puts() instead.

puts("Starting the scheduler...");

Memory:

You allocated memory to stack, but never free it.

void *stack = malloc(stack_sz);

Failure to deallocate memory using free leads to buildup of non-reusable memory, which is no longer used by the program. This wastes memory resources and can lead to allocation failures when these resources are exhausted.

free(stack);

Comments:

You could use the /* ... */ comment format instead of the // ... format when commenting over multiple lines.

// value == 0 means just starting
// value == -1 means spawning new coroutine
// value positive means hop back to a specific pid

You could also condense your comments down a bit.

/*
 * If 'value' is 0, it is just starting; if -1 it is spawning.
 * If 'value' is positive, we "hop" to a specific PID.
 */

Resources:

Coroutine implementations for C
Coroutines in C
Building Coroutines
Libtask: a Coroutine Library for C and Unix


Randomly generate set of size M from array of size N

Your understanding of Fisher-Yates is incorrect: this is precisely Fisher-Yates. It merely differs from some implementations in accumulating at the start of the array rather than the end. As such the main part of the body is correct (and uniform, modulo artefacts of the RNG).

The alternative way round, accumulating at the end, would be

    for i in range(m):
        j = len(arr)-1-i
        rand = random.randint(0, j)
        arr[j], arr[rand] = arr[rand], arr[j]

    return arr[-m:]

However, I find the special case a bit confusing. if len(arr) < m I would expect an exception, and since that isn't the case I think there should be a comment to document the behaviour.


Calculate all the prime numbers between two given numbers

The efficiency of the prime function is probably the most interesting aspect of this exercise. You're limiting the search space to up to the square root of the number, which is good, but the fact that you're looking for all primes in a range would make many other prime searching algorithms usable, such as the Sieve of Eratosthenes, which fairly efficiently gets you the primes from 2 through N. The issue is that which algorithm to use in your case depends on runtime inputs: if the user asks for prime numbers between 2 and a large N there are heaps of efficient algorithms. If they instead ask for primes between a large N and N+1 it probably makes much more sense to just look at those two numbers. I'm not a mathematician, but choosing which algorithm to use depending on the range seems like a subject worth studying.
I don't see why the algorithm would not work for numbers 4, 6, 8 and 9 - that seems like either a subtle bug in the loop or just a misunderstanding. I would add some test cases to prime and verify it with lots of different inputs.
prime takes a u128, but then drops precision when converting it to f64 before taking the square root. Since Integer -> Float -> Integer conversion can succeed while changing what the value is, I suspect there are corner cases where the range is miscalculated. See also this discussion.


Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list

Your if(head == null || k < 0) special case is unnecessary, since it is covered by the if(k > map.size() -1) test.  You should also never omit the "optional" braces for a multi-line block.

Actually, the if(k > map.size() -1) test could also be eliminated, if you used Map.getOrDefault(…, -1).

The loop would be more easily recognized if written as a for loop.

public static int getKthToLastElement(LinkedListNode head, int k) {
    int index = 0;
    Map<> map = new HashMap<Integer, Integer>();
    for (LinkedListNode n = head; n != null; n = n.next) {
        map.put(index++, n.data);
    }
    return map.getOrDefault(map.size() - 1 - k, -1);
}

I think that converting the linked list to an ArrayList would be better than converting it to a HashMap.  You would then be converting a cumbersome linked list into a kind of list that is useful and idiomatic in Java.


Fetching detail for a given ID, which might not exist

In this case, I would suggest that this exception should be classified as a 'Boneheaded' exception as defined by Eric Lippert because there is no reason why the code should throw the exception at all.  Exceptions are expensive, as is handling them so I would make every effort to have code that only has them in TRULY exceptional circumstances.

It seems to me like the reason the _detail[id] throws a NullReferenceException is because the GetDetailForNewObjects method had a problem which could be in many forms, but I'll outline two below.

This problem could be one of

Your DB Query (assuming that is what is happening) couldn't find any records.

Solution: return a null object.  Don't try to access something you know has a reasonable possibility of being null, instead check again for null and return null if no object exists after the call.  Let the calling code figure out what to do with a null (maybe search results are null, this is not an exception).

Your DB had a connection issue / timeout

Solution:  Again, THIS is the exception that should be passed up.  We shouldn't handle a DB exception (since there it typically nothing that can be done about it), just to throw a null reference exception.  This behavior would make debugging more difficult since it hides the actual DB connection issue.  Bubble the DB exception upwards so the code / developer can respond to that, instead of an ambiguous NullReferenceException because ultimately, we need to know WHY it was null since clearly we weren't expecting it to be.

In both cases, we as developers know how to handle the situation (given the assumptions I laid out).

I would write the above code something like this:

public Detail GetDetail(int id) {
    if(id < 0) {
        throw new ArgumentException("id", "Argument should have a positive value.");
    } // end if
    Detail returnValue = null; // value store that is only assigned if the call succeeds
    if (!_detail.ContainsKey(id)) {
        GetDetailForNewObjects(id); // assuming this adds the key to the dictionary.
        if(_detail.ContainsKey(id)) { //Cheaper and safer than handling an exception
            returnValue = _detail[id].Data;
        } // end if
    } // end if

    return returnValue;
} // end function GetDetail

Eric Lippert has a great description of when / how to handle different types of exceptions here: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx

Further reading:

https://softwareengineering.stackexchange.com/questions/133560/how-to-avoid-throwing-vexing-exceptions
Is catching 'expected' exceptions that bad?


Faster output to Sheet from a collection of Dictionaries

A couple of review points.

Goto. Using Goto is a real bad smell. In your case, you can remove the spaghetti very easily.

Sub getData(Parsed As Object, company As String, a, wb)
        'Parsed contains a collection of dictionaries parsed from a JSON input'
        Dim oSheet As Variant
        Dim i As Long
        Dim j As Long
        For Each oSheet In ActiveWorkbook.Sheets
            'Identify the sheet containing the name of the company'
            Dim matchSheet As String
            If InStr(UCase(oSheet.Name), UCase(company)) Then
                matchSheet = oSheet.Name
            Else
                GoTo nextIteration
            End If
                ' [Main Code Block]
nextIteration:
        Next oSheet
End Sub

Becomes

Sub getData(Parsed As Object, company As String, a, wb)
        'Parsed contains a collection of dictionaries parsed from a JSON input'
        Dim oSheet As Variant
        Dim i As Long
        Dim j As Long
        For Each oSheet In ActiveWorkbook.Sheets
            'Identify the sheet containing the name of the company'
            Dim matchSheet As String
            If InStr(UCase(oSheet.Name), UCase(company)) Then
                matchSheet = oSheet.Name
                ' [Main Code Block]
            End If
        Next oSheet
End Sub

Much cleaner!

Select. I can see why your code does not work without using Select. And you do not need it. You have unqualified references to Range objects (in this case Cells) that are acting on the active sheet. By selecting the sheet, you are changing the active sheet but there is no guarantee that it is going to stay that way!

            wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(Parsed.Count, ArrayLen(a))) = Values
            'populationg the headers for that data'
            wb.Sheets(matchSheet).Range(Cells(1, 1), Cells(1, ArrayLen(a))).Value = a
            wb.Sheets(matchSheet).Range("D:D").NumberFormat = "General"

Is better expressed in a With statement for brevity and ease of reading (note that the "." are also in front of the Cells, this is the critical change to your original code).

            With wb.Sheets(matchSheet)
                .Range(.Cells(1, 1), .Cells(Parsed.Count, ArrayLen(a))) = Values
                'populating the headers for that data'
                .Range(.Cells(1, 1), .Cells(1, ArrayLen(a))).Value = a
                .Range("D:D").NumberFormat = "General"
            End With

ReDim. Probably not a huge issue, but you ReDim every loop instance on values that are passed in at the start. Set your Values array up once before you enter the loop. By the looks of your code, you clobber the values in the array each time you go through the loop, so you don't even have to clear it.

I would guess that your biggest performance hit is iterating through the dictionaries. If you could bring your data in in a cleaner fashion, it may help your performance.


Website monitor - if site is down, kill the process, contact admin and restart server

Indent code blocks

To improve readability,
it's good to indent code blocks in loops and if statements.
For example:

while true
do
    /usr/bin/curl -sSf --max-time 10 $SERVER > /dev/null 2>&1
    CS=$?

You indented some if statements, but not all. Indent all.

Replace elif with else if possible

In these conditions:

    if [ $CS -ne 0 ]
    then
    echo "$SERVER is down"

    elif [ $CS -eq 0 ]
    then
    echo "$SERVER is up"

If $CS is not-not-zero, then when can it be? Zero, of course!
So the elif can be a simple else.

Use $(...) instead of `...`

`...` is old-fashioned and error prone. Use $(...) instead.

ps ... | grep ... | grep -v grep

Instead of:

ps -eaf | grep 'python -m fore.server' | grep -v grep

A common workaround is:

ps -eaf | grep '[p]ython -m fore.server'

This works, because this way in the output of ps, the process python -m fore.server will still match, but grep '[p]ython -m fore.server' will not match.

However, in this particular example you should go a bit further, see the next point.

Look suspiciously at grep in a pipeline ending with awk

awk is fast and powerful,
and very often can easily do grep's job too when it's in the same pipeline.

For example instead of this:

ps -eaf | grep 'python -m fore.server' | grep -v grep | awk '{print $2}'

You can rewrite the whole thing using awk alone:

ps -eaf | awk '/python -m fore.server/ {print $2}'

This is not only shorter and less troublesome (no need for the grep [p]ython trick),
and there are less processes executed in the pipeline.

Don't repeat yourself

You do some things twice, with identical or very similar commands:

Finding the PID of the Python process
Sending an email with the message that the server is down
Sending an email with the message that the server is back up

It would be better to move common operations to helper functions.

Other simplifications

Instead of this:

    if [[ "" !=  "$PID" ]]

You can write as:

    if [[ $PID ]]


BFS to check if path from start node to end node exists

Notes:

You should strive to keep the left-hand side type as general as possible. That means HashMap<Integer, ArrayList<Integer>> graph should be
Map<Integer, List<Integer>> graph.
This is preferrable to enable simple substitution of implementations.
For more information why that's useful, look up the "Liskov Substitution Principle"

The same considerations apply for edges and visited, though interestingly not for queue.
It's significantly easier for the compiler and the JVM to iterate with an int counter and not an Integer counter, because the latter requires unboxing and boxing on every single operation you perform.
Your algorithm only performs forward jumps. While the implications of the problem itself, as well as the fact that you're actually checking every single node that's reachable forward mean that you never have to consider backward jumps, that is problematic for general graph searches.
You can save a ton of time by implementing the Queue with a TreeSet. Using a Set prevents duplicate iterations, which you currently do not. You should also be able to get a lot of speed out of "greedily" searching, by jumping as far ahead as you possibly can in each step.

Note that what I said in 4 also should give you a hint as to how you can solve the problem without using a graph-search.


Function to find longest word in a string

Good on you for writing real tests.

Overall, the code seems fine as-is (edit: Actually, no. See David Harkness' comment on the question; arguments.split should be str.split) though I do have a few comments:

The JavaScript convention is to use camelCase for variable names - not snake_case.
Splitting by " " works, but a more comprehensive solution would be to split by /\s+/. That is, split by one or more whitespace characters. That way you avoid zero-length strings in the array if there are two spaces in a row, and it'll also split on newlines and other whitespace. And if you trim() the string first, you'll also avoid empty strings at the start/end if the input string has leading or trailing whitespace.

Also the whole thing can be made more functional (and use some ES6 syntax):

function longest(string) {
  return string
    .trim()
    .split(/\s+/)
    .reduce((longest, word) => word.length > longest.length ? word : longest);
}

reduce (aka "fold" in other languages), when given no 2nd argument, will use the first element - the first word - in the array as its initial memo. The callback then either reuses that word, or replaces it when it finds one that's longer. Whatever the memo is at the end is what gets returned.

Another approach, much less functional, could be to use String.replace as a "scan" function:

function longest(string) {
  var length = 0;
  var longestWord = "";
  string.replace(/\S+/g, (word) => {
    if(word.length > length) {
      length = word.length;
      longestWord = word;
    }
    return ""; // for good measure; otherwise all words will be replaced with "undefined" in-memory
  });
  return longestWord;
}

The regex finds any run of non-whitespace character of length 1 or more. It's not terribly pretty, since replace isn't being used "as intended", really, and there are some closure side-effects. It doesn't have the memory consumption of the previous solution however (no array used to hold the split string).


Test if a key exists anywhere in a nested object

Your code has a couple of problems:

Semantic

You are using the construction key in obj, without checking if key is an actual property of obj. If obj is not an Object, but instead something resembling a class:

var PolarBear = function() {
  this.cuddly = true;
}

PolarBear.prototype.growl = function() {
  //nothing
}

Passing an instance of PolarBear to your function will return a function reference whenever you check if "growl" is a key. You could change this behaviour by checking if obj.isOwnProperty( key ) is true, or checking if obj is an Object.

Logic errors

Early return

If a key is an Array, and that array does not contain your key, your code will return anyway, even though you have not checked every key yet.

An example would be key "c" in the following Object. It is there, but your code would return false instead of 2, because the Object under key "a" does not contain a key "c".

{
  "a" : {
    "b" : 1
  }
  "c" : 2
}

Not exact key

Your code does not check if the key requested is the actual key we get. Some keys are transformed to an actual key. For example:

{
  "" : 1,
  "null" : 2,
  "false" : 3
}

Obviously, "" in obj would return true, but so would [] in obj, or null in obj, or false in obj, even though strictly speaking there is no key with that name. You could instead do Object.keys( obj ).indexOf( key ) > -1.

Not returning key of Object under Array

You are silently ignoring Arrays. I suspect you do this because you do not want to return keys in Arrays, but this also means that if you have an Object inside your Array, you'll silently ignore this. For example, the key "c" in the following Object will be ignored, and thus false will be returned

{
  "a" : [
    { "b" : 1 },
    { "c" : 2 }
  ]
}


Some suggestions:

shellcheck should give you a few suggestions. I won't mention things I expect it to find.
Uppercase names are by convention only used for exported variables.
SUBDIRECTORY_OK is unused. If it's a magic variable this probably should be mentioned.
SIZER is only used once, so it should be inlined.
wc -w 8.30 from GNU coreutils, at least, does not output any spaces, so tr -d ' ' might be unnecessary.
(($# > 0)) would usually be written [[ "$#" -gt 0 ]].
Throwing away standard error means the script will be harder to debug. If there's specific output there you want to hide you can use cmd 2> >(grep -v … >&2)
commit_len is slow because for each commit you run a git command & more to count the number of commits before it. Which means you traverse the Git history N times. I think you'll get the same result by running size "$1".
You can use shift to simplify things like "${@:2}" to just "$@".
dc is not a tool I'm familiar with, but it will certainly be faster to count using something like awk to gobble the whole stream in one command. while read is actually surprisingly slow.


Find the first occurrence of a substring in a string

Comments about your code:

I believe that you would rename it to something like strstr if you could.

You should accept pointers to const char, since you don't modify them.

You should initialize i and n right inside the loop. It will narrow their scope and make the code more maintainable since it won't pollute the scope of the function. On top of that, they will be deallocated whenever the loop ends.

using int for index is a very bad idea. The biggest issues with it that it is signed and not guaranteed to be large enough. You should use size_t instead, because it is guaranteed that size_t will have enough capacity to index array of maximum possible size.

You're increasing overhead by using subscript ([]) operator.

Loop could be rewritten in other, more readable and straightforward form, one of which is shown in suggested implementation. I know that you would like to have high performance, but I don't think that it is that important in this situation. May be with more context of the usage of the algorithm I could suggest particular algorithm (there are quite a few of them). The best in my opinion is Boyer–Moore string search algorithm.

Suggested implementation:

I think that strncmp should be used. I know that including string.h header defeats the purpose, but you could write your own. It increases code reuse in C!

To make it work we just need to precalculate length of the substring.

const char *strs(const char *text, const char *substr)
{
    size_t substrlen = strlen(substr);
    while (*text != 0)
    {
        if (strncmp(text, substr, substrlen) == 0)
        {
            return text;
        }
        ++text;
    }

    return NULL;
}

The performance gain from the data being const depends on physical constness and the compiler. Further reading.

About performance gain..


How to write a method that takes a general iterator as input argument?

How about:

template<typename C>
void ConvertUtility::ConvertEdgeIndexList(C const& edgeIndex)
{
     typename C::const_iterator sit;
     for(sit=edgeIndex.begin(); sit!=edgeIndex.end(); ++sit)
     {                                      //        ^^ Prefer pre-increment on iterators.

     }
}

PS. Stackoverflow may be a better site for this type of question.


Customized method for dataframe in my analysis module

This if statement

    if ind < 3 :
        transformed_str.append(data_str[ind])
    else:
        transformed_str.append(data_str[ind])
        transformed_str.append(sep_line)

Can be rewritten as

    transformed_str.append(data_str[ind])
    if ind >= 3:
        transformed_str.append(sep_line)


Technically the code is broken: it will accept a ")" string as valid (test at line 25 doesn't flag an error if the stack is empty).

Naming

I think you got a bit overboard. Names shall be descriptive, which doesn't imply that they shall be long. individualCharRight is definitely confusing. I'd suggest something like innermost perhaps.

delimiterCheck also doesn't reflect the nature of the function. It is supposed to test a validity of nested brackets; isNested could be more to the point.

Error reporting

For a low level function I'd recommend to avoid printing anything, but return an error code instead. There are 2 clearly defined error conditions (an unbalanced closing bracket and an unclosed opening one); the method should return an error code and a position of an offending bracket. The latter observation means that a bracket position should be recorder at the stack along with the bracket itself.

Interface

As mentioned above, the method should return an error code and an error location.


You're stuck at a point where your readability is good, and any performance improvements are going to come at the expense of making the code more ugly. Additionally, you're already
making architecture choices based on the compiler's interpretation of 'unsigned'. It's already not pretty.

Oh, and the un-braced 1-line for-loop is a problem for readability too.

I don't know of any optimizations that are available at this point that will not come with the portability, or readability cost. For a block-size of 16 bytes, and with a likely 4-byte unsigned value, the odds are that your loop will iterate 4 times only anyway.

The compiler may unroll that loop, and move on.

The above is just a waffle that really means: from here on, you cannot accomplish all three: clean code, portability, and performance. You need to compromise somewhere.

Profiling would be the logical thing to do. profile your current code, and establish a baseline.

I would then suggest that you investigate whether you can have a larger block size. Any alignment fiddling you may have to do will pay off better if you are working with larger blocks. Can you batch these blocks in to 1MB contiguous regions?

With larger contiguous blocks you could then consider vectorization, alignment, and other optimizations that have an increased, and fixed setup cost, but improved throughput.

Additionally, I would consider forcing bigsize_t to be unsigned long long, and then manually unroll the loop. If you find an exact type that is 64 bits (there has to be one? and, if not, you can have an alternate implementation...), then you can force your type to match:

#include <limits.h>

#if UINT_MAX == 18446744073709551615ULL
typedef unsigned int big64_t;
#elif ULONG_MAX == 18446744073709551615ULL
typedef unsigned long big64_t ;
#elif ULLONG_MAX == 18446744073709551615ULL
typedef unsigned long long big64_t;
#else
#error "Cannot find unsigned 64bit integer."
#endif

big64_t *s = reinterpret_cast<big64_t *>(dst);
const big64_t *au = reinterpret_cast<const big64_t *>(a);
const big64_t *bu = reinterpret_cast<const big64_t *>(b);

s[0] = au[0] ^ bu[0];
s[1] = au[1] ^ bu[1];

With systems that are not natively 64-bit, the compiler will adjust the operation to be relatively efficient anyway.

In the event that this is the year 2100, and all datatypes are 128 bit, or more, then you should possibly add the code that does a single 128-bit XOR for your input.

I see the above as being as portable, and equally readable. As for the performance, that will require a profile and benchmark.


Mouseover effects for social network icons

Styling and readability

Your indentation is incorrect. This makes it harder to read, and makes people assume that "mouseout" belongs to a different Object that it actually does.

Whitespace is not always consistent (e.g. $(this).rotate({animateTo:360}); versus other uses of Objects.

DRY

As you correctly noted, this code repeats itself quite a bit.

The code seems to only differ in id and logo name. You have various options:

You create a function that sets this. I am not entirely sure what you would name it, but something like setRotationEffects( id, logoName ); might do the trick.
You can use named functions for mouseout and mouseover. This will leave you with a basic boilerplate for each id:

$("#linkedin").rotate({
  bind:
  {
    mouseover : whatEverYouCallIt,
    mouseout  : whatEverOtherThingYouCallIt
  }
});

This might be more optimal if you expect to have other similar constructs with different effects.

Similarly:

The id in the mouseover and mouseout handler is not needed. In the handler you can use $(this) instead. This leaves you with only the name of the logo.

You can consider pulling this name from the existing logo. After all, the logo was set to a particular name in the first place. This makes all these identical.
You can use an anonymous function containing a function call with parameters (function() { doTheThings( id, logoName ); }.

Note: It might be just me, but I link "optimize" to "performance", and DRY has nothing to do with performance. We use DRY to make maintenance easier, not to make code outperform "WET" code.


Checking to see whether a document can be deleted

I assume that checkIfLocked() returns void, and throws a BusinessException if the document is locked.

There is one way to succeed, and many ways to fail.  I think it would be beneficial to rearrange the code to make it obvious what the criteria for success are:

public void checkIfCanDelete() throws BusinessException {
    if (editable && canDelete()) {
        checkIfLocked();
        return;  // Can delete
    }

    // Can't delete.  We just have to choose a reason for the denial.
    if (canDelete()) {
        assert !editable;
        throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);
    } else if (newDoc) {
        throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT);
    } else if (getSetting().isExcludedFromDeploy()) {
        throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT);
    }
    checkIfLocked();
    throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);
}

The code above preserves the same logic as the original.  However, if you're not picky about which reason you pick for the denial, you could simplify the code further:

public void checkIfCanDelete() throws BusinessException {
    checkIfLocked();

    if (!(editable && canDelete())) {
        throw new BusinessException(
            newDoc ?
                BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT :
            getSetting().isExcludedFromDeploy() ?
                BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT :
                BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS;
        );
    }
}


Configuring MVC 5 project with service layer and DI and UOW

public class BaseController : Controller
{
    protected IUnitOfWorkService UnitOfWorkService;
    private readonly IEmployeeService _employeeService;

    protected BaseController(IUnitOfWorkService unitOfWorkService)
    {
        UnitOfWorkService = unitOfWorkService;
        _employeeService = unitOfWorkService.EmployeeService;
    }
}
public class HomeController : BaseController
{
    private readonly IEmployeeService _employeeService;

    public HomeController(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)
    {
        _employeeService = unitOfWorkService.EmployeeService;
    }

    public ActionResult Index()
    {
        var emp = _employeeService.GetEmployee(employeeId);
        ...
    }

    ...
}

I don't see a reason here to have private readonly IEmployeeService _employeeService; in the HomeController. It would be better to make the _employeeService variable of the BaseController protected so it can be used by the objects which inherits the BaseController.
Why is the protected IUnitOfWorkService UnitOfWorkService; not readonly ?

Style

Using abbreviations or naming variables is bad practice. Does it hurt to name the variable IEmployeeRepository _employeeRepo like IEmployeeRepository _employeeRepository ?
It does not hurt to use braces {} for single if statements but will make the code less error prone. I would like to encourage you to always use them.


Is this a decent way of writing a start-stop-daemon script?

Probably, you also may implement condrestart:

  The condrestart (conditional restart) option only starts the daemon if it is currently running.
  This option is useful for scripts, because it does not start the daemon if it is not running.

Quote from question about condrestart at LinuxQuestions


You have a lot of repetition in your code.
The only thing different with the 2 lines of code repeated over and over is the argument.

You could put all of these arguments into a list and iterate over them, running those 2 lines of code for each:

List<String> states = Arrays.asList(isRQMRunning_3, startRQM_4,
  pendingChangesStatus, acceptPendingChanges_8,
 loadWorkspace_5, acceptPendingChanges_8, fixConflicts_9);

for (String state : states)
{
    // Loop until array is complete
    CompletableFuture<String> cf = CompletableFuture.completedFuture(state);

    if (!cf.isDone())
    {
        break;
    }

    System.out.println("Value- " + cf.get());
}


Showing a JDialog whenever there is an exception

At first I had two different methods for each one but now I combined
  them into one.

I would have made 3 methods instead of one.

public static void showError(String errorMessage) {
    showError(errorMessage, "Error!");
}

public static void showError(Exception exceptionError) {
    String errorMessage = "Message: " + exceptionError.getMessage()
                + "\nStackTrace: " + Arrays.toString(exceptionError.getStackTrace());
    String title = exceptionError.getClass().getName();
    showError(errorMessage, title);
}

public static void showError(String errorMessage, String title) {
    JOptionPane.showMessageDialog(null, errorMessage, title, JOptionPane.ERROR_MESSAGE);
}

In this way the readability is improved, unnecessary checks are removed as well as casts.
And it is easier to maintain.


Bugs

Colorama Not Initialized

Colorama should be initialized, to ensure proper operation:

import colorama

colorama.init()

Clear Screen

  sh: cls: command not found

On non-Windows machines, cls is not defined

Instead, simply use colorama to clear the screen.

def clear():
    print(colorama.ansi.clear_screen())

Play again

Do you want to play again? <Y>es or <N>oY
Do you want to play again? <Y>es or <N>oN
Do you want to play again? <Y>es or <N>oy
Do you want to play again? <Y>es or <N>on
Do you want to play again? <Y>es or <N>o

No answer seems to provide the expected behaviour, due to:

while play_again != 'y' or play_again != 'n':

always being True.  You need the and conjunction, not or.

Unused variables

toh = TowerOfHanoi(n1, 1, 2, 3)

toh is never used after this point.  So, why store it in a variable?

Global variables

a = [i for i in range(1, n1 + 1)]
b = []
c = []

toh = TowerOfHanoi(n1, 1, 2, 3)

a, b, and c are used inside the TowerOfHanoi class, but are not passed to the class.  Instead they are globals variables that must be properly initialized corresponding to the value n1 passed to the TowerOfHanoi constructor.

These lists should be created by the class itself, based on the argument passed to the constructor.  Moreover, they should be members of the class, not globals.

Code Duplication

This code:

    for i in a1:
        s = ' ' * (m - i + 1)
        h = Fore.RED + s + '██' * i + s + Style.RESET_ALL

        x.append(h)

is replicated 3 times, with a1 changing to b1 and c1, and x changing to y and z.  Perhaps you could refactor this into its own function, taking the rod list as input, and generating & returning the lists internally?

    def rod_images(self, rod):
        # Fill rod with required 0's at top
        rod = [0] * (self.n - len(rod)) + rod

        image_rows = []
        for i in rod:
            spaces = ' ' * (self.n - i + 1)
            row = Fore.RED + spaces + '██' * i + spaces + Style.RESET_ALL
            image_rows.append(row)

        return image_rows

Then you could simply write:

    def parser(self, a1, b1, c1):

        x = self.rod_images(a1)
        y = self.rod_images(b1)
        z = self.rod_images(c1)

        # ... etc ...

Zero, One & Many

In programming, there are 3 important numbers: zero, one, and many.  How many rods do you have?  More than one, so ... you have many rods.  Many items are stored in containers, such as lists, not individual variables.  So instead of this:

    self.r1 = r1
    self.r2 = r2
    self.r3 = r3

write something like:

    self.rods = [r1, r2, r3]

Then, instead of

    print(' ' * self.n + str(self.r1)
          + ' ' * (self.n * 2 + 1) + str(self.r2)
          + ' ' * (self.n * 2 + 1) + str(self.r3))

you can take advantage of the fact that you are doing something with each item in the list, in order.  In this case, you are converting each item to a string, and then joining them together with a bunch of spaces in-between:

    print(' ' * self.n
          + (' ' * (self.n * 2 + 1)).join(str(rod) for rod in self.rods)

But ... that still looks ugly.  What you are really doing is printing out 3 values, each centred in a n * 2 + 2 character wide field:

    width = self.n * 2 + 2
    print((f"{{:^{width}}}"*3).format(*self.rods))

With 3 disks, this creates the format string "{:^8}{:^8}{:^8}" which centres the 3 values each in 8 character wide fields.

A similar method could be used to centre the discs when printing, as long as the colour/style codes are removed from the disc "values" and moved to the format string itself, so they don't mess up the character counts for automatic centring.

Unnecessary Default Arguments

Calling solve(), with no arguments, is only done from __init__().  So the only time the default arguments are used is that one call.  So why complicate the method with default arguments which must be set via a number of if _ is None: tests?  Simply use:

self.solve(self.n, self.r1, self.r2, self.r3, 0, 1, 2)

in the __init__() method, and remove the default arguments and default argument substitution code.


I tinkered a bit with the fiddle, I have the following observations:

If you were to place the colons in the HTML, then you would no longer need to concatenate the colons into the time fields:

  :
  :
  ::

You could generalize prependZero so that it works for both seconds and milliseconds by passing the requested length:

  function prependZero( time, length ){
      time = time + "";
      while( time.length < length ){
      time = '0' + time;
    }
    return time;
  }

or a more Golfic version which calculates the amount of zeroes that will be required:

function prependZero2( time, length ){
    time = time + "";
    return new Array( Math.max( length - time.length + 1 , 0 ) ).join("0") + time;
}

if(minutes > 60) minutes = minutes % 60; is the same as minutes = minutes % 60; is the same as minutes %= 60;.
Your code would be much cleaner if you split out time calculations from prettyfying the numbers.

You could have a function that is dedicated to time calculations:

function updateTime(domAttr, prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
  var startTime = new Date();
  timeUpdate = setInterval(function(){
    var timeElapsed = new Date().getTime() - startTime.getTime();

    // calculate hours
    hours = parseInt(timeElapsed/1000/60/60) + prev_hours;

    // calculate minutes
    minutes = parseInt(timeElapsed/1000/60) + prev_minutes;
    minutes %= 60;

    // calculate seconds
    seconds = parseInt(timeElapsed/1000) + prev_seconds;
    seconds %= 60;

    // calculate milliseconds
    milliseconds = timeElapsed + prev_milliseconds;
    milliseconds %= 1000;

    setStopwatch( hours , minutes , seconds , milliseconds );

  },25);  // update time in stopwatch after every 25ms

  return timeUpdate;
}

and a function that just updates the DOM:

function setStopwatch( hours , minutes , seconds , milliseconds ){
    require(["dojo/dom-attr"], function(domAttr){
        domAttr.set("hours"       , "innerHTML", prependZero( hours, 2 ) );
        domAttr.set("minutes"     , "innerHTML", prependZero( minutes, 2 ) );
        domAttr.set("seconds"     , "innerHTML", prependZero( seconds, 2 ) );
        domAttr.set("milliseconds", "innerHTML", prependZero( milliseconds, 3 ) );
    });
}

resetStopwatch then becomes as simple as

function resetStopwatch(){
    setStopwatch( 0, 0, 0, 0 );
}

A very minor nitpicking, but the require array is hard to read, you should figure out how Dojo proposes you should indent that array.
Another nitpicking is that you trust the DOM as your data model (you retrieve the values from the labels when you hit Resume), that is a bad practice in general, but acceptable for a timer project.

You can check the end result here.


Java loop extracting month and year between two dates

The code would be simpler if you used a Calendar object as the loop variable.

Calendar current = …;
Calendar end = …;

for (; current.before(end); current.add(Calendar.MONTH, 1)) {
    SeguimientoSeccion seccion = new SeguimientoSeccion();
    seccion.setMonth(1 + current.get(Calendar.MONTH));  // natural month number
    seccion.setYear(current.get(Calendar.YEAR));
    secciones.add(seccion);
}

Consider implementing a SeguimientoSeccion.setMonthYear(m, y) method instead, as it's probably useless to set one of the fields without also setting the other.


Is there a better way to write these two nested loops in Erlang?

In general, nested for loops translate well to list comprehensions:

Prods = [I*J || I <- lists:seq(100,999), J <- lists:seq(100,999)]
// Generates a list of products to perform further logic on


Solving the N-queens puzzle the Racket or Scheme way

Not sure if this is "the Racket way" but this one is faster, using Racket's sets and for loops:

(define (queens n)    ; n-queens, see http://en.wikipedia.org/wiki/Eight_queens_puzzle

  (define res null)   ; accumulator for results

  (define (s lst diags1 diags2 row columns)
    (if (= row n)
        (set! res (cons lst res))        ; got a result, remember it
        (for ((col (in-set columns)))    ; for every column left
          (define diag1 (+ col row))     ; compute diagonal 1
          (define diag2 (- col row))     ;     and diagonal 2
          (unless (or (set-member? diags1 diag1) (set-member? diags2 diag2)) ; if diagonals not already taken
            (s (cons (cons row col) lst)
               (set-add diags1 diag1)
               (set-add diags2 diag2)
               (add1 row)
               (set-remove columns col))))))

  (s null (set) (set) 0 (apply set (range n))) ; initial call
  res)

(time (for-each displayln (queens 8)))


While your code "works" for you, there are a lot of small mistakes in it. I'm listing them straight from top to bottom.
#include "stdio.h"

Since stdio.h is a header from the standard library, as opposed to a header you define yourself in your project, you should include it using #include <stdio.h> instead.
typedef struct Car {
    char*           name;
    unsigned int    price;
} Car;

The name of the car should be a const char * since later, you assign string literals like "Chevy" to that field, and string literals are read-only.
To prevent this possible bug in the future, let the C compiler warn you about issues like these. For GCC, pass the compile options -Wall -Wextra -Werror -O2. Since you didn't say which development environment you use, you have to find out how to add these options yourself.
void print_cars(Car* cars[]) {
    for (int i=0; cars[i] != NULL;i++) {
        printf("\n<Car: %s, Price: $%d>", car->name, car->price);
    }
}

Since print_cars does not modify the cars, its parameter should be const Car* cars[], just add the const.
There should be a single space around assignment operators. That is, write int i = 0 instead of int i=0. There should be a single space after the semicolon as well.
When a program produces output, the end-of-line marker \n should go to the end of the line, not to the beginning.
void depreciate(Car* cars[]) {
    for (int i=0; cars[i] != NULL; i++) {
        cars[i]->price = cars[i]->price * 0.95;
    }
}

Instead of writing cars[i]->price twice, you can make use of the combined assignment operator *= by writing: cars[i]->price *= 0.95.
The floating-point number 0.95 cannot be represented exactly in binary. You should experiment a little with a car price that would end up evenly. But even then you could end up with rounding errors. I wrote the following test snippet, which shows that for some prices, the actual result ends up lower than expected, because what you see as 0.95 is really 0.9499999999999999555910790149937383830547332763671875 for the computer.
#include <stdio.h>

int main(void)
{
    for (int i = 0; i < 1000; i++) {
        printf("%d: %.20f, %.20f, %d\n",
            i,
            i * 0.95,
            i * 95 / 100.0,
            i * 95 / 100);
    }
}

To keep the programming simple, you should stick to the last variant i * 95 / 100, until you get more experienced with floating point numbers.
int main(int argc, char* argv[]) {

    ...
    return 1;
}

The function main is special regarding its return value. Returning 1 means failure, returning 0 means success. Many other C functions return 0 for success (just like main) and -1 for failure. Others return non-zero for success and zero for failure. Things vary a lot, and you have to learn the meaning for each function individually. There are some patterns though, so it's not completely chaotic.
All in all, it's a well-written program. After modifying the few details I mentioned, it's perfect.


I took a shot at this as well. I think @Hangy had a few good ideas but ended up with a rather complex solution. I haven't added any caching so you might want to add that yourself afterwards.

What I changed:

Different check for null which is clearer in my opinion.
Braces for one-line statements.
Extracted member parsing to a separate method.
Instead of holding all data of PropertyInfo and FieldInfo, I simply use a Dictionary<string, object> which translates to <FieldName, FieldValue>.
Unused properties and fields data is eligible for GC as soon as you extracted the needed information.
Got rid of the Enumerator and added some juicy LINQ.

The end result:

public static class EqualityAttribute
{
    public static bool AreEquals<T>(T source, object obj) where T : class
    {
        if (ReferenceEquals(source, obj))
        {
            return true;
        }

        var convertedTarget = obj as T;
        if (convertedTarget == null)
        {
            return false;
        }

        var obj1Members = GetFieldEqualityMembers(source);
        var obj2Members = GetFieldEqualityMembers(obj);

        var noMembersToCompare = obj1Members.Values.Count == 0 && obj2Members.Values.Count == 0;
        if (noMembersToCompare)
        {
            return false;
        }

        if (obj1Members.Keys.Any(key => !obj1Members[key].Equals(obj2Members[key])))
        {
            return false;
        }

        return true;
    }

    private static Dictionary<string, object> GetFieldEqualityMembers<T>(T obj)
    {
        var properties = obj.GetType().GetProperties(BindingFlags.Public |
                                                     BindingFlags.NonPublic |
                                                     BindingFlags.Instance)
            .Where(x => x.GetCustomAttribute<EqualityMemberAttribute>() != null)
            .ToDictionary(x => x.Name, x => x.GetValue(obj));

        var fields = obj.GetType().GetFields(BindingFlags.Public |
                                             BindingFlags.NonPublic |
                                             BindingFlags.Instance)
            .Where(x => x.GetCustomAttribute<EqualityMemberAttribute>() != null)
            .ToDictionary(x => x.Name, x => x.GetValue(obj));

        properties.ToList().ForEach(x => fields.Add(x.Key, x.Value));
        return fields;
    }
}


Programming Language Identification in JS

Instead of ||, you could stuff the patterns in an array and use array.some(). If one of the patterns match the string, it will return immediately with true and skipping the rest of the array.

const patterns = []
patterns.push(pattern1)
patterns.push(pattern2)
patterns.push(pattern3)
return patterns.some(p => string.match(p))

Taking it further, you can use a key-value pair of language name and patterns. Then use Object.keys and array.find to find which key has the set of patterns that match the string. For the sake of brevity, variable names are shortened.

const l = {
  java: [/* array of java patterns */],
  python: [/* array of python patterns */],
  c: [/* array of c patterns */]
}

// "For each language in languages, find the language that contains a
// pattern that matches the string"
const language = Object.keys(l).find(k => l[k].some(p => s.match(p)))

Also note that some languages have common syntaxes. If you want to go this route, you'll have to find syntax that's unique to the language or risk mistaking one language for another. For instance, True may be a Python boolean... or a variable name in Java. The same with class, is it a Python class or Java class. What if I defined a string in Java that's valid Python?


Method to get user information (OOP / MVC approach)

What you have isn't really a function to search for a user, but a function to get a user, either by id or by name.

So instead of having one function that does two different things, why not have two functions?

public function getUserById($db_con, $id){
    $queryGetUser = $db_con->prepare('SELECT * FROM users WHERE user_id=:id');
    [...]
}

public function getUserByUsername($db_con, $username){
    $queryGetUser = $db_con->prepare('SELECT * FROM users WHERE user_username=:username');
    [...]
}

Now you don't have to pass empty strings to the function (which is really confusing to use), and the functions have a proper name as well.