texts: Longest Substring Without Repeating Characters in ReasonML/Ocaml

texts:
LeetCode Problems 3. Longest substring without repeating characters

  Given a string, find the length of the longest substring without repeating characters.

  Examples:

    Given "abcabcbb", the answer is "abc",  length 3.

    Given "bbbbb", the answer is "b", length 1.

    Given "pwwkew", the answer is "wke", length 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

I did the question in ReasonML. However, I use a lot of if statement, it is an inappropriate coding style in function programming. Please feel free to comment, how to modify the source as functional programming oriented e.g. type-driven development, pattern matching, etc.

 let explode = s => List.init(String.length(s), String.get(s));

 module LongestSubstringWithoutRepeatingCharacters: {
    let longestSubstringWithoutRepeatingCharacters: string => int;
    let run: unit => unit;
  } = {
    let longestSubstringWithoutRepeatingCharacters = l1 => {
      let ll = explode(l1);
      let myQueue = Queue.create();
      let rec aux = (queue, x: char, xs: list(char), ceil: int, counter: int) => {
        switch (xs) {
        | [] => ceil
        | [h, ...t] =>
          if (Queue.is_empty(queue) === false) {
            if (h != x) {
              if (h != Queue.top(queue)) {
                Queue.push(h, queue);
                aux(
                  queue,
                  h,
                  t,
                  ceil > counter ? ceil : ceil + 1,
                  counter + 1,
                );
              } else {
                let _c = Queue.pop(queue);
                aux(queue, h, t, ceil, counter - 1);
              };
            } else {
              Queue.clear(queue);
              aux(queue, '@', [h, ...t], ceil, 0);
            };
          } else {
            Queue.push(h, queue);
            aux(queue, h, t, ceil > counter ? ceil : ceil + 1, counter + 1);
          }
        };
      };
      aux(myQueue, '@', ll, 0, 0);
    };

    let run = () => {
      Printf.printf(
        "longestSubstringWithoutRepeatingCharacters : %d\n",
        longestSubstringWithoutRepeatingCharacters("abcabcbb"),
      );
    };
  };


texts:
I have a React functional component where users can add a movie from a list to their dashboard. I'm displaying a toast (Material UI Snackbar) to show the result. The result can be good: movie has been added, or bad: movie is already added to your watchlist.
const addMovie = (movie: IMovie) => {
  const isMovieDuplicate = !checkForDuplicate(movies, movie);
  if (isMovieDuplicate) {
    movies.push(movie);
    const sortedMovieList = sortMovieList(movies);
    setMovies(sortedMovieList);
    addMovieToLocalStorage(sortedMovieList);
  }
  const message = isMovieDuplicate ?
    movie.original_title + ' has been added to your watchlist.' :
    movie.original_title + ' is already added to your watchlist.';
  const variant = isMovieDuplicate ? {variant: 'success'} : {variant: 'warning'};
  displaySnackbar(message, variant);
};

const displaySnackbar = (message: string, type: any) => {
  enqueueSnackbar(message, type);
};

const sortMovieList = (movies: IMovie[]) => {
  return orderBy(movies, [(movie: IMovie) =>
    returnSortType(movie, sortConfig.selectedSortType)], [sortConfig.orderType ? 'asc' : 'desc'],
  );
};

First I call a function that checks the if the current movie already exists in the movieList array. If so it returns a true. The isMovieDuplicate takes the opposite value, so in case of there being a duplicate it will be false so that the if statement is not executed.
In the if statement I push the movie object in the movies array. Then I use a function to return an sorted array. Users can specify how they want to sort the list based on title, release date.
I use the sortedMovieList value to call my React hook setMovies and put he array in the React state. Then I use that same array and put the data in my local storage. At some point this local storage will be replaced with an actual database.
When the if statement is completed I want to show the result in a snackbar (toast). Based on the isMovieDuplicate variable I create the context for the toast and pass that to the displaySnackbar function which renders it on the page.
This all works, but it doesn't feel "clean". There's quite some code, maybe I could move the code for creating the message into the displaySnackbar method?


texts: Adding fruits to a basket, allowing selection from ID and name

texts:
I'm writing a tool which users can select multiple choices at once. Whilst I can't provide the actual content, I've replicated it with fruit. I'm replicating some functionality from Nikto where it allows different flags like "-mutation abcd".

for example here we have three fruits:

1- apple
2- orange
3- kiwi

I wanna let users to type "12" or "appleorange" or "21" or "orangeapple" for selecting apple and orange, or "123" or "appleorangekiwi" or vice versa to select apple, orange and kiwi and etc.

Assume that there are more than 3 choices, so it would be pain in the neck if I want to write elif statement for all multiple selections.
How can I make my code simpler and shorter?

Here is my code:

fruits_ls = []

def add_fruits():
    while True:
        print("choose your favorite fruits:\n"
            "1- apple\n"
            "2- orange\n"
            "3- kiwi\n"
            "4- exit\n")

        my_fruits = input()
        if my_fruits == str(1) or my_fruits == "apple":
            fruits_ls.append("Apple")
        elif my_fruits == str(2) or my_fruits == "orange":
            fruits_ls.append("Orange")
        elif my_fruits == str(3) or my_fruits == "kiwi":
            fruits_ls.append("Kiwi")
        elif my_fruits == str(12) or my_fruits == "appleorange" or my_fruits == str(21) or my_fruits == "orangeapple":
            fruits_ls.append("Apple")
            fruits_ls.append("Orange")

        elif my_fruits == str(13) or my_fruits == "applekiwi" or my_fruits == str(31) or my_fruits == "kiwiapple":
            fruits_ls.append("Apple")
            fruits_ls.append("Kiwi")

        elif my_fruits == str(23) or my_fruits == "orangekiwi" or my_fruits == str(32) or my_fruits == "kiwiorange":
            fruits_ls.append("Orange")
            fruits_ls.append("Kiwi")

        elif my_fruits == str(4) or my_fruits == "exit":
            break

add_fruits()

print(fruits_ls)


texts: Check if a game of Tic-Tac-Toe has a winner

texts:
I've implemented a Tic Tac Toe game with a public method checkWin() to check if the game has a winner. This is my code.

public class TicTacToe {
    int size;
    int [][] board;

    public TicTacToe(int size){
        this.size = size;
        board = new int[size][size];
        for (int i = 0; i <size ; i++) {
            for (int j = 0; j <size ; j++) {
                board[i][j] = -1;
            }
        }

    }

    public void markCross(int row, int col){
        if(row >= size || col >= size) {
            throw new IllegalStateException("Invalid grid point");
        }
        board[row][col] = 1;

    }

    public void markZero(int row, int col){
        if(row >= size || col >= size){
            throw new IllegalStateException("Invalid grid location");
        }
        board[row][col] = 0;
    }

    public boolean checkWin(){
       int countOnes = 0;
        int countZeros = 0;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {

                if(board[i][j] == 0) countZeros++;
                else if(board[i][j] == 1)countOnes++;
            }
            if(countZeros == size || countOnes == size) return true;
            break;
        }
        countOnes = 0;
        countZeros = 0;

        //check diagonal right

        for (int i = 0, j= 0; i <size ; i++, j++) {
            if (board[i][j] == 0) countZeros++;
            else if(board[i][j] == 1) countOnes++;
        }
        if(countOnes == size || countZeros == size) return true;

        //check diagonal left
        for (int i = size-1, j= size-1; i >= 0 ; i--, j--) {
            if (board[i][j] == 0) countZeros++;
            else if(board[i][j] == 1) countOnes++;
        }
        if(countOnes == size || countZeros == size) return true;

        return false;

    }
}


texts:
I received my code review comments for the following method:

private RequiredDocumentEntity GenerateRequiredDocumentMapping(string documentTypeCode, params string[] alternativeDocumentIds)
{
    int alternativeDocumentCount = alternativeDocumentIds?.Length ?? 0;
    List<DocumentTypeEntity> satisfyingDocuments = new List<DocumentTypeEntity>(alternativeDocumentCount + 1);  // A document can always satisfy itself, hence the + 1
    DocumentTypeEntity documentType = null;

    if (documentTypeCode != null)
    {
        documentType = GetDocumentType(documentTypeCode);
        satisfyingDocuments.Add(documentType);
    }

    alternativeDocumentIds.Select(GetDocumentType)
                          .ForEach(satisfyingDocuments.Add);

    return new RequiredDocumentEntity() { SatisfiedBy = satisfyingDocuments };
}

The issue the reviewer had with this method was that the initialization of the list's capacity made the code difficult to read. It was also stated that it was a micro-optimization to save the list from doubling upon resize. This I agree with, to an extent. The list will have, at most 6, elements in it upon return. My argument against that would be that while it is a micro-optimization, if you can calculate how many elements will be in a list, why wouldn't you simply initialize the list's capacity?

Therefore, my question is:  Does the initialization as written make this code difficult to read?


texts: Read Twitter direct messages and check messages for links

texts:
I'm learning Clojure and I'm doing a little thing that reads direct messages from Twitter using twitter-api wrapper. The code doing that is below.

(ns twitterbot.my-twitter
    (:require [twitter.oauth :refer [make-oauth-creds]]
              [twitter.api.restful :refer [direct-messages]]
              [clojure.edn :as edn]
              [clojure.string :as string]))

(defn- load-credentials [filename]
  (edn/read-string (slurp filename)))

(def ^:private credentials-from-file (load-credentials "credentials.edn"))

(def ^:private oauth-credentials
  (make-oauth-creds (credentials-from-file :consumerkey)
                    (credentials-from-file :consumersecret)
                    (credentials-from-file :usertoken)
                    (credentials-from-file :usersecret)))

(defn- has-url? [message]
  (seq (:urls (:entities message))))

(defn- trusted-user? [message]
  (= (credentials-from-file :trusteduser) (:sender_screen_name message)))

(defn- get-url [message]
  (:expanded_url (nth (:urls (:entities message)) 0)))

(defn links-from-direct-messages []
  (let [messages (direct-messages :oauth-creds oauth-credentials)]
    (map get-url (filter has-url? (filter trusted-user? (:body messages))))))

As I'm new to Clojure, I would like to know whether I'm doing things in the correct way and how to do them better. I feel like the coding style and layout is off at least in links-from-direct-messages, but I even though I tried to follow this style guide, I'm not sure how it should be. Also as the data structure from Twitter is quite nested, I wonder how I should be going through them.


texts:
I'm using the following code to parse html, This code is working but since I'm new to JavaScript and working in alone project I would appreciate if you can give me some tips and feedback how can I improve this code,or it is fine...

The requirements are:

  Insert a new script after given script ID(in the code after test-ui-bootstrap')
  For given script ID update attribute value (when the key is given)

code need to update script content after existing script with new content.
The code is working and I use part of it from SO past post

https://jsfiddle.net/st6xg7Lj/1/

Here is the code to convert and convert back

function parseHtml(html) {

  // replace html, head and body tag with html_temp, head_temp and body_temp
  html = html.replace(/<!DOCTYPE HTML>/i, '<doctype></doctype>');
  html = html.replace(/(<\/?(?:html)|<\/?(?:head)|<\/?(?:body))/ig, '$1_temp');

  // wrap the dom into a <container>: the html() function returns only the contents of an element
  html = "<container>"+html+"</container>";
  var element = $(html); // parse the html

  return element;
}

function convertBackToHtml(element) {

  // reset the initial changes (_temp)
  var extended_html = element.html();
  extended_html = extended_html.replace(/<doctype><\/doctype>/, '<!DOCTYPE HTML>');
  extended_html = extended_html.replace(/(<\/?html)_temp/ig, '$1');
  extended_html = extended_html.replace(/(<\/?head)_temp/ig, '$1');
  extended_html = extended_html.replace(/(<\/?body)_temp/ig, '$1');

  // replace all &quot; inside data-something=""
  while(extended_html.match(/(<.*?\sdata.*?=".*?)(&quot;)(.*?".*?>)/g)) {
    extended_html = extended_html.replace(/(<.*?\sdata.*?=".*?)(&quot;)(.*?".*?>)/g, "$1'$3");
  }

  return extended_html;
}

Here is the code to create new script with content and update the values

var html = $('textarea.input').val();

  // parse the html to an element
  var element = parseHtml(html);

  // do your calculations on the parsed html
  $("<script>alert(\"test\");<\/script>").insertAfter(element.find('#test-ui-bootstrap'));
  element.find("#test-ui-bootstrap").attr('data-test-ui-libs123', "test.bbb");
  element.find("#test-ui-bootstrap").attr('src', 'resources/aaaa/test-ui-core.js');

  // convert the element back to html
    var extended_html = convertBackToHtml(element);

Since I need to run this code in production very soon and Im fairly new In JS I'd like to get your feedback,I really need it.

The code itself is working OK


texts: How to improve this functional python trial division routine?

texts:
The following functional program factors an integer by trial division. I am not interested in improving the efficiency (but not in decreasing it either), I am interested how it can be made better or neater using functional constructions. I just seem to think there are a few tweaks to make this pattern more consistent and tight (this is hard to describe), without turning it into boilerplate.

def primes(limit):
        return (x for x in xrange(2,limit+1) if len(factorization(x)) == 1)

def factor(factors,p):
        n = factors.pop()
        while n % p == 0:
                n /= p
                factors += [p]
        return factors+[n] if n > 1 else factors

def factorization(n):
        from math import sqrt
        return reduce(factor,primes(int(sqrt(n))),[n])

For example, factorization(1100) yields:

[2,2,5,5,11]

It would be great if it could all fit on one line or into two functions that looked a lot tighter -- I'm sure there must be some way, but I can not see it yet. What can be done?


texts: Variables, references and pointers - Write the function zero (...) so that the following code works correctly

texts:
I have following homework exercise from lecture "Variables, references and pointers":

  Write the function zero (...) so that the following code works
  correctly:
      int x = 3;
      zero(x);
      cout << x << endl;  // writes 0

This is my solution:

#include <iostream>

using namespace std;

void zero(int &);

int main(void) {
    int x = 3;
    zero(x);
    cout << x << endl;
    return 0;
}

void zero(int & num) {
    num = 0;
}

What do you think about it?


texts: Show list of states depending on user selection

texts:
I have some data that needs to bind to my view depending on the user selection.

Example: changing the list of states in a dropdown depending on the selected country.

My understanding is, there are two ways to do this:

Have a global JS variable, say,
var model, which has a property, "states". This contains all the relevant data of states.

So, I bind the data from the "states" property of the model variable depending on the selection of country.

Code:

In my view:

<select name="state" ></select>
<select name="country" >
   <option value="US" >USA</option>
   <option selected="selected" value="CN" >CHINA</option>
   <option value="IN" >INDIA</option>
</select>
<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model)); //Model is my C# object that I am converting into a JS object
</script>

In my JS:

$(document).ready(function () {
    stateSelection(model.StateList)
})

function stateSelection(stateList) {
        var jStates = jQuery('select[name="state"]');
        var selectedCountry = jQuery('select[name="country"] option:selected').val();
        var provinceExists = false;
        jStates
                .children()
                .remove()
                .end()
        if (stateList.length > 0) {
            jQuery.each(stateList, function (key, val) {
                if (selectedCountry === val.ID) {
                    jStates
                        .append('<option value="' + val.Value + '"  class="' + selectedCountry + '" >' + val.Text + '</option>');
                }
            });
        }
    }

Make an ajax call whenever the country dropdown selection is made, then pass the country name/id as parameter and get a response object that contains the list of states that I want to display, and bind them to my view.
In my JS:

$.ajax({
    type: "POST",
    url: Home/GetStates,
    data: $('select[name="country"] option:selected').val(),
    error: function (xhr, status, error) {
    },
    success: successFunction
});

function successFunction(data) {
    stateSelection(data) //data contains the list of states
}

My question basically is, is it bad practice to have a rather large JS object (list of states) as a global variable - or does it make sense to get only the data I need from my server, only when I need it.

I'm trying to understand which one would be the better approach and under what conditions. Or is there a better alternative?

Update:

I tried both and found that loading the data into my DOM was the better way. Not only was the user experience seamless but it helped me avoid writing additional server side code and database calls. Loading the states into my browser did not have any noticeable impact on the front end performance if anything we thought it was better user experience - no loaders - no ajax calls. Thanks to everyone who answered below.


texts: Finding all points on the line where distance between each of them is dividable by X

texts:
recently I received ( during job interview) a challange to write a method for finding a largest subset of points where distance between them is dividable by a set number.

example points array is A =[-3,-2,1,0,8,7,1]

example number we will be dividing by is 3

so for array above  the biggest subset is [-2,1,7,1]
because:

distance between points is counted as follows abs(A[1] - A[2]) = 3

distance between points 7 and -2 is 9 --> 9 % 3 = 0 so its ok.

I wrote code:

var A = [-3, -2, 1, 0, 8, 7, 1];
    var biggestArray = [];
    (A).forEach(element => {
        Z=[];
        Z.push(element);
        for (i = 0; i < A.length; i++) {
            if (element !== A[i]) {
                var distance = Math.abs(element - A[i]);
                if (distance % 3 === 0) {
                    Z.push(A[i]);
                }
            }

        }
        if(Z.length>biggestArray.length){
            biggestArray=Z;
        }
    });
    console.log("biggest Array length:"+biggestArray.length);
    console.log("points: "+biggestArray);

For each element from entry array i check its distance with any other element. If it is %3 then I add this point do result array. After each outer loop iteration i check if current result is bigger than last. If yes then I store new one. I receive correct data at least for array given to me.

This task seems to be quite easy ( am I not seeing something?)
Also it will do n^2 operations. Is there any nice way to tone it down?


texts: Short Erlang function to demonstrate hd and tl

texts:
I'm simultaneously learning Erlang and writing a short guide on list operations. Here is a trivial function I wrote to demonstrate hd and tl:

headAndTail(List) ->
  Head = hd(List),
  Tail = tl(List),
  {Head, Tail}.

This works, but it throws "Warning: variable 'Head' is unused." I know this function could be written with {hd(List), tl(List)}, but is the way I did it considered bad practice?


texts: Finding duplicate files on a disk using MD5

texts:
I started learning Python a month ago (used to write programs in Delphi before). Can you please take a look at my code and give me some tips what is good and what is bad in it?

The aim is to find duplicate files on a disk and saves this information. I'm using md5 hash. Is it right to use global variable like I did?

import os
import time
import hashlib

def md5_sum(path, block_size=256*128, hr=False):
    md5 = hashlib.md5()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(block_size), b''):
            md5.update(chunk)

    if hr:
        return md5.hexdigest()
    return md5.digest()

def md5_simple(path, chunk):
    if chunk:
        return md5_sum(path, 8192)
    else:
        return hashlib.md5(open(path, 'rb').read()).digest()

def walking(path, chunk=False):
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            global dupl_string
            try:
                if len(found_files) % 500 == 0:
                    print(len(found_files))

                fname = os.path.join(dirpath, filename)
                file_size = os.path.getsize(fname)
                found_files[fname] = file_size

                if chunk:
                    file_hash = md5_sum(fname, 8192)
                else:
                    file_hash = md5_simple(fname, file_size > 1000 * 1024 * 1024)

                if file_hash in hash_files:
                    dupl_string += 'Src: ' + hash_files[file_hash] + ', dupl: ' + fname + '\n'
                else:
                    hash_files[file_hash] = fname

            except OSError:
                print('OSError: ' + fname)

my_dir = "C:"
dupl_string = ''
found_files = dict()
hash_files = dict()

time1 = time.time()

try:
    walking(my_dir)
finally:
    if dupl_string:
        with open('dupl.txt', 'w') as f3:
            f3.write(dupl_string)

    with open('files.csv', 'w') as f:
        for key, value in sorted(found_files.items(), key=lambda item: item[1], reverse=True):
            f.write("%s, %s\n" % (key, value))

    print("Elapsed: " + str(time.time() - time1) + ' sec')


texts:
This is from a C# library I'm writing that checks for updates through a PHP script.

public bool CheckForUpdate(Request Request)
{
    HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateServerAddress + "http://{0}/update.php?{1}" + Request.ToString());
    httpRequest.UserAgent = "KMUpdaterClient/" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
    httpRequest.Accept = "text/plain";
    HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        string responseString = String.Empty;
        using(StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            responseString = sr.ReadToEnd();
        }
        response.Close();
        switch (responseString.Substring(0, 3))
        {
            case "UTD":
                //Application is up to date
                return false;
            case "AVL":
                return true;
            case "ERR":
                throw new ApplicationException("An error occured on the server: " + responseString.Substring(4));
            default:
                //Unexpected
                throw new ApplicationException("An unexpected response was recieved by the server: " + responseString);
        }
    }
    else
    {
        switch (response.StatusCode)
        {
            //Generated by web app
            case HttpStatusCode.BadRequest:
                throw new ArgumentException(String.Format("The Request passed to CheckForUpdate was incomplete: AppName:{1}; Channel:{2}; Version:{3}", Request.AppName, Request.Channel, Request.Version));
            case HttpStatusCode.Unauthorized:
                throw new UnauthorizedAccessException("The serial number for this application was invalid.");
            case HttpStatusCode.ServiceUnavailable:
                throw new AppDomainUnloadedException("The web service is currently unavailable.");
            //Common server errors
            case HttpStatusCode.NotFound:
                throw new FileNotFoundException("The updater server page could not be accessed.");
            case HttpStatusCode.InternalServerError:
                throw new WebException("The web server encountered an error.");
            //Unexpected server errors
            default:
                throw new ApplicationException("An unexpected error occured: " + response.StatusCode);
        }
    }
}

After writing it, I just felt that it was a bit too long. Is this an OK size for a web request? If not, where could I trim it down?


texts:
I have two lists of dictionaries where both have the same "id" key but otherwise different data.
list1 = [{"id":1, "spam": 3, "eggs": 5}, {"id": 2, "spam": 5, "eggs": 7}]
list2 = [{"id":1, "knights": 5, "coconuts": 2}, {"id": 2, "knights": 3, "cocounts": 8}]

I know I can do a nested loop something like this (I know I can use dict.update as well, but just writing it out as an exampel):
for id in list1:
    for i in list2:
        if id['id'] == i['id]:
           id['knights'] = i['knights']
           id['coconuts'] = i['coconuts']

but can anyone tell me the more pythonic or quicker way to do this? matching two lists with millions of rows in each does not practically work this way.
Expected result is:
[{"id": 1, "spam": 3, "eggs": 5, "knights": 5, "coconuts": 2}, {"id": 2, "spam": 5, "eggs": 7, "knights": 3, "coconuts": 8}]


texts: Get property value from object tree in a recursive way

texts:
Consider the following structure,

let condition = { and: [ { id: 3 }, { pageId: '1' } ] }

I want to get the id property value in a recursive way, it can be also nested inside other conditions.

for example the structure could be like that

let condition = {or: [{ and: [ { id: 3 }, { pageId: '1' } ] }, {age: 10}]}

I ended using this but I don't like the final syntax

  function getIdConditionValue(cond) {
    if (isArray(cond.and)) {
      return map(cond.and, getIdConditionValue);
    } else if (isArray(cond.or)) {
      return map(cond.or, getIdConditionValue);
    }
    if (cond.id) return cond.id;
  }

const id = getIdConditionValue(condition).filter(x => x)[0];

It is working, but I would like to remove .filter(x => x)[0] part from the calling function, which I added because the returned value would be like this [1, undefined].


texts:
I am working on some code which checks whether or not to unlink a file on the basis of the class:

File.unlink(file.path) if file.is_a? File

I think it would be more idiomatic to check whether the object responds to the unlink message:

File.unlink(file.path) if file.respond_to? :unlink

Is there any good reason to prefer the is_a? approach?


texts:
The task:

  We're given a hashmap associating each courseId key with a list of
  courseIds values, which represents that the prerequisites of courseId
  are courseIds. Return a sorted ordering of courses such that we can
  finish all courses.

  Return null if there is no such ordering.

  For example, given {'CSC300': ['CSC100', 'CSC200'], 'CSC200':
  ['CSC100'], 'CSC100': []}, should return ['CSC100', 'CSC200',
  'CSCS300'].

My solution:

const isEveryCourseCovered = courses => courses.every(c => !Boolean(c));
const getCourseOrder = courses => {
  const courseSubjects = Object.keys(courses);
  const courseRequirements = Object.values(courses);
  const courseOrder = [];

  do {
    courseSubjects.map((subject, i) => {
      if (subject) {
        courseRequirements[i].map((requirement, idx) => {
          if (courseOrder.includes(requirement)) {
            courseRequirements[i].splice(idx, 1);
          }
        });
        if (!courseRequirements[i].length) {
          courseOrder.push(subject);
          delete courseSubjects[i];
        }
      }
    });
  } while(!isEveryCourseCovered(courseSubjects));

  return courseOrder;
};

const coursesObj = {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []};
console.log("result ", getCourseOrder(coursesObj));


texts: Cancelling Local WebClient ASync Operation

texts:
I had previously asked this question on SO.  The answer pointed me towards using the task parallel library for multiple parallel downloads.  I'm not actually utilizing this exact code, but it got me to rethink my design.

The one open issue that wasn't really addressed (and I didn't ask it), cancelling the a local WebClient.  It isn't as simple as just calling WebClient.CancelASync(); since the scope of WebClient is long gone by the time you need to cancel.

This isn't my code or even how I am approaching the problem, but just part of the test example I put together to see how this works.  It seems to work, although it means having to wait for an event callback before the cancel is called.  So I was wondering if there was another alternative.

private bool pendingCancel = false;
private Queue<Uri> queue = LoadQueue();

public void ASyncDownload()
{
    if (queue.Count == 0) return;

    var uri = queue.Dequeue();

    WebClient client = new WebClient();
    client.DownloadProgressChanged
        += (sender, e) =>
        {
            if (pendingCancellation)
            {
                ((WebClient)sender).CancelAsync();
                return;
            }

            //do something to report progress
        };

    client.DownloadDataCompleted
        += (sender, e) =>
        {
            if (!e.Cancelled || pendingCancel)
            {
                if (e.Error == null)
                {
                    // do something with e.Results
                }
                else
                {
                    // report error
                }
            }
            else
            {
                // report cancellation
            }
        };

    client.DownloadDataAsync(uri);
}

My thought process is for any long running downloads, waiting until the next item in the queue to exit would not be appropriate, so the idea would be to call CancelASync() on the sender of the DownloadProgressChanged event handler.

Is this the best alternative short of putting a webClient field in the class?  And are there dangers or possible unpredictable behavior that I have not found in my testing?


texts:
I was recently in a situation where I had to use vanilla js (no es6 and no http libraries, so I came up with this simple wrapper for get calls :

var Http = (function() {
    function Http() {
        this.xhr = new XMLHttpRequest();
    }
    Http.prototype.get = function(url, onload) {
        this.xhr.onreadystatechange = function() {
            if (this.readyState === 4 && this.status == 200) {
                onload(this.responseText);
            }
        }
        this.xhr.open("GET", url);
        this.xhr.send();
    }
    return Http;
})()

And I would use it like this :

var http = new Http();
http.get('endpoint', function() {});

Can you see any potential problems with this approach like memory leaks insecurities etc. and would you and if possible, how, add something to improve it, like ability to handle multiple get() in row from the same http object?


texts: What do you think about this usage of for loop in JavaScript?

texts:
Algorithm that I had to write is a perfect case for while, or do..while loop, however I found out that if I will implement it with a for loop I will save few lines of code and also scope of variables will be more appropriate. Take a look at the following code:

        for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0; i++ ) {
            fakePosition.top -= i * 10;
            offset = this.documentView.getOffsetFromPosition( fakePosition );
            fakePosition = this.documentView.getRenderedPosition( offset );
        }

As you can see second parameter is very atypical as for for loops. My mine reason to switch to this loop was fact that I need iterator (i) and offset variables inside loop (and only there).

What do you think about this approach?


texts: Merging multiple sorted arrays into one sorted array

texts:
I would like to merge multiple arrays that are already sorted, into one sorted array.

My arrays look like this :

{
  "arrays": [
    [
      {
        "type": "tag",
        "position": "start",
        "text": true,
        "offset": 1280,
      }
      {
        "type": "tag",
        "position": "end",
        "text": true,
        "offset": 1350,
      }
    ],
    [
      {
        "type": "tag",
        "position": "start",
        "text": false,
        "offset": 1121,
      },
      {
        "type": "tag",
        "position": "end",
        "text": true,
        "offset": 1300,
      }
    ],
    ],
...
}

My current implementation looks like this :

function getMinFromArrays(arrays, state) {
    let minIndex = -1;
    for (let i = 0, l = arrays.length; i < l; i++) {
        if (state[i] >= arrays[i].length) {
            continue;
        }
        if (minIndex === -1) {
            minIndex = i;
        }
        if (arrays[i][state[i]].offset < arrays[minIndex][state[minIndex]].offset) {
            minIndex = i;
        }
    }
    if (minIndex === -1) {
        throw new Error("minIndex negative");
    }
    return minIndex;
}

module.exports = function (arrays) {
    const totalLength = arrays.reduce(function (sum, array) {
        return sum + array.length;
    }, 0);

    const resultArray = new Array(totalLength);

    const state = arrays.map(function () { return 0; });

    let i = 0;

    while(i <= totalLength - 1) {
        const arrayIndex = getMinFromArrays(arrays, state);
        resultArray[i] = arrays[arrayIndex][state[arrayIndex]];
        state[arrayIndex]++;
        i++;
    }

    return resultArray;
};

I think It might be possible to optimize this code (sometimes, it seems to be quite slow (70ms for 10 arrays of size 5000 each).


texts: How to make this code fit into the base class

texts:
I have lots of classes that inherit from abstract base class, which has abstract method

public class BaseClass<T>
{
    protected abstract void GetItems();
}

each subclass have almost the same implementation

protected override void GetItems()
{
    // some preparation code here which is the same for all sublcasses

    // calls async method that handles the result in anonymous method
    // method name is different for each of the subclass that implements it
    _model.GetXXXAsync(a =>
    {
        // same code here for all sublclasses
    });
}

So, basically, the difference is only in the GetXXXAsync method. This is the method signature:

void GetXXXAsync(Action<EntityResultArgs<T>> operationCompleted);

WHat would be the best way to refactor this code to place it in a base class, to avoud repeating 30 lines of code in each subclass, while changing only the method name and T type?


texts:
Here is the problem:

Given a numpy array 'a' that contains n elements, denote by b the set
of its unique values in ascending order, denote by m the size of
array b. You need to create a numpy array with dimensions  n×m , in
each row of which there must be a value of 1 in case it is equal to
the value of the given index of array b, in other places it must be 0.

import numpy as np

def convert(a):
    b = np.unique(sorted(a))
    result = []
    for i in a:
        result.append((b == i) * 1)
    return np.array(result)

a = np.array([1, 1, 2, 3, 2, 4, 5, 2, 3, 4, 5, 1, 1])
b = np.unique(sorted(a))
print(convert(a))

This is my solution. is there some improvments that I can make?
I'm not sure about declaring regular list to the result and then converting it into np.array.


texts: Which products should be purchased with the given amount of money: Hackerrank?

texts:
I am writing code for the challenge given here . Below the text:

  Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they
  pool their money to buy ice cream. On any given day, the parlor offers
  a line of flavors. Each flavor has a cost associated with it. Given the value of and the of each flavor for trips to the Ice Cream
  Parlor, help Sunny and Johnny choose two distinct flavors such that
  they spend their entire pool of money during each visit. ID numbers
  are the 1- based index number associated with a cost. For each trip to the parlor, print the ID numbers for the two types
  of ice cream that Sunny and Johnny purchase as two space-separated
  integers on a new line. You must print the smaller ID first and the
  larger ID second.

  For example, there are flavors having cost = [2, 1, 3, 5, 6]. Together they have money = 5 to spend.
  They would purchase flavor ID's 1 and 3  for a cost of 2 + 3 = 5  . Use 1 based indexing
  for your response.

I have written code for the problem. However, it is running for most of the test cases except three. The error message that they show is that "Your code did not execute within the time limits". Apparently the code needs to be optimized. Can anyone please tell how may I do that?

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the whatFlavors function below.
    static void whatFlavors(int[] cost, int money) {

         int baseItem=0, comparedItem = 0,totalAmount=0, chosenFlavour1=0,
                chosenFlavour2=0,flag=0;
        for(int i = 0 ; i<(cost.length-1); i++)
        {
            baseItem = cost[i];
            for(int j = (i+1); j< (cost.length);j++)
            {
                comparedItem= cost[j];
                totalAmount = baseItem + comparedItem;

                if(totalAmount == money)
                {
                    chosenFlavour1 = i;
                    chosenFlavour2 = j;
                    flag = 1;
                    break;
                }

            }

            if(flag == 1)
            {
               break;
            }
        }

        chosenFlavour1++;
        chosenFlavour2++;
        System.out.println(chosenFlavour1+" "+chosenFlavour2);

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int t = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int tItr = 0; tItr < t; tItr++) {
            int money = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            int n = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            int[] cost = new int[n];

            String[] costItems = scanner.nextLine().split(" ");
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int i = 0; i < n; i++) {
                int costItem = Integer.parseInt(costItems[i]);
                cost[i] = costItem;
            }

            whatFlavors(cost, money);
        }

        scanner.close();
    }
}


texts:
I have written a function to populate values into a class whose structure is as given below

 public class Country
    {
        public string Name { get; set; }
        public string Continent { get; set; }
        public string Zone { get; set; }
        public India IndiaInfo { get; set; }

    }

   public class India
    {
        public List<State> StateInfo{get; set;}
    }

    public class State
    {
        public string StateName { get; set; }
        public string StateCode { get; set; }
    }

The values are populated into the class object as shown below

public void PopulateCountry(string name, string Asia , string GMT , string AbcState, string RichState)
    {
        Country objCountry = new Country();
        objCountry.Continent = Asia;
        objCountry.Name = name;
        objCountry.Zone = GMT;

        **India objIndia = new India();
        objIndia.StateInfo = new List<State>;
        State objState = new State();
        objState.StateCode = AbcState;
        objState.StateName = RichState;
        objIndia.StateInfo.Add(objState);
        objCountry.IndiaInfo = objIndia;**

    }

In the above method to populate the object of class Country I have taken a brute force approach and put the values in the class and the code is giving results too.  However this code is not following some of the best practices and can be further enhanced /rewritten especially the one in Bold.  Can someone point out the things/features/practices of C# I am missing.

Edit# 1 Magus pointed out some of the conventions i was not following Regarding this particular method, PopulateCountry 1) can we have better methods to instantiate the state object/india object , taking into account their relationship as per class structure 2) the last line of code where i have directly assigned the object,is that fine and according to standards?


texts: Ordering data.frames elegantly by factor

texts:
I have a mock_Data:

structure(list(Sample = structure(c(29L, 31L, 21L, 25L, 15L,
17L, 13L, 27L, 23L), .Label = c("109d0", "109d2", "116d0", "116d2",
"125d0", "125d2", "136d0", "136d2", "138d0", "138d2", "141d0",
"141d2", "144d0", "144d2", "18d0", "18d2", "28d0", "28d2", "30d0",
"30d2", "39d0", "39d2", "4d0", "4d2", "70d0", "70d2", "73d0",
"73d2", "82d0", "82d2", "83d0", "83d2"), class = "factor"), Clinical = structure(c(1L,
2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L), .Label = c("low faecal Salmonella shedding",
"persistent faecal Salmonella shedding"), class = "factor")), .Names = c("Sample",
"Clinical"), row.names = c(NA, 9L), class = "data.frame")

And I need to reorder it so that the rows with the same Clinical factor are together.

So far I generated this function :

reorder_by_factor <- function(data, factor){
  # Function to get the indices of an unamed rows
  flev <- levels(factor)
  ac <- function(data, factor, x){
    # Extract rownames
    rownames(data)[with(data, factor == x)]
  }
  ap <- sapply(flev, ac, data = data, factor = factor )
  unlist(ap)
}

that outputs the index of each factor ordered, and I can use it as mock_Data[reorder_by_factor(mock_Data, mock_Data$Clinical),]

I would like to be able to use it like lm with just reorder_by_factor(mock_Data, Clinical) and if possible make it more elegant and general, so it could take several factors and reorder them one, after the other. Also I would like to know which code would broke the function (aside from a data.frame with rownames)


texts:
I created simply database service with get, insert, get all image names and verify exist method.

All images will be store in blob storage with unique filename + postfix size. Next one I have image model, with simple expression for mapping object select, methods for detection Webp format and existing.

All methods:

GetAllImageNames() - return enumerable list of imageNames
Insert(string filename) - insert filename
site GetImage(string filename) - return image entity, mapped to
ImageModel ImageExist(string filename) - return true/false
Delete(string filename) - delete file by filename

I wrote the Image object entity that represents a database object:

public class Image
{
    public int Id { get; set; }

    public string Filename { get; set; }
}

This is a very simple entity, no comments are needed I think.

ImageModel (object result structure):

public class ImageModel
{
    public string Filename { get; set; }

    public ImageSize Size { get; set; }

    public static Expression<Func<Image, ImageModel>> ToModel()
    {
        return image => new ImageModel
        {
            Filename = image.Filename,
            Size = image.Size
        };
    }

    public bool Exists()
    {
        return !string.IsNullOrEmpty(Filename);
    }

    public bool IsWebp()
    {
       //Now implement for now
    }
}

This model class is very simply again:

ToModel() is a function for mapping to results data.

And finally DatabaseImageService:

public interface IImageDatabaseService : IRepository<Image>
{
    Task<IEnumerable<string>> GetAllImageNames();

    Task Insert(string filename);

    Task Delete(string filename);

    Task<ImageModel> GetImage(string filename);

    Task<bool> ImageExist(string filename);
}

IRepository is design pattern Repository for manipulation with database operations. It's possible to use it as DI of course. But I like to use it as an inherit interface of the current entity.

public class ImageDatabaseService : Repository<Image>, IImageDatabaseService
{
    public ImageDatabaseService(DbContext dbContext, IUnityOfWork unityOfWork) : base(dbContext)
    {
        this.UnityOfWork = unityOfWork;
    }

    private IUnityOfWork UnityOfWork { get; set; }

    public async Task<IEnumerable<string>> GetAllImageNames()
    {
        return await this.Select(s => s.Filename).ToListAsync();
    }

    public async Task Insert(string filename)
    {
        this.InsertAsBatch(filename);
        await this.UnityOfWork.SaveAsync();
    }

    public async Task Delete(string filename)
    {
        var image = await this.FirstOrDefaultAsync(s =>
            s.Filename.Equals(filename, StringComparison.InvariantCultureIgnoreCase));
        if (image != null)
        {
            this.Remove(image);
            await this.UnityOfWork.SaveAsync();
        }
    }

    public async Task<bool> ImageExist(string filename)
    {
        var image = await GetImage(filename);
        return image.Exists();
    }

    public async Task<ImageModel> GetImage(string filename)
    {
        return await this.Where(s => s.Filename.Equals(filename, StringComparison.InvariantCultureIgnoreCase))
            .Select(ImageModel.ToModel()).FirstOrDefaultAsync();
    }

    private void InsertAsBatch(string filename)
    {
        var image = this.Create();
        image.Filename = filename;
        //possibly another image attributes

        this.Add(image);
    }
}

UnityOfWork is a design pattern for saving data to my database, used in combination with the Repository pattern.


texts: Performing data transportations in RxJS with Promises

texts:
I'm using RxJS 5.0.0-alpha.12 to perform some data transformations, and some of those transformations use Promises.

return observable
.flatMap(item => {
  return Observable.zip(

    Observable.fromPromise(fs.readFile('./config.json')),

    Observable.of(item),

    (s1, s2) => {
      return {
        config: JSON.parse(s1.toString()),
        testResult: s2
      };
    }
  );
})
.flatMap(item => {
  return Observable.zip(

    Observable.fromPromise(
      getStudentIdFromStudentNumber(item.testResult['Student Primary ID'])
    ),

    Observable.of(item),

    (s1, s2) => {
      return {
        'Test Date': s2.config.testConstants.ROGL_Begin_Year.testDate,
        'Student Id': s1,
        'Student Number': s2.testResult['Student Primary ID'],
        'Grade Level': s2.testResult.Grade,
        'Composite Score Alpha': s2.testResult['Composite Score']
      };
    }
  );

});

Note that both fs.readFile (fs here being the name given to fs-promise) and getStudentIdFromStudentNumber return a Promise.

It seems like having to zip the original item that is getting emitted from observable with the results of each Promise is cumbersome. Is there a cleaner way to use the results of these two Promises with this Observable?

What makes this tricky (to me) is sometimes the Promise relies on a field within the item object emitted by observable (eg., getStudentIdFromStudentNumber), and other Promises may not rely on item (eg., fs.readFile).


texts: Using a BaseController in MVC asp.net to reuse the repository

texts:
I have a repository class that impliments a repository Interface.
In my Controllers I want a way to access the repository without creating constructors each time in the controller. So now all my Controllers have to do is inherit from Base. Any pitfalls to this, or how I can write it differently.

public class BaseController : Controller
    {
        public IRepository Repo {get;set;}
        public IStudentRepositroy StudentRepo {get;set;};
      public BaseController() : this(new Repository(),new StudentRepository())
      {

      }
      public BaseController(IRepository repo,IStudentRepository studentRepo)
      {
          Repo = repo;
          StudentRepo = studentRepo;
      }

    }


texts:
Very new to OOP with Python - and feel like I still don't totally get OOP. However I thought I'd put together a personal online book library to practice inheritance, methods, docstrings etc.
Program allows one to add books (comics or novels - with comics inheriting from novels) to one's own library, and create a custom reading lists.
There are a few different methods. For example, a library method which will return all books over a specified length.
Note that I've removed quite a lot from this, just so it's not 5 pages long! I would normally have several different types of books, attributes such as Author etc. But hopefully from the below you get a good idea of the structure.
Speaking of structure, I would just like to know if mine is any good. Also there is an issue whereby if you remove a book from the library, it will still show up in any reading lists I created. I don't know if there's a way to deal with this, or if I'm thinking about this the wrong way.
class Library:

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

    def add_book(self, book):
        self.books.append(book)

    def remove_book(self, book):
        self.books.remove(book)

    def pages_over_n(self, number):
        """Returns books that have more than specified number of pages"""
        return [book for book in self.books if book.pages > number]

    def get_library(self):
        """Returns all books in Library"""
        return self.books

    def __repr__(self):
        return f"Library({self.books})"

    def __str__(self):
        return f"Library has {len(self.books)}"

class Novel:

    def __init__(self, title, pages, publicationDate):
        self.title = title
        self.pages = pages
        self.publicationDate = publicationDate

    def __repr__(self):
        return f"Novel({self.title}, {self.pages}, {self.publicationDate})"

    def __str__(self):
        return f"Media: {self.title}"

class ComicBook(Novel):

    def __init__(self, title, pages, publicationDate, artist):
        super().__init__(title, pages, publicationDate)
        self.artist = artist

    def get_artist(self):
        return f"Artist: {self.artist}"

    def __repr__(self):
        return (f"ComicBook({self.title}, {self.pages}, "
                f"{self.publicationDate}, {self.artist})")

class ReadingList:

    def __init__(self):
        self.list = []

    def add_book(self, book):
        """Add book to reading list"""
        self.list.append(book)

    def remove_book(self, book):
        """Remove book from reading list"""
        self.list.remove(book)

    def total_pages(self):
        """Returns total pages in reading list"""
        total = 0
        for book in self.list:
            total += book.pages
        return total

    def __repr__(self):
        return f"ReadingList({self.list})"

    def __str__(self):
        return f"Reading list of size {len(self.list)}"

# Initialise Library
library = Library()

# Create a few books
novel1 = Novel("Harry Potter", 500, 1991)
novel2 = Novel("LotR", 1000, 1960)
novel3 = Novel("Game of Thrones", 2000, 2018)
comic1 = ComicBook("Batman", 100, 2020, "Stan Lee")

# Add books to library.
library.add_book(novel1)
library.add_book(novel2)
library.add_book(novel3)
library.add_book(comic1)

# Create a new reading list.
readingListOne = ReadingList()

# Add a couple of books to reading list.
readingListOne.add_book(novel1)
readingListOne.add_book(comic1)


texts:
I have the code below to get an infinite generator of the products of an iterable (e.g. for the iterable "ABC" it should return

A, B, C, AA, AB, AC, BA, BB, BC, CA, CB, CC, AAA, AAB, AAC etc.

for product in (itertools.product("ABC", repeat=i) for i in itertools.count(0)):
    for each_tuple in product:
        print(each_tuple)

How would I remove the nested for loop, or is there a better approach?


texts:
I am trying to make a generic form parser for Javascript. The idea being, a developer could drop the function onto a form and sumbit via AJAX, or do something with a form besides submit it. The result will be in the same format used in a query string.

What I have posted works, so I am basically wondering if this is a good design? What could be improved? Thanks for the help!

function test_submit(id){
    var results=[],form=document.getElementById(id);
    for(var i=0;i<form.elements.length;++i){
        var obj=form.elements[i];
        if(obj.name&&!obj.disabled){
            switch(obj.tagName){
            case 'SELECT':
                for(var j=0;j<obj.length;++j){
                    if(obj.options[j].selected){
                        var value=obj.options[j].value;
                        if(!value)value=obj.options[j].text;
                        results.push(obj.name+'='+escape(value));
                    }
                }
                break;
            case 'INPUT':
            case 'TEXTAREA':
                var type=obj.type,value=obj.value;
                if(type)type=type.toLowerCase();
                if(type&&(type=='radio'||type=='checkbox')){
                    if(obj.checked)results.push(obj.name+'='+(value?escape(value):'on'));
                }
                else results.push(obj.name+'='+escape(value));
                break;
            }
        }
    }
    return results.join('&');
}


texts: Parsing a string with named sections and a key-value pair on each line

texts:
I have a response String as shown below which I need to parse it and store it my class. Format is shown below:

task name followed by this dotted line -------------  which is also fixed
and then just below key:value pair. It can have many key value pair

Below is the response string.

abc-------------
Load:79008
Peak:4932152

def-------------
Load:79008
Peak:4932216

ghi-------------
Load:79008
Peak:4874588

pqr-------------
Load:79008
Peak:4874748

Below is my class:

public class NameMetrics {

    private String name;
    private Map<String, String> metrics;

    // setters and getters

}

In the above class, name should be abc and metrics map should have Load as the key and 79008 as the value and same with other key:value pairs. Below is the code I have.

String response = restTemplate.getForObject(url, String.class);
BufferedReader reader = new BufferedReader(new StringReader(response));
NameMetrics current = null;
Map<String, String> metricsHolder = null;
List<NameMetrics> result = new ArrayList<>();
while (true) {
  String s = reader.readLine();
  if (s == null) {
    break;  // end reached
  }
  if (s.trim().isEmpty()) {
    continue;  // Skip empty line
  }
  int cut = s.indexOf(':');
  if (cut == -1) {
    cut = s.indexOf('-');
    if (cut == -1) {
      continue;
    }
    metricsHolder = new HashMap<String, String>();
    current = new NameMetrics();
    current.setName(s.substring(0, cut));
    result.add(current);
  } else if (current != null) {
    metricsHolder.put(s.substring(0, cut), s.substring(cut + 1));
    current.setMetrics(metricsHolder);
  }
}

I'd like a code review to see whether this can be improved in any way?


texts:
I'm reading this very good book, C# Player's Guide, to learn C#. I then plan to make video games with Unity 3D after.

In one of the chapters, he asks us to make a (really) simple calculator as a console application using the switch statement:

  The program that we’ll make is going to be a simple calculator. We’re
  going to ask the user to type in two numbers and then type in a math
  operation to perform on the two numbers.

  Use a switch statement to handle the different operations in different
  ways. Allow the user to type in ’+’ for addition, ’-’ for subtraction,
  ’*’ for multiplication, ’/’ for division, and ’%’ for remainder.

What do you think of my first program? Is it well-formatted and well-written?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleCalculator
{
  class Program
  {
    static void Main(string[] args)
    {
        //use for the string operation choice
        int operation = 0;
        //stock the result of the operation
        double result = 0;

        //Ask user first number
        Console.WriteLine("Type you first number :");
        string stringFirstNumber = Console.ReadLine();
        double firstNumber = Convert.ToDouble(stringFirstNumber);

        //Ask user second number
        Console.WriteLine("Type you second number :");
        string stringSecondNumber = Console.ReadLine();
        double secondNumber = Convert.ToDouble(stringSecondNumber);

        //Ask user operation to use
        Console.WriteLine("Enter the operation + (addition), - (soustraction), * (multiplication), / (division), ^ (exposant) or % (reste) :");
        string stringOperation = Console.ReadLine();

        // Convert string choice to integral
        if (stringOperation == "+" || stringOperation == "addition")
        {
            operation = 1;
        }
        else if (stringOperation == "-" || stringOperation == "soustraction")
        {
            operation = 2;
        }
        else if (stringOperation == "*" || stringOperation == "multiplication")
        {
            operation = 3;
        }
        else if (stringOperation == "/" || stringOperation == "division")
        {
            operation = 4;
        }
        else if (stringOperation == "^" || stringOperation == "exposant")
        {
            operation = 5;
        }
        else if (stringOperation == "%" || stringOperation == "reste")
        {
            operation = 6;
        }

        //Do someting depending on the operation choose
        switch (operation)
        {
            case 1:
                result = firstNumber + secondNumber;
                break;

            case 2:
                result = firstNumber - secondNumber;
                break;

            case 3:
                result = firstNumber * secondNumber;
                break;

            case 4:
                result = firstNumber / secondNumber;
                break;

            case 5:
                result = Math.Pow(firstNumber, secondNumber);
                break;

            case 6:
                result = firstNumber % secondNumber;
                break;
        }
        Console.WriteLine("\nResult of " + firstNumber + " " + stringOperation + " " + secondNumber + " = " + result + ".");
        Console.ReadKey();
    }
  }
}


texts: How to speed up interval lookup for a piecewise defined function?

texts:
At the innermost loop of my software is a lookup of a function value from a piecewise defined function with interpolation between the sample points.

Illustration:

*                                                *
   *                               *
          *      *
|--|------|------|--------X---------|-------------|

There are several different interpolation methods in between the sample points.

My current implementation consists of two arrays, one for the interval endpoints and one for the function values. Searching is done via std::upper_bound if the array is large and find_if if the arrays are small. Based on the access patterns the speed improved tremendously by adding a cache value for the previous positions interval and checking if it is still valid for the new position

[1%] if (x >= *cache && x < *(cache + 1)) {
    outside = false;
    position = cache;
} else if (x < *begin || x > *end) {
    outside = true;
} else {
    outside = false;

    if (n_ < 64) {
[3%]    position = std::find_if(begin, end, std::bind2nd(std::greater_equal<argument_type>(), x)) - 1;
    } else {
        position = std::upper_bound(begin, end, x) - 1;
    }
    cache = position ;
}

The lookup currently still takes about 5% of total execution time, which seems too much.
I have indicated costs of the most expensive lines which is the comparison with the cached position [1%] and the linear search [3%].

Is there a faster way to lookup the interval which contains X?

Edit

I have included the switch after profiling since Linear search can faster for small arrays (and there are a lot of small arrays).

Edit
It seems the std::find_if implemenation is actually faster than binary search after all.
I have made a test here: http://ideone.com/Fo5ZeW

#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;

double* binary_search8(double* arr, const double& x)
{
  if (x<arr[4]) {
    if(x<arr[2]) {
      if(x<arr[1]) {
        return arr;
      } else {
        return arr + 1;
      }
    }
    else { //2..3
      if(x<arr[3]){
        return arr + 2;
      } else {
        return arr + 3;
      }
    }
  } else { // 4..7
    if(x<arr[6]) {
      if(x<arr[5]) {
        return arr + 4;
      } else {
        return arr + 5;
      }
    } else { //6..7
      if(x<arr[7]) {
        return arr + 6;
      } else {
        return arr + 7;
      }
    }
  }
}

double* binary_search16(double* arr, const double& x)
{
    if (x<arr[8]) return binary_search8(arr, x);
    else return binary_search8(arr+8, x);
}

int main() {
double test[16] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150};

  vector<double> test_vals;
  size_t num_elem = 10000000;
  for (size_t i=0; i<num_elem; i++)
    test_vals.push_back(rand()%150);

  clock_t begin, end;
  double elapsed_secs;

  // Linear search
  double linavg = 0;
  begin = clock();
  for (size_t i=0; i<num_elem; i++) {
    linavg += *(find_if(test, test+16, bind2nd(std::greater_equal<double>(), test_vals[i]))-1);
  }
  end = clock();
  elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  cout << "linear secs: " <<elapsed_secs << ", testval = " << linavg << std::endl;

  // Binary search
  double binavg = 0;
  begin = clock();
  for (size_t i=0; i<num_elem; i++) {
    binavg += *binary_search16(test, test_vals[i]);
  }
  end = clock();
  elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  cout << "binary secs: " <<elapsed_secs << ", testval = " << binavg << std::endl;

  // Binary search 2
  double binavg2 = 0;
  begin = clock();
  for (size_t i=0; i<num_elem; i++) {
    binavg2 += *(std::upper_bound(test, test+16, test_vals[i])-1);
  }
  end = clock();
  elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  cout << "binary2 secs: " <<elapsed_secs << ", testval = " << binavg2 << std::endl;

  return 0;
}


texts: Sending device data of 10k items with Parallel.ForEach

texts:
I have a deviceList of more than 10k items and want to send data by calling another method.

I tried to use Parallel.Foreach but I'm not sure is this the correct way to do it.

I have published this webapp on azure,
I have tested this for 100 it works fine but for 10k it got timeout issue.

  This is working code , I need a improvement here :)

private List<Task> taskEventList = new List<Task>();
public async Task ProcessStart()
{
    string messageData = "{\"name\":\"DemoData\",\"no\":\"111\"}";
    RegistryManager registryManager;

    Parallel.ForEach(deviceList, async (device) =>
    {
        // get details for each device and use key to send message
        device = await registryManager.GetDeviceAsync(device.DeviceId);
        SendMessages(device.DeviceId, device.Key, messageData);
    });

    if (taskEventList.Count > 0)
    {
        await Task.WhenAll(taskEventList);
    }
}

private void SendMessages(string deviceId, string Key, string messageData)
{
    DeviceClient deviceClient = DeviceClient.Create(hostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);
    //created separate Task
    var taskEvents = Task.Run(() => ProcessMessages(deviceId, string messageData));
    taskEventList.Add(taskEvents);
}

private async Task ProcessMessages(string deviceId, string messageData)
{
    var startTime = DateTime.UtcNow;
    while (DateTime.UtcNow - startTime < TimeSpan.FromMinutes(15))
    {
        await deviceClient.SendEventAsync(messageData);
    }
}


texts: Proper imports and exports for nodejs and the browser

texts:
The Library is meant to be re-used for both the browser and the nodejs runtime environment, publishing this code for a code review to make it better and concise.
Question: How to build a library in an elegant way that's usable on both platforms, Browser Landscape and NodeJS runtime environment.
Following implementation takes care of that, but seeking for any room for improvement.

Import
nodeJS convenience_product.js
let MyLib;

// import for either browser and the nodeJS
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    MyLib = require("../dist/mylib");
} else {
    MyLib = window.MyLib;
}

class ConvenienceProduct extends MyLib.Product {

    constructor() {
        console.log("Hello ConvenienceProduct");
    }
}

Browser index.html
<head>
    <script src="../dist/mylib.js"></script>
    <script src="convenience_product.js"></script>
</head>

Export
nodeJS + Browser dist/mylib.js
"use strict";

(() => {  // using IIFE to avoid polluting browser namespace

    /** @class MyLib.Product **/ // this helps in code hinting
    class Product {
    }

    let MyLib = {
        Product: Product
    }

    if (typeof window !== "undefined") {
         window.MyLib = MyLib;
    } else {
         module.exports = MyLib;
    }

})();


texts: Throwing an exception within a try/catch block in PHP

texts:
Is there a cleaner way to do this?

    try {
        $ffprobe      = FFProbe::create();
        $streams      = $ffprobe->streams($infile);
        $videoStreams = $streams->videos();
        $audioStreams = $streams->audios();

        if (!$videoStreams) {
            throw new Exception("Could not find a video stream for file: " . $infile . PHP_EOL);
        }

    } catch (RuntimeException $e) {
        throw $e;
    }


texts:
I wrote the following code for move a box to right and return it to left, and repeat this action forever.

This code works, but is there a better solution?

function move(){
 let box = document.getElementById("box");
 if(box.style.left.replace("px","") < 180 && check == true){
   moveRight(box);
  }else if (box.style.left.replace("px","") == 180 || check == false)
    {

      if(box.style.left.replace("px","") > 0){
          check = false;
          moveleft(box);
      }else if (box.style.left.replace("px","") == 0){
            check = true;
        }
    }
}
function moveRight(box){
   if(box.style.left != ""){
     let temp = box.style.left.replace("px","");
     temp = parseInt(temp);
     box.style.left = temp+1+"px";
   }else{box.style.left = "1px";}
}
function moveleft(box){
   if(box.style.left != ""){
     let temp = box.style.left.replace("px","");
     temp = parseInt(temp);
     box.style.left = temp-1+"px";
   }else{box.style.left = "1px";}
}
var check = true;
setInterval(move,10);
#plan{
        width: 200px;
        height: 200px;
  background: #00C0FF;
        position: relative;
 }
 #box{
     width: 20px;
  height: 20px;
  background: red;
        position: absolute;

}
<!DOCTYPE html>


texts:
Below are two promises: the first does a bit of nesting and the second is all anon then calls that return one function in them. Which do you prefer? Any improvements?

Promise A:

fsRedux.ensureLink = function(srcPath, dstPath){
  dstPath = fsRedux.predictDir(srcPath, dstPath)
  var dstDir = path.dirname(dstPath)
  return fsRedux.exists(dstPath).then(function(exist){
    if(!exist){
      return fsExtra.mkdirsAsync(dstDir).then(function(){
        return fsExtra.linkAsync(srcPath, dstPath)
      })
    }
    return false
  })
}

Promise B:

fsRedux.ensureLink = function(srcPath, dstPath){
  dstPath = fsRedux.predictDir(srcPath, dstPath)
  var dstDir = path.dirname(dstPath)
  return fsRedux.exists(dstPath).then(function(exists){
      return fsRedux.ifFalseThrow(exists, false, new Error(dstPath+" exists cannot ensure link"))
    }).then(function(){
      return fsExtra.mkdirsAsync(dstDir)
    }).then(function(){
      return fsExtra.linkAsync(srcPath, dstPath)
    })
}


texts:
I'm seeking code review comments for the following implementation.

jsFiddle

/**
* You need to run a number of async tasks, but you're being rate limited.
* Run as many concurrent tasks as you can, queueing the rest for when the
* tasks are complete.
*/

/**
* @param concurrency: number of concurrent tasks that can be run
*/
var ConcurrencyQueue = function (concurrency) {
    this.concurrency = concurrency;
    this.queue = [];
    this.count = 0;
};

/**
* add an asynchronous task to the queue. it will get executed immediately
* until the concurrent task count reaches this.concurrency. then, queue it until
* tasks are complete.
* @param task: function which takes a callback argument (done)
*/
ConcurrencyQueue.prototype.enqueue = function (task) {
    var self = this;
    self.count = self.count + 1;

    var done = function () {
        self.count = self.count - 1;
        if (self.queue.length) {
            self.queue.splice(0, 1)[0](done);
        }
    };

    if (self.count > self.concurrency) {
        self.queue.push(task);
    }

    if (self.count <= self.concurrency) {
        task(done);
    }
};

/**
 * tasks passed to concurrency queue are async and call the callback "done"
 * after they complete.
 */

function exampleTask (done) {
    console.log('started');
    setTimeout(function () {
        console.log('completed');
        done();
    }, Math.floor(Math.random() * 2000));
};

var queue = new ConcurrencyQueue(2);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);


texts:
I am only a beginner when it comes to programming, but after reading tons of tutorials on and offline, I have been able to create this simple math quiz. It does work as intended, and I'm really just fishing for someone to yell at me for doing something glaringly bad practice in the code below.

using System;

namespace ForthConsoleProject
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Random randomgen = new Random();

            //int timer = 30; I considered a timer function but that ended up being way over my head.
            int num01 = randomgen.Next(11);
            int num02 = randomgen.Next(11);
            int playeranswer;
            int answer;
            int numofquestions;
            int numofquestionsleft;
            int numofcorrect = 0;

            Console.Write("How many questions would you like to answer? ");
            numofquestions = Convert.ToInt32(Console.ReadLine());
            numofquestionsleft = numofquestions;

            // This is the loop which handles the actual question/answer core of the game.
            // Answering a question correctly increases your score.
            while (numofquestionsleft > 0){

                Console.Write("What is " + num01 + " times " + num02 + "? ");
                answer = num01 * num02;
                playeranswer = Convert.ToInt32(Console.ReadLine());
                if (answer == playeranswer)
                {
                    Console.WriteLine(playeranswer + " is correct!");
                    numofcorrect++;
                }
                else {
                    Console.WriteLine(playeranswer + " is incorrect! Try again.");
                }
                Console.ReadKey();
                numofquestionsleft--;
                num01 = randomgen.Next(11);
                num02 = randomgen.Next(11);
            }
            // Letting the user know how many answers they got right.
            Console.WriteLine("You got " + numofcorrect + " of " + numofquestions + " correct!");
            Console.ReadKey();

        }
    }
}


texts: JavaFX lazy loading of images in TableView

texts:
This code is based off https://stackoverflow.com/questions/25711103/javafx-combobox-lazy-loading-images but modified to work with a TableCell

Firstly, the model object should have an observable File property which represents the image to load.

We need some background executors

ExecutorService exec = Executors.newCachedThreadPool();

Then in the initializer:

TableColumn<Model, File>= new TableColumn<>("");
colImage.setPrefWidth(64);
colImage.setCellFactory(param -> {

    //Set up the ImageView
    final ImageView imageview = new ImageView();
    imageview.fitWidthProperty().bind(Bindings.subtract(colImage.widthProperty(), 7));
    imageview.setPreserveRatio(true);

    //Loading task
    ObjectProperty<Task<Image>> loadingTask = new SimpleObjectProperty<>();

    //Set up the Table
    TableCell<Model, File> cell = new TableCell<Model, File>() {
        @Override
        public void updateItem(File item, boolean empty) {
            //Stop already running image fetch tast
            if (loadingTask.get() != null &&
                    loadingTask.get().getState() != Worker.State.SUCCEEDED &&
                    loadingTask.get().getState() != Worker.State.FAILED) {

                loadingTask.get().cancel();
            }
            loadingTask.set(null);
            //Load image if not null
            if (empty || item == null) {
                imageview.setVisible(false);
            } else {
                imageview.setVisible(true);
                Task<Image> task = new Task<Image>() {
                    @Override
                    public Image call() throws Exception {
                        System.out.println("fetch image");
                        Image image = SwingFXUtils.toFXImage(ImageIO.read(item), null);
                        return image;
                    }
                };
                loadingTask.set(task);
                task.setOnSucceeded(event -> {
                    imageview.setImage(task.getValue());
                    System.out.println("got image");
                });
                exec.submit(task);
            }
        }
    };
    // Attach the imageview to the cell
    cell.setGraphic(imageview);
    return cell;

});
colImage.setCellValueFactory(cellData -> cellData.getValue().fileProperty());
tableView.getColumns().add(0, colImage);

How it works:

When the file property is updated the updateItem method spawns a Task that loads the image and updates the ImageView. However, TableCells are reused and thus an image might be still loading when updateItem is called again. To prevent this, the Task for that TableCell is stored in a property, and cancelled if it is still running when updateItem is called again.


texts:
I'm working on a simple statistics problem with Pandas and sklearn. I'm aware that my code is ugly, but how can I improve it?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression

df = pd.read_csv("sphist.csv")
df["Date"] = pd.to_datetime(df["Date"])
df.sort_values(["Date"], inplace=True)
df["day_5"] = np.nan
df["day_30"] = np.nan
df["std_5"] = np.nan

for i in range(30, len(df)):
    last_5 = df.iloc[i-5:i, 4]
    last_30 = df.iloc[i-30:i, 4]
    df.iloc[i, -3] = last_5.mean()
    df.iloc[i, -2] = last_30.mean()
    df.iloc[i, -1] = last_5.std()

df = df.iloc[30:]
df.dropna(axis=0, inplace=True)

train = df[df["Date"] < datetime(2013, 1, 1)]
test = df[df["Date"] >= datetime(2013, 1, 1)]
# print(train.head(), test.head())

X_cols = ["day_5", "day_30", "std_5"]
y_col = "Close"

lr = LinearRegression()
lr.fit(train[X_cols], train[y_col])
yhat = lr.predict(test[X_cols])
mse = mean_squared_error(yhat, test[y_col])
rmse = mse/len(yhat)
score = lr.score(test[X_cols], test[y_col])

print(rmse, score)

plt.scatter(yhat, test[y_col], c="k", s=1)
plt.plot([.95*yhat.min(), 1.05*yhat.max()], [.95*yhat.min(), 1.05*yhat.max()], c="r")
plt.show()

It relies on hard-code iloc indices, which is hard to read or maintain. How can I change it to column names/row names?
The codes look messy. Any advice to improve it?


texts:
Just because I've never written a real Sieve of Eratosthenes, I decided I should probably write one just to make sure I know what it is.  I'd like (constructive) criticism on best practices, potential problems, and anything else you see fit:

static int GetNthPrime(int n)
{
    List<int> primes = new List<int>() { 2, 3 };

    int potentialPrime = 5;

    while (primes.Count < n)
    {
        int squareRootPotentialPrime = (int)Math.Sqrt(potentialPrime);

        for (int i = 1; i < primes.Count; i++)
        {
            if (potentialPrime % primes[i] == 0)
            {
                break;
            }

            if (primes[i] > squareRootPotentialPrime)
            {
                primes.Add(potentialPrime);
                break;
            }
        }
        potentialPrime += primes[0];
    }

    return primes[n - 1];
}


texts:
I have made an any class in C++, base loosely on boost::any, but written differently. I am checking to see if I have done it correctly and that there are no mistakes in it:

class any
{
public:
    any()
        : dt(new data<void *>(0))
        {
        }

    template<class T>
        any(const T &value)
        : dt(new data<T>(value))
        {
        }

    any(any &rhs)
        : dt(rhs.dt->duplicate())
        {
        }

    ~any()
        {
        delete dt;
        }

    template<class T>
        T cast() const
        {
        if (type() == typeid(T))
            {
            return (reinterpret_cast<data<T> *>(dt)->val);
            }
        throw std::exception("invalid cast type");
        }

    template<class T>
        operator T() const
        {
        return (cast<T>());
        }

    template<class T>
        bool is() const
        {
        return (type() == typeid(T));
        }

    any &operator=(any &rhs)
        {
        if (this != &rhs)
            {
            delete dt;
            dt = rhs.dt->duplicate();
            }
        return (*this);
        }

    template<class T>
        any &operator=(const T &value)
        {
        delete dt;
        dt = new data<T>(value);
        return (*this);
        }

    any &swap(any &rhs)
        {
        std::swap(dt, rhs.dt);
        return (*this);
        }

    template<class T>
        bool operator==(const T &value) const
        {
        return (type() == typeid(T) &&
            cast<T>() == value);
        }

    bool operator==(any &rhs) const
        {
        return (type() == rhs.type() &&
            dt->cmp(rhs.dt));
        }

    template<class T>
        bool operator!=(const T &value) const
        {
        return (!((*this) == value));
        }

    bool operator!=(any &rhs) const
        {
        return (!((*this) == rhs));
        }

    const std::type_info &type() const
        {
        return (dt->type());
        }

protected:
    struct dummy
        {
    public:
        virtual const std::type_info &type() const = 0;
        virtual bool cmp(dummy *rhs) const = 0;
        virtual dummy *duplicate() = 0;
        };

    template<class T>
        struct data
            : public dummy
        {
    public:
        data()
            : val()
            {
            }

        data(const T &value)
            : val(value)
            {
            }

        ~data()
            {
            }

        const std::type_info &type() const
            {
            return (typeid(T));
            }

        bool cmp(dummy *rhs) const
            {
            return (val == reinterpret_cast<data<T> *>(rhs)->val);
            }

        dummy *duplicate()
            {
            return (new data<T>(val));
            }

        T val;
        };

    dummy *dt;
    };


texts:
I have this Excel macro I created to highlight all instances of a number if at least one instance is already highlighted before running the macro.

Sub highlightXIDs()
    Dim prods As Object: Set prods = CreateObject("Scripting.Dictionary")
    Dim lastRow As Long: lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    Dim tRange As Range

    For Each tRange In ActiveSheet.Range("A2:A" & lastRow)
        If tRange.Interior.ColorIndex <> xlNone Then prods.Add Key:=tRange.Value, Item:=tRange.Interior.Color
    Next

    Dim prod As Variant, xidMap As Object
    Set xidMap = getXidMap(ActiveSheet.Range("A2:A" & lastRow))
    For Each prod In prods.keys
        xidMap(prod).EntireRow.Columns("A").Interior.Color = prods.Item(prod)
    Next prod
End Sub

'get a "map" of each unique xid value to the rows containing it
Function getXidMap(rng As Range) As Object
    Dim rv As Object, c As Range, currVal, cStart, i, tmp
    Set rv = CreateObject("scripting.dictionary")
    For Each c In rng.Cells
        tmp = c.Value
        If Len(tmp) > 0 Then
            If rv.exists(tmp) Then
                Set rv(tmp) = Application.Union(c, rv(tmp))
            Else
                rv.Add tmp, c
            End If
        End If
    Next c
    Set getXidMap = rv
End Function

Before:

After:

Is this an efficient use of the included vba objects or should I change something?
For the line where I check the cell color, which would be more accurate/efficient in finding any cell that has fill color (excluding conditional formatting):

.Interior.ColorIndex <> xlNone

Or

.Interior.Color <> -4142

Or would these both work the same with the same amount of accuracy?


texts:
I've written this a short time ago. Do you see anywhere I can improve my logic? This is my first python script.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from ftplib import FTP  # ftplib comes with the py install

class Ftp:

    def __init__(self, hostname, username, password, port=21):

        print '\nConnecting to %s on port %d' % (hostname, port)

        ftp = FTP()

        try:
            ftp.connect(hostname, port)
        except:
            raise Exception('\n\nConnection failed: %s:%d' % (hostname, port))

        try:
            ftp.login(user=username, passwd=password)
            self.start = ftp.pwd()

            print 'Login Successful: %s\n' % username
        except:  # ftplib.error_perm
            raise Exception('\n\nAuth: \n%s@%d\n\n' % (hostname, username))

        self.ftp = ftp
        self.hostname = hostname

    def end(self):
        try:
            self.ftp.quit()
        except:
            pass
        print '\n\nConnection to %s has been closed\n' % self.hostname

    def ls(self):
        return self.ftp.nlst()

    def get(self, file):
        return self.ftp.retrbinary(
            'RETR ' + file, open('%s/%s' % (self.hostname, file), 'wb').write)

    def cwd(self, file):
        return self.ftp.cwd(file)

    def pwd(self):
        return self.ftp.pwd()

    def download(self):
        print 'Downloading Files:'
        self._dl()
        print '\nAll Files Downloaded'
        self.end()

    def _dl(self, changedir='/'):

        if changedir is not '/':
            self.cwd(changedir)
        current = self.pwd()
        folders = []
        files = self.ls()

        for file in files:
            try:
                self.cwd(file)
                if current is not '/':
                    path = '%s%s/%s' % (host, current, file)
                else:
                    path = '%s%s%s' % (host, current, file)
                if not os.path.exists(path):
                    os.makedirs(path)
                    if path != '%s/.' % host:
                        folders.append(path)

                self.cwd(current)
            except:
                if current is not '/':
                    self.get('%s/%s' % (current, file))
                else:
                    self.get('%s' % file)
                print '    %s' % file
        try:
            for fold in folders:
                print '  /%s' % fold
                self._dl(fold.replace(host, ''))
        except:
            pass

Usage:

hosts = ['domain01.com', 'domain02.com']
user = 'username'
password = 'secr3t'

for host in hosts:
    Ftp(host, user, password).download()

I tried to make it as PEP8 compliant as it can be. It is a short file and straightforward. I need better commenting.


texts: Normalize Sparse Matrix along rows in C++ Eigen

texts:
I wrote a function to normalize sparse matrix along rows using C++ Eigen; however, I feel that it can be improved, and that I am not using some built in functions of Eigen.

#include <iostream>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <vector>
#include <math.h>

using namespace Eigen;

std::vector<double> get_weights(SparseMatrix<double, RowMajor> sm);
SparseMatrix<double, RowMajor> row_normalize(SparseMatrix<double, RowMajor> sm);

int main()
{
  MatrixXd silly(6, 3);

  silly << 0, 1, 36,
           0, 3, 0,
           0, 0, 0,
           3, 2, 1,
           0, 1, 0,
           2, 0, 9;

  SparseMatrix<double, RowMajor> sparse_silly = silly.sparseView();

  SparseMatrix<double, RowMajor> normalized = row_normalize(sparse_silly);
  std::cout << "normalized" << std::endl;
  std::cout << normalized << std::endl;

  SparseMatrix<double, RowMajor> test = normalized * normalized.transpose();
  // Checking that all diagonal elements of non-zero rows are 1
  std::cout << "test" << std::endl;
  std::cout << test << std::endl;

  return 0;
}

SparseMatrix<double, RowMajor> row_normalize(SparseMatrix<double, RowMajor> sm)
 {
   std::vector<double> weights = get_weights(sm);
   SparseMatrix<double, RowMajor> sm_weights(sm.rows(), sm.rows());
   for(int i = 0; i < weights.size(); ++i)
     {
       sm_weights.insert(i,i) = weights[i];
     }

   return sm_weights * sm;
 }

std::vector<double> get_weights(SparseMatrix<double, RowMajor> sm)
{
  std::vector<double> weights;
  for (int i = 0; i < sm.rows(); ++i)
    {
      double my_sum = 0;
      double *val_ptr = sm.row(i).valuePtr();

      if(sm.row(i).nonZeros())
        // avoid division by zero problem
        {
          for (int j = 0; j < sm.row(i).nonZeros(); ++j)
            {
              my_sum += (*val_ptr * (*val_ptr));
              val_ptr++;
            }
          weights.push_back(1.0 / sqrt(my_sum));
        }
      else
        {
          weights.push_back(0);
        }
    }
  return weights;
}


texts:
The common lisp function copy-tree is often implemented in a recursive way,
and thus is prone to stack overflow.

Here is my attempt at writing an iterative version, one-pass, no stack,
no unnecessary consing, version of copy-tree in common-lisp, working
with nested, perhaps dotted, lists.

 (defun my-copy-tree (tree)
     (do* ((result (list tree))
           (node result)
           (next))
          ((null node) result)
       (cond ((and (consp (cdar node))(atom (caar node)))
              (setf (cdr node) (cons (cdar node) (cdr node))
                    (car node) (caar node)
                    node (cdr node)))
             ((consp (cdar node))
              (setf (cdr node) (cons (cdar node) (cdr node))
                    (car node) (cons (caar node) (cdr node))
                    node (car node)))
             ((consp (caar node))
              (setf (car node) (cons (car node) (cdr node))
                    (cdr node) (cdaar node)
                    node (car node)
                    (car node) (caar node)))
             (t (setf next (cdr node)
                      (cdr node) (cdar node)
                      (car node) (caar node)
                      node next)))))

The performance is ok. In fact, on sbcl it is faster than the
native implementation, and almost as fast as copy-list for proper lists.
It also has no problem making copies of "reversed" lists like the one given by

(reduce 'cons (make-list 1000000 :initial-element 0))

(by the way, are there any lisp implementation with a native copy-tree
 that does not stack-overflow on these kind of deep lists ?)

Unfortunately, my code is unreadable, and I must say I can't really understand
it now without drawing a whole page of cons cells. Also it is not very flexible,
e. g. there is no obvious way to turn it into a reduce-tree, in contrast
to the recursive version.

How to rewrite the code above in a more readable and flexible way, and
so to speak in a more lispy way, without losing performance ?

Writing an efficient implementation of copy-tree in lisp should be a standard exercice but google didn't bring anything relevant.


texts:
I recently asked to use eval() for a module function. Now I ended up doing a very weird function which does what I want. I like the idea I made it but I'm not so sure if this is state of the art, or more, good to build an application on.

index.html:

<script src="module.js"></script>

<script>

require('alert');

bam(); // 9
</script>

module.js:

(function () {

    var require = window.require = function (fnName) {

        var dependencies = fnName.split(' '); // load multiple dependencies etc. (not nessecairy now)

        // REAL CASE WOULD BE, TO LOAD A .JS FILE INTO A STRING VAR
        var code = 'var bam = function() { var x = 1; var y = 2; var z = (x+y)*3; alert(z); }';

        return (function () {
            window.eval(code);
        })();
    }
})();

Is this a good solution for a require function like in PHP if I only load and eval() files made by me?


texts: How to re register dynamic scripts registered with ClientScriptManager in asp dot net using session was bad idea

texts:
Following the normal pattern of adding inline scripts to gridview row/s is a bad practice it used to work like below

 protected void CustomersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.DataRow:
                DataRowView drv = (DataRowView)e.Row.DataItem;
                if (drv != null)
                {
                    string sKey = drv["Id"].ToString();                                e.Row.Attributes.Add("onclick","location.href='manage.aspx?="+sKey+"'");
                }
                break;
        }
    }

hence i switched over to event registration pattern which worked like below

protected void CustomersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                StringBuilder _sbDynamicScript = new StringBuilder();
                _sbDynamicScript.AppendLine("Sys.Application.add_load(function(){");
                _sbDynamicScript.AppendLine("try{");
                break;
            case DataControlRowType.DataRow:
                DataRowView drv = (DataRowView)e.Row.DataItem;
                if (drv != null)
                {
                    string sKey = drv["Id"].ToString();
                    e.Row.Attributes.Add("id", randomNumber);
                    _sbDynamicScript.AppendLine("if($get('" + randomNumber + "'))$addHandler($get('" + randomNumber + "'),'click',function(evnt){location.href='manage.aspx?id='="+ sKey +"'})");
                }
                break;
            case DataControlRowType.Footer:
                _sbDynamicScript.AppendLine("}catch(err){alert(err.message)}})");
                if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), "customerapp"))
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "customerapp", _sbDynamicScript.ToString(), true);
                }
                Session["clientScript"] = _sbDynamicScript.ToString();
                break;
        }
    }

notice rowType is used to create dynamic script. Here's something that's happening up there

1.add a random number as ID for the gridview row

2.then add a click event handler using the asp.net ajax

make the make navigate away on click

Bug's ahoy:

Notice that in footer template i have put that script into session, that was my mistake. You see the scripts registered using registerstartup script are not persisted on postbacks and have to be re-registered. i have put a check on PageLoad to do below

 if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), ""))
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "customerapp", Session["clientScript"].ToString(), true);
            }

  notice the script is registered from
  session!! Well it happens some times
  that the Gridview records are changed
  by postback. But since session has
  already the key in it, the
  rowdatabound event script fails to get
  registered with new script. So what do
  i do in this situation. Can i get some
  other way to persist the script and
  make it run whenever gridview binds
  again

btw the script registered will look like below

Sys.Application.add_load(function () {
    try {
        if ($get('ElSxrM4myH4%3d')) {
            $addHandler($get('ElSxrM4myH4%3d'), 'click', function (evnt) {})
        }
    } catch (err) {
        alert(err.message)
    }
})


texts: Forming combinations of a 16 bit binary number

texts:
I wrote this code to form combinations of a 16 bit binary number (I know it is in output is string format, but it is my goal to just print all possible 16 bit binary numbers). My question is, can this code be optimized? How can I calculate the time complexity of this code?

public class Combinations {

    static int len;

    public static void formCombinations(StringBuilder start,String[] possible)
    {
        if(start.length()==len)
        {
            System.out.println(start);
            return;
        }
        for(int i=0;i<possible.length;i++)
        {
            formCombinations(start.append(possible[i]), possible);
            start.deleteCharAt(start.length()-1);
        }
    }

    public static void formCombinations(int len,String[] a) {
        Combinations.len=len;
        formCombinations(new StringBuilder(""), a);
    }

    public static void main(String[] args) {
        String a[]={"0","1"};
        formCombinations(16, a);
    }
}


texts:
I decided to strengthen my "vanilla JavaScript" skills since I've lately been getting more into jQuery and just discovered the potential of node.js.

As a result, I decided to make a basic alarm clock in javascript and html. (Plus I needed an alarm clock).

Here's the Fiddle

// Load an alarm sound
    var sound = new Audio("http://www.freespecialeffects.co.uk/soundfx/sirens/alarm_01.wav");
    sound.loop = true;

// I just made this because It's easier to read.
getID = function(value){ return document.getElementById( value ); };

// List of all my objects im working with, and variables
var hour = getID("hour"),
    minute = getID("minute"),
    second = getID("second"),
    aHour = getID("aHour"),
    aMinute = getID("aMinute"),
    aSecond = getID("aSecond"),
    aSwitch = getID("aSwitch"),
    aOff = getID("turnOff"),
    refreshTime = 500,
    alarmTimer = null;

aSwitch.On = false;
aSwitch.value = "OFF";

// Turns the alarm off or on
function alarmSwitch(){
    switch( aSwitch.On )
    {
        case false:
            aSwitch.On = true;
            aSwitch.value = "ON";

            alarmSet();
        break;
        case true:
            aSwitch.On = false;
            aSwitch.value = "OFF";

            // CLEARS THE BEEPER
            clearTimeout( alarmTimer );
        break;
    }
}

// Stops the alarm and closes the "stop button"
function disableAlarm(){
    sound.pause();
    aOff.style.display = "none";
}

//Fires the BEEPER noise, -- this is called from the alarmTimer timeout
function alarmFire(){
    if( aSwitch.On )
    {
        aOff.style.display = "block";
        sound.play();
    }
    else
        alert("error..");
}

/*This is how the beeper goes off:
 * It first checks the set time so the alarm can go to the
 * next day without the user putting the date in.
 * The beeper goes off over the span of milliseconds difference.
 */
function alarmSet(){
    clearTimeout( alarmTimer );

    var tomo = false;// tomorrow.
    if( aHour.value < hour.value )
        {tomo = true;}
    else if( aHour.value == hour.value && aMinute.value < minute.value )
        {tomo = true;}
    else if( aHour.value == hour.value && aMinute.value == minute.value
            && aSecond.value < second.value )
        {tomo = true;}

    var date = new Date(), year = date.getFullYear(), month = date.getMonth(), day = parseInt( date.getDate() );

    if( tomo ){day += 1;}

    time = new Date( year, month, day, aHour.value, aMinute.value, aSecond.value, date.getMilliseconds() );
    time = ( time - (new Date()) );

    // This turns the alarm back on if it's off when this function is called.
    if( aSwitch.On == false)
        alarmSwitch();

    alarmTimer = setTimeout( function(){alarmFire();} ,parseInt(time) );
}

// This is how the clock works
timeRefresh = function(){
    date = new Date();
    hour.innerHTML = date.getHours();
    hour.value = hour.innerHTML;
    minute.innerHTML = date.getMinutes();
    minute.value = minute.innerHTML;
    second.innerHTML = date.getSeconds();
    second.value = second.innerHTML;

    setTimeout("timeRefresh()", refreshTime);
};

// This is called whenever the inputs are changed to stop invalid forms.
numCap = function( obj, min, max){
    obj.value = Math.max(obj.min, Math.min(obj.max, obj.value) );

    alarmSet();// Starts up the alarm automatically when a value is changed.
};

window.onload=function(){
    timeRefresh();

    var a = getID("aHour");
    a.value = hour.innerHTML;
    a = getID("aMinute");
    a.value = minute.innerHTML;
    a = getID("aSecond");
    a.value = second.innerHTML;
};

I would love for some feedback on my code! What could I do to improve/simplify the code?

Also, if you would like to see the HTML page along with it, just ask!