If you forbid function calls you cannot use getters which then is a big restriction. If you allow them it is hard to get it safe. Also your regexes will have collateral damages and filter legal expressions. So I think your approach is not so good. Don't allow users to mess with format strings. Use Template from string for that purpose.

to your regexes:

if you have a re for function you do not need one for system
[\w] includes [\d]
your re function catches only calls without arguments
re function and re system do not care about whitespaces and are vulnerable
all regexes do collateral damage when matching outside the format braces

here are some more test that currently fail

    '''
    some attacks
    >>> safe_format('a_function(666)')
    ''

    >>> safe_format('a_function ()')
    ''

    >>> safe_format('{os. system("dir")}')
    ''

    some collateral damage
    >>> safe_format('...system(left) {5}')
    '...system(left) 5'

    >>> safe_format('f() gives {5}')
    'f(g) gives 5'

    '''


Calculate all anagrams of a word with Perl

You have written very self-documenting code! That's good. However, you seem somewhat new to Perl, so I'll walk you through some Perl-specific best practices and idioms.

Namespaces/Packages/Modules, use vs. require

You have put your implementation into a separate file anagrams.pm, which you load via require 'anagrams.pm'. When writing a Perl module, we should put it into its own namespace. There is a relationship between file paths and package names: a package Foo::Bar::Baz should reside in a file Foo/Bar/Baz.pm. It is customary for package names to use PascalCase. Lower-case names are only used for pragmas such as strict or warnings that modify how Perl itself behaves. While package names look hierarchical, they are only so by convention: Foo::Bar is not technically an “inner package” of Foo, although names are often used in this manner. Top-level package names should not be used for “real” code, since this is likely to clash with package names from CPAN (the open-source Perl module repository). The Local:: namespace can be used to avoid clashes, since no CPAN module will ever use it. However, if you want to distribute your module, you should reserve a namespace: either by publishing your code in CPAN under a specific module name, or by registering a PAUSE account name. The PAUSE account name can be used as a reserved namespace. E.g. I have some unpublished personal software under the AMON:: prefix.

Assuming you do not intend to distribute your code, using the name Local::Anagrams might be sensible.

To load a module, there are three main techniques available:

require 'path' is rarely used, since the module system is often preferable.
require Module::Name searches for Module/Name.pm in all registered module locations at runtime. This form is only used for deferred module loading, where we only want to load a module if a specific code path was taken.
use Module::Name is like require Module::Name, but at “compile time”. It is the preferred module loading mechanism, since it allows the loaded module to put symbols into the loading namespace.

The problem with namespaces is that symbol names become tediously long. For example, the get_permutations sub from Local::Anagrams would be accessed as Local::Anagrams::get_permutations. When loading our module with use, we can allow certain symbols to be exported from our namespace. Traditionally, the built-in Exporter module is used. In the package-global variable @EXPORT_OK, we list the names of all subroutines we want to make available. The useing module can then list the sub names it wants to import:

package Local::Anagrams;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = qw/ get_permutations is_element_in_list /;

...

Then in get_anagrams.pl:

use Local::Anagrams 'get_permutations';

And in anagrams.t:

use Local::Anagrams qw/ get_permutations is_element_in_list /;

In larger software systems, exporting symbols doesn't really scale and may still introduce name clashes. The Sub::Exporter module allows the importing module to customize the imported subroutines, but at some point you might give up and prefer to deliver your functionality via an object-oriented rather than procedural interface.

Previously, I said that Perl searches for modules in “all registered module locations”. These can be inspected in the @INC global variable. For example, the current working directory . is usually part of @INC. But unless you install your custom modules via CPAN, they will not generally be in one of the expected locations. If we want to load a module relative to the location of a script, we have to add a new module location:

# in get_anagrams.pl:
use FindBin;  # finds the location of our script
use lib "$FindBin::Bin/../lib";

use Local::Anagrams;

This assumes a standard project directory layout such as

anagrams-project/
  bin/
    get_anagrams.pl
  lib/
    Local/
      Anagrams.pm
  t/
    anagrams.t

For tests, I don't use Find::Bin. Instead, I supply the library directory to the test runner, e.g. perl -Ilib t/anagrams.t or prove -l t.

get_anagrams.pl

All Perl scripts should use a shebang – generally #!/usr/bin/perl or #!/usr/bin/env perl. While this is only used on Unix systems or in some web servers, I'd still recommend using it even on Windows.

my $number_of_arguments = $#ARGV + 1 is a complicated way of saying my $number_of_arguments = @ARGV. Actually, the variable $number_of_arguments is useless here, and you could use @ARGV directly.

Error messages should go on STDERR, not STDOUT. This becomes really important when your program is used in a pipe, or with shell redirection. E.g. perl get_anagrams.pl > anagrams.txt would write the error to the file rather than displaying it to the user. Instead:

say STDERR "Usage: get_anagrams.pl <word>";
exit 1;

Note that after STDERR there is no comma. You could also use method syntax:

use IO::File;
...

STDERR->say("Usage: get_anagrams.pl <word>");
exit 1;

If the exact exit code is not relevant, you could just throw an exception with die, which would have the same effect, except for the exit code being 255 (= -1):

die "Usage: get_anagrams.pl <word>\n";

If you do not want to hardcode the name of the executed program, you can use the special $0 variable:

die "Usage: $0 <word>\n";

This may or may not result in a better error message.

It may not be the most readable style, but I like the statement modifier versions of Perl's control flow constructs a lot. For example, I'd write your loop as

say for get_permutations shift @ARGV;

When say or print aren't given an explicit argument, they default to the implicit $_ context variable, which is used by for/foreach loops when not given an explicit loop variable.

get_permutations():

When looping over all indices of an array, do not use a C-style for loop. Instead, use a range-base loop

for my $i (0 .. $#letters) { ... }

or just instruct Perl to iterate over all indices with keys @letters (available since v5.12.0):

for my $i (keys @letters) { ... }

Note that for and foreach are synonymous, so you have no reason to type out the longer name.

Your algorithm doesn't handle the empty string. get_permutations('') should return the single-element list ''. With it, all cases can be reduced to the two alternatives zero-length or n-length input strings; special-casing 1 and 2 is unnecessary.

sub get_permutations {
  my ($string) = @_;
  my @letters = split //, $string;

  return '' if not @letters;

  my @permutations;
  for my $i (keys @letters) {
    ...
  }
  return @permutations
}

The pattern

for my $var (@input) {
  push @output, simple_expression($var);
}

can be reduced to

push @output, map { simple_expression($_) } @input;

though some people prefer explicit loops for readability.

remove_letters_by_index

Try to avoid single-character operations whenever possible, since these are not at all efficient in Perl. We can implement this function without having to split the string. To remove d (index 3) in the string abcdef, we concatenate the string with indices 0–2 (length 3) and 4–5 (length 2):

0 1 2 3 4 5
|a|b|c|d|e|f|

substr("abcdef", 0, 3) . substr("abcdef", 3+1);

substr takes a start index and a length. Care has to be taken that the substr starting index is a legal index, which is relevant when we are trying to remove the last character.

sub remove_letters_by_index {
  my ($string, $index) = @_;
  return substr($string, 0, $index) if $index + 1 >= length $string;
  return substr($string, 0, $index) . substr($string, $index + 1);
}

We could also just ask Perl to delete a specific character in a string:

sub remove_letters_by_index {
  my ($string, $index) = @_;
  substr($string, $index, 1) = '';
  return $string;
}

With arrays, two similar solutions are possible. We can use the splice function to remove elements from a list:

sub remove_letters_by_index {
  my ($string, $index) = @_;
  my @letters = split //, $string;
  splice @letters, $index, 1;
  return join '', @letters;
}

Or we can use slices to access a range in the list. Slices use a list of indices, which can be generated by a range, and ranges use two indices as inclusive bounds. Since empty ranges do not pose any issue, we do not have to special-case the last character.

sub remove_letters_by_index {
  my ($string, $index) = @_;
  my @letters = split //, $string;
  return join '', @letters[0 .. $index - 1, $index + 1 .. $#letters];
}

is_element_in_list

This function is only ever used in the tests, so it should rather be defined in the test file. It has nothing to do with the single responsibility of the anagrams module, which is finding anagrams.

You require that the $element be a truthy value, and report any falsey values as not found. The following scalars are falsey: undef, 0, '', '0', and any object that has overloaded boolean context or logical negation. Of these values, '' and '0' may legitimately occur in a list of anagrams: get_permutations('') and get_permutations('0'). If you are trying to guard against undef values, always test for definedness. And don't just return a failure – if this is an error, throw an error!

use Carp; # exports `croak`

# `croak` is like `die`, but reports the location
# where `is_element_in_list` was called.
croak "element must be defined" if not defined $element;

The @list is unnecessarily copied. When you pass arrays or hashes to a Perl subroutine, they are flatted to a list. The code

my @array = (1, 2, 3);
some_sub(@array);
my %hash (a => 1, b => 2);
some_sub(%hash);

is effectively equivalent to

some_sub(1, 2, 3);
some_sub('a', 1, 'b', 2);

To avoid this, we can pass array references. An array reference $ref = \@array is a scalar value. To access the array under the reference, we need to dereference it as @$ref or @{ $ref } and can access elements like $ref->[0]. Then:

sub is_element_in_list {
  my ($needle, $haystack_ref) = @_;

  croak "needle must be defined" if not defined $needle;

  for my $item (@$haystack_ref) {
    return 1 if $needle eq $item;
  }

  return 0;
}

Called as:

ok(is_element_in_list('abc', \@retrieved_permutations));

While modules must return a true value, this is usually accomplished with just 1; rather than return 1;.


Command line utility to output modified Markdown

Have you looked at https://github.com/caolan/async? It can really help with organizing your code. As the name implies, async was created to help with writing asynchronous code. While you are only calling one asynchronous function, we can still use it to help us structure our entire program.

Async aside, the general idea is to use functions to help us break down our problem. Instead of a loop within a loop, we can think about what that inner loop is doing and create a function to replace it (for example, our replaceChar function below).

With this in mind and using https://github.com/caolan/async#waterfall, we could write something like:

#!/usr/bin/env node

var fs = require('fs')
var program = require('commander')
var markdown = require('markdown').markdown
var async = require('async');

function printResult(e, r) {
    if (e) {
        throw e;
    }
    else {
        console.log(r);
    }
}

function parseMarkdown(data, cb) {
    cb(null, markdown.parse(data));
}

function replaceChar(node, search, replace) {
    var i;
    var re0 = new RegExp(search + '(?=\b)', 'g');
    var re1 = new RegExp(search + '(?!\b)', 'g');
    for (i = 1; i < node.length; ++i) {
        node[i] = node[i].replace(re0, replace).replace(re1, replace);
    }
    return node;
}

function replaceQuotes(tree, cb) {
    var i;
    for (i = 1; i < tree.length; i++) {
        tree[i] = replaceChar(tree[i], '"', '“');
        tree[i] = replaceChar(tree[i], "'", "‘");
    }
    cb(null, tree);
}

function replaceHr(tree, cb) {
    var i;
    for (i = 1; i < tree.length; i++) {
        if (tree[i][0] === 'hr') {
            var hr = tree[i]
            var p = tree[i + 1]

            hr.splice(0, 1, 'para', '* * *')
            p.splice(1, 0, {'class': 'noind'})
        }
    }
    cb(null, tree);
}

function convertToHtml(tree, cb) {
    cb(null, markdown.renderJsonML(markdown.toHTMLTree(tree)));
}

program
  .version('0.0.1')
  .usage('<keywords>')
  .parse(process.argv)

if (!program.args.length)
  program.help()

var filename = program.args[0]

async.waterfall([
    fs.readFile.bind(fs, filename, 'utf8'),
    parseMarkdown,
    replaceQuotes,
    replaceHr,
    convertToHtml
], printResult);


Getting data from API every x seconds and store it in a database

Quickly overviewing the code - it would work.
If you are into a more readable approach, I may have just a few (minor) comments:

Declare fetchItems as async, and use await for axios.

Instead of a for loop, use response.data.stashes.filter().
Adding all items in separate queries seems odd, is there a way to push all of them in a single transaction? Build the query outside in a helper function.

So your flow may look something like this:

const fetchItems = () => {/*... axios ...*/};
const filterItems = (item) => {/*.. return true or false */};
const buildQuery = (items) => {/*.. return SQL string ..*/};

async function execute() {
  try {
    const items = (await fetchItems()).filter(filterItems);
    const query = buildQuery(items);
    await db.query(sql);
  } catch (err) {
  /* handle it */
  }
}


Constructing an SQL expression from three parameters

My thought would be to create a collection of objects that can be iterated over. Each object would have an interface like the following.

def _getQuery(activity,pollutant,feedstock):
  for matcher in MATCHERS:
    if matcher.matches(activity,pollutant,feedstock):
      return matcher.get_result(activity,pollutant,feedstock)
  raise Exception('Not matched')

Then you build up the set of matcher classes for the various cases and ad an instance of each to MATCHERS. Just remember that earlier elements in the list take precedence to later ones. So the most specific cases should be first in the list ans the most general cases should be at the end.

NOTE:
Your string building code is vulnerable to SQL-injection. If you do go forward with manually building your selection strings, your input needs to be more thoroughly sanitized.


Encrypting a user's file with a key that isn't stored but only known by the user

I honestly disagree with this whole approach.  First, storing files IN a relational database is rarely a good strategy, limited almost exclusively to use cases where you want to perform binary searches against the binary artifacts.  That is not your use case here. Outside of that, you are just adding a lot of overhead to your typical database management operations (making DB backups/snapshots, replicating data across DB servers, etc.) without really any added value in having the files in the DB.

Your use case is simply one of needing to operate on the file in it's entirety, so I would think typical directory-based disk storage or cloud-based file storage mechanisms would make much more sense in terms of being able to operate against the collection of files as you typically would a collection of files.  Your database could then only store reference to the files.  I would have a strong bias towards using OS-based mechanisms for archiving, syncing, encrypting/decrypting, etc.   PHP obviously can give you entry points to these sorts of operations.

I also VERY much question your encryption approach (and the approach for trying to roll your own logic).  You are talking about what would seem to be an assymmetric cryptography use case here, but you are attempting to execute this using a symmetric encryption approach.  This approach seems to not make sense, because, as soon as the end user passes their key to the application, the application can now decrypt the data, as it now has the shared symmetric encryption key.

In this case you then need to generate a shared key for each user. This would beg the question as to why the user even needs to pass the shared key, since the application should theoretically already store it.  This means the application could decrypt the data without user interaction, which seems to not be what you desire.

If you truly want an assymmetric approach, then you probably need to forfeit the idea of the application performing ANY decryption at all. That should be up to the end user and/or a client-side application where this operation takes place.  Outside of that, it seems you are defeating the entire purpose of what you are trying to do, which is storage of an encrypted file without the ability for the application to decrypt it, without the user having a key.


"Researcher Hatim is right or wrong" challenge

You don't need a class

I highly recommend the Stop Writing Classes presentation. The typical situation it describes : a class with two methods, an init and a run is exactly what you've done.

Changing this already makes your code much simpler.

def run_test_case(file_):
    n, m = file_.readline().split()
    n = int(n)
    m = int(m)
    first_gender = []
    second_gender = []

    for i in range(m):
        x, y = 0, 0
        x, y = file_.readline().split()
        if first_gender == [] and second_gender == []:
            first_gender[ len(first_gender) : ] = x
            second_gender[ len(second_gender) : ] = y
        elif (x in first_gender and y in first_gender) or (x in second_gender and y in second_gender):
            print 'Suspicious lizard found!'
            return
        elif (x in first_gender and y not in  second_gender):
            second_gender[ len(second_gender) : ] = y
        elif (x in second_gender and y not in first_gender):
            first_gender[ len(first_gender) : ] = y
        elif (y in first_gender and x not in second_gender):
            second_gender[ len(second_gender) : ] = x
        elif (y in second_gender and x not in first_gender):
            first_gender[ len(first_gender) : ] = x
    print 'No suspicious lizard found!'

def start(filename):
    file_ = open(filename, 'r')
    num_test_cases = int(file_.readline())
    for i in range(num_test_cases):
        run_test_case(file_)

Close your file

You open a file but never close it. You should but it's quite normal to forget it. A nice solution not to forget it is to use the with statement.

def start(filename):
    with open(filename, 'r') as file_:
        num_test_cases = int(file_.readline())
        for i in range(num_test_cases):
            run_test_case(file_)

Separation of concerns

Your run_test_case functions does way too much : file reading to get input, getting solution for the problem, printing out the answer. It would be much nicer to have this splitted into individual functions. Among other things, it would make your code easier to test. Code-challenge are very good candidates for unit tests because the algorithm involved is usually pretty tricky, the input and ouput are usually pretty clear, no side-effect is expected and you are provided some simple tests with the problem.

Rewriting this gives :

def find_suspicious_lizard(interactions):
    first_gender = []
    second_gender = []
    for x, y in interactions:
        if first_gender == [] and second_gender == []:
            first_gender[ len(first_gender) : ] = x
            second_gender[ len(second_gender) : ] = y
        elif (x in first_gender and y in first_gender) or (x in second_gender and y in second_gender):
            return True
        elif (x in first_gender and y not in  second_gender):
            second_gender[ len(second_gender) : ] = y
        elif (x in second_gender and y not in first_gender):
            first_gender[ len(first_gender) : ] = y
        elif (y in first_gender and x not in second_gender):
            second_gender[ len(second_gender) : ] = x
        elif (y in second_gender and x not in first_gender):
            first_gender[ len(first_gender) : ] = x
    return False

def run_test_from_file(filename):
    with open(filename, 'r') as file_:
        num_test_cases = int(file_.readline())
        for i in range(num_test_cases):
            n, m = file_.readline().split()
            n = int(n)
            m = int(m)
            interactions = []
            for i in range(m):
                x, y = file_.readline().split()
                interactions.append((x, y))
            print('Suspicious lizard found!' if find_suspicious_lizard(interactions) else 'No suspicious lizard found!')

if __name__ == '__main__':
    (script, filename) = argv
    run_test_from_file(filename)
    assert find_suspicious_lizard([('1', '2'), ('2', '3'), ('1', '3')])
    assert not find_suspicious_lizard([('1', '2'), ('3', '4')])

With the test I've added, I can now tweak the algorithm and maybe see quickly if I break something.

Do things the easy way

second_gender[ len(second_gender) : ] = y seems like a complicated way to add an element to an array/list. If only there was an append method on Lists. Oh great, it is actually the first method documented.

def find_suspicious_lizard(interactions):
    first_gender = []
    second_gender = []
    for x, y in interactions:
        if first_gender == [] and second_gender == []:
            first_gender.append(x)
            second_gender.append(y)
        elif (x in first_gender and y in first_gender) or (x in second_gender and y in second_gender):
            return True
        elif (x in first_gender and y not in  second_gender):
            second_gender.append(y)
        elif (x in second_gender and y not in first_gender):
            first_gender.append(y)
        elif (y in first_gender and x not in second_gender):
            second_gender.append(y)
        elif (y in second_gender and x not in first_gender):
            first_gender.append(x)
    return False

Performance

You call foo in bar many times with the same values. It could be worth storing the result:

        x_in_first = x in first_gender
        y_in_first = y in first_gender
        x_in_second = x in second_gender
        y_in_second = y in second_gender
        if x_in_first and y_in_first:
            return True
        elif x_in_second and y_in_second:
            return True
        elif x_in_first and not y_in_second:
            second_gender.append(y)
        elif x_in_second and not y_in_first:
            first_gender.append(y)
        elif y_in_first and not x_in_second:
            second_gender.append(y)
        elif y_in_second and not x_in_first:
            first_gender.append(x)

It also helped me to think about the logic you've written and helped me to find... a bug!!

Bug

Adding a simple test case (I knew it would be worth it) shows that there is something wrong in your code.

assert not find_suspicious_lizard([('1', '2'), ('3', '4'), ('3', '5'), ('4', '5')])  # should return true because of triplet 3-4-5.


Converting data when output std container via ostream_iterator

It seems to me that if you want to insert an object into a stream, the "right" way to do it is normally to define an operator<< for that type. That goes for strongly typed enums just as much as it does for class/struct objects.

#include <iostream>
#include <vector>
#include <utility>
#include <iterator>

enum class colors { red, green, blue };
std::vector<colors> v = { colors::blue, colors::red };

std::ostream &operator<<(std::ostream &os, colors const &c) {
    return os << std::underlying_type<colors>::type(c);
}

int main() {
    std:copy(v.begin(), v.end(), std::ostream_iterator<colors>(std::cout, "\n"));
}

That seems simple and straightforward enough that I'd be at least a little surprised to see a substantially cleaner/simpler solution (at least in C++ as it's currently defined; obviously, it's open to argument that some other language or some future definition of C++ could make things cleaner).

Using something like std::transform puts the burden in the wrong place. It requires that all code that uses the type in question contain and encode "knowledge" of the internals of the enumeration. What you generally want is to contain the complexity and the internals of the type in one place, so the rest of the code can just work with its external interface. An external interface of stream << object is simple and straightforward. Forcing the rest of the world to work with an interface of stream << std::underlying_type<colors>::type(c); anything but straightforward or simple. It's ugly and nasty.


More efficient columnar transposition decryption

Allow me to provide a bit of a different approach. I know it does not exactly answer your questions, but I believe it makes them somewhat obsolete.

This is how I would do the decrypt:

function decrypt(sentence) {
    var result = '';
    var pos = 0;

    var words = sentence.split(' ');
    words = words.map(function(word) {
       return word.split('');
    });

    while(true) {
       char = words[pos].shift();
        if (! char) {
            break;
        }
        result += char;

        pos = pos > words.length -2 ? 0 : pos + 1;
    }

    return result;
}

For a working example: http://jsfiddle.net/35jyyv8g/1/

Note that I left the key out, since it is not really necessary with the spaces in the input.


Sending an email every half hour if a certain condition is met

We know what this is 30*60*1000 but you should put that into a variable instead of just letting it lay around out there naked like that.

public long waitTime = 30*60*1000;

and you can put it in whatever scope that you want to and use it as often as you like, just make sure that if you change it you know what it will affect.


There's a few issues I can see with this code.

The repositories are are sitting in the presentation layer. A big no no. It's software 101, don't place data access in your presentation layer, and not good to put business logic in the presentation layer.

Those _roleRepository calls need to go in to a RoleRetrievalService or something similar. That centralise the business logic.

Your repositories should to sit behind a service layer which handles all of the calls to the DAL. Your service layer should contain business logic and data transformation which turns those DAL entities in to models which can be consumed by the presentation layer.

The query which does the left join should go in the service layer with the parameters required to execute the query being passed in as parameters. You could also pass in the sort options as well.

That last statement which builds the results (jsonData) is exactly what should be produced by your service layer.

It all hinges one how much time you have and how much technical debt you want to incur :)


Parameters

As a starting point, I'd usually advise against passing bools as parameters--especially passing more than one bool to a particular function. I have better ways to spend my time than memorizing the meaning of:

foo(..., false, false, true);

vs.

foo(..., false, true, false);

I suppose I could barely see something like this if you were doing something like passing some bools, and it was putting them together into a bit set, so true, false, true basically just meant 101, but for something like this where each has a unique meaning, it seems unusually difficult to read.

Basic Utility

At least in my opinion, however, that nearly pales compared to the mere fact that I don't see much point in the function existing at all.

People who are accustomed to C++ are generally fairly accustomed to how the standard library works. Most of use would generally rather get an iterator than an index. If we want to search from end to beginning, passing rbegin() and rend() to find makes that intent fairly clear.

For example, if I want to search for the last item, starting 4 from the end, I'd have a much easier time understanding this:

auto p = std::find(foo.rbegin()+4, foo.rend(), value);

...rather than:

int p = Vec_find(foo, foo.size(), value, 4, false, true, true);

or:

int p = Vec_find(foo, foo.size(), value, 4, true, false, true);

[At least as I read things, those are basically the same--either find the last item, or find the first, starting from the end. Oh, and pardon me if I'd passed the wrong thing for the size parameter--I couldn't figure out exactly what it was supposed to do.]

Granted, iterators do tend to lead to fairly verbose code, but in this case, using your code can be even more verbose. I'm pretty sure when ranges become generally available (and sooner, for people who only need to target one compiler, or don't mind using Boost) quite a few people will welcome them with open arms. They can reduce verbosity quite a bit. Given a choice, however, between using this and using the standard library directly, I'd take the standard library without a second thought.


Taking the first few items of a list until a target sum is exceeded

So, a couple things:

The problem statement says nothing about printing data, so you can omit the print statement, and thus the entire else: clause, entirely.
The problem statement says to return a list, and you're just returning the last item in that list, not the entire list.

Here's a short but inefficient way to do it:

def numberlist(nums, limit):
    i = 0
    while sum(nums[:i]) < limit:
        i += 1
    return nums[:i]

or a more efficient but longer way:

def numberlist(nums, limit):
    prefix = []
    sum = 0
    for num in nums:
        sum += num
        prefix.append(num)
        if sum > limit:
            return prefix


Arduino: Change the color & color intensity of a LED periodically

I agree that the switch statement smells. One way to avoid it is to abstract LED values into the array, and let change_color_intensity operate on it:

void change_color_intensity(int which, int start, int stop, int delta)
{
    int values[] = { 0, 0, 0 };
    for (values[which] = start; values[which] != stop; values[which] += delta) {
        set_leds(values[0], values[1], values[2]);
        delay(DELAY_WITHIN_LOOP);
    }
}

Note that I change a while loop into a IMHO more readable for. I also changed some names for the same reason.

Another approach is to abstract LED names, and get rid of setLed altogether:

void change_color_intensity(int which, int start, int stop, int delta)
{
    for (in value = start; value != stop; value += delta) {
        analogWrite(which, value);
        delay(DELAY_WITHIN_LOOP);
    }
}

with the caller defining a pin array:

    int LED = { RED_LED_PIN, GREEN_RED_PIN, BLUE_RED_PIN };
    for (pin = 0; pin < 3; pin++) {
        change_color_intensity(LED[pin], 0, 256, 1);
        ....
    }

I am not sure I understand what you mean by multiple function invocations. If you are concerned with invoking change_color_intensity twice in a loop, I see no problem with it.


Does setting the same element in a list does something at all?

No, that code is totally useless. Unless....

Same element twice

As it is a List, what happens if it contains the element twice?

Let's say we have a List containing two elements of the type Strip:

stripA, stripB

stripA and stripB are equal, that is, the class have implemented .equals. Then and only then, this code will do something useful. If aStrip is stripB then it will modify the list to become:

stripB, stripB

One inside, one outside, both .equals

The same is true if the List contains stripA only and you call the method with aStrip again as stripB. Remember that stripA.equals(stripB) is true so here's what happens:

 if (playerStrips.contains(aStrip)) {

Yes. .contains on a Collection uses .equals to see if it contains or not, so this will return true.

 playerStrips.indexOf(aStrip)

indexOf also uses .equals and the index of stripA is returned.

playerStrips.set(playerStrips.indexOf(aStrip), aStrip);

So what happens here is that the index of stripA is set to stripB.

Small Improvement

There's really no reason to use both indexOf and contains. You could do this instead:

int index = playerStrips.indexOf(aStrip);
if (index != -1) {
    playerStrips.set(index, aStrip);
}

However

If this functionality has been added because of this reason, I personally think it is a bad reason to add it. This code is more confusing than anything else. Do it differently. Either aStrip should not really be equal to bStrip, or something else should be modified. The reason for why one would want to replace aStrip with bStrip when they are already equal goes beyond my understanding.

Strip.equals

Holy.... mess!

First of, why use Boolean when you can use boolean? Secondly, why use a boolean at all when you can use return?

Also, you could probably use instanceof instead of getClass. But you should look at the StackOverflow question about this.

I have to question the usage of tempID, it does not feel like a clean solution to me - whatever problem it is meant to solve.

By following the program execution, you can see that if one of those if (condition) return true is not true that the only possible return value is false. Therefore, it can be simplified with return condition;

Because of the above, there will be no reason to use any else as there's a return inside the previous if.

Therefore, your .equals method can be simplified to:

@Override
public boolean equals(Object obj) {
    if (obj instanceof Strip) {
        final Strip other = (Strip) obj;
        if (null == this.id && null == other.id) {
            return this.tempId.equals(other.tempId);
        }
        if (null != this.id) {
            return this.id.equals(other.id)
                    || this.id.equals(other.tempId);
        }
        if (null != other.id) {
            return other.id.equals(this.id)
                    || other.id.equals(this.tempId);
        }
    }
    return false;
}


You can refactor the findPath logic somewhat and reduce the indent level while preserving the method's behavior:

// Prints possible paths from bottom left to top right
public static void findPath(int n, int i , int j, int[][] mat, ArrayList<Integer> path)
{
    if(i == 0 && j == n - 1)
    {
        System.out.println();
        for(Integer step: path)
        {
            System.out.print("," + step);
        }
    }

    boolean rightStep = isPossibleStep(i + 1, j, n, mat);
    if(!isPossibleStep(i, j - 1, n, mat) && !rightStep)
        return;

    path.add(rightStep ? ++i : --j);
    findPath(n, i, j, mat, path);
}

isPossibleStep can also be simplified by use of short-circuit logic. The following expresses the intent more directly with the benefit of being terse:

public static boolean isPossibleStep(int i, int j, int n, int[][] mat)
{
    return mat[i][j] != 1
        && i < n
        && j > 0;
}


Loop through a list of URLs multi-threading and check return code in python

Here is what I decided to change the code to this version, which runs a lot faster:

import urllib.request
import urllib.error
import time
from multiprocessing import Pool

start = time.time()

file = open('url10.txt', 'r', encoding="ISO-8859-1")
urls = file.readlines()

print(urls)

def checkurl(url):
    try:
        conn = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        # Return code error (e.g. 404, 501, ...)
        # ...
        print('HTTPError: {}'.format(e.code) + ', ' + url)
    except urllib.error.URLError as e:
        # Not an HTTP-specific error (e.g. connection refused)
        # ...
        print('URLError: {}'.format(e.reason) + ', ' + url)
    else:
        # 200
        # ...
        print('good' + ', ' + url)

if __name__ == "__main__":
    p = Pool(processes=20)
    result = p.map(checkurl, urls)

print("done in : ", time.time()-start)

Url.txt file contains a list of urls

http://yahoo.com
http://www.google.com

I have about a 1000 urls to check and it seems to work. Any suggestions to improve the functionality?


Faster function iteration on Pandas df with axis=1

The easiest way to get a small speed-up  is swap these two lines:

filterdatemediaplanid_day = (atlas_df.Date == row.Date) & (atlas_df.MediaPlanIndex == row.MediaPlanIndex)
filterdatemediaplanid_total = (atlas_df.MediaPlanIndex == row.MediaPlanIndex)

to:

filterdatemediaplanid_total = (atlas_df.MediaPlanIndex == row.MediaPlanIndex)
filterdatemediaplanid_day = (atlas_df.Date == row.Date) & filterdatemediaplanid_total

This part of the code does not serve any purpose:

if row.Amnet == "Amnet":
    spend = atlas_df.AmnetCost * (row.Impressions / filterdatemediaplanid_day)

Since you don't return right away and afterwards comes an if/elif/else block that is guaranteed to modify spend, anything you calculate here will be overwritten.

While some people adhere to the single exit policy, I prefer early returns:

if row.CostMethod == 'FLF' or row.CostMethod == 'CPH':
    total_impressions = atlas_df.ix[filterdatemediaplanid_total, 'Impressions'].sum()
    if total_impressions >= 500:
        return row.BookedRate * (row.Impressions/ total_impressions)
elif row.CostMethod == 'CPC':
    return row.BookedRate * row.Clicks
elif row.CostMethod == 'CPM':
    return row.BookedRate * row.Impressions / 1000.0
return 0

total_impressions_day is not used anywhere and total_impressions should only be calculated if needed.


Cleaning up a redundant switch statement

I would create a list of usercontrols. Based on the amount of controls that need to be visible, traverse the list and set x controls to visible.

protected void DisplayUserControls(List<UserControl> controls, int numberOfControls)
{
    Contract.Requires( numberOfControls >= 0 && numberOfControls <= controls.Count );

    for ( int i = 0; i < numberOfControls; ++i )
    {
        controls[ i ].Visible = true;
    }
    for ( int i = numberofControls; i < controls.Count; ++i )
    {
        controls[ i ].Visible = false;
    }
}

Or rather in one go:

protected void DisplayUserControls(List<UserControl> controls, int numberOfControls)
{
    Contract.Requires( numberOfControls >= 0 && numberOfControls <= controls.Count );

    for ( int i = 0; i < controls.Count; ++i )
    {
        controls[ i ].Visible = i < numberOfControls;
    }
}


Vectorizing matrix operation instead of for loop in circular matrices

This is easy using numpy.roll, for example:

zx = np.roll(x, 1) * (np.roll(x, 2) + np.roll(x, -1)) - x


Producer/consumer implementation using Tasks and BlockingCollections

Did you know that Task.Result blocks? Your code isn't asynchronous at all - and it can't be unless DoRead is.

Effectively your code is starting a new task and then blocking while it completes - there's no benefit to starting the task at all!

As a small aside, Task.Run is easier than using Task.Factory.StartNew.

If I were you, I'd just remove the Task.


Large dataset with pyspark - optimizing join, sort, compare between rows and group by with aggregation

I believe the below solution should solve for what you are looking to do in a more efficient way. Your current method involves a lot of "shuffle" operations (group by, sorting, joining). The below should help reduce the number of shuffle operation in your Spark job.

get leading start date
get disabled records
add column indicating whether product ever disabled (max of is disabled)
capture replacement dataset
get max replacement date
create indicator for current lifecycle records
filter data for current lifecycle records.

# csv input
df = spark.read.csv('productlist.csv', header=True, inferSchema=True)
# get ordered and unordered windows
wo = Window.partitionBy("product_id").orderBy("start_date")
wu = Window.partitionBy("product_id")
df1 = df.withColumn("lead_start_date", F.lead(col("start_date"), 1).over(wo))\
        .withColumn("is_disabled", F.when((col("end_date").isNotNull()) &
                                          ((col("end_date") != col("lead_start_date")) | (col("lead_start_date").isNull())), 1).otherwise(0))\
        .withColumn("has_been_disabled", F.max(col("is_disabled")).over(wu))\
        .withColumn("replacement_date", F.when((col("end_date").isNotNull()) &
                                          (col("end_date") == col("lead_start_date")) & (col("lead_start_date").isNotNull()), col("start_date")).otherwise(lit(None)))\
        .withColumn("max_replacement_date", F.max(col("replacement_date")).over(wu))\
        .withColumn("is_current_lifecycle_record", F.when(((col("replacement_date") == col("max_replacement_date")) & col("replacement_date").isNotNull()) |
                                                            ((col("has_been_disabled") == 0) & (col("max_replacement_date").isNull())), 1).otherwise(0)) # never disabled / replaced
# filter for current lifecycle record and select target columns
df_final = df1.filter(col("is_current_lifecycle_record") == 1).select(["product_id", "start_date"])


This seems like a cool project, and a nice first introduction to web scraping! I'll cover some general advice first, and then address your main concern: speed.

General

You use two spaces for indentation. PEP-8 recommends 4 spaces (most code editors have the option to automatically convert tabs to spaces, which I highly recommend).
While on the subject, PEP-8 also recommends two blank lines between top-level functions.
In general, the use of globals is discouraged. There are some exceptions:

Global constants are okay;
Under certain circumstances, avoiding global state would result in unacceptably complicated code.

However, neither of these apply here. Using global, non-const variables makes your code harder to debug, and is a burden for anyone reading / updating it in the future. You can avoid global state here easily by passing variables as parameters.
In my opinion, show_logo() is a bit overkill. I'd make it a constant instead (LOGO).
The while loop in handle_menu() can be improved:

while True:
  try:
    global n_of_comics
    n_of_comics = int(input(">> ").strip())

There's no need to call str.strip() before passing the return value to int.

  except ValueError:
    print("Error: incorrect value. Try again.")
    continue

The error message is a bit vague. Why is the value incorrect? Maybe something like 'Error: expected a number. Try again.' would fit better.

  if n_of_comics > len(found_comics) or n_of_comics < 0:
    print("Error: incorrect number of comics to download. Try again.")
    continue

This error message is quite clear :)

  elif n_of_comics == 0:
    sys.exit()
  else:
    break

You don't need the else clause here, since the elif clause stops the program if executed. In fact, you can simply return n_of_comics there. Putting this all together:

while True:
  try:
    global n_of_comics
    n_of_comics = int(input(">> "))
  except ValueError:
    print("Error: expected a number. Try again.")
    continue
  if n_of_comics > len(found_comics) or n_of_comics < 0:
    print("Error: incorrect number of comics to download. Try again.")
    continue
  elif n_of_comics == 0:
    sys.exit()
  return n_of_comics

Your 'main routine' isn't encapsulated in a function, which means it's hard to test / explore functions individually from a Python interactive session (or from a separate file). I suggest putting all this top level code into a main() function:

def main():
    show_logo()

    all_comics = fetch_comic_archive()
    found_comics = filter_comic_archive(all_comics)

    handle_menu()

    start = time.time()
    for link in generate_comic_link(found_comics, n_of_comics):
        print("Downloading: {}".format(link))
        move_to_dir(DEFAULT_DIR_NAME)
        url = grab_image_src_url(link)
        download_image(url)
    end = time.time()

    print("Successfully downloaded {} comics in {:.2f} seconds.".format(n_of_comics, end - start))

You can then check if __name__ == "__main__", to run main if the script is called as the main program (see 'What does if __name__ == "__main__" do?'):

if __name__ == "__main__":
    main()

I don't get the point of move_to_dir(). It handles the case where the current working directory has been changed, and it's called for each comic to download. That seems pretty pointless to me. Instead, I would only create the directory once, in main():

DEFAULT_DIR_NAME = "poorly_created_folder"
COMICS_DIRECTORY = os.path.join(os.getcwd(), DEFAULT_DIR_NAME)

...

def download_image(link):
    ...
    with open(os.path.join(COMICS_DIRECTORY, file_name), "wb") as file:
        ...

...

def main():
    ...
    try:
        os.mkdir(COMICS_DIRECTORY)
    except OSError as exc:
        sys.exit("Failed to create directory (errno {})".format(exc.errno))
        # `sys.exit` will write the message to stderr and return with status code 1

generate_comic_link() is superfluous. The following functions all do the same:

def generate_comic_link(array, num):
    # Using itertools.islice()
    for link in itertools.islice(array, 0, num):
        yield link

def generate_comic_link2(array, num):
    # Using slicing
    for link in array[:num]:
        yield link

def generate_comic_link3(array, num):
    # Using slicing with yield from
    yield from array[:num]

itertools.islice() is overkill (and a little harder to read). Since generate_comic_link3() is a one-liner, you can probably get rid of the function altogether, iterating over the URLs directly using slicing.
A bit of a nitpick, but req = <requests>.get(<url>) is wrong. requests.get doesn't return the request, it returns the response. Thus, response = <requests>.get(<url>) makes more sense.
Some of your variables could (should) be constants:

url = 'http://www.poorlydrawnlines.com/archive/'
# Might be
ARCHIVE_URL = "http://www.poorlydrawnlines.com/archive/"

pattern = re.compile(r'http://www.poorlydrawnlines.com/comic/.+')
# Might be
COMIC_PATTERN = re.compile(r"http://www.poorlydrawnlines.com/comic/.+")

(I prefer double quotes, as you might be able to tell)
In fetch_comic_archive():

all_links = []
for link in soup.find_all('a'):
    all_links.append(link.get('href'))
return all_links

... might be a one-liner:

return [link.get("href") for link in soup.find_all("a")]

In filter_comic_archive():

filtered_links = [i for i in archive if pattern.match(i)]
return filtered_links

There's no need for the intermediate variable.

Using threading.Thread

Now for the actual challenge: improving performance.
You don't need asynchronous lxml, threads will do just fine here!
By wrapping the relevant code into a function, we can spawn any amount of threads to do the work:

import threading

def download_comic(link):
    print("Downloading: {}".format(link))
    move_to_dir(DEFAULT_DIR_NAME)
    url = grab_image_src_url(link)
    download_image(url)

...

def main():
    ...
    for link in generate_comic_link(found_comics, n_of_comics):
        thread = threading.Thread(target=download_comic, args=(link,))
        thread.start()
    thread.join()
    # Join the last thread to make sure all comics have been
    # downloaded before printing the time difference
    ...

Rewrite

Putting everything together (I've changed names, reordered some functionality and added comments explaining certain changes):

import time
import os
import sys
import re
import threading

# PEP-8 recommends a blank line in between
# stdlib imports and third-party imports.

import requests
# Importing `requests` *and* `get` from `requests` is confusing
from bs4 import BeautifulSoup as bs

DEFAULT_DIR_NAME = "poorly_created_folder"
COMICS_DIRECTORY = os.path.join(os.getcwd(), DEFAULT_DIR_NAME)
LOGO = """
a Python comic(al) scraper for poorlydwarnlines.com
                         __
.-----.-----.-----.----.|  |.--.--.
|  _  |  _  |  _  |   _||  ||  |  |
|   __|_____|_____|__|  |__||___  |
|__|                        |_____|
                __ __   __
.--.--.--.----.|__|  |_|  |_.-----.-----.
|  |  |  |   _||  |   _|   _|  -__|     |
|________|__|  |__|____|____|_____|__|__|

.-----.----.----.---.-.-----.-----.----.
|__ --|  __|   _|  _  |  _  |  -__|   _|
|_____|____|__| |___._|   __|_____|__|
                      |__|
version: 0.2 | author: baduker | https://github.com/baduker
"""
ARCHIVE_URL = "http://www.poorlydrawnlines.com/archive/"
COMIC_PATTERN = re.compile(r"http://www.poorlydrawnlines.com/comic/.+")

def download_comics_menu(comics_found):
    print("\nThe scraper has found {} comics.".format(len(comics_found)))
    print("How many comics do you want to download?")
    print("Type 0 to exit.")

    while True:
        try:
            comics_to_download = int(input(">> "))
        except ValueError:
            print("Error: expected a number. Try again.")
            continue
        if comics_to_download > len(comics_found) or comics_to_download < 0:
            print("Error: incorrect number of comics to download. Try again.")
            continue
        elif comics_to_download == 0:
            sys.exit()
        return comics_to_download

def grab_image_src_url(url):
    response = requests.get(url)
    soup = bs(response.text, "html.parser")
    for i in soup.find_all("p"):
        for img in i.find_all("img", src=True):
            return img["src"]

def download_and_write_image(url):
    # `download_and_write_image` is a bit more accurate, since
    # it also writes the image to the disk
    file_name = url.split("/")[-1]
    with open(os.path.join(COMICS_DIRECTORY, file_name), "wb") as file:
        response = requests.get(url)
        # Replced `get` with `requests.get`
        file.write(response.content)

def fetch_comics_from_archive():
    # Merged `fetch_comic_archive` and `filter_comic_archive`
    # into a single function
    response = requests.get(ARCHIVE_URL)
    soup = bs(response.text, "html.parser")
    comics = [url.get("href") for url in soup.find_all("a")]
    return [url for url in comics if COMIC_PATTERN.match(url)]

def download_comic(url):
    print("Downloading: {}".format(url))
    url = grab_image_src_url(url)
    download_and_write_image(url)

def main():
    print(LOGO)

    comics = fetch_comics_from_archive()
    comics_to_download = download_comics_menu(comics)

    try:
        os.mkdir(DEFAULT_DIR_NAME)
    except OSError as exc:
        sys.exit("Failed to create directory (errno {})".format(exc.errno))

    start = time.time()
    for url in comics[:comics_to_download]:
        thread = threading.Thread(target=download_comic, args=(url,))
        thread.start()
    thread.join()

    end = time.time()
    print("Successfully downloaded {} comics in {:.2f} seconds.".format(
        comics_to_download, end - start)
    )

if __name__ == "__main__":
    main()

Results

Non-threaded:

The scraper has found 957 comics.
How many comics do you want to download?
Type 0 to exit.
>> 6
Downloading: http://www.poorlydrawnlines.com/comic/new-phone/
Downloading: http://www.poorlydrawnlines.com/comic/new-things/
Downloading: http://www.poorlydrawnlines.com/comic/return-to-nature/
Downloading: http://www.poorlydrawnlines.com/comic/phone/
Downloading: http://www.poorlydrawnlines.com/comic/stars/
Downloading: http://www.poorlydrawnlines.com/comic/big-dreams/
Successfully downloaded 6 comics in 37.13 seconds.

Threaded:

The scraper has found 957 comics.
How many comics do you want to download?
Type 0 to exit.
>> 6
Downloading: http://www.poorlydrawnlines.com/comic/new-phone/
Downloading: http://www.poorlydrawnlines.com/comic/new-things/
Downloading: http://www.poorlydrawnlines.com/comic/return-to-nature/
Downloading: http://www.poorlydrawnlines.com/comic/phone/
Downloading: http://www.poorlydrawnlines.com/comic/stars/
Downloading: http://www.poorlydrawnlines.com/comic/big-dreams/
Successfully downloaded 6 comics in 7.07 seconds.

Alternatively: using concurrent.futures.ThreadPoolExecutor

If you run the rewritten code, you may notice the program takes a couple of seconds to shut down after (reportedly) having downloaded all images. This is because the last thread started doesn't necessarily end last (that's the whole point of threads, after all!). To avoid this, and to get rid of some of the boilerplate code, we can use ThreadPoolExecutor.map() and ThreadPoolExecutor.shutdown().

I've created a GitHub gist here which uses ThreadPoolExecutor together with requests.Session, which reuses the underlying TCP connection, potentially resulting in even better performance.


Computing the average of several numbers

This is quite good for a homework exercise.

I would recommend a for loop instead of the while:

for (int ValuesProcessed = 0; ValuesProcessed < ListSize; ++ValuesProcessed) {

This puts all the logic of iteration together where you are less likely to overlook
some detail, unlike the while loop where the initial value of ValuesProcessed,
the test for termination of the loop, and setting ValuesProcessed for the next
iteration are done in three different places.

I tend to follow the philosophy of declaring things as close to where they are used
as possible, so I would move the declaration and initialization of ValueSum after
the "Please enter" printout. But I don't think there's a strong argument for doing this.
(It would merely swap the order of two lines of code, not a big deal.)

Contrary to another answer, I like your decision to declare ListSize in your main()
function. (It's another example of "declaring things as close to where they are used
as possible".) Although ListSize is a "constant" in the sense that you have declared it
const (which I think is a good idea), it is really just the end condition of a
single loop in the program, or to put it another way, the length of a list of inputs
that the program is about to read.


Naming Conventions

The variable all doesn't tell what it contains. allElements does reflect what it contains.

clean, i, foo, capture - huh?

filter, the name of the function has nothing to do with filtering. It is iterating over some data and calling provided callback for each property.
Global Variables

all is global variable. Global variables is bad practice. Please see Why are global variables considered bad practice? and I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?.
Using Proper Methods

map is used to update each element in collection. Here, map is used just to iterate over the elements. You can use each, for, forEach, etc. in such case.
Diving into DOM

In filter callback, you're diving into DOM three times to get the same element. The element can be cached and reused.
Method Chaining

replace() in filter() can be chained.
Unnecessary code

foo.hasOwnProperty(i) is not required as .data() only returns data-* properties in an object.
.toLowerCase() can be safely removed and i flag on the next replace regex can be used.

Also, HTML is case insensitive. No transformation is needed when changing attribute.

That is too much code for such a small functionality. I've rewritten the code. See the explanation in the code comments.

// Select all elements in DOM
// and iterate over them
$('*').each(function() {
  // Cache the element reference
  // $(this) refers to the current element in the collection
  var $this = $(this);

  // Get the key-value of all `data-*` attributes
  // on current element
  var data = $this.data();

  // Get all the keys of data-attributes
  var keys = Object.keys(data);

  // Check if this element have data-* attribute on it
  if (keys.length) {

    // Iterate over each data attribute
    keys.forEach(function(key) {

      // Check if attribute starts with `intl` followed by Uppercase character
      if (/^intl[A-Z]/.test(key)) {
        // Get the attribute name
        // As the attribute name is camelCase, last word is the attribute name
        var attribute = key.match(/[A-Z][a-z]*$/)[0];

        // Update the attribute in DOM
        $this.attr(attribute, data[key]);
      }
    });
  }
});

test href


Add comma/and between string array in java

Welcome to Code Review, I have some hints about your code, starting from your main method:
public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};

    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));
}

You have defined several arrays forcing the multiple print , you can obtain the same result defining an 2d array storing arrays of different dimensions like below :
public static void main(String[] args) {
    String[][] authors = { {"a"},
                           {"a", "b"},
                           {"a", "b", "c"},
                           {"a", "b", "c","d"},
                           {"a", "b", "c","d","e","f"}};

    for (String[] row : authors) {
        System.out.println(displayAuthors(row));
    }
}

About the print of the authors array you can distinguish three cases :

array with zero elements : you will print the "" empty string.
array with one element : you will print the unique element of the
array.
array with more than one element : you will print elements with ", "
as separator except for the penultimate element and the last one
that will be separated by "and".

You can rewrite your displayAuthors method in this way:
public static String displayAuthors(String[] authors) {
    if (authors == null) { return ""; }

    switch (authors.length) {
        case 0: return "";
        case 1: return authors[0];
        default: return helperDisplayAuthors(authors);
    }
}

I defined a new method called helperDisplayAuthors :
private static String helperDisplayAuthors(String[] authors) {
    final int length = authors.length;
    String result = "";

    for (int i = 0; i < length - 2; ++i) {
        result += authors[i] + ", ";
    }

    return String.format("%s%s and %s", result,
            authors[length - 2], authors[length - 1]);
    }

}

The method String.format helps you to compose the final string. Here the code of your class:
public class SeparateAuthors {

    public static void main(String[] args) {

        String[][] authors = {{"a"},
                              {"a", "b"},
                              {"a", "b", "c"},
                              {"a", "b", "c", "d"},
                              {"a", "b", "c", "d", "e", "f"}};

        for (String[] row : authors) {
            System.out.println(displayAuthors(row));
        }
    }

    public static String displayAuthors(String[] authors) {
        if (authors == null) { return ""; }

        switch (authors.length) {
            case 0: return "";
            case 1: return authors[0];
            default: return helperDisplayAuthors(authors);
        }
    }

    private static String helperDisplayAuthors(String[] authors) {
        final int length = authors.length;
        String result = "";

        for (int i = 0; i < length - 2; ++i) {
            result += authors[i] + ", ";
        }

        return String.format("%s%s and %s", result,
                authors[length - 2], authors[length - 1]);
    }

}


My best guess given the information:
You are doing some expensive ismember operations. You can try to get rid of them by tracking Done in a different way.

Perhaps you can use a more efficent way to do it in the same location, or perhaps you need to move it inside the loop and do it in a very cheap way there.


Change random list of numbers into all 5's using simple evolution simulation

Picking up where Josay left off:
Simulating evolution
The current algorithm has some flaws as an evolution simulation:

Entities inherit their parents' fitness. Fitness should be determined by the entity's traits; it isn't a trait in its own right.
Entities only age when they reproduce, and the number of offspring doesn't depend on the fitness. This means all entities reproduce eventually; fitter ones just do it faster! Furthermore, the number of offspring doesn't depend on the fitness, so all entities have the same reproductive success! In an evolution simulation, fitter organisms should have more reproductive success.

Some other oddities:

Only one organism per step can reproduce. Why not let them all reproduce at once?
Randomness is introduced in too many places: in particular, the fitness is random, but it's also compared to a random number. You only need one of these. It's better to keep randomness out of the fitness function entirely, so its results are more meaningful and it's easier to debug.
The population grows without bound. It should probably be limited, perhaps with random.sample.

It's not necessary to model aging at all in a simple evolution simulator. You can simply have every organism die in every generation. Or you can have them die randomly, without keeping track of age.
There are two important parts of a genetic algorithm:

The fitness function: given an organism, how successful is it?

The breeding function: Given a population and a fitness function, produce the next generation. There are a lot of options here: you can choose parents randomly weighted by fitness, or let everything reproduce a few times and keep the fittest children, or let everything reproduce according to its fitness and keep random children.

Design
Fitness does not make much sense as a class, because its instances don't represent anything. If each instance represents a population, it could be a Population. But it's simpler to represent a population as a list of organisms, with no separate class. (Not everything needs to be a class!)
Some of the methods of Fitness should be operations on a single Entity, not a whole population.
Several functions modify objects unnecessarily. In particular, fitness_method should simply return a fitness rather than modifying the Entity. (This causes a bug: the fitness of 5 increases over time!)
Minor style issues
Some names could be improved:

fitness_method is fitness. Method names should say what they do, not the fact that they're methods.
aging should be removeOldOrganisms.
Entity is vague. Organism is more specific. Populations can be called population, not entities.

The loop to print a population is repeated and should be factored out.
raw_input can print a prompt, so the separate print before it is unnecessary. But there's no need to wait for user input at all.
It's not necessary to rename random.
How I'd do it
Here's a version with most of the above changes:
import random

class Organism:
    def __init__(self, number):
        self.number = number
    def fitness(self):
        "How many children can this organism have?"
        return 3 if self.number == 5 else 2
    def reproduce(self):
        "Make a child. Currently children are just copies of the parent."
        return Organism(self.number)

max_population = 100

def nextGeneration(population):
    children = []
    for x in population:
        n_children = random.randint(0, x.fitness())
        children += [x.reproduce() for _ in range(n_children)]
    return random.sample(children, min(len(children), max_population))

def printPopulation(population):
    for x in population:
        print x.number, x.fitness()

population = [Organism(random.randint(1, 10)) for _ in range(10)]
printPopulation(population)

for gen in range(10):
    print "Generation", gen, "population", len(population)
    population = nextGeneration(population)
    printPopulation(population)

This uses fitness to determine the number of children rather than which children survive; either is reasonable.


Longest string in a vector — two implementations

The first version of the algorithm uses a traditional C++03-era for loop with iterators. The only modern element is the auto used to deduce an std::vector<std::string>::iterator. The second loop uses a C++11 range-based for loop whose syntax is close to the one used in Java. The range-based for loop is now preferred for several reasons:

Its terse syntax (when iterators are fully spelled out, a traditional for loop is ugly).
Its genericity: a range-based for loop also works with C arrays and std::valarray.
end is automatically cached instead of being evaluated at each iteration.

That's it for the for loops: the range-based for loop is preferred. However, there are some things that could be improved in your second version:

You should pass lines as a const reference. When you don't need to modify an instance, a const reference is good since it avoids a useless copy.
In your range-based for loop, you should write const auto& since you don't modify line either. It currently performs many useless copies of full std::strings just to get their size. Actually, the best thing to write in range-based for loops is generally auto&&, but the explanation may be a little complicated since it involves lvalues, rvalues, const-correctness and type deduction.


There's incorrect/inconsistent indentation in:

HEY CHRISTMAS TREE result
YOU SET US UP 0

and

HEY CHRISTMAS TREE isZero
YOU SET US UP 0

The ArnoldC wiki says you should declare 0s and 1s as the "macros" @I LIED and @NO PROBLEMO

HEY CHRISTMAS TREE isZero
    YOU SET US UP @I LIED

In your method divisible, the end of method statement is not on the same indentation as the start declaration.

The indentation in these two blocks is two vs four:

IT'S SHOWTIME
    HEY CHRISTMAS TREE maxValue

and:

LISTEN TO ME VERY CAREFULLY divisible
  I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE dividend

You ought to stick to one consistently.

IT'S SHOWTIME
    HEY CHRISTMAS TREE maxValue
    YOU SET US UP @NO PROBLEMO

There we go! Using the macros!

Oh, wait...

HEY CHRISTMAS TREE n
YOU SET US UP 0

Never mind...

And again...

    HERE IS MY INVITATION n
        GET UP 1


If you expect your code will ever be used from C++ (which a lot of C code is) then  you should not use any identifiers with a double underscore.

#ifndef BITMAP__
    //        ^^   May cause problems in C++

As this is reserved for the implementation in C++. Also the term BITMAP is very generic and you are very likely to clash with other libraries try and make it more unique to your project.

You are assuming that a char is 8 bits.

#define BIT (8*sizeof(byte))

The standard does not say this (it is at least 8 bits) but it is actually defined via the macro CHAR_BITS so you should use:

#define BIT (CHAR_BITS*sizeof(byte))

Your header file is how most people will first see your code and try and understand how to use it. Thus putting the parameter names into the header file is probably a good idea as it helps document their usage.

bool bitmapGet   (byte *, int);
void bitmapSet   (byte *, int);
void bitmapReset (byte *, int);
int  bitmapSearch(byte *, bool, int, int);

Additional the action of bitmapSearch is not obvious thus a comment on its usage in the header would probably be a good idea. Actually a small blurb about how the first parameter can be an array would probably be a good idea (as it is not obvious without reading the code).

Be careful with comments:

/* pos is something from 0 to 7*/

This is only true if you make assumptions (A: that sizeof(byte) == 1 B: you multiply this by 8). The comment should have been:

/* pos is a value between [0, BIT) */

Note the use of '[' on the left and ')' on the right. It is mathematical notation indicating that 0 is inclusive and BIT is not included in the range (it is common in both C/C++ documentation).


Idiomatic Rust style is to place braces on same line. When the function definition gets longer than one line then the brace lives on the next line all on its own.
Learn and love the entry API. Not only does the code end up clearer, it's faster too.
Don't use magic numbers. What is 10 supposed to mean? Why not 9 or 11 or 42? The very least you can do is to create a name for the magic value that indicates its purpose. However, there are usually better options in Rust. For example, if you need to indicate a potential absence of something, use Option.
It's very rare to use ref in a let pattern binding.
Avoid uses of unwrap, especially when they parallel existing code that ensures that the unwrap cannot fail. Usually there's a way to avoid duplicating the check.
Learn about transformative methods on Option and Result, map being the one used here.
Don't use an explicit return at the end of a function.

use std::collections::BTreeMap;

fn insert_dup<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32, v: V) {
    map.entry(k).or_insert_with(Vec::new).push(v)
}

fn remove_dup_internal<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32) -> Option<usize> {
    map.get_mut(&k).map(|vec| {
        vec.pop();
        vec.len()
    })
}

fn remove_dup<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32) {
    if remove_dup_internal(map, k) == Some(0) {
        map.remove(&k);
    }
}

Even better, the helper function isn't needed with the Entry API. We can also note that comparing the length against 0 is the same as the is_empty method:

use std::collections::btree_map::Entry;

fn remove_dup<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32) {
    if let Entry::Occupied(mut entry) = map.entry(k) {
        entry.get_mut().pop();
        if entry.get().is_empty() {
            entry.remove();
        }
    }
}

Now adding and removing a value each only require a single location computation and lookup.

Parameterizing the key can be done by:

Replacing i32 with K.
Adding K to the generic declaration list.
Following the compiler error message to restrict K to types that implement Ord.

use std::collections::{btree_map::Entry, BTreeMap};

fn insert_dup<K, V>(map: &mut BTreeMap<K, Vec<V>>, k: K, v: V)
where
    K: std::cmp::Ord,
{
    map.entry(k).or_insert_with(Vec::new).push(v)
}

fn remove_dup<K, V>(map: &mut BTreeMap<K, Vec<V>>, k: K)
where
    K: Ord,
{
    if let Entry::Occupied(mut entry) = map.entry(k) {
        entry.get_mut().pop();
        if entry.get().is_empty() {
            entry.remove();
        }
    }
}

  Any reason you are calling both entry.get and entry.get_mut in remove_dup?

This can be interpreted multiple ways:

"Why not call entry.get in both cases?" — because the chained pop needs a mutable receiver in order to do its work.
"Why not call entry.get_mut in both cases?" — this would compile, but the value doesn't need to be mutable for is_empty, and I find it better to opt-out of as much mutability as possible.
"Why not call entry.get_mut once and store it in variable?" — Now that non-lexical lifetimes are enabled, the straight-forward way works and you should do this. Before that, however,you would run into borrow checker issues because binding the result of get_mut to a variable will cause entry to be borrowed for the rest of the scope. This prevents using entry.remove:

if let Entry::Occupied(mut entry) = map.entry(k) {
    let vec = entry.get_mut();
    vec.pop();
    if vec.is_empty() {
        entry.remove();
    }
}

error[E0505]: cannot move out of `entry` because it is borrowed
  --> src/main.rs:17:13
   |
14 |         let vec = entry.get_mut();
   |                   ----- borrow of `entry` occurs here
...
17 |             entry.remove();
   |             ^^^^^ move out of `entry` occurs here

If get or get_mut were expensive, you could introduce a scope to constrain the borrow:

if let Entry::Occupied(mut entry) = map.entry(k) {
    let should_remove = {
        let vec = entry.get_mut();
        vec.pop();
        vec.is_empty()
    };
    if should_remove {
        entry.remove();
    }
}

However, I don't believe that get or get_mut are expensive.


My take on this:

For console apps, I like to use a more OOP approach.

A Message class to hold a string array to handle a multiline message, and if the message requires a response a string of the characters allowed, will allow you to replace all those string literals with named variables:

class Message
{
    public String[] message { get; }
    public String choices { get; }
    public Message()
    {
        message = new String[0];
        choices = "";
    }
    public Message(String choices, params String[] message)
    {
        this.message = message;
        this.choices = choices.ToLower();
    }
}

To compliment this class, a static storage class(Messages) to put names to the various messages that will be required.  I put a simple print method in there as well:

static class Messages
{
    public static Message startMessage = new Message("", "Welcome to RockScissorPaper");
    public static Message instructions = new Message("", "When you're ready to play, press the desired number.",
            "The computer will reveal its choice and who won.");
    public static Message rockWins = new Message("", "Rock breaks Scissors.", "Rock wins.");
    public static Message scissorsWins = new Message("", "Scissors cuts Paper.", "Scissors wins.");
    public static Message paperWins = new Message("", "Paper covers Rock.", "Paper wins.");
    public static Message playAgain = new Message("yn\n", "Would you like to play again?(y/n)");
    public static Message continuePlay = new Message("", "Press any key to continue.");
    public static Message choices = new Message("0123", "1 - Rock", "2 - Scissors", "3 - Paper", "0 - Quit", "\nWhich do you choose?");
    public static Message goodbye = new Message("", "Thank you for playing.  Goodbye.");
    public static Message tie = new Message("", "A tie.  You both chose the same.");
    public static Message wrongChoice = new Message("", "You made a wrong choice.  Try again.");

    public static void PrintMessage(TextWriter tOut, Message message)
    {
        tOut.WriteLine();
        foreach (var s in message.message)
        {
            tOut.WriteLine(s);
        }
    }
}

This approach makes it very easy, with minimal refactoring, to create language choices for your app.

For classes that require I/O, I like to keeps things flexible and use base classes instead of hard coding standard I/O.  This makes it very easy to leverage networking at some point.

For the game class(RockScissorPaper), a method to get the user's input, clears a lot of code from the PlayGame method.

private static char GetChoice(TextWriter tOut, TextReader tIn, Message message)
{
    char choice = '\0';
    bool done = false;
    do
    {
        Messages.PrintMessage(tOut, message);
        string response = tIn.ReadLine().ToLower();
        choice = response.Length > 0 ? response[0] : '\n';
        if (message.choices.Contains(choice))
        {
            return choice;
        }
        Messages.PrintMessage(tOut, Messages.wrongChoice);
    } while (!done);
    return choice;
}

I find an enum for the different states of the game, helps with the decision process to decide a winner:

private enum State
{
    None = 0,
    Tie = 1,
    Rock = 3,
    Scissors,
    Paper
}

Notice the Rock constant starts at 3. This allows simple math and one conditional to decide which player is the winner. Once the winner is decided the switch block to select which message to display is very simple:

private static Message GetWinner(State comp, State player)
{
    if (comp == State.None || player == State.None)
    {
        throw new ArgumentOutOfRangeException("Both 'comp' and 'player' must be 'Rock', 'Scissors' or 'Paper'.");
    }
    int cmptr = (int)comp;
    int plyr = (int)player;
    State winner = State.None;
    if (player == comp)
    {
        winner = State.Tie;
        plyrScore++;
        compScore++;
    }
    else if(plyr % 3 == (cmptr - 1) % 3)
    {
        winner = player;
        plyrScore += 2;
    }
    else
    {
        winner = comp;
        compScore += 2;
    }
    switch (winner)
    {
        case State.Tie:
            return Messages.tie;
        case State.Rock:
            return Messages.rockWins;
        case State.Scissors:
            return Messages.scissorsWins;
        case State.Paper:
            return Messages.paperWins;
        default:
            return new Message("", "");
    }
}

I've incorporated the score calculation here, as well.  I noticed you scored a tie  the same a win.  Typically a tie is considered half a win.  I would prefer to see a win at 2 points and a tie at 1.

With these helper methods done, the game play is almost trivial to code:

static class RockScissorsPaper
{
    private static RandomEngine rnd = new RandomEngine();
    private enum State
    {
        None = 0,
        Tie = 1,
        Rock = 3,
        Scissors,
        Paper
    }
    static int plyrScore = 0;
    static int compScore = 0;
    public static void PlayGame(TextWriter tOut, TextReader tIn, String name, int rounds)
    {
        plyrScore = 0;
        compScore = 0;
        Messages.PrintMessage(tOut, Messages.startMessage);
        for(int round = 0; round < rounds; ++round)
        {
            Messages.PrintMessage(tOut, Messages.instructions);
            int choice = GetChoice(tOut, tIn, Messages.choices) - '0';
            State compChoice = (State)Enum.GetValues(typeof(State)).GetValue((rnd.Next(0, 300) % 3) + 2);
            State playerChoice = (State)(choice + 2);
            tOut.WriteLine($"The player chose {playerChoice}.\nThe computer chose {compChoice}.");
            Messages.PrintMessage(tOut, GetWinner(compChoice, playerChoice));
            tOut.WriteLine($"The score is:\n{name} - {plyrScore}\nComputer - {compScore}");
            Messages.PrintMessage(tOut, Messages.continuePlay);
            tIn.Read();
        }

    }

    private static char GetChoice(TextWriter tOut, TextReader tIn, Message message)
    {
        char choice = '\0';
        bool done = false;
        do
        {
            Messages.PrintMessage(tOut, message);
            string response = tIn.ReadLine().ToLower();
            choice = response.Length > 0 ? response[0] : '\n';
            if (message.choices.Contains(choice))
            {
                return choice;
            }
            Messages.PrintMessage(tOut, Messages.wrongChoice);
        } while (!done);
        return choice;
    }
    private static Message GetWinner(State comp, State player)
    {
        if (comp == State.None || player == State.None)
        {
            throw new ArgumentOutOfRangeException("Both 'comp' and 'player' must be 'Rock', 'Scissors' or 'Paper'.");
        }
        int cmptr = (int)comp;
        int plyr = (int)player;
        State winner = State.None;
        if (player == comp)
        {
            winner = State.Tie;
            plyrScore++;
            compScore++;
        }
        else if(plyr % 3 == (cmptr - 1) % 3)
        {
            winner = player;
            plyrScore += 2;
        }
        else
        {
            winner = comp;
            compScore += 2;
        }
        switch (winner)
        {
            case State.Tie:
                return Messages.tie;
            case State.Rock:
                return Messages.rockWins;
            case State.Scissors:
                return Messages.scissorsWins;
            case State.Paper:
                return Messages.paperWins;
            default:
                return new Message("", "");
        }
    }
}


Reading a Bitmap from disk on a separate thread on Android

I would implement a progress bar to inform the user of the image loading status to eliminate confusion to what it's going on.

Also, you could deactivate the button for as long as the thread is running. And reactivate it in onPostExecute().


C++ Class wrapper on top of WinMain/DllMain

it's better to explicitly call init and exinit than pass a bool to "Check" to say which will one will get called.  maybe call them "Start" and "Exit"

Also, I'd suggest not making them virtual, if you want to be able to extend it...use a protected virtual

public: bool Start();
protected: virtual bool StartImpl();

void CInit::Start()
{
   StartImpl();
}

This gives you a bit more control over the calling in to your API.  (Also a mostly recommended best practice for C++).

It's called "Non Virtual Interface" or NVI.  It does have pros and cons.  But in this case I think it would be quite useful.


Speed-Distance-Time Calculator in Rust 1.8

You have extra indentation on the use statement and in your implicit returns.
I don't like the detail printed between the prompt and the entry of the value:

Enter distance:
Enter a floating point number!

I'd reorder these two lines, or combine them.
There's no need for the match in the prompt to evaluate to a value, it can directly return from the function.
This change allows you to switch to an if let statement because you'd only care about one variant.
If you keep the loop structure to read strings, you could consider keeping one allocated String to store into. You need to be careful to reset the string between loops, but it's a bit more efficient.
There's no need to specify the type on variables in the calc_* functions. Type is defined by the call to get_param.
Could extract some duplication for the prompt "Enter ...:" and move it to the prompt function.
Actually, "prompt" is a better verb than "get"; "get" is almost always a weak verb.
Don't declare a variable with a wider scope than needed - declare answer inside the match arms in main.
Actually, there's no reason to have a variable for answer at all, inline the call into the println!.
Actually, why split the printing inside and outside of the calc_* functions? Might as well do it all in one place.
What about supporting various cases of input like "SpEED"? Could match against a lowercased version of the string.

use std::io;

fn prompt_for_value(value_name: &str) -> f64 {
    println!("Enter {}:", value_name);

    loop {
        println!("Enter a floating point number!");

        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("failed to read line");

        if let Ok(num) = input.trim().parse() {
            return num;
        }
    }
}

fn calc_speed() {
    let distance = prompt_for_value("distance");
    let time     = prompt_for_value("time");
    println!("Speed = distance / time");
    println!("Speed = {} / {}", distance, time);
    println!("Speed = {}", distance / time);
}

fn calc_time() {
    let speed    = prompt_for_value("speed");
    let distance = prompt_for_value("distance");
    println!("Time = distance / speed");
    println!("Time = {} / {}", distance, speed);
    println!("Time = {}", distance / speed);
}

fn calc_distance() {
    let speed = prompt_for_value("speed");
    let time  = prompt_for_value("time");
    println!("Distance = speed * time");
    println!("Distance = {} * {}", speed, time);
    println!("Distance = {}", speed * time);
}

fn main() {
    println!("Hello, would you like to calculate speed, distance or time?");

    let mut calc_input = String::new();
    io::stdin().read_line(&mut calc_input).expect("failed to read line");

    match calc_input.to_lowercase().trim() {
        "speed"    => calc_speed(),
        "distance" => calc_distance(),
        "time"     => calc_time(),
        _          => println!("Enter speed, distance or time!"),
    }
}

Here's an alternate version of prompt_for_value that I might have written, but it's a bit different.

use std::io::BufRead;

fn prompt_for_value(value_name: &str) -> f64 {
    let stdin = io::stdin();

    println!("Enter {} (floating-point):", value_name);

    for line in stdin.lock().lines() {
        let line = line.expect("failed to read line");

        if let Ok(num) = line.trim().parse() {
            return num;
        }
    }

    panic!("Ran out of input");
}


JavaScript bottom-up tree transformer aimed for performance

Hmmm,

I don't think your code works,

var tree = [[1,2,[1,2,[5]]],[[3,4],[5,6]],[1,2,[1,2,[5]]],[[3,4],[5,6]]];

gives

[[3, 77], [[3, 4], 77], [1, 2, [1, 2, [5]]], [[3, 4], [5, 6]]]

I would have expected that you want that last [5,6] to be 77 in your fiddle.

Furthermore, as RoToRa mentioned

It is not clear in your code what you want to achieve
Comma separated statements to avoid curly braces are evil, python much?
Going through a tree pretty much asks for a recursive solution because you need to keep track of where you are

This function seems to do what you want thru recursion:

function transform( node, f )
{
  node = f(node) || node;
  var index = node.length;
  if( index )
  {
    while( index-- )
    {
      node[index] = transform( node[index] , f );
    }
  }
  return node;
}

Or, if you drop those curlies which you seem to like:

function transform( node, f )
{
  node = f(node) || node;
  var index = node.length;
  if( index )
    while( index-- )
      node[index] = transform( node[index] , f );
  return node;
}

I originally wanted to use [].map which would be cleaner, however you insisted speed.

Update: I checked jsperf for the fastest loop and it turns out there is a new loop variant that blows the other approaches out of the water: http://jsperf.com/loops/142

Using this approach the code would look like this:

function transform( node, f )
{
  node = f(node) || node;
  if( node.length )
    for (var i = 0, child; child = node[i]; i++)
      node[i] = transform( child , f );
  return node;
}


You have a bug right on the first statement:

while(isspace(*nptr++)) // skip white space
    ;

I didn't vote to close your post as off-topic for broken code to make a point:
it might seem cool to do two things at once in a loop condition (condition + increment),
it's not recommended, for two reasons:

It's best to have one statement per line

A for (;;) is an exception, where it's allowed

The loop condition should be about the condition. Leave it at that, move the incrementing logic inside the loop body in a while loop.

The bug is an off-by-one error: when the first digit is found,
the condition is false, but the pointer will be still incremented,
moving past the first digit. As a result, a string like "123" gets parsed as 23.

The fix is simple, and follows the above recommendations about writing loops:

// skip white space
while (isspace(*nptr)) {
    nptr++;
}

  I'm currently a little bit unhappy with the idea, that my code can't do anything against values smaller than INT_MIN and values greater than INT_MAX, but I can't come up with a solution that fits my expectations of good code.

Hm, the method is declared to return an int...
So it seems you don't like that int is limited within INT_MIN and INT_MAX by the language. There's just one thing to do: change the return type to something bigger, like a long!

Finally, when comparing against a variable to multiple files in the same conditional expression, often it's more readable to put the conditions in numerical increasing order, for example instead of this:

while(*nptr >= '0' && *nptr <= '9')

Write like this:

while('0' <= *nptr && *nptr <= '9')


While technically this isn't reviewing your code, IMO this is the better solution: Do sort via MySQL

SELECT id, value, type
FROM a_table
WHERE id IN (15, 75, 45, 13);
ORDER BY FIELD(id, 15, 75, 45, 13)

PHP isn't the fastest language and should therefor not be used for sorting/ordering sets of data if other solutions are present. Looping in PHP is slow (but sometimes negligible, like the while(fetch)). MySQL, in this case, is a whole lot faster then PHP.

At the same time, this is more readable (IMO) and better to maintain.


That's a very naive bruteforce algorithm.  To optimize this sort of calculation you can usually "turn it around" by doing something like: for each possible divisor, computing the number of times it'll feature as a contributor and adding them up.  And if you can get it to work by just iterating over primes, it'll be even better/faster.


You have:
bool valid() const {
    return ptr == nullptr;
}

I think you meant != there. Regardless, you probably don't need this method; and if you must have it, consider spelling it either
operator bool() const { return ptr != nullptr; }
// or else
bool operator==(std::nullptr_t) const { return ptr != nullptr; }

Try the following program:
int main() {
    MallocRaii m(10);
    MallocRaii n(10);
    m = std::move(n);  // infinite loop
}

This is because std::swap is implemented in terms of move-assignment, but you've chosen to implement move-assignment in terms of std::swap! Here are some slides on the subject (full disclosure: I wrote them).

A minor nit:
   if(this->ptr != nullptr)
        free(this->ptr);

You're missing a space after if; and you don't need the test anyway, because free(nullptr) is already guaranteed to do the right thing. Simply write
~MallocRaii() { free(ptr); }

You make ptr a public member variable. This allows anybody to come along and modify it:
MallocRaii m(10);
m.ptr = nullptr;  // oops! memory leak!

Prefer to expose the value of the pointer (but not an actual reference to it) via an accessor, traditionally spelled get().
T *get() const { return ptr; }

Finally, be aware that you could always just use std::unique_ptr<T, decltype(free)> instead of writing your own class; or at least that you could pretty easily implement your MallocRaii class in terms of unique_ptr. This would give you foolproof swap/move/no-copy boilerplate for free (via the Rule of Zero), and would be shorter as well.


(EDIT: Go look at @RE60K's solution before mine. His is faster and easier to understand.)

Unfortunately, I don't think this code will work, efficiency aside.

for combo in combinations(arr, i):

Here, you're looping through permutations, but the challenge asks for subarrays.

Instead, you should do something like:

def maxLen(n, arr):
    for subarray_length in range(n, 0, -1):
        for subarray_start in range(len(arr) - subarray_length + 1):
            subarray = arr[subarray_start : subarray_start + subarray_length]
            if sum(subarray) == 0: return len(subarray)
    return 0

Which works, but isn't terribly quick. If sum is O(n), then this is O(n^3).

I was able to come up with a quicker algorithm (O(n^2)) which seems to be consistently faster on my timeit tests (which may not be perfect).

To show the idea of how this works, I'll use an example.

Consider if the input array were [1, -4, 4, -3, -1, 8, -3].

We'd start by trying the whole array, which sums to -4. Then we'd try all arrays one size down, then two, etc.

Let's skip to trying subarray size 3, since that's where the answer lies. First we try [1, -4, 4] which sums to 1. Normally, we'd then try the next subarray, [-4, 4, -3], but we can take a shortcut here. These two subarrays only differ by two items: the first item of the first, and the last item of the second. As such, we can instead keep a running sum, and only worry ourselves with those two key items.

So, instead, we go like this: first length 3 subarray is [1, -4, 4], which sums to 1. The next item after this subarray is -3. We add this to the running sum, and remove 1, (+= -3, -= 1), and then consider our array to have moved to the right one. So, the next item we consider is the one after -3, namely, -1. And so we continue and find that our running sum does hit 0, and so return 3.

def max_len_2(arr_len, arr):
    for sub_len in range(arr_len, 0, -1):  # For all subarray lengths
        arr_sum = sum(arr[0:sub_len])  # Get the initial sum
        if arr_sum == 0: return sub_len  # Return if it works
        for gain_index in range(sub_len, arr_len):  # Otherwise, loop through all the indices after the array
            arr_sum -= arr[gain_index - sub_len]  # Drop first item in array
            arr_sum += arr[gain_index]  # Gain first item after array
            if arr_sum == 0: return sub_len  # If sum works, return
    return 0

This is more efficient, awesome! But we can take it one step further. What we just did is we used information we already know about a row in order to have to make less calculations. Essentially, we're not wasting any information.

And we can do this between rows, as well, in order to be even more efficient (although still O(n^2), but whatever...).

I'll explain this algorithm with the same example, [1, -4, 4, -3, -1, 8, -3].

We start by noting that the sum of this is -4. We'll call this sum 0 0. If it were 0, we'd be done, but it isn't.

Now, we start with the largest subarrays, length 6. We note that the first subarray is the same as the whole array, except for the last element; so, the sum is sum 0 0 minus the last element, which is -3. The sum is -4 - -3 = -1. This is sum 1 0. The second length-6 subarray is the same as the whole array, except for the first element, so we know the sum is sum 0 0 - first element = -4 - 1 = -5.

Now, onto length 5. The sum of the first length 5 subarray (sum 2 0) is the same as the first length 6 subarray (sum 1 0), except for the first element...

See the pattern? With each new subarray length n, sum n k = sum (n-1) k - last element of array (n-1) k. The only exception here is that there is 1 length-7 sub, 2 length-6, 3 length-5, etc.; each time we gain a subarray, and this new sub isn't accounted for with this algorithm. Instead, we know that the sum of the last sub sum n k is the same as sum (n-1) k - first element of array (n-1) k Note the difference: it's the first element we're taking away, not the last.

def max_len_dynamic_programming(arr_len, arr):
    dp = []  # This is our data storage

    # We initialize it with the sum of the array
    s = sum(arr)
    if s == 0: return arr_len
    dp.append([s])

    for sub_len in range(arr_len - 1, 0, -1):  # Iterate over sub lengths, decreasing...
        row = []  # We'll construct the new row
        prev_row = dp[-1]  # With info from the old row
        prev_row_len = arr_len - sub_len

        for i in range(prev_row_len):
            # This is where the magic happens.
            # cell is `sum n k`, and
            # prev_row[i] is `sum (n-1) k`,
            # and arr[i + sub_len] is
            # the last item of `array (n-1) k`
            cell = prev_row[i] - arr[i + sub_len]
            if cell == 0: return sub_len
            row.append(cell)

        # Deal with the last element seperately
        last = prev_row[-1] - arr[~sub_len]  # -sub_len - 1
        if last == 0: return sub_len
        row.append(last)

        dp.append(row)

    return 0

If you want a faster*, harder-to-understand version, make these swaps in the code:

Swap

row = []
prev_row = dp[-1]
prev_row_len = arr_len - sub_len

for

prev_row = dp[-1]
prev_row_len = arr_len - sub_len
row_len = prev_row_len + 1
row = [0] * row_len

& swap row.append(cell) for row[i] = cell

& swap row.append(last) for row[-1] = last

*Most of the time, in my tests, at least. The swaps change this from using all dynamic arrays to preinitialized arrays for each row, and dynamic for the grid. Going full-preinitialized-arrays will be even faster some of the time. Not sure how to tell when it'll be faster and when it'll be slower.


Parsing a long without using inbuilt function parseLong

If the condition if(number==null || number.isEmpty()) holds true the method should throw a ParseException rather than incorrectly returning 0.

Also your logic for non-negative numbers isn't quite correct, as you are ignoring the first character if the length of the input is > 1. To fix this you should include charAt(0) in your else statement as follows:

    if(number.charAt(0)=='-'){
        isNegative=true;
    }
    else {
        n = getValue(number.charAt(0));

        for(int i=1;i<number.length();i++){
            n = n*10 + getValue(number.charAt(i));
        }
    }

Also in your getValue method your check, whether the character is a digit can be simplified:

public int getValue(char ch){
    if (Character.isDigit(ch)){
        return ch - 48;
    } else {
        throw new NumberFormatException();
    }
}

These are local optimizations. I would consider converting the string to an array of integers first (and by doing that determine, whether the string is valid in the first place) and then compute the value. By doing the computations as you go you are risking doing them in vain if a later input character is not a digit.

One thing that is missing in your code is considering the maximum value for a long and checking for violations.