Recursively reading a directory in node.js

My comments are inline starting with the //*. I also very much encourage you to look at async libraries such as Q.

var dutils = require('./dutils');

//* Why export an object with a single function? Why not just export the function itself?
module.exports = {
    //* I don't like intermixing method implementation with exports declaration because you tend to be
    //* looking for very different things when looking at each. Hoisting to the rescure!
    //*     module.exports = { getIndex: getIndex };
    //*     ... later ...
    //*     function getIndex(ignore, cb) {
    //*         ...
    getIndex: function(ignore, cb) {
        //* What if they didn't pass a  callback? Might as well check here and throw an error. Otherwise
        //* there will be a confusing error later on

        //* What is `this`? I **highly** recommend not using the `this` parameter unless you
        //* understand _very_ well what it does and how it works. You can almost always achieve the same
        //* thing using simpler techniques
        var root = this.root;
        //* cds is not a good variable name - I have no idea what this represents reading it
        var cbs = 1;
        var index = {};

        // recursive function for walking directory
        (function walk(dir) {

            //* I usually prefer naming callback functions. Not only does it allow you to give a good
            //* label to the code but the function will show up labeled in stack traces
            fs.readdir(dir, function(err, files) {
                //* Be aware that it is possible for the callback to be triggered multiple times when there are
                //* errors. This is an unusual interface and just be certain that you do this on purpose
                if (err) return cb(err);

                //* Again, I would recommend labeling this function.
                //* Also I'm not sure if this will follow symlinks or not but if does then this might end up in
                //* an endless loop.
                files.forEach(function(fileName) {
                    // prepare
                    var filePath = path.join(dir, fileName); // filePath with root
                    var relFilePath = path.relative(root, filePath); // filePath without root

                    //* I don't think this is really a useful comment as it doesn't say much more than
                    //* the code itself does. I also usually prefer putting the `return` statement for early returns
                    //* on its own line to make the early return stand out visually.
                    // if the file is on our ignore list don't index it
                    if (dutils.globmatch(filePath, ignore)) return;

                    var stats = fs.statSync(filePath);
                    var isDir = stats.isDirectory();

                    index[relFilePath] = {
                        isDir: isDir,
                        mtime: stats.mtime
                    };

                    //* This comment is not very useful as it - again - just restates what the code does
                    // if the file is a directory, walk it next
                    if (isDir) {
                        // count the number of callbacks that are running concurrently
                        cbs++;
                        walk(filePath);
                    }
                });

                // our callback was completed
                cbs--;

                // if all callbacks were completed, we've completely walked our directory
                if (cbs === 0) cb(null, index);

                //* Is the entire point of the `cbs` counter to see if any `readdir` operation resulted in an error?
                //* that seems to be all that it does. Why not just have a `var lastError = null` in `getIndex` and
                //* rather than checking for err do `if(lastError = err) return`. That way if `err` is truthy you have
                //* an error, otherwise you do not
                //*
                //* Also keep in mind that cb will be called multiple times but each time with the
                //* same instance of the index object. That means that previously invoked callbacks will be
                //* having this object mutate underneat them. This might be exactly what you want but it is unuaual
                //* and should definitely be documented clearly. At the very least you want a big bold doc comment
                //* on this function
            });
        })(root);
    }
}

Here is an article I wrote on this parameters


Prime Number Generator Time Limit Exceeded

I see some things that may help you improve your code.  I'll start with the stylistic pieces and then move on to the basic algorithm and the speed-up you're seeking.

Fix your formatting

This code has peculiar indentation that makes it difficult to tell when a function begins and ends.  Fixing that would hlep.

Use <cmath> instead of <math.h>

The difference between the two forms is that the former defines things within the std:: namespace versus into the global namespace.  Language lawyers have lots of fun with this, but for daily use I'd recommend using <cmath>.  See this SO question for details.

Use all of the required #includes

The function std::scanf is used but its declaration is in #include <cstdlib> which is not actually in the list of includes.  Similarly std::fill needs #include <algorithm>.

Avoid non-portable type assumptions

The code currently contains this line

std::scanf("%llu %llu", &m, &n);

That might be just fine with your compiler on your machine, but on mine, the compiler complains:

  warning: format ‘%llu’ expects argument of type ‘long long unsigned int*’, but argument 2 has type ‘uint64_t* {aka long unsigned int*}’

The simplest way to avoid that problem is to use the C++ stream extractors instead:

std::cin >> m >> n;

There is a parallel problem (and fix) with std::printf.

Use the right constructor

The code currently contains these two lines:

std::vector<bool> flags(n + 1);
std::fill(flags.begin(), flags.end(), true);

Why not simply use the constructor version that does both of these?

std::vector<bool> flags(n + 1, true);

Use your knowledge of the mathematical domain

The only even prime number is 2, so you could optimize for both space and performance by only storing bits that correspond with odd numbers.  Further, it's clear that if we eliminate even numbers, the inner sieve loop can look like this instead:

for (uint64_t j = i * i; j <= n; j += 2 * i) {

Avoid doing the same work twice

In the case that there are multiple trials, one simple optimization would be to compute the sieve only once (based on the largest n) and then simply use it multiple times rather than re-calculating the sieve for every trial.

Do work at compile time instead of runtime

Another optimization would be to compute the sieve at compile time rather than runtime.  If you're using C++14 or better, one can compute the sieve at compile time.


Good stuff, I particularly like State being a purely abstract interface, that's exactly how to best do modern inheritance.

State needs a virtual destructor

This is 100% required in this case, since you delete states from pointers of State.

Reduce API surface

You have too many push_state() functions

void push_state(const StateRef& state);
void push_state(State* state);

template<class T>
void push_state();

You would be better off having just the single:

void push_state(const StateRef& state);

What looks like "convenience" to you just ends up being "confusing" for possible users of the class as they have to wonder "which one of these should I be using?"

Take objects by value if you are taking ownership

void push_state(const StateRef& state);

should be:

void push_state(StateRef state);

Your function currently will always go through a copy-constructor, and for shared_ptr<> this is definitely non-trivial as that has to be thread safe.

By taking the StateRef by value, this gives users control over whether to provide a RValue, move in a LValue, or provide a copy of some other object. Maximum flexibility without any overloads.

This brings us to:

Prefer unique_ptr over shared_ptr

I see no shared ownership scemantics here, unique_ptr would be better simply for performance reasons. But you may have other parts of the larger codebase that warrant it. That comment is just about the code I see in isolation.

That's pretty much all I've got here.


Comments on my Java pattern for Mutable turned Immutable objects

If you really want to avoid object creation, you have no other choice as dropping final, e.g.:

public interface Something {

    public int getSomeInteger();
    public String getSomeString();

    public static class Mutable implements Something {
        private int someInteger;
        private String someString;
        private boolean open = true;

        public int getSomeInteger() {
            return someInteger;
        }

        public String getSomeString() {
            return someString;
        }

        public Something.Mutable setSomeInteger(int someInteger) {
            assert open;
            this.someInteger = someInteger;
            return this;
        }

        public Something.Mutable setSomeString(String someString) {
            assert open;
            this.someString = someString;
            return this;
        }

        public Something make() {
            open = false;
            return this;
        }
    }
}

But this pattern is brittle, and the Java runtime is pretty good in dealing with object creation these days, so if you don't write a graphic or math lib or so, you shouldn't care about.


Editing HTML based on instructions in a data structure

Personal preference, but I'd suggest 2-space indentation. You'll most likely nest a lot of stuff in JS, and using 4-space indentation can easily throw you over to the right side of your screen.

Another approach to reducing indentation overhead is to "return early" or offload the functionality to a separate function and use a ternary operation. This is especially when you have single if blocks with no else.

function foo(){
  var something = ''
  if(condition){
    something = doSomething();
  }
  return something;
}

// is the same as returning early:

function foo(){
  var something = ''
  if(!condition) return something;
  something = doSomething();
  return something;
}

// is the same as using a ternary:

function foo(){
  return condition ? doSomething() : '';
}

  This is the input: please notice that that in the firstobj of the array (there is scenario which the next attribute is not provided which say to put the new script at the bottom) the next said put the script tag after script that have ID "ui-boot"

When you have to explain your code, that's a sign that you have done something bad. In this case, you had to explain what next in the first element is, and id on the second element.

Being consistent in your objects as well as good naming schemes are a good start:

var extendedHtmlObject = [{
  action: 'new',
  type: 'script',
  properties: null,
  content: 'console.log(‘hello world’);'
  position: {
    anchor: '#ui-boot',
    placement: 'after'
  }
}, {
  action: 'update',
  type: 'script',
  properties: {
    id: 'ui-boot',
    src: '/test/test2/-co.js',
    'data--ui-comersion': '1.17',
  },
  content: '',
  position: null
}];

While there are legitimate use cases for a switch, it's usually a sign that indicates that some function is trying to do too many things. Also, switch can bloat easily and forgetting break is a danger waiting to happen. Consider using key-value pairs instead:

function actions(key, args){
  switch(key){
    case: 'foo':
      return doFoo(args);
      break;
    case: 'bar':
      return doBar(args);
      break;
    case: 'baz':
      return doBaz(args);
      break
  }
}

var value = actions(keyargs);

// is the same as

var actions = {
  foo: function doFoo(){...},
  bar: function doBar(){...},
  baz: function doBaz(){...}
};

var value = actions[key](args);

  could I maybe improve it with JS prototype?

If this is a singleton module, it doesn't make sense to use prototypes. Prototypes make sense when you create multiple instances that "inherit" the same methods. If you only create one instance, then it doesn't make sense to use a mechanism that was meant for building multiple instances of something.


I'm wondering if settings.php is in the same directory tree where you have other scripts like index.php served by the web server.
I don't know if this is possible on Heroku,
but I recommend to move files that should never be served by the web server outside of the document root.

One time, I had a web server malfunction: the well-tuned configuration file got replaced with something primitive, and php disabled, where visiting settings.php in a browser would simply display the contents of the file without running through the PHP interpreter. Sure, this seems unlikely to happen, but by moving sensitive files outside the document root, you can effectively safeguard against such or similar misconfiguration issues. I also find it good organization to separate public files from internal details. So my PHP projects all have a public/ directory inside, containing practically views only, the model is elsewhere, cleanly separated.

About this:

define('DB_URL', 'mysql://root:password@localhost:3306/database');

Even if it's a dedicated and isolated database for your project only,
I don't see why would you ever use the root account.
Create a dedicated user with carefully selected grants instead.

Needless to say, settings.php should have restrictive permissions in the filesystem.


Deserializing a byte array from Java in C++

Obviously the code isn't portable to big-endian machines. I'll use C syntax, since I'm more familiar with that than C++.

If you have endian.h, you can use the functions in there; if not, you should have arpa/inet.h which defines functions for swapping network byte order (big-endian) to host byte order, but lacks a function for 64-bit values. Look for either be16toh (from endian.h) or ntohs (from arpa/inet.h) and friends.

Why not read directly into the values:

fread((void *)&employeeId, sizeof(employeeId), 1, file);
employeeId = be16toh(employeeId);

Since you can manipulate pointers in C, you just need to provide a universal pointer (void *) to the read function where it should place the results. The & operator takes the address of a value. Once that is done, you can manipulate the value directly, as above.

Using this Java test code:

import java.io.*;

public class write {
  public static void main(String... args) throws Exception {
    final FileOutputStream file = new FileOutputStream("java.dat");
    final DataOutputStream data = new DataOutputStream(file);

    final long time = System.currentTimeMillis();
    final short value = 32219;

    //  fill a table with a..z0..9
    final byte[] table = new byte[36];
    int index = 0;
    for (int i = 0; i < 26; i++) {
      table[index++] = (byte)(i + 'a');
    }
    for (int i = 0 ; i < 10; i++) {
      table[index++] = (byte)(i + '0');
    }

    data.writeLong(time);
    data.writeShort(value);
    data.writeInt(table.length);
    data.write(table);
    data.close();

    System.out.format("wrote time: %d%n  value: %d%n  length: %d%n  table:%n", time, value, table.length);
    for (int i = 0; i < table.length; i++) {
      System.out.format("%c ", (char)table[i]);
    }
    System.out.println();
  }
}

The output from this code is:

wrote time: 1380743479723
  value: 32219
  length: 36
  table:
a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9

You can read the values in with this C code:

#include <stdio.h>
#include <stdlib.h>
#include <endian.h>
#include <sys/types.h>

int main(int argc, char **argv) {
  int64_t time;
  int16_t value;
  int32_t length;
  u_int8_t *array;

  FILE *in = fopen("java.dat", "rb");

  fread(&time, sizeof(time), 1, in);
  time = (int64_t)be64toh( (u_int64_t)time);

  fread(&value, sizeof(value), 1, in);
  value = (int16_t)be16toh( (u_int16_t)value );

  fread(&length, sizeof(length), 1, in);
  length = (int32_t)be32toh( (u_int32_t)length );

  array = (u_int8_t *)malloc(length);
  fread(array, sizeof(array[0]), length, in);

  fclose(in);

  printf("time: %ld\nvalue: %d\narray length: %d\narray:\n", time, value, length);
  for (int i = 0; i < length; i++) {
    printf("%c ", array[i]);
  }
  printf("\n");

  free(array);
  return 0;
}

I compiled this on Ubuntu x64 with clang. Its output was:

./a.out
time: 1380743479723
value: 32219
array length: 36
array:
a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9

Keep in mind that the only unsigned types in Java are byte (8 bits) and char (16-32 bits).


My first build.gradle for a 3D space graphics program

The part where you create directories with a single file removeme.txt doesn't belong in a build.gradle file of an Android project. This appears to be a one time setup for your project, specifically for using Git as the version control system. After a single execution followed by a commit, this code is pointless, it doesn't need to be executed again, so I suggest to put it in a separate helper script file.

It's a very minor thing, but to keep "empty"directories in Git, a common name for the place holder file seems to be .gitkeep


In the issue 23 of The Monad.Reader, there is a nice discussion of FizzBuzz and how to solve it efficiently in Haskell. The efficiency being in terms of future extensions such as "output Bazz if it's a multiple of 7, FizzBazz if it's a multiple of 21, (...)". The proposed solution is linear in the number of conditions.

The final answer goes something like this (but I'd advise you to go through the paper: it's a pretty nice read!):

fizzbuzz n = (test 3 "Fizz" . test 5 "Buzz") id (show n)
  where test d s x | n `mod` d == 0 = const (s ++ x "")
                   | otherwise = x


However I didn't like that it expects the AJAX request to request JS and then having a partial render inside a jQuery method that then makes an assumption about #content existing to render it inside. So effectively the response is also handling how it should be used.

I actually think this is best practice for a non-SPA solution. It's a great approach because you will know how the page is structured. It works even if there's multiple posts because you can assign object IDs to the posts in the HTML, which then lets you target those objects in your JQuery selector.

So you'd be looking at something like:

$('.post[data-object-id=<%= post.id %> .likes').html('<%= j render(partial: 'likes/like_button', locals: {likes: post.likes}) %> ')

Now if you want to do something fancy with the HTML beyond just inserting it at the appropriate location, then you'd indeed make an AJAX request for the HTML, and attach a handler to the promise generated from the AJAX request which would handle the HTML response appropriately.


When to use Assert
Generally assert() is a debugging tool. The GeekforGeeks website itself warns against using it in certain cases.

If the NODEBUG compilation flag is used in the file the assertion is removed.

It might be better to use if statements and write the output to std::cerr. That would provide a much more meaningful error message.

Reduce Complexity, Follow SRP
The Single Responsibility Principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

  Robert C. Martin expresses the principle as follows:
          A class should have only one reason to change.

While this is primarily targeted at classes in object oriented languages it applies to functions and subroutines well.

The more separate functions there are the easier it is to understand or read the code. This also makes it easier for any programmer to maintain or debug the code.

The main() function could be broken up into at multiple functions. The main() function should generally just control the program and handle any exceptions that get to that point.

An example of a decent main() function for this program might be:

int main() {
    int t;
    std::cin >> t;
    assert(t >= 1 && t <= 100);
    int x;

    while (t--)
    {
        std::vector<int> vec = getTestCase(x);

        std::cout << ((executeTestCase(vec, x)) ? 1 : 0) << std::endl;
    }

    return 0;
}

The first function that might be of use is an test case input function.

std::vector<int> getTestCase(int &x)
{
    int n;
    std::cin >> n;
    assert(n >= 1 && n <= 100);
    std::vector<int> vec(n);
    for (int i = 0; i < n; i++)
    {
        int val;
        std::cin >> val;
        vec.push_back(val);
    }

    std::cin >> x;

    return vec;
}

The second function that might be of use would be a that finds if there are values that meet the proper conditions.

bool executeTestCase(std::vector<int> vec, int x)
{
    bool found = false;
    int sum = 0;
    int n = vec.size();

    for (int i = 0; i < n - 3; i++)
    {
        for (int j = i + 1; j < n - 2; j++)
        {
            for (int k = j + 1; k < n - 1; k++)
            {
                for (int l = k + 1; l < n; l++)
                {
                    sum = vec[i] + vec[j] + vec[k] + vec[l];
                    if (sum == x)
                    {
                        found = true;
                        break;
                    }
                }
            }
        }
    }

    return found;
}

Improve Performance
Since the code is using a C++ container class, it might be possible to use iterators to improve performance. Once the code is broken up into functions and compiled -O3 it can be profiled to find where any bottlenecks exist.


There is indeed room for improvement, however slim it may be.

Get rid of the list

import sys

highest_fibo = int(sys.argv[1])

f1 = 0
f2 = 1

for _ in xrange(highest_fibo):
    f1, f2 = f2, f1 + f2
    print f2,

If you want to make it even simpler, there is even a function to compute fibonacci numbers and if you are interested, I leave it up to you to find it.

Before I go, I think I should explain this part which may seem confusing:

f1, f2 = f2, f1 + f2

This takes advantage of tuple assignment in python. The process begins by creating a tuple of both the left hand side and the right hand side of the expression. Then the right hand side of the expression is evaluated. Then the process of tuple unpacking begins where in each value on the left hand side is assigned to the one on the right.
This simple python trick allows for us to write a one line swap


I can't find any very useful invariant but sum of length of list should be constant. So we can make following assertion:

static int length(Node node) {
    int result = 0;
    while (node != null) {
        result++;
        node = node.next;
    }
    return result;
}

public static Node reverse(Node head) {
    if (head == null || head.next == null) {
        return head;
    }

    int totalLength = length(head);

    Node prev = null;
    Node curr = head;
    Node next = null;

    while (curr != null) {
        assert length(prev) + length(curr) == totalLength;
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    assert length(prev) + length(curr) == totalLength;

    return prev;
}

It is a bit of a stretch but we can make it easier to understand why invariant is preserved by showing that single node is moved from one list to another:

static class Node {

    // rest of class without changes

    @Override
    public String toString() {
        return  data + " -> " + next;
    }

}

static class List {
    Node head;
    int size() {
        return length(head);
    }

    Node removeFist() {
        Node oldHead = head;
        head = head.next;
        return oldHead;
    }

    boolean isEmpty() {
        return head == null;
    }

    void prepend(Node newHead) {
        newHead.next = head;
        head = newHead;
    }

    static List of(Node node) {
        List list = new List();
        list.head = node;
        return list;
    }
}

static int length(Node node) {
    int result = 0;
    while (node != null) {
        result++;
        node = node.next;
    }
    return result;
}

public static Node reverse(Node head) {
    if (head == null || head.next == null) {
        return head;
    }

    List reversed = List.of(null);
    List input = List.of(head);
    final int totalSize = input.size();

    while (!input.isEmpty()) {
        assert reversed.size() + input.size() == totalSize;
        reversed.prepend(input.removeFist());
    }
    assert reversed.size() + input.size() == totalSize;

    return reversed.head;
}

Sadly I wouldn't call that improvement. Maybe it would made more sense if List class I added also contained Node tail.


Verify that a path doesn't contain . or .. or // and doesn't end with /

Much better
I like your version much better than the original.  I don't see any cases you missed - it appears to work the same as the original function.  The only comment I have is that the path argument should be marked const.  But maybe you aren't allowed to change that.


Getting data from database through Ajax post request

PHP

SQL injection vulnerabilities

This code is wide-open to SQL injection attacks. User input should be sanitized as supplied to the query using parameters (e.g. with mysqli_prepare() and bind_param()).

Indentation

The indentation is somewhat consistent but then in some places it increases without a block-level change - e.g. in the PHP code most lines are indented with four spaces, which is very common, and then when $sql is declared it increases to eight spaces.

$conn = mysqli_connect($host, $user, $pass, $db);
      $sql = "SELECT * FROM `foodtablebusiness` WHERE category = " . $categoryID;

Fetching results

Instead of using a while loop with mysqli_fetch_assoc() just to push into an array, use mysqli_fetch_all() to get an array with one call.

Selecting fields

Additionally, the SQL query selects all fields - i.e. with SELECT *. Instead of selecting *, specify the field names needed in order to exclude any fields not needed in the front end.

Javascript

Variable scope

In this line:

ajaxRequest = createAJAXRequestToPopulateList(selector.options[selector.selectedIndex].value);

it makes a global variable ajaxRequest because there is no var, let or const keyword before it. Use const to limit the scope to the function addActivityItem.

Utilizing jQuery

It appears that jQuery is used, given the usage of $.ajax() (though if that is wrong then the following won't work). Presuming that is the case, then the other code can be simplified using jQuery utilities.

For example:

var selector = document.getElementById("categorySelector");
ajaxRequest = createAJAXRequestToPopulateList(selector.options[selector.selectedIndex].value);

can be simplified to the following using the .val() method:

const selector = $('#categorySelector');
const ajaxRequest = createAJAXRequestToPopulateList(selector.val());


Elegantly handle github API requests exceptions

One way to slightly speed-up is by reducing the overhead of the requests module. Currently your code has to establish a connection once for every team, re-transmitting the authentication API code and so on. This is a solved problem, you could use sessions.

You would have to start it with a context-manager in you outer function (where you loop over all of the team-names to create) and pass the session object to the create_team function.

I also shuffled some code out of the try block, you should have only the least possible amount in there, so you can be sure what exactly raised an error. I also inserted early returns, but there are other schools of thought which prefer a single exit for functions at the cost of having more code in the try block.

I also tried including a bare bones implementation for your outer function, but yours might be slightly different, of course.

I used str.format, where applicable instead of string addition.

import requests

OAUTH_TOKEN = "XXX"
HEADERS = {'Authorization': 'token {}'.format(OAUTH_TOKEN)}
GH_API_URL = "http://github.com/XXX"

def create_teams(org, team_names):
    with requests.Session() as session:
        session.headers.update(HEADERS)
        for team_name in team_names:
            create_team(session, org['login'], team_name)

def create_team(session, org_name, team_name):
    '''
    Try to create a team and return its id.
    If it already exists return id
    '''
    data = {
        "name": team_name,
        "permission": "push"
    }
    url = '{}orgs/{}/teams'.format(GH_API_URL, org_name)
    try:
        response = session.post(url, data=json.dumps(data))
        response.raise_for_status()  # throw exception if request does not return 2xx
    except requests.exceptions.HTTPError as e:
        if response.status_code == 422:  # Unprocessable Entity
            json_response = json.loads(response.text)
            # Unprocessable because already exists
            if json_response['errors'][0]['code'] == 'already_exists':
                print('{} not created, team already exists!!!'.format(team_name))
                # get the id of existing team
                return get_teamID_from_name(session, org, team_name)
        # Unprocessable for some other reason or other HTTP error != 422
        print(' HTTP error: {}'.format(e))
        return -1

    except requests.exceptions.RequestException as e:
        print('Connection error: {}'.format(e))
        return -1

    # http status is 2xx, team must have been created
    json_response = json.loads(response.text)
    return json_response['id']  # get id of new team from response


Firstly, your code doesn't actually work. Run it against your example data and DUPLICATE_LENGTH. It has no results. So I'm going to look at your code stylistically and ignore the algorithm for now:

import codecs

# Constants
DUPLICATE_LENGTH = 30;

No need for that semicolon

FILE_NAME = "data.txt"
SHOW_RESULTS_WHILE_PROCESSING = True

def showDuplicate(duplicate):

python style guide recommends seperation_by_underscores for function names

    print("Duplicate found:{0}".format(duplicate))

fileHandle = codecs.open(FILE_NAME, "r", "utf-8-sig")
fileContent = fileHandle.read()
fileHandle.close()

Python style guide recommends words_seperated_by_underscores for variable names.

substringList = []  #contains all possible duplicates.
duplicatesList = [] #contains all duplicates

for i in range(0, len(fileContent) - DUPLICATE_LENGTH):

No need for the 0, range(x) == range(0, x)

    end = i + DUPLICATE_LENGTH
    duplicate = fileContent[i:end]

I'd combine those two lines. I'd also not call it a duplicate as its not a duplicate, just a substring.

    if duplicate in substringList and '|' not in duplicate:

I not clear what significance the |  has

        duplicatesList.append(duplicate)
    else:
        substringList.append(duplicate)

resultList = []
currentMatch = duplicatesList[0]
currentMatchPos = 1

Any sort of complex logic should really be in  a function, not at the module level.

for i in range(1, len(duplicatesList)):

Do you really need the indexes? Maybe you should use for duplicate in duplicatesList[1:]

    if currentMatch[currentMatchPos:] in duplicatesList[i]:
        currentMatch += duplicatesList[i][-1]
        currentMatchPos += 1
    else:
        if SHOW_RESULTS_WHILE_PROCESSING:
            showDuplicate(currentMatch)

        resultList.append(currentMatch) # this match is closed, add it!
        currentMatch = duplicatesList[i]
        currentMatchPos = 1

I dislike the structure of this code. You are manipulating several variables across loop iterations which makes the code hard to follow. But since the algorithm is simply incorrect for what you are doing I can't really tell you how to fix it.

if not SHOW_RESULTS_WHILE_PROCESSING:
    for duplicate in resultList:
        showDuplicate(duplicate)

if not resultList:
    print "Awesome, no duplicates were found!"

Ok, now for the actual algorithm. I think wilberforce has misinterpreted what you want. His algorithm requires the duplication to be aligned, which I don't think you want.

The simple brute force strategy is as follows:

# look at every position where the duplicates could start
for x_idx in range(len(file_content)):
    for y_idx in range(x_idx):
        # count the length of the duplicate
        for length, (x_letter, y_letter) in enumerate(zip(file_content[x_idx:], file_content[y_idx:])):
            if x_letter != y_letter:
                break
        # if its good enough, print it
        if length > DUPLICATE_LENGTH:
            showDuplicate(file_content[x_idx:x_idx + length])

A more efficient and clever algorithm is to use dynamic programming:

# we create 2D list (list of lists) where lengths[x][y] will be length
# of the duplicate which ends on letter x-1 and y-1 in the file content
# so we will calculate the length of duplicate for every combination of two positions
file_size = len(file_content) + 1
lengths = [ [None] * file_size for x in range(file_size) ]

# If we are before the characters, the length of the duplicate string is
# obviously zero
for x in range(file_size):
    lengths[x][0] = 0
    lengths[0][x] = 0

for x in range(1, file_size):
    # we don't check cases where x == y or y > x
    # x == y is trivial and y > x is just
    # the transpose
    for y in range(1, x):
        if file_content[x-1] == file_content[y-1]:
            # if two letters match, the duplicate length
            # is 1 plus whatever we had before
            duplicate_length = lengths[x][y] = lengths[x-1][y-1] + 1
            if duplicate_length > DUPLICATE_LENGTH:
                showDuplicate(file_content[x-duplicate_length:x])
        else:
            # if the files don't match the duplicate ends here
            lengths[x][y] = 0

My two programs produce slightly different results. The first says:

Duplicate found: michael
Duplicate found:michael

The second says:

Duplicate found: michae
Duplicate found: michael

The difference is because the actual match is 7 characters long. As a result, it matches twice. I don't know what results you actually do want, so I haven't looked into it.


A couple of suggestions:

Use requests instead of urllib. This is mostly a matter of preference but I think you'll find it easier to work with.

An example on how this would look is:

import requests

page = requests.get('http://rabota.ua/zapros/python/%D0%BA%D0%B8%D0%B5%D0%B2').content

Fix the bug

In some cases you'll get:

  Traceback (most recent call last):
  http://rabota.ua/company209907/vacancy6312501
      vacancies[x]['link'])) UnicodeEncodeError: 'ascii' codec can't encode characters in position 26-33: ordinal not in range(128)

Which means you're trying to parse characters which cannot be decoded as they are. I'd recommend using the encode function to get rid of it:

for x in vacancies:
    print('{}\n{}\n{}\n'.format(
        vacancies[x]['company'].encode('ascii', 'ignore'),
        vacancies[x]['position'].encode('ascii', 'ignore'),
        vacancies[x]['link'].encode('ascii', 'ignore')))

Instead of using a counter, you could use the builtin that Python already has: enumerate().

This:

inx = 0
for x in a:
    inx += 1
    vacancies[inx].update({'company': x.get_text()})

Will become:

for counter, x in enumerate(a, 1):
    vacancies[counter].update({'company': x.get_text()})

So far, we have this:

from bs4 import BeautifulSoup
import requests

page = requests.get('http://rabota.ua/zapros/python/%D0%BA%D0%B8%D0%B5%D0%B2').content
soup = BeautifulSoup(page, "lxml")

a = soup.find_all("a", class_="t")

vacancies = {}
for counter, x in enumerate(a, 1):
    vacancies[counter] = {
        'position': x.contents[0].strip(),
        'link': 'http://rabota.ua{}'.format(x.get('href'))
    }

a = soup.find_all("a", class_="rua-p-c-default")[2:]

for counter, x in enumerate(a, 1):
    vacancies[counter].update({'company': x.get_text()})

for x in vacancies:
    print('{}\n{}\n{}\n'.format(
        vacancies[x]['company'].encode('ascii', 'ignore'),
        vacancies[x]['position'].encode('ascii', 'ignore'),
        vacancies[x]['link'].encode('ascii', 'ignore')))

Other suggestions:

I'm not a fan of your naming conventions:

a might become href_tag
x might become element

More, I'd split everything into functions as this will make your code readable and easier to maintain:

from bs4 import BeautifulSoup
import requests

URL = 'http://rabota.ua/zapros/python/%D0%BA%D0%B8%D0%B5%D0%B2'

def get_html():
    return BeautifulSoup(requests.get(URL).content, 'lxml')

def parse_html():
    content = get_html()
    href_tag = content.find_all('a', class_='t')

    vacancies = {}
    for counter, element in enumerate(href_tag, 1):
        vacancies[counter] = {
            'position': element.contents[0].strip(),
            'link': 'http://rabota.ua{}'.format(element.get('href'))
        }

    href_tag = content.find_all("a", class_="rua-p-c-default")[2:]

    for counter, element in enumerate(href_tag, 1):
        vacancies[counter].update({'company': element.get_text()})

    for element in vacancies:
        print('{}\n{}\n{}\n'.format(
            vacancies[element]['company'].encode('ascii', 'ignore'),
            vacancies[element]['position'].encode('ascii', 'ignore'),
            vacancies[element]['link'].encode('ascii', 'ignore'))
        )

if __name__ == '__main__':
    parse_html()

Yet another way of splitting the logic of your program:

from bs4 import BeautifulSoup
import requests

URL = 'http://rabota.ua/zapros/python/%D0%BA%D0%B8%D0%B5%D0%B2'

def get_html():
    return BeautifulSoup(requests.get(URL).content, 'lxml')

def get_position_and_link(content):
    href_tag = content.find_all('a', class_='t')

    vacancies = {}
    for counter, element in enumerate(href_tag, 1):
        vacancies[counter] = {
            'position': element.contents[0].strip(),
            'link': 'http://rabota.ua{}'.format(element.get('href'))
        }

    return vacancies

def update_info(content):
    company_href_tag = content.find_all("a", class_="rua-p-c-default")[2:]
    vacancies = get_position_and_link(content)

    for counter, element in enumerate(company_href_tag, 1):
        vacancies[counter].update({'company': element.get_text()})
    return vacancies

def main():
    content = get_html()
    vacancies = update_info(content)

    for element in vacancies:
        print('{}\n{}\n{}\n'.format(
            vacancies[element]['company'].encode('ascii', 'ignore'),
            vacancies[element]['position'].encode('ascii', 'ignore'),
            vacancies[element]['link'].encode('ascii', 'ignore'))
        )

if __name__ == '__main__':
    main()

You can see that I also added if __name__ == '__main__'. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

As @Mathias suggested in comments, instead of using the encode() function, you might as well do:

def main():
    content = get_html()
    vacancies = update_info(content)

    for element in vacancies:
        for info in ('company', 'position', 'link'):
            print(vacancies[element][info])
        print('\n')

The advantage of this method might appear when you have a lot of unrecognised ascii characters which, with the first version, may lead to something like: .,..


If you have a lot of conditions I recommend you to use an HashMap (associative array in php) to store the conditions, like this :

$notificationsItems = [
    "All" => "AllNotification",
    "Accept" => "AcceptTrackRequest",
    "Deny" => "DenyTrackRequest"
];

When you have your pair, you can test all the conditions through a simple foreach:

foreach ($notificationsItems as $postValue => $objectAttr) {
    if ($_POST["item"] == $postValue) {
        $notificatioSetting->{$objectAttr} = $_POST["status"];
        break; //we make an early termination
    }
}

This version mimic exactly the elseifcode. As itzmukeshy7 put in his response, there is a solution with fewer lines of code :

if(in_array($_POST["item"], $notificationsItems)) {
    $notificationSetting->{$notificationsItems[$_POST["item"]]} = $_POST["status"];
}

In this way adding more conditions will be really easy while making the code more extensible and more decoupled. In addition you'll make explicit the association between a post value and the corresponding attribute in the object, which is good for your futur self or colleague(s).


I can't speak for the language you a using specifically, but I have always been lead to believe that declaring variables within if and try statements is bad form. Can't say I've ever seen one in a catch statement, but I believe the same principle might apply.

You seem to be wrapping a lot in that try block. Do you expect that

var mappedToken = tokenTask.Result;

could actually throw an exception? If not, I would personally recommend removing it from that code block.

To be clear, how much code to put in a try block would be a matter of opinion, but are you obeying the single responsibility principle? I would posit that the code would be simplified if the reader knew what is expected to throw an exception at a glance. Your try block is responsible for 6 different tasks by my count. Should the reader assume that all of those tasks are capable of faulting, and that the resulting exception should be the same regardless of which part failed and which part was successful? If UpdateSSOToken were to execute but Task.WhenAll failed are we in the same boat we would be in if UpdateSSOToken had failed? Something to consider.

As for is it a good idea to have the exception at all-

  The method you choose depends on how often you expect the event to
  occur.

To help you determine that you should consider the following about the WhenAll method of Tasks-

  If any of the supplied tasks completes in a faulted state, the
  returned task will also complete in a Faulted state

This answer cites some useful information on exception with tasks, including

  An Async Primer by Bill Wagner

which goes into detail about the await pattern. I would suggest at least reading the primer if none of the other links, I believe it directly addresses your question.


Exit early

Instead of stuffing everything in one return statements, return as early as possible.

if (!projects.Any()) return Enumerable.Empty<string>();

can be the first statement of your method. It saves recreating the hashset objects and it makes the flow of your method with its recursion more clear. I think sacrificing a bit of "conciseness" for readability is worth it.

ToArray

Are unnecessary and cause additional loops over your sets.

Except and HashSet

Enumerable.Except is already implemented using sets. The second argument is added to a set and the first is streamed through it. Creating the HashSet manually is a wasted effort. See the reference source.

So dependents can just be:

var dependents = references.Select(d => d.Dependent);

Contains and HashSet

Contains on the other hand benefits from the HashSet overload, since the Enumerable.Contains implementation just loops over the sequence. So build should be a HashSet to cope with larger inputs. While we're at it, we're using Linq, so ToHashSet().

static IEnumerable<string> Make(
    IEnumerable<string> projects,
    IEnumerable<(string Dependency, string Dependent)> references)
{
    if (!projects.Any())
    {
        return Enumerable.Empty<string>();
    }
    var dependents = references.Select(d => d.Dependent);
    var build = projects.Except(dependents).ToHashSet();
    if (!build.Any())
    {
        throw new Exception("Circled references detected.");
    }
    else
    {
        return build.Concat(Make(
              projects.Except(build),
              references.Where(r => !build.Contains(r.Dependency))));
    }
}


Count the number of ways to make a given sum using one number from each array

function get_sum ($dice, $sum) {
    ...
    echo count($sumcount);
}

Both the stated specification and the function name say that it will return the count, not print it.

Well, the function name get_XXX says it will return something. If you gave me the signature get_sum ($dice, $sum) and asked me to implement the body I would ask what $dice was for, since the signature clearly says that the body will be return $sum;. Surely there's a better name?

    $sumcount = array();
    ...
    echo count($sumcount);

That's a rather memory-inefficient way of counting something. Why not increment an integer counter instead of adding an array to an array?

                                $good_res = array();
                                array_push( $good_res, $die1, $die2, $die3, $die4, $die5);

Why not $good_res = array($die1, $die2, $die3, $die4, $die5)?

            if($num_of_dice == 5){
                foreach($dice[2] as $die3){
                    foreach($dice[3] as $die4){
                        foreach($dice[4] as $die5){
                            if($die1 + $die2 + $die3+ $die4 + $die5 == $sum){
                                $good_res = array();
                                array_push( $good_res, $die1, $die2, $die3, $die4, $die5);
                                array_push($sumcount, $good_res);
                            }
                        }
                    }
                }
            }

Again, the aim is to count. If $die1 + $die2 + $die3 + $die4 + $die5 == $sum, why does the loop over $die5 care what $die3 is? You could as well say

foreach ($dice[0] as $die1) {
    $counter += get_sum(array_slice($dice, 1), $sum - $die1);
}

You need to handle a couple of base cases, but that gives you code which should have fairly similar performance to the current code but is much much simpler. Then ask yourself how to memoise. Then ask yourself how to replace the recursion with iteration. The final result will be an iterative method which is about 10 lines long, handles any number of dice, and runs much faster than your current code.


A few comments:

It is cleaner to define the position parameter as unsigned or
size_t as it cannot be negative. Same applies to the for loop counter.
There is a memory leak, as you don't do delete on the removed
node.
Names like temp and temp2 are not reader-friendly. How about
current_node? Speaking of which, the assignment to temp2 is redundant.
The code should validate that we don't go beyond the end of the list. We can of course assume that invalid index cannot be passed to the function, but it's a dangerous assumption that does not lead to defensive code.
While we're on the parameter validation topic; if we get passed an empty list (i.e. head == NULL), there will again be undefined behaviour irrespective of the value of position.
If we delete the last node, the code will behave in an undefined manner (most likely crash). Consider that temp2->next will be NULL in that case, which means that temp2->next->next won't be a happy statement.
Speaking of last comment, do you have unit tests in place? If so, it'd be good to have edge cases covered (delete first node, delete last node, empty list etc.)

Hope this helps.


Singly Linked list implementation in C++

I see a number of things that may help you improve your code.

Prefer references to raw pointers

In modern C++, we tend not to use raw pointers very often.  In this case, It would probably be better to have two different classes, one would be a LinkedList class and the other would be a Node class.  That way, instead of starting with a pointer, you can start with an object.

Use objects

You have a Node structure and then separate functions that operate on Node data. With only a slight syntax change, you would have a real object instead of C-style code written in C++.

Use whitespace to improve readability

Lines like this:

head=push_front(-21,head);

become much easier to read with a little bit of whitespace:

head = push_front(-21, head);

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.

Use consistent naming

The code includes print() (lowercase) and Search() (uppercase).  It would be better for both functions to have similar case.  I tend to use capital letters to name clases or structs such a Node and then lowercase letters for functions such as print or search.

Match new with delete

If you allocate memory using new, you must also free it using delete or your program will leak memory.  This program leaks memory.

Use more descriptive names

The code's DetectCircle function seems to return true if the list is circular.  Generally, it's good to name boolean functions so that their sense is unambiguous.  For example, I'd probably call it isCircular.

Omit return 0

If your program completes successfully, the return 0 at the end of main() will be generated automatically, so it's not needed in C++ programs.


Definitions

//FUNCTION PROTOTYPES:

Given that you have everything in one file, you could simply change the declaration order and get rid of these.  Function prototypes are necessary only when you are linking multiple files together (or in the odd case of two or more functions that call each other circularly).  They are overkill here.

int Ascending   (long long x,long long y);
int Descending  (long long x,long long y);

While the compiler won't care, adding spaces between the function name and the parameters list makes this look like something other than a function to me.  I.e. I find this notation confusing.

main

long long arraysize = sizeof(array)/sizeof(*array);

There is a type explicitly for handling size data.  You may think that you are being more inclusive by using long long, but you are actually moving errors from where the problem occurs to where clipping occurs.  In programming, it is generally better to be consistent than right.  Because even if you are more right, you will be wrong in your interactions.

size_t array_count = sizeof(array) / sizeof(*array);

The size_t type is what is used in library functions dealing with sizes.  Using it here means that if you add an additional sort that does a malloc, that you will be using the right type.

I also changed the name of the variable.  One, because I prefer the name count for something that represents the number of elements in a collection.  Two, because words should be separated by something.  In C, the standard is to use underscores.  In other languages, they often use casing to indicate where new words begin (I disagree with that actually, but at least it is common).  It's much easier to read if you use something to say where new words begin.  Otherwise, the reader has to think about it when we want the reader's attention on what the code is doing.

Similarly, I added spaces around the /.  This makes it easier to see where one token ends and another begins.

I didn't change it here, but I would prefer a name like data or sample_data instead of array.  I can easily see the type of the variable.  What I want to know is what it represents.  Thus, sample_data or test_data would best tell me what I wouldn't otherwise know from the declaration.

quicksort(array,0,arraysize-1,Ascending);

Again, I'd find this easier to read with more spacing.

quicksort(array, 0, array_count-1, Ascending);

You could also add spaces in array_count - 1, but it's not strictly necessary.

my_random

    result = (long long) result;

This does a double cast.  Since result is a long double, this casts to long long and then back to long double.  Presumably that's not what you wanted.  Instead, use a different variable on the left hand side.  Note that you should probably add min after the cast rather than before.

Your max value is inclusive, meaning that it's a valid result from this function.  However, you add 1.0 to MAX_RAND which makes it exclusive of the upper bound.  I.e. result will never be 1.0.  This seems incorrect.

You also just cast from floating point to integer, which drops the fractional part.  This will tend to bias the result down.

size_t my_random(size_t min, size_t max) {
    long double intermediate;
    size_t result;

    intermediate = (double)rand() / (double)RAND_MAX;
    intermediate *= max - min;

    result = (size_t) (intermediate + .5);
    result += min;

    return result;
}

Now it's clear where we are doing casts.  We have a declarations section, a floating point section, an integer section, and a return section.  We do only one implicit cast (to max - min which is cast to long double by the multiplication).  All other operations are done with variables that are already of the same type.

I still have one problem with this.  It's quite possible for max - min to be larger than RAND_MAX.  If that happens, there are some potential pivots that we'll never pick.

Also, this function is not robust if max < min.  In that case, the results could be weird.

quicksort

    quicksort(array, begin  , q, cmp);
    quicksort(array, (q + 1),  end   , cmp);

If you are going to do this, please keep the commas with the token before them:

    quicksort(array, begin,   q,   comparison_function);
    quicksort(array, (q + 1), end, comparison_function);

Also note that the spacing between end and cmp was simply wrong.

I also renamed cmp to comparison_function here.  Given how little it's used, it seemed better to favor readability over convenience here.  This is what Larry Wall calls true laziness -- commenting your code so that it's easier to read later.  In application, you will spend more time reading code than writing it.  It's only in the somewhat artificial environment of learning that you can spend more time writing code than reading it.  So it's better to get in the habit of writing readable code than terse code.

Comparing

return ( !(Ascending(x,y)) );

You define Descending as not Ascending, however this gives the two of them different meaning.  Something is Ascending if x < y but is Descending if x >= y.  Better might be

// Descending is the reverse of Ascending
return Ascending(y, x);

This is a little harder to follow but it now makes it Descending if y < x.  Another way to put this is that it is now Ascending in the opposite direction.

    }while ((cmp(array[i],pivot)) && array[i] != pivot);

This logic can also be simplified then.  Because all our comparison functions only return TRUE for a strict inequality, we don't need an extra inequality check on this one (the other is still needed).

    } while ( cmp(array[i], pivot) );

Note that qsort gets around this by demanding that the comparison functions return zero for equality and positive or negative values for inequalities.


First project in Javascript: NearestNeighbor Calculator

Are you hoping for the arc length around a sphere or the Earth? What about going through the earth in a straight line? Currently your math solves the sphere but not Earth.
The earth has 2 radi that are used to solve the arc length.
R = √ [ (r1² * cos(B))² + (r2² * sin(B))² ] / [ (r1 * cos(B))² + (r2 * sin(B))² ]
B = Latitude
R = Radius
r1 = radius at equator
r2 = radius at the poles

But your Haversine method is otherwise correct =D


Parsing a text file of nested structures using a state machine

The obvious answer is to make currentstate an explicit return value from your functions, for example:

def do_out():
    print "doing OUT - transitioning to DNARRAY"
    return state.DNARRAY

Then handle it appropriately in the final loop:

def decisions():
    currentstate = state.OUT
    while(currentstate != state.END_OF_FILE):
        currentstate = statemap[currentstate]()
    print "done!"


Efficient text to binary conversion in Java

Sure, you may speed up your code execution. But the core problem remains: Inresponsive UI executing a long running task.

If you expect the user wait for completion a long running task you should consider UI supported synchronized mechanisms to adress it.

Asynchronous execution is mentioned here:

http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

The idea is: Execute your code in a separate thread and synchronize results by publishing them through the Java FX thread.


Function to get the most frequently appearing pixel

There are numerous problems with the code. First of all, fread never returns EOF (which is -1). The loop should end when it reads less than 3 bytes.

Second, max_count is index, not a color value. I presume you meant rgb[max_count].

Test a file pointer returned by fopen for not being NULL.

Test a return value of fseek.

Avoid magic numbers. I suppose 54 is a size of certain header. Create a constant with a meaningful name. Better yet, define a header structure and take its sizeof.


Your code's quite good. I'd however change it in the following ways:

Move the creation of the lits out of the buble_sort.
Remove the prints from buble_sort.
Follow PEP8.
Change for i in range(...) to while True:.
Use better variables. num_list to array could do.
Use str.format, rather than string addition.
Change the creation of num_list to use a list comprehension.

def bubble_sort(array):
    while True:
        swapped = False
        for j in range(len(array)-1):
            if array[j] > array[j+1]:
                array[j], array[j+1] = array[j+1], array[j]
                swapped = True
        if not swapped:
            break

if __name__ == '__main__':
    amount = input("How many numbers you would like to sort:")
    array = [
        int(input("Enter {} number:".format(i)))
        for i in range(int(amount))
    ]

    print("The values input are as follows: {}".format(array))
    bubble_sort(array)
    print("The sorted list is: {}".format(array))


Actionscript web service and web method call classes

I don't see why would you put every method of the service in a separate class. A "method" is a function of the class. I imagine you wanted to decouple your code, but doing it this way you will force a lot of overhead:

the service is instantiated for every 'method' called, and then, hopefully, garbage collected (as you remove event listeners and there's no more references to the service left)
because of above, the service is stateless; with time you may want to add some functionality like caching, but you'd need to change whole code structure for that
CfdWS - not descriptive name; your way of decoupling code will force you to make three or even five times more classes then you normally would, so I would expect a hell on the file-naming level
really, dividing to so many classes is not a good idea - you don't want to switch between files all the time; try to put related code in one Class, and if it grows big, create some helper classes

I think you already understand the benefit of a good MVC implementation, try Robotlegs, it really makes a life easier:
http://www.robotlegs.org/


var myLatlng = new google.maps.LatLng(<?php echo get_post_meta($post->ID,'school_latitude',true); ?>, <?php echo get_post_meta($post->ID,'school_longitude',true); ?>);

Instead of echoing directly onto the script, consider putting the values in an array, convert it to JSON using json_encode, and echo the JSON to a variable outside your script. Then use that variable like any other JS variable. This is possible because JSON is (most of the time) valid JS object syntax. Afaik, this is how Drupal passes down configs from server to the client.

<?php
  $configs = [
    'lat' => get_post_meta($post->ID,'school_latitude',true),
    'lng' => get_post_meta($post->ID,'school_longitude',true)
  ];
?>

var configs = <?php echo json_encode($configs); ?>; // var configs = { "lat": "VALUE", "lng": "VALUE" };

initialize(configs.lat, configs.lng);

The advantage of this approach is that you lessen the area where PHP is in touch with JS, reducing any breakage caused by some mishap in printing values.

function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}

window.onload = loadScript;

I'm pretty sure you did it this way because you wanted it to load async. First off, onload fires after the entire page, images and all are loaded and is probably the very last event that fires in a page load cycle. If you have a page that's heavy with images, onload will take forever to fire. Consider listening to DOMContentLoaded instead.

Next is the entire procedure itself. If you take a look at the Google script, there are hints that it's already doing the same thing. So I believe this procedure isn't necessary. Using a script tag should suffice.

In the end, only the following should be necessary. Order of the two shouldn't matter since the maps script will probably call callback asynchronously. initialize would have been defined by then.

<script src="http://maps.google.com/maps/api/js?sensor=false&callback=initialize"></script>
<script>
  function initialize() {
    ...
  }
</script>


Reading from a .txt file to a pandas dataframe

When opening very large files, first concern would be memory availability on your system to avoid swap on slower devices (i.e. disk).

Pandas is shipped with built-in reader methods. For example the pandas.read_table method seems to be a good way to read (also in chunks) a tabular data file.

In the specific case:

import pandas

df = pandas.read_table('./input/dists.txt', delim_whitespace=True, names=('A', 'B', 'C'))

will create a DataFrame objects with column named A made of data of type int64, B of int64 and C of float64.

You can by the way force the dtype giving the related dtype argument to read_table. For example forcing the second column to be float64.

import numpy as np
import pandas

df = pandas.read_table('./input/dists.txt', delim_whitespace=True, names=('A', 'B', 'C'),
                   dtype={'A': np.int64, 'B': np.float64, 'C': np.float64})


Calculate the Hamming difference between two DNA strands

Your code is really all that there is to it. It is clear and concise: one method to validate the input (validateInputs) and the rest of the method to calculate the Hamming distance with a simple loop.

A couple of comments:

In case of inputs of different length, you are (rightfully) throwing a IllegalArgumentException like this:

if (s1.length() != s2.length()) {
  throw new IllegalArgumentException();
}

This is a generic IllegalArgumentException with no message. You might want to add a message so that it is clearer to the caller what went wrong; it would also help the debugging (imagine a bigger application).
To resemble what is done by the existing Objects class, you could rename your validating method to requireSameLength and make it return the length:

private static int requireSameLength(String s1, String s2) {
    if (s1.length() != s2.length()) {
        throw new IllegalArgumentException();
    }
    return s1.length();
}

This has the advantage that the method name is now self-documenting and it is returning the correct value, which means we can chain the result (just like requireNonNull which returns the non-null value or throws an exception).
import java.util.Optional; is not needed, you aren't using it.
Consider making the class final since it looks like a utility class (only public static methods).

If you're using Java 8, you could write this a bit shorter using the Stream API:

public static int compute(String s1, String s2) {
    int length = requireSameLength(s1, s2);
    return IntStream.range(0, length).map(i -> s1.charAt(i) == s2.charAt(i) ? 0 : 1).sum();
}

private static int requireSameLength(String s1, String s2) {
    if (s1.length() != s2.length()) {
        throw new IllegalArgumentException();
    }
    return s1.length();
}

It maps each index to 0 or 1 based on whether the two input Strings have equal characters at that index, and sums the result.


I see one major issue:

static std::vector<std::function<void(GLFWwindow*, int, int)>> resizeEventCallbacks;

You should never put a static variable declaration like that in a header. That will cause every file that includes the header to have a local copy of that variable. What you probably want is to put that declaration in the .cpp file so that it is local to that file only. The resizeEventCallbacks is an implementation detail that should be known only to eventmanager.cpp functions.


Add events dispatching for ActionScript framework Robotlegs

FileStream class has its own events which are dispatched when the file operation is successful or not.

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/filesystem/FileStream.html#eventSummary

A possible refactor of the code is

protected function writeToFile():void{
    _destinationFile = File.applicationStorageDirectory.resolvePath(_newPath);

    var fs:FileStream = new FileStream();

    fs.open(_destinationFile, FileMode.WRITE);
    fs.writeBytes(_buffer, 0, _buffer.length);

    fs.addEventListener(Event.CLOSE, dispatchFileCreatedEvent);

    fs.close();

}

Thanks to krasimir of knowledge Robotlegs Community for his help in arriving at this answer.


You can use a more efficient algorithm. It's clear that the unique value is equal to the xor of all numbers in the vector. One can write a nice one-liner to compute it:

std::accumulate(v.begin(), v.end(), (uint32_t)0, [](uint32_t a, uint32_t b) { return a ^ b; })

The time complexity is the same (as a hash table works in O(1) on average), but this code is likely to work faster in practice. It also requires O(1) extra memory, while your solution needs O(n), so it's more space efficient.

I'd also say that your code is little bit confusing (it inserts keys implicitly via [] operator but erases them explicitly). It took me a while to figure out what's going on. I think that the solution with a set is a little bit more clear as it makes all insertions and deletions explicitly:

unordered_set<uint32_t> seen;
for (const auto& elem : v) {
     if (seen.count(elem))
         seen.erase(elem);
     else
         seen.insert(elem);
}
return *seen->begin();

You can also omit return 0 in the main function (it returns 0 by default, anyway).


Check if a string is a permutation of a palindrome

Documentation

You should definitely add a docstring. It took me a few seconds to figure out was was going. Make sure to add some examples in the docstring as well.

Naming

The name cache may not be the best name. Why? Let's look at the definition of cache:

  is a hardware or software component that stores data so future requests for that data can be served faster

I don't really believe you use cache to serve stuff faster. I believe odd_occuring_letters is a better idea. (I don't like long names, maybe challenge yourself to a shorter name? Maybe odd_letters? Think about it.)

(More) Comments

Even then, odd_occuring_letters isn't the most descriptive name, so you should include some comments as to what your code does. Don't over do it though.

Remember saying something like:

# Check the length of odd_occuring_letters is less than or equal to one.
return len(odd_occuring_letters) <= 1

Is not good. But saying:

# A word can have at most 1 odd character and still be palindrome.
return len(odd_occuring_letters) <= 1

explains to me why you return the length compared to one.


Rendering elements (which can change numbers) using jQuery

First off: It's invalid HTML to have a div directly inside an ul element. Any special reason you need the

? Modern CSS techniques usually don't need additional elements like that.

You shouldn't repeatedly call the getter methods in a loop like that. If they do more work than just returning an array, then it's wasted performance.

let notFoundNodes = graphFactory.getNotFoundNodes();
for (let x = 0; x < notFoundNodes.length; x++) {
  htmlNodes = htmlNodes + '
' + notFoundNodes[x] + '
';
}

Or, considering you are using let which is part of ECMAScript 2015, you could alternatively use a for ... of loop:

for (let notFoundNode of graphFactory.getNotFoundNodes()) {
  htmlNodes = htmlNodes + '
' + notFoundNode + '
';
}

Concatenating strings in loops are also quite a wasteful operation, because they cannot be optimized by the runtime environment. A better way is to collect the strings in an array, and then joining them together at the end:

var htmlNodes = ['
'];

// ...

for (let notFoundNode of graphFactory.getNotFoundNodes()) {
  htmlNodes.push('
' + notFoundNode + '
');
}

// ...

htmlNodes.push('
');
$('#pinnednodeslist').html(htmlNode.join(''));

In order to avoid mixing the HTML you could use a template engine. There are literally dozens out there, with many pros and cons, which can make the choice a bit overwhelming. For an example I'll use Handlebars.js:

The template is placed inside a script element somewhere in your HTML:

Once during page initialization you compile the template:

var source = document.getElementById("tags-template").innerHTML;
var tagsTemplate = Handlebars.compile(source);

And then later you can repeatedly use the compiled template to render the data:

var context = {
   notFoundNodes: graphFactory.getNotFoundNodes(),
   pinnedNodes: graphFactory.getPinnedNodes()
};
var html = tagsTemplate(context);
$('#pinnednodeslist').html(html);

EDIT: BTW, nothing in this (or your original code) really requires jQuery. The last line could simply replaced with:

document.getElementById('pinnednodeslist').innerHtml = html;

The next step could be to use more advanced library such as React, Vue.js or Angular. These are frameworks that not only render the data with a template engine, but also can (among other things) react to changes in the data and re-render automatically when even needed. This however requires learning a bit of a different way of programming.

Finally, if the data displayed is coming from the server (via AJAX for example), then you could consider having the server render the HTML instead of sending the raw data.


Not a lot to review,

obviously the most repeated part of your code is appointment_reminder_responses, if you create a variable called root and then built your routes with concatenations like
root + "/confirmation_thanks" then that would be a good start.

Furthermore you create a function that takes a string and modifies so that
"xxx/zzzz/yyyy" becomes "xxx/zzz#yyyy" and use that function for the first 2 routes.


One thing which I noticed is this little spelling error in the code

static IExeptionHandlerProvider _exeptionHandlerProvider = null;

Both the name of the interface and the name of the field should be fixed by adding a c -> IExceptionHandlerProvider _exceptionHandlerProvider = null;

public static void HandleException(FaultException<DefaultFaultContract> fault)

You should initialze the StringBuilder's with a starting capacity, because the default capacity of a StringBuilder is 16 characters, and if it is reached the capacity will be doubled which involves copying the current buffer to the newly created buffer.

By choosing the initial capacity to be e.g 256 you will maybe waste some memory but you avoid the internal increasing of the buffer.


Script to load controllers dynamically for AngularJS

Feedback

This is an interesting way of loading controllers. I like the application of the promises. It does feel a little weird not to have an ng-app directive but it makes sense given the nature of your code.

Suggestions

The suggestions below can simplify the code, but may not necessarily be optimal or have desired browser support.

Iterating functionally

One could utilize a functional approach instead of the declarative for loop:

for(var i = 0;i < ngControllers.length;i++)

Because each iteration pushes a promise into the array promises, that loop can be replaced by a call to Array.map():

var promises = Array.prototype.map.call(ngControllers, function(ngController)

Or .map could be called on an array after converting the nodeList to an array via Array.from() (but beware of Browser compatibilty on that)

var promises = Array.from(ngControllers).map(function(ngController)

Or for a completely es-6 approach, use the spread operator:

var promises = [...ngControllers].map(function(ngController)

At the end of each iteration, simply return the promise instead of pushing it into the array.

    // Push promises to array to resolve them all together later on
    return promise;//promises.push(promise);
}); //end the call to .map()

Bear in mind that the functional approach would likely be somewhat slower because a function call is added for each iteration, but for a small number of controllers this should be a negligible difference. If you would like to become more familiar with functional JavaScript, I recommend these exercises.

Use partial(-ly applied) functions for callbacks

Instead of making a closure just to call resolve():

script.addEventListener('load', function() {
    resolve(script);
});

Use Function.bind() (different than (angular.bind()) to create a partially applied function for each time resolve() is called.

script.addEventListener('load', resolve.bind(null, script));

Bear in mind that the event listener would pass an event argument to the callback, but that should be the second argument when script is bound as the first argument.

The same is true for calling the bootstrap function after all promises have been resolved:

Promise.all(promises).then(function() {
    angular.bootstrap(document, ['app']);
});

Can be simplified like below:

Promise.all(promises).then(angular.bootstrap.bind(null, document, ['app']));

Use addEventListener instead of onload

This likely wouldn't be an issue in a small application but in case there was other code (potentially multiple functions) that needed to be executed when the page is loaded, it might be simpler just to use window.addEventListener('DOMContentLoaded', function() {...}) instead of window.onload = function() {...};


void hash(std::string const& password, std::string const& salt, long iter, DigestStore& digest)
...
for (int loop = 1; loop < iter; ++loop)
        ...
        for (std::size_t loop = 0; loop < digestSize; ++loop)

"A long an int and a std::size_t all walked into a bar..." couldn't they all be std::size_t?
Also, overriding the loop variable is unnecessarily confusing.

    std::copy(std::begin(tmp), std::end(tmp), std::begin(digest));

I feel like this could just be digest = tmp; with an appropriate assignment operator.

salt + "\x00\x00\x00\x01"s

Could this be a named constant (or even a named function)? Or maybe add a comment to explain why this is here.

            digest[loop] = digest[loop] ^ tmp[loop];

Nitpick: could use ^=

Perhaps the output should be a return value, not written to a reference?

I don't know enough about cryptography / security to assess the algorithm / safety aspects of this.


Method for sorting numbers from user input

Interesting question,

I cant understand why you would need this functionality. It does not seem to sort at all, but in same cases it will remove dupes.

This code is so bad, you should first use the built in tools in JsFiddle and then come back.

Click TidyUp first, your JavaScript indenting is all over the place.
Then click JsHint, every red dot on the left hand side indicates 1 problem, there are many lines with multiple problems, so you will have to do this exercise multiple times.


Iterating thousands of times over large collections: advices

If you are particularly interested in doing substring look-ups, you could look into the Trie data structure.  You will be stuck writing your own, however, as there is no implementation I know of in the BCL.

Alternatively, if you just want to put something together quick, you could just use a normal, single-level-deep dictionary keyed by file name.  If you build your dictionary for existing MP3s first using an actual System.Collections.Hashtable or (preferably) System.Collections.Generic.Dictionary<TKey,TValue>, the key lookups will be constant-time.

The only loops you will need are the initial loop to build the correct file path dictionary, then the loops over .m3u files with sub-loops over their referenced files.  Retrieving the correct mp3 reference for each file in a m3u is just value = dictionary [key] or dictionary.TryGetValue (key, out value).  The lookups themselves are not loops - rather, they generate hash codes for the keys which ultimately translate to array indexes in the underlying data structure.


function urandom_rand($min = 0, $max = 0x7FFFFFFF)
{
    $min = (int)$min;
    $max = (int)$max;
    if ($max <= $min)
        trigger_error('Minimum value must be greater than maximum value.');
    if ($min < 0 || $max > 0x7FFFFFFF)
        trigger_error('Values must be between 0 and 2147483647.');

    $M = bcadd(0x7FFFFFFF,1); // (up bound of iv)+1
    $N = bcadd($max-$min, 1); // how many different values this function can return
    $h = bcmod($M, $N); // the last h integers from unpack are "invalids"

    do
    {
        $bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
        $r = unpack("N", $bytes)[1] & 0x7FFFFFFF;
    } while ($r > ($M-$h));
    return (bcmod($r, $N) + $min);
}

Valid values for $bytes are

0x00000000...0xffffffff

After the unpack(), every value from $bytes is matching exactly one value of:

-0x80000000..0x00000000..0x7ffffffff

So, perfect-equiprobability. After bitwise &, every value from unpack() matches exactly two values of:

0x00000000..0x7ffffffff

Now, we cut that interval into S sub-intervals of [KN..(K+1)N[ (S>=1 because $max<=0x7fffffff) plus one remaining interval I. Then, we map each [KN..(K+1)N[ to [0..N-1].

So far, each value from [0..N-1] has exactly S ways to be picked.

Now, let's deal with the remaining interval I (might be an empty interval). If $r is in that interval, then we cannot do anything with it: we cannot easily match elements from I with elements from [0..N-1] because their size mismatch (I has less elements). We could group elements from [0..N-1] and then match these elements with I but that's far too complex for the earn.

So, if $r is in that remaining I, easy way is just to pick another $r.

Since I has h = (0x7fffffff+1)%N elements, that's why we keep picking random values as long as $r > (0x7fffffff+1)-h.

Only problem you can have is that the function urandom_rand() may take anytime to execute, since it loops until it luckily gets a $r outside I.

Here is one scenario of exploiting the inequiprobability problem:

Let's say you pick a random number out of {0,1,...14}, expecting a probability of p(0)=P(1)=...=p(14)=1/15=6.67%. People can bet on a number, and they will get 14.5x their bet if they win (the 0.5x remaining is your commission).

If you actually have p(0)=7.03% and p(1)=..=p(14)=6.64% then one can bet on 0 and expect 7.03% chances to win 14.5x their bet. So they averagely win 7.03%*14.5=1.01935. Since it's greater than 1, you can keep betting forever and be a winner, despite the casino's commission.

There are probably similar betting game applied to cryptography.

Last correction to my comment about ceil(log(N,k)) (I was tired yesterday night): correct formula is

floor(log(N,k)+1)

gives the number of digits of N in base k for N integer and N>=1

Without using bc function:

function urandom_rand($min = 0, $max = 0x7FFFFFFF)
{
    $min = (int)$min;
    $max = (int)$max;
    if ($max <= $min)
        trigger_error('Minimum value must be greater than maximum value.');
    if ($min < 0 || $max > 0x7FFFFFFF)
        trigger_error('Values must be between 0 and 2147483647.');

    // Decrease everything from 1st version by $N to avoid INT overflow
    // if min == 0 and max == 0x7fffffff then these M,N,h will overflow
    // BUT in such case, MNh won't be used (see loop below)
    // 1 <= $max - $min <= 0x7FFFFFFE
    $N = ($max - $min) + 1; // 2 <= $N <= 0x7FFFFFFF
    $M = (0x7FFFFFFF - $N) + 1; // 1 <= $M <= 0x7FFFFFFE
    $h = $M % $N; // 0 <= $h <= $N-1 <= 0x7FFFFFFE

    do
    {
        $bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
        $r = unpack("N", $bytes)[1] & 0x7FFFFFFF;
        if ($min == 0 && $max == 0x7FFFFFFF)
            return $r; // direct corresponding
    } while (($r - $N) > ($M - $h));
    return (($r%$N)+$min);
}


Async/await and Task vs Task.Factory.StartNew and Result

I'd prefer the first method because it's making more efficient use of resources (provided the async methods you call are really async and not just wrappers around synchronous methods) and it also looks cleaner.

To quote from this MSDN blog:

  ... the only asynchronous methods that should be exposed are those that have scalability benefits over their synchronous counterparts ...

What you are doing in your second method is basically calling the async methods in a synchronous way just to then in turn wrap it into a task. This will have scalability issues because it's using up a dedicated thread (at least in the current implementation of the task library) while the async methods you call might have more efficient means of achieving their asynchronicity (like IO completion ports or timer callbacks)


I am not a Javascript programmer, so I will try my best how to explain to use a dictionary. A dictionary means you can add a value to a key

Example from dotnet perls

# Creations of a dictionary
var dictionary = {"Corporation":534,"LLC":535,"LLP":536,"Partnership":537,"Sole Proprietorship":538,"Limited Partnership":539};

# Getting values of dictionary
new_inputFive = dictionary[inputfive]

# For instance when inputfive="LLC" new_inputFive = 535


Validator for mathematical expressions in infix notation

You can already reuse operators in each methods by making it a constant. You can create a Set and use the containsmethod instead of this.isIn.

You can simplify validateEndCharacters, if ( condition ) { return true } else { return false } can always be simplified by return condition.

The two else if looks like the second block will never be executed :

...
} else if (this.isIn(c, operators) && prevOperator == '\0') {
    prevOperator = c;
} else if (this.isIn(c, operators) && prevOperator == '\0') {
    isValid &= false;
    break;
}


Assuming ES6 is available (you tagged ES6, you have let and const, etc.), this can be simplified.

First, you can compute ahead the number of pages you want to include. You don't need to loop through to check. In this case, your loop depends on who is lesser between MAX_PAGES_IN_PAGER and totPages. You can use Math.min.

const limit = Math.min(totPages, MAX_PAGES_IN_PAGER);

Next, instead of loops and push, you can use array methods. Let's start off by taking out the loop. To loop n times with arrays, you can create a filled array with n dummy items. This is possible with Array(n).fill(0). Then, instead of push, we use map. We turn the n dummy values into values we need.

return Array(limit).fill(0).map(_ => ({
  page: ...,
  href: ...,
  type: ...
}));

In other news, use template strings to construct strings instead of concatenating. Note that template strings use backticks instead of quotes.

pageUri.replace(`list-${page}`, `list-${pageNumber}`)

Ternaries are hard to read. However, there's a way to keep them readable. What you are doing is right, putting further conditions at the false end of the ternary. They can be written in a cascading manner for readability.

"type": pageNumber == page ? "current"
       : pageNumber > page ? "next"
                           : "prev"

Lastly, name your variables properly. totPages is confusing because "tot" doesn't tell me what it is. pager is confusing because it sounds like an object with methods, when it's just an array of objects representing pages.

Also, quotes on object keys are optional unless you are using key names with invalid characters.

In the end:

function createPageList(pageUri, page, totalPages) {

  const limit = Math.min(totalPages, 6);

  return Array(limit).fill(0).map((fill, index) => {

    const pageNumber = (page < 3 ? 1 : page - 3) + index ;

    return {
      page: pageNumber,
      href: pageUri.replace(`list-${page}`, `list-${pageNumber}`)
      type: pageNumber == page ? "current"
           : pageNumber > page ? "next"
                               : "prev"
    };
  });
}


Validate fields in Python dictionary using dictionary of lambdas

lambda is redundant here as you can use _id directly as well:

    map_keys = dict(
        _id=_id
    )

Other than that, your approach seems ok. You are reinventing the wheel though and it might be a good idea to research existing libraries.


This question might be a better fit for another board, since you're asking for different algorithms. CodeReview is more for reviewing your current implementation. As 200_success mentioned, Quantitative Finance can perhaps give you some ideas for what to model, Game Development might have some ideas for "steering" randomness, and of course StackOverflow, if you're unsure of how to implement a different algorithm.

Just know that since it's hideously complicated to make a stock market game that doesn't feel like a total dice roll (and practically impossible to make a truly accurate simulation), most games just use the real stock market but fake money. That way, players have all the right sources of information to help decide their trades, which is the really hard thing to simulate. Will you simulate press releases? Earnings calls? Analyst/stock pundit predictions? The local and global economy? Fraud? Savage rabbits attacking Foxconn's factory and disrupting production for practically every electronics manufacturer in the world? Yeah... it's tough.

And of course, there's the thing that a stock price actually reflects: Trading activity. All the news in the world won't move a stock's price if no one is buying or selling. But it also means that the market is a feedback system, so your players' trades may impact prices (if the trades are large enough). So again: It's hideously complicated.

The best I can offer here is a review of your current code.

Your original question's code was very, very dense. You've since added some comments and whitespace, which was otherwise the first thing I'd suggest.
Your use of randomness introduces a potential problem: The stock rising or falling forever. Improbable, yes, but possible. You guard against the stock going negative, but still. Your guard mechanism is also a bit blunt. Theoretically a stock could trade below $1 for a while, and then suddenly - because it was about to go negative - it's at $10 regardless of its volatility or range. I'd probably invest in some of those penny stocks, on the off-chance that that happens. You should probably have a mechanism for delisting a stock instead, if it falls too low.
With your current solution, there's always at least a 20% chance that the market goes your way. Having 1-in-5 odds isn't great, but in real life there are much worse odds to be had (like betting on a company that's suddenly gone into bankruptcy after an accounting scandal and its CEO being eaten by wombats or something). It just feels like the 20/50/80 odds are a bit too coarse.
Having both a min/max price and a "volatility factor" might be redundant. Setting the min/max close to the current price should reduce volatility, and setting them further away should increase volatility. Or you might only use volatility, and let the stock do what it wants with no special min/max.

In terms of code, things look ok, except that this line

this.pastValues[this.pastValues.length] = this.value;

could just be

this.pastValues.push(this.value);

I'd also consider extracting the round-to-two-decimals code, since I'm sure you'll find it useful elsewhere.

As for changes, I'd probably change the price by a percentage instead. That way, it can't fall below zero:

Stock.prototype.generateValue = function () {
  var minPercentage = this.min / this.value,
      maxPercentage = this.max / this.value,
      range = maxPercentage - minPercentage,
      change = Math.random() * range + minPercentage;

  this.value = Math.round(this.value * change * 100) / 100;

  this.pastValues.push(this.value);

  return this.value;
};

Of course, you'll want to continually update the min/max range to "steer" the price one way or the other (just make sure that max >= min >= 0).

Regardless, how you want to do all this really depends on how the game part plays.


Is this a good way to implement let-with?

JavaScript's with statement allows one to modify object members.  This may not be possible for certain types of values (such as strings) using the let-with macro as defined above.

One could generalize let-with to bind values from several association lists.  It could have the form:

(let-with
    ((alist0 (key00 key01 key02...))
     (alist1 (key10 key11 key12...)))
  expr0
  expr1
  ...)

Aside from being more general, the above form closely resembles the let form.  I prefer this over the simpler form, though I would understand if your taste and needs differ.

Here's my implementation of the general form--it uses two auxiliary macros, one to generate two lists (alists and their corresponding keys) and the other to emit the actual code (which looks almost exactly like your definition above):

(define-syntax let-with
  (syntax-rules ()
    ((let-with bindings . body)
     (gen-let-with bindings () () body))))

(define-syntax gen-let-with
  (syntax-rules ()
    ((gen-let-with () alists keys body)
     (emit-let-with-code alists keys body))
    ((gen-let-with ((alist (key)) . rest-bindings) alists keys body)
     (gen-let-with
      rest-bindings
      (alist . alists)
      (key . keys)
      body))
    ((gen-let-with ((alist (key . rest-keys)) . rest-bindings) alists keys body)
     (gen-let-with
      ((alist rest-keys) . rest-bindings)
      (alist . alists)
      (key . keys)
      body))))

(define-syntax emit-let-with-code
  (syntax-rules ()
    ((emit-let-with-code (alist ...) (key ...) (expr ...))
     (let ((key (cond ((assq 'key alist) => cdr))) ...) expr ...))))

Perhaps there is a simpler definition.  I haven't played with macros in a while. =)

Here are some examples:

(define alist '((first . "Jane") (middle . "Q") (last . "Doe")))
(define blist '((first . "John") (middle . "R") (last . "Lee")))
(define clist '((first . "Jose") (middle . "S") (last . "Paz")))
(define first '((title . "Ms") (suffix . "Esq")))

(let-with
    ()
  "Hello, world!")    ;    => "Hello, world!"

(let-with
    ((alist (first middle last)))
  (string-append first " " middle ". " last))    ;    => "Jane Q. Doe"

(let-with
    ((alist (first))
     (blist (middle last)))
  (string-append first " " middle ". " last))    ;    => "Jane R. Lee"

(let-with
    ((alist (first))
     (blist (middle))
     (clist (last)))
  (string-append first " " middle ". " last))    ;    => "Jane R. Paz"

(let-with
    ((first (title))
     (alist (first))
     (blist (middle))
     (clist (last))
     (first (suffix)))
  (string-append first " " middle ". " last))    ;    => "Jane R. Paz"

(let-with
    ((alist (first middle last)))
  (set! first "Rose")
  (string-append first " " middle ". " last))    ;    => "Rose Q. Doe"

(let-with
    ((alist (first middle last)))
  (string-append first " " middle ". " last))    ;    => "Jane Q. Doe"

Since let-with expands into a single let, the third-to-last example works.

The last two examples demonstrate the inability to modify a value in its corresponding association list.


PHP code to make a WHOIS request and return the received data

I have accepted the answer from @ShapeOfMatter, however I have documented the actions/comments for each of their findings below.

This was my first question on Code Review SE, and I realise I should have been more clear about the usage context of the code and the fact that it's an excerpt from a larger application.

Efficiency

  You should close the socket when you're done with it.

Thanks, implemented in the full program.

  What are the sleep(1) lines for? You're already waiting for data to become available on the socket.

The sleeps are to add a delay between WHOIS lookups if whois() is called from a loop (which it is in the full program). This is to help prevent hitting WHOIS server rate limits.

Having the sleep inside the whois() function isn't ideal, so I've moved this to the loop that calls the function instead. In the full program the sleep time can also be manually overridden via a command-line argument.

  I would be tempted to make your timeouts and retry count optional arguments with default values, but that's not a huge deal.

The hard-coded timeout and retries are fine for now, but I have added a backlog item to reconsider in future.

Security

  Most of the security concerns are probably outside your control.

  How do you know if the server you're opening the socket to is the one you actually wanted? Do you care if a 3rd party is reading these messages? Could a 3rd party alter the messages in transit?

  Very likely these aren't problems you need to worry about, but depending on the application they might be.

The program is designed with the idea that all WHOIS data is untrusted, as it is a plaintext protocol that has no native encryption or integrity checking.

The attacks that I am primarily concerned about are RCE, local information disclosure and DoS caused by reading malformed/malicious data from a [spoofed/compromised] WHOIS server. In the full program, the WHOIS data is parsed and certain content extracted out of it, however this is only string manipulation - the content is never executed, used to write arbitrary files, used to connect to arbitrary network locations, etc.

The WHOIS lookups and responses do not need to be confidential in this case.

I have conducted around 12 hours of fuzz testing against the WHOIS function using Radamsa, where fuzzed WHOIS responses were repeatedly served in order to test the resilience and robustness of the code. No crashes, hangs or other issues were identified, and all errors were handled as expected.

Code Quality

  Calling exit() from an error handler probably isn't a great idea. If this is going to be used in a web-service of any kind, then this is actually a security issue: Anyone who can cause problems with your connection to the whois server can now break your site.

This is part of a command-line application with no associated web services. I should have clarified this in the original question.

Outputting the error and exiting is the intended action for the error handler.

  Format the comment at the top as a PHPDoc to help IDEs and intellisense.

Good idea, thanks. Added this as a backlog item.

  Don't do multiple assignments on one line.

The full program doesn't have this, I had actually added these manually when writing the Stack Exchange question, to reduce the number of code lines in the question box.

  Don't name a variable $null. You could name it $dummy or $temp or have separate $read and $except. You may also have the option of passing anonymous empty arrays in-line.

Thanks, adjusted in the full program.

  return isn't typically written like a function; it's a language command on the level of try or class.

Thanks, adjusted all returns in the full program.

  When you're writing a loop, your first thought should be a for loop (or foreach), which will serve just fine here.

A while loop is acceptable for now, however I have added this as a backlog item to reconsider in future.

  Use type-signatures for your functions.

Thanks, adjusted all functions in the full program.


LINQ approach to flatten Dictionary to string

Something like this should work:

public static string ToString(this Dictionary<string,string> source, string keyValueSeparator, string sequenceSeparator)
{
  if (source == null)
    throw new ArgumentException("Parameter source can not be null.");

  var pairs = source.Select(x => string.Format("{0}{1}{2}", x.Key, keyValueSeparator, x.Value));

  return string.Join(sequenceSeparator, pairs);
}


Using Fibonacci sequence to generate musical melodies

fibo

fibo is a fine function, but I would suggest a more complete name like fibonacci just to make it 100% clear that it returns fibonacci numbers to someone that did not read your plaintext introduction.

divBy7

divBy7 is not a good function: it is trivial and most importantly does not do what it says. It returns the remainder of dividing by 7, not the result of dividing by 7. I would delete this function.

calcNums

calcNums is not general enough, I feel no need for the take 16 at the start of it, this function has the potential to calculate as many fibonacci mod 7 as you want, let the caller decide how many to take.

Incidentally fibonacciMod7 is a better name for the function as it says what it does: calcNums was way too general.

returnNote

returnNote is too verbose and fails badly (= with no meaningful error message) if I pass it anything bigger than 6.

returnNote n
  | n `elem` [0..6] = "ABCDEFG" !! n
  | otherwise = error "n will never be higher than 6 due to the pisano period. (And it must be positive)"

This implementation is more concise and incorporates the comment into the code so that it can be shown to the user when he uses the function incorrectly.