texts: Mini school database with JS revealing module pattern

texts:
I tried the module pattern for the first time, with this exercise as a problem to solve: http://exercism.io/exercises/javascript/grade-school/readme

It's a small exercise requiring simple tasks :

  Add a student's name to the roster for a grade

  "Add Jim to grade 2."
  "OK."

  Get a list of all students enrolled in a grade

  "Which students
  are in grade 2?"
  "We've only got Jim just now."

  Get a sorted list of
  all students in all grades. Grades should sort as 1, 2, 3, etc., and
  students within a grade should be sorted alphabetically by name.

  "Who
  all is enrolled in school right now?"
  "Grade 1: Anna, Barb, and
  Charlie. Grade 2: Alex, Peter, and Zoe. Grade 3…"

This is the test suite (jasmine based) http://exercism.io/exercises/javascript/grade-school

This is my implementation with the revealing module pattern

function School () {
  var rosterDb = {};

  // Private
  var sort = function(gradeNumber) {
    return rosterDb[gradeNumber].sort();
  }

  // Public
  var roster = function() {
    for(var index in rosterDb) {
      sort(index);
    }
    return rosterDb;
  };

  var add = function(student, grade) {
    if (rosterDb[grade] == undefined) rosterDb[grade] = [];
    rosterDb[grade].push(student);
  };

  var grade = function(grade) {
    if (rosterDb[grade] != undefined) return sort(grade);
    else return rosterDb[grade] = [];
  };

  return {
    roster: roster,
    add: add,
    grade: grade
  };
}

module.exports = School;

I just had two objectives : 1/ make it pass all tests 2/ use the revealing module pattern. The first part is easy to verify, but the second one is harder. I would like some opinions on that


texts:
I created a simple class which serialises and deserialises Json and C# objects. How is it looking?

JsonHandler:

class JsonHandler
{
    public T GetObjFromJson<T>(string filePath)
    {
        T retObj = default(T);

        try
        {
            string jsonStr = string.Empty;
            if (File.Exists(filePath))
            {
                byte[] bytes = File.ReadAllBytes(filePath);
                jsonStr = Encoding.Default.GetString(bytes);
                if (!string.IsNullOrWhiteSpace(jsonStr))
                    retObj = JsonConvert.DeserializeObject<T>(jsonStr);
            }
        }
        catch (Exception ex)
        {
            string message = ex.Message;
        }

        return retObj;
    }

    public bool WriteObjAsJson(string filePath, object obj)
    {
        bool successfulWrite = false;

        try
        {
            string jsonString = JsonConvert.SerializeObject(obj);
            byte[] bytes = Encoding.Default.GetBytes(jsonString);
            File.WriteAllBytes(filePath, bytes);
            successfulWrite = true;
        }
        catch (Exception ex)
        {
            string message = ex.Message;
        }

        return successfulWrite;
    }
}

The main things I'm concerned about is the reading all bytes. I guessed that is the most bulletproof solution? Ideally I'd be using this as part of a PCL in a mobile application (Xamarin) in the near future.

class Program
{
    static void Main(string[] args)
    {
        string filePath = @"C:\Users\me\somewhere\textFile.txt";
        var d = new DummyClass("Danny");
        var handler = new JsonHandler();
        bool successfulWrite = handler.WriteObjAsJson(filePath, d);
        Console.WriteLine(successfulWrite);
        DummyClass returnObj = handler.GetObjFromJson<DummyClass>(filePath);
        if (returnObj != null)
            Console.WriteLine($"Name: {returnObj.Name}");
    }
}

class DummyClass
{
    private string _name;
    public string Name { get { return _name; } set { _name = value; } }

    public DummyClass(string name)
    {
        Name = name;
    }
}

I am only using the DummyClass for some quick testing purposes. Not so concerned with the above two classes, and I only included them to show an example of how the JsonHandler class will be used.


texts: Am I using Golang concurrency correctly to increase reliability?

texts:
This code takes text from the standard input, maps it to a struct (if possible), and creates a JSON string from that.

I'm using a barcode scanner for the input, and I've attempted to use goroutines to ensure that if something goes wrong with the parsing or JSON-marshalling, the program will continue to receive and process input from the scanner.

Am I doing this correctly, and am I doing it in the most effective, efficient, or idiomatic way?

Because all I care about for this post is the concurrency, I've left out all code that parses the input and creates JSON.  Additionally, the only thing I do with the JSON right now is print it back out.

Thanks for taking a look at this.

package main

import (
    "fmt"
    "status2/shoporder"
)

func main() {
    var input string
    for input != "exit" {
        fmt.Scanln(&input)
        ch := make(chan string)
        quit := make(chan bool)
        go parseInput(input, ch, quit)
        go sendJson(ch, quit)
    }
}

// Take the input and generate some JSON, then return it along a channel.
func parseInput(input string, ch chan string, quit chan bool) {
    // shoporder.Parse() uses regexp to validate the input, and returns a JSON string.
    son, ok := shoporder.Parse(input)
    if !ok {
        // If the input could not be parsed into JSON, then ignore and shut down
        // both goroutines.
        quit <- true
        return
    }
    ch <- son
}

// This will eventually send the JSON using websockets, but for now I just
// print it back out.
func sendJson(ch chan string, quit chan bool) {
    select {
    case json := <-ch:
        // For now I just print the JSON.
        fmt.Println(json)
    case <-quit:
        // I make sure to quit the goroutine, because I'm worried about creating a
        // bunch that never end and just hang around.  Do I need to do this?
        return
    }
}


texts:
This allows me to search each cell J4:J6525 in range K4:K6525. If it is found it will paste the values in Offset(0, 2) (column M).

I run it for files with more than 60000 lines, and sometimes much bigger. It takes a long time to complete. How can I make this run faster?

Sub Finder()

Dim WhereToSearch As Range, WhatToSearch As Range, ValueFound As Range, ValueSearched As Range

Set WhereToSearch = ActiveSheet.Range("K4:K6525")
Set WhatToSearch = ActiveSheet.Range("J4:J6525")

For Each ValueSearched In WhatToSearch

Set ValueFound = WhereToSearch.Find(What:=ValueSearched, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

If Not ValueFound Is Nothing Then

ValueFound.Offset(0, 2) = ValueFound

End If
Next
End Sub


texts:
Please review my code for printing a Christmas Tree.
The idea was to merge some functional programming ideas (immutability, streams) and OOP (every thing is a small object).

I'm looking for a review focused on readability of the code.

Here is a output from the code:

    *
   ***
  *****
 *******
*********

And the code:

fun main(a: Array<String>) {
    print(Tree(height = 5))
}

class Tree(val height: Int) {
    override fun toString(): String {
        return (0..height - 1)
                .map { i ->
                    Stage(i, height)
                }
                .joinToString(
                        separator = "\n",
                        postfix = "\n"
                )
    }
}

class Stage(val idx: Int, val height: Int) {
    override fun toString(): String {
        val trunkWidth = TrunkWidth(idx)
        val margin = Margin(MarginWidth(TreeWidth(height), trunkWidth).value())
        return listOf(
                margin,
                Trunk(trunkWidth.value()),
                margin
        ).joinToString(separator = "")
    }

}

class MarginWidth(val tree: TreeWidth, val trunk: TrunkWidth) {
    fun value(): Int {
        return (tree.value() - trunk.value()) / 2
    }
}

class TreeWidth(val height: Int) {
    fun value(): Int {
        return height * 2 - 1;
    }
}

class TrunkWidth(val idx: Int) {
    fun value(): Int {
        return 1 + 2 * idx
    }
}

class Trunk(val size: Int) {
    override fun toString(): String {
        return UniformString(size, "*").toString()
    }
}

class Margin(val size: Int) {
    override fun toString(): String {
        return UniformString(size, " ").toString()
    }
}

class UniformString(val size: Int, val char: String) {
    override fun toString(): String {
        return (0..size - 1)
                .map { char }
                .joinToString(separator = "")
    }
}


texts:
I have written an algorithm that generates a Fibonacci series to the \$Nth\$ number. The code below works fine, but as a beginner I know I must be writing pretty ugly code.

For example I think it is probably not good practice to declare and initialize the variables where I have, but I am confused about what would be the best place.

All comments and advice on code style etc. are welcome.

package algorithms;

import java.util.Scanner;

/**
* This class will generate a list of fibonacci numbers
* @author Richard
*
*/
public class FibonacciGenerator {

/**
 * This method will generate a list of fibonacci numbers
 * @param args
 */
public static void main(String[] args) {
    //declare vars and set initial values
    int number = 0, previousNumber = 0, twoNumbersAgo = 1;
    Scanner input = new Scanner(System.in);

    //prompt user for nth number
    System.out.println("Enter the n'th number for your Fibonacci series: ");

    //set loop counter equal to given nth number
    int n = input.nextInt();

    //loop through as many times as n
    for (int counter=1;counter<=n;counter++){

        //setting each new number in list equal to the sum of the previous two
        number = (previousNumber) + (twoNumbersAgo);

        //print out number
        System.out.print(number+" ");

        //change vars to be next two numbers
        twoNumbersAgo = previousNumber;
        previousNumber = number;
    }
    //close resources
    input.close();
}
}


texts: Finds a pattern in a string by returning index of where the pattern starts in the string in Java

texts:
This is the challenge I tried in Codefights: Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview. Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1. How can I make it faster? Thanks in advance. Here's my code, which is still slow for larger input cases(string of around 10^6 characters):

int findFirstSubstringOccurrence(String s, String x) {
   int j=0;
   for (int i=0; i<=(s.length()-x.length()); i++) {
       j=0;
       while ((j<x.length()) && s.charAt(i+j)==x.charAt(j)){
           j++;
       }
       if (j == x.length())
           return i;
       if(s.charAt(i+j)!=s.charAt(i))
           i += j;
   }
   return -1;
}


texts:
I created this program which runs with no error, but I'd like to have some comments if it is possible to optimize it, since I need to run the program with N = 3200. In this case it takes a lot of time to end. I left it running during the night to get the answer.

The math notation of the program:

\$
A = (a_{ij}) \space \text{is an} \space N \times N \space \text{matrix} \\
B = \text{max_prod(A)} \space \text{is an} \space N \times N \space \text{matrix where} \\
\space \space \space \space \space b_{ij} = \min\{\max(a_{ik}, b_{kj}); k = 1, \dots,N\}
\$

import numpy as np

def min_max(mat1, mat2, i, j):
    ''' this function takes 2 matrices and 2 indexes
    and return the minimum of the element wise maximum
    between row i of mat1 and col j of mat2 '''
    return min(np.maximum(mat1[i,:], mat2[:,j]))

def max_prod(mat1,mat2):
    ''' this function takes 2 matrices and return a new matrix
    where position (i,j) is min_max(mat1, mat2, i, j) '''
    n = len(mat1)
    my_prod = np.zeros((n,n), dtype=float)
    for i in range(n):
        for j in range(i,n):
            my_prod[i,j] = min_max(mat1,mat2,i,j)
            my_prod[j,i] = min_max(mat2,mat1,j,i)
    return my_prod

N = 5
A = np.random.randint(1,20, size=(N,N))

print max_prod(A,A)


texts:
I have written a simple JavaScript function to make an array reactive (i.e. observable). Is there anything I could improve? What the code does is take an array, a callback and a this value as arguments, then whenever the array gets updated or a value gets added to it, it runs the callback with the specified this value. It works similar to the obsolete Array.observe().

function arrayObserve(array, callback, thisArg){
    var result = [];
    result.push.apply(result, array);
    function getterAndSetter() {
        if (Array.isArray(array))
            var currentArray = result;
        else
            var currentArray = Object.keys(result);
        console.log(result);
        currentArray.forEach( function(prop){
            if (Array.isArray(result))
                var currentProp = result.lastIndexOf(prop);
            else
                var currentProp = prop;

            Object.defineProperty(array, currentProp, {
                configurable: true,
                enumerable: true,
                set: function(val) {
                    result[currentProp] = val;
                    callback.call(thisArg, result);
                },
                get: function() {
                    return result[currentProp];
                }
            });
            //}
            if (typeof result[currentProp] == 'object') {
                arrayObserve(result[currentProp], callback, result);
            }
        });
    }
    getterAndSetter();
    ['pop','push','reverse','shift','unshift','splice','sort','map','filter'].forEach( function(method){
        Object.defineProperty(array, method, {
            configurable: false,
            enumerable: false,
            writable: true,
            value: function () {
                var noReturnMethods = ['push', 'pop', 'reverse', 'shift', 'unshift'];
                if (noReturnMethods.indexOf(method) > -1) {
                    Array.prototype[method].apply(result, arguments);
                } else {
                    var results = Array.prototype[method].apply(result, arguments);
                    result = results;
                }
                callback.call(thisArg, result);
                getterAndSetter();
                return result;
            }
        });
    });
    return result;
}


texts:
Building on the answer in C++ class member callback simple examples, I've tried to put together a simple subject-observer pattern without needing to inherit a virtual Observer class. I also wanted to isolate most of the C++11 funny stuff within the Subject. bind and function are little-used features, so keeping the number of uses low should reduce opportunities for programmer errors.

Example class name Subject. Callback for this example takes one bool argument. In Subject declaration:

public:
    template<class T> void addCallback(T* object, void(T::*mf)(bool))
    {
        callbacks_.emplace_back(std::bind(mf, object, std::placeholders::_1));
    }
private:
    std::vector<std::function<void(bool)>> callbacks_;

In Observer declaration (class name for example Observer):

    void nameDoesntMatter(bool);

In Subject implementation, to call observers:

for (const auto& cb: callbacks_)
    cb(booleanValue);

In Observer implementation, to register callback, assuming sub points to the Subject class in question:

sub->addCallback(this, &Observer::nameDoesntMatter);

Seems pretty simple. Seems to work ok.

Questions:

How can I alter this so that an observer can remove its registration with the subject?
If I'm worried about speed, is there a significant difference between the traditional virtual base class implementation of this pattern and the one described here?
Did I make a mistake in my implementation?


texts: Python function to generate Spanish conjugations

texts:
I tried to make a Python function to generate present tense Spanish conjugations.

from unidecode import unidecode
def solveSpanishPresent(pronoun,verb):
  if unidecode(verb).endswith("ar"):
    arDict = {"yo": "o", "tú": "as", "usted": "a", "él": "a", "ella": "a", "nosotros": "amos", "vosotros": "áis", "ustedes": "an", "ellos": "an", "ellas": "an"}
    verb = verb[:-2] + arDict[pronoun]
    return verb
  if unidecode(verb).endswith("er") or unidecode(verb).endswith("ir"):
    erDict = {"yo":"o", "tú":"es", "usted":"e", "él":"e", "ella":"e", "nosotros":"emos", "vosotros":"éis", "ustedes":"en", "ellos":"en", "ellas":"en"}
    irDict = {"nosotros":"imos", "vosotros":"ís"}
    if (pronoun == "nosotros" or pronoun == "vosotros") and verb.endswith("ir"):
        verb = verb[:-2] + irDict[pronoun]
    else:
        verb = verb[:-2] + erDict[pronoun]
    return verb


texts: Connect to MySQL and fetch a list of customers asynchronously using C#

texts:
I am connecting with a database and returning values from a Web API controller.  For better performance, I am doing it completely asynchronously with a new task.

Am I doing it the correct way? Am I using correct the using statements? Is the await correct in Open, Close connection and sda.FillAsync?

public async Task<HttpResponseMessage> Get()
{
    return await Task.Run(() => GetAllCustomers());
}

private async Task <HttpResponseMessage> GetAllCustomers()
{
    DataTable Customers = new DataTable();

    using (MySqlConnection con = new MySqlConnection(""))
    using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers", con))
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                await con.OpenAsync();
                cmd.CommandType = CommandType.Text;
                MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
                await sda.FillAsync(Customers);
            }
        }

        catch (MySqlException ex)
        {
            ex.Message.ToString();
        }
        finally
        {
            await con.CloseAsync();
        }
    }
    return ControllerContext.Request
             .CreateResponse(HttpStatusCode.OK, new { Customers });
}


texts: Truth table generator for an arbitrary function

texts:
Summary: This function generates a truth table for a boolean function of variable number of arguments. The name of the function passed and its arguments are deduced outside of the computable function scope. The returned value is a logical matrix with columns corresponding to function arguments and result.

library(R.utils)
library(stringr)

truthTable <- function(func, valuesOnly = F) {
  numArguments <- length(formals(func))
  if(valuesOnly) {
    values <- vector(length = 2^numArguments)
    for (i in 1:(2^numArguments)) {
      arguments <- rev(as.logical(intToBits(i-1)))[-(1:(32-numArguments))]
      values[i] <- do.call(func, as.list(arguments))
    }
    return(values)
  }
  result <- matrix(nrow = 2^numArguments, ncol = numArguments + 1)
  colnames(result) <- c(names(formals(func)), as.character(substitute(func)))
  for (i in 1:(2^numArguments)) {
    arguments <- rev(as.logical(intToBits(i-1)))[-(1:(32-numArguments))]
    result[i, ] <- c(arguments, do.call(func, as.list(arguments)))
  }
  return(result)
}

Example:

majority <- function(a, b, c) {
  return ((a & b) | (b & c) | (a & c))
}

truthTable(majority)

Result:

         a     b     c majority
[1,] FALSE FALSE FALSE    FALSE
[2,] FALSE FALSE  TRUE    FALSE
[3,] FALSE  TRUE FALSE    FALSE
[4,] FALSE  TRUE  TRUE     TRUE
[5,]  TRUE FALSE FALSE    FALSE
[6,]  TRUE FALSE  TRUE     TRUE
[7,]  TRUE  TRUE FALSE     TRUE
[8,]  TRUE  TRUE  TRUE     TRUE

Possible improvements:

Faster conversion of numeric iterator to logical vector
Usage of apply instead of iterative computation

What could be improved?

Any advice would be appreciated.


texts: Random array of numbers without repeating - oojs practice

texts:
I'd like to practice oojs so I've written code:

function Randoms(c, l, h) {
    var count = c,
        min = l,
        max = h,
        nums = Array(),
        self = this;

    //returns random number from given max and min
    var getRand = function () {
        return Math.floor(Math.random() * (max - min) + min);

    };

    //checks if given number is unique
    var check = function (a) {
        for (var i = nums.length - 1; i >= 0; i--) {
            if (nums[i] == a) {
                return true;
            }
        }
        return false;
    };

    //makes array with random, unique numbers
    this.build = function () {

        var r = getRand();

        if (nums.length === 0) {
            nums.push(r);
        } else {
            do {
                r = getRand();
            } while (check(r));

            nums.push(r);
        }

        if (nums.length == count) {
            return true;
        } else {
            this.build();
        }
    };

    //returns array
    this.get = function () {
        return nums;
    };

    //simulating constructor
    this.build();

}

var a = new Randoms(1, 1, 18);
console.log(a.get());

The purpose is to get array with random, unique numbers.

What do you think? Is it a good code or does it require modyfications?


texts:
So I have some code that works as PDO. But is it secure? I'm trying to prevent SQL injection. This is my first PDO script and was hoping to see if it was done correctly. Here it is.

<?php
echo 'Your query code has been submited';

$host = "localhost";
$pass = "root";
$user= "root";
$dbname = "users";
try{
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e){
    echo $e->getMessage();
 }

$code = $_POST['email'];

$DATA = $con->prepare("INSERT INTO users (code) VALUES (:code)");
$DATA->bindValue(':code', $code);
$DATA->execute();
?>


texts:
To get familiar with the Rust language I've decided to implement the method of Sieve of Eratosthenes to find primes up to a number N.

I have created the following code that both prints the prime number and whether it is prime in tabular format and prints a vector consisting of the prime numbers.

As additional library I'm using the external library bit-vec.

extern crate bit_vec;

const MAXIMUM_PRIME: u32 = 1000;

use bit_vec::BitVec;

fn main() {
    let mut prime_bit_vector = BitVec::from_elem((MAXIMUM_PRIME + 1) as usize, true);
    let sqrt_prime = ((MAXIMUM_PRIME as f64).sqrt() as u32) + 1;

    for i in 2..(sqrt_prime+1) {
        if prime_bit_vector[i as usize] {
            let mut j = i * i;
            while j <= MAXIMUM_PRIME {
                prime_bit_vector.set(j as usize, false);
                j += i;
            }
        }
    }

    let maximum_prime_length = MAXIMUM_PRIME.to_string().len();
    for i in 0..(MAXIMUM_PRIME+1) {
        println!("{index:<width$} {is_prime}", index = i, is_prime = prime_bit_vector[i as usize], width = maximum_prime_length as usize);
    }

    let primes: Vec<_> = prime_bit_vector.iter().enumerate().filter(|t| t.1).map(|t| t.0).collect();
    println!("Primes: {:?}", primes);
}


texts: MVVM Calling command by name from CommandBindings

texts:
For example I have this property in my ViewModel.

public IStorageFolder CurrentFolder
{
    get
    {
        return _currentFolder;
    }
    set
    {
        Set(ref _currentFolder, value);
        CommandBindings[nameof(NavigateCommand)].Execute(Model);
    }
}

private IStorageFolder _currentFolder = null;

CommandBindings.cs

public class CommandBindings
{
    ...

    public ICommand this[string name]
    {
        get
        {
            return GetCommandByName(name);
        }
    }

    public ICommand GetCommandByName(string name)
    {
       ...
    }
}

Navigate.cs

public class NavigateCommand : ExplorerCommand
{
    public override bool CanExecute(IExplorerModel model)
    {
        return true;
    }

    public override async Task ExecuteAsync(IExplorerModel model)
    {
        ....
    }
}

CommandBindingsProvider.cs

public class CommandBindingsProvider : ICommandBindingsProvider
{
    public CommandBindings GetBindings()
    {
        var commandInfos = new List<CommandInfo>();
        var serviceLocator = ServiceLocator.Current;
        var explorerCommandTypes = GetExplorerCommandTypes();

        foreach (var commandType in explorerCommandTypes)
        {
            var command = serviceLocator.GetInstance(commandType) as ICommand;
            if (command == null) throw new Exception($"No instance registered for {commandType.FullName} command.");
            var commandName = commandType.Name;
            var commandInfo = new CommandInfo(commandName, command);
            commandInfos.Add(commandInfo);
        }

        var bindings = new CommandBindings(commandInfos);
        return bindings;
    }

    private static IEnumerable<Type> GetExplorerCommandTypes()
    {
        var assembly = typeof(ExplorerCommand).GetTypeInfo().Assembly;
        foreach (Type type in assembly.GetTypes())
        {
            if (type.GetTypeInfo().GetCustomAttributes(typeof(ExplorerCommandAttribute), true).Count() > 0)
            {
                yield return type;
            }
        }
    }
}

Commands are registered in CommandBindings by nameof class.
I execute them by using this syntax in code:

CommandBindings[nameof(NavigateCommand)].Execute(Model);

and by this syntax in XAML :

<ic:InvokeCommandAction Command="{Binding CommandBindings[NavigateCommand}]" />

which looks bad for me, but I can't argue it. Is there any rules that I volatile? In any case, is there anything that can improve readability of this line?

Why?

If I want to add new functionality to my control, I create command class, inherit it from ExplorerCommand, decorate it with ExplorerCommandAttribute and I am done. CommandBindings are populated by retrieving all commands decorated by this attribute. I didn't change ViewModel for that. Also UI menu items are populated from this CommandBindings and there is no need to change UI too. This is flexibility that I achieved and won't lose it.


texts: GET and POST with Flask - optimum performance

texts:
I have this code to POST and save a digest to redis, and retrieve it from redis on a GET. This uses Python and Flask, of course.

@app.route("/message/<shasum>", methods=['GET'])
def get_message(shasum):
    message = redis.get(shasum)
    if message:
        return jsonify(message=message)
    else:
        abort(404)

@app.route("/digest", methods=['POST'])
def get_digest():
    if request.headers['Content-Type'] == 'application/json':
        message = json.loads(request.data)
        sha = sha256(message['message'].encode('utf-8')).hexdigest()
        redis.set(sha, message['message'])
        return (jsonify(digest=sha), 201)
    else:
        return (jsonify(message="Bad Request"), 400 )

what else can I do to improve the performance of this little piece of code, specifically on the POST side and can it be improved on the GET side too?


texts: Git commit logger for daily stand-up meeting

texts:
At work, my team hosts a daily standup, in which we discuss what we're working on, what we did the day before and any potential blockers for future development.
I thought as a fun little side project that I would write a script in bash to go through each directory in my /dev/ folder and get all commits from the previous day.
We use Git for the most part, but I do have one or two repositories still under a different source control system. This code is to mitigate that problem 2>> /dev/null;.
Here is the code:
gitUsername="userNameHere"
echo "Here are yesterday's commits:"

for dir in ./*/ ;
    do (cd "$dir"; git log --pretty=format:'%Cred%h%Creset -%Creset %s %Cgreen(%cD) %C(bold blue)<%an>%Creset' --since yesterday --author $gitUsername} 2>> /dev/null;);
done;

echo "That's everything."

I have never written anything in bash before, so any suggestions would be much appreciated!
Also, just a side note in case anybody is interested, we don't read commits to measure workload, I am printing them more as a reminder of the things I was working on the day before.


texts: Splitting URLs into hierarchy-level directories

texts:
The goal is to split a URL like http://q.com/a/b/c to:

['http://q.com/a', 'http://q.com/a/b', 'http://q.com/a/b/c']

My code:

import urlparse

def get_domain_with_protocol(url):
    url_parts = urlparse.urlparse(url)
    return "{scheme}://{netloc}/".format(
        scheme=url_parts.scheme,
        netloc=url_parts.netloc
    )

def get_url_directories_combinations(url):
    url = url.rstrip('/')
    path = urlparse.urlparse(url).path[1:]
    parts = path.split('/')
    domain_with_protocol = get_domain_with_protocol(url)

    url_combinations = [domain_with_protocol + '/'.join(parts[:index + 1])
                        for index in range(len(parts))]
    return url_combinations

print get_url_directories_combinations('http://example.com/a/b/c/')

I think this code is ugly and a more Pythonic approach might be possible. There are libraries like hyperlink and posixpath etc. which can be used for path manipulation etc.

How would you improve this code? I'm open to using well-tested, popular libraries if that means less code and more stability.


texts: Calculating the sum of array elements to the left and right

texts:
I am using C++ to code the following logic:

  An Array is given we have to traverse the array such that sum of array elements to its left must be equal to sum of elements to its right.

BTW this is hackerrank Problem.

Here's the code , but this is giving me time-out, that is my code is too slow for very large input, I want to make it faster.

int sumArray(int arr[],int start,int end){
    int sum = 0;
    for(int i=start;i<=end;i++)
        sum += arr[i];
    return sum;
}

// this is inside main
int ar[N];
    for(int n=0;n<N;n++)
        cin>>ar[n];

    bool found = false;
    if(N == 1)
        found = true;
    for(int i=1;i<N;i++){
        int left = sumArray(ar,0,i-1);
        int right = sumArray(ar,i+1,N-1);
        if( left == right)
            found = true;
    }
    if (found)
        cout<<"YES"<<endl;
    else
        cout<<"NO"<<endl;

  This is how the problem works, this is given array
   1 2 3

  1 2 3 3

  In the first test case, no such index exists.

  In the second test case, A[0] + A[1] = A[3]. So 2(start from 0) is the position where this condition occurs.

  this is slow for N=10000 elements in array it excceds 2ms time limit

So where should my code be improved? My mind says I should give a try with   dynamic programming because I am calling same process each time and start it from zero. Is there any good method to do this. Or is there a better way to make above code work for large inputs (I know there's some better way)?

All suggestions are warmly welcomed!!


texts:
This is the "Beautiful Binary String" problem at HackerRank:

Alice has a binary string. She thinks a binary string is beautiful if and only if it doesn't contain the substring 010.
In one step, Alice can change a 0 to a 1 or vice versa. Count and print the minimum number of steps needed to make Alice see the string as beautiful.
For example, if Alice's string is 010 she can change any one element and have a beautiful string.

This is my Python code:
def beautifulBinaryString(b):
    temp = list(b)
    count,i = 0,0
    if len(b) == 3 and b == "010": count += 1
    elif len(b) == 3 and b != "010": count = count
    else:
        while (i+3 <= len(temp)):
            if temp[i:i+3] == ['0','1','0']:
                count += 1
                del temp[i:i+3]
            else: i += 1
    return count

It seems to me as having too many conditionals (though readable, I guess). Is there a more concise way to accomplish this?
Some test cases:
0101010
01100

2
0


texts:
I find myself having to loop through a lot of async calls all over the place in my code base.  The current pattern we are using is to declare SemaphoreSlim(maxcount) and then await sem.WaitAsync(), Create a new task, add it to a List and then repeat.  To control the release the new task itself has a reference to sem and does the release on final.  There is a step in there to look for and remove completed tasks.  This is a pattern that was inherited and is used for multiple different types of async calls.  As I develop new code I was hoping to simply this into a single helper class where I can just queue the work until I hit a set limit and then have to wait to add the next once a slot as freed up.

The calls are all async (as this is a 3rd party lib that we don't control).  Also, the library I maintain has to be used in both winform and asp.net processes, so keeping it async seems ideal.  The targets are usually waiting web services (5-10s range), in which we don't want to slam, but at the same time we typically have 1000's of items in the queue (3rd part has no bulk update implementation -- one element at a time type situation).

This is what I have come up with (naming is still a work in progress):

// Assume this is the parameter to the method we're calling over and over again
private class _ProcessArg
{
  public Guid ID { get; set; }
}

// The method that we are calling over and over again
private async Task _Process(_ProcessArg arg, CancellationToken ct)
{
  await Task.Run(() => { System.Diagnostics.Debug.WriteLine(arg.ID.ToString())});
}

// The main loop where we generated the data for the call.
private async Task _RunMainLoop(CancellationToken ct)
{
  int maxThreads = 10;
  ConcurrentQueue<Guid> queue = new ConcurrentQueue<Guid>();

  // Typically this would be the database load/whatnot
  for (int i = 0; i < 100000; i++)
  {
    queue.Enqueue(Guid.NewGuid());
  }

  AsyncTaskMutex mutex = new AsyncTaskMutex(maxThreads);
  while (true)
  {
    Guid id;
    if (queue.TryDequeue(out id))
    {
      await mutex.QueueTask<_ProcessArg>(_Process, new _ProcessArg
      {
        ID = id,
      }, ct);
    }
    else
    {
      await mutex.DrainQueue(ct);
      break;
    }
  }
}

// Class I'm looking for peer review on
public class AsyncTaskMutex
{
  private SemaphoreSlim _sem;
  private List<Task> _tasks;

  public AsyncTaskMutex()
    : this(10)
  {
  }

  public AsyncTaskMutex(int maxTasks)
  {
    _sem = new SemaphoreSlim(maxTasks, maxTasks);
    _tasks = new List<Task>();
  }

  public async Task DrainQueue(CancellationToken ct)
  {
    await Task.WhenAll(_tasks);
    _tasks.RemoveAll(t => t.IsCompleted);
  }

  public async Task QueueTask<T>(Func<T, CancellationToken, Task> func, T args, CancellationToken ct = default(CancellationToken))
  {
    await _sem.WaitAsync(ct);
    try
    {
      Task task = func(args, ct);
      task.GetAwaiter().OnCompleted(_OnCompleted);
      _tasks.Add(task);
    }
    catch (OperationCanceledException)
    {
      // Intentional ignore
      return;
    }
  }

  private void _OnCompleted()
  {
    _sem.Release(1);
    _tasks.RemoveAll(t => t.IsCompleted);
  }

}


texts:
I wrote a little script to automate upgrading Firefox to a new version under Debian, since I don't want to install it from unstable and the snap version has rendering issues.

Any comments are welcome, is there anything I have missed or any potential problems?

#!/bin/bash

# firefox_upgrade - program to upgrade firefox quantum

error_exit()
{
    echo "$1" 1>&2
    exit 1
}

firefox_path=""
firefox_file=""

# parsing path and filename
if [ $# -ne 1 ]; then
    error_exit "usage: $0 firefox_quantum_path"
else
    firefox_path="$1"
    firefox_file="${firefox_path##*/}"
fi

# checking if input is a valid file
if [ ! -f "$firefox_path" ]; then
    error_exit "Invalid file! Aborting."
fi

# removing previous install, if existent
firefox_bin="/opt/firefox"
if [ -e "$firefox_bin" ]; then
    rm -rf $firefox_bin
else
    echo "$firefox_bin doesn't exist."
fi

# removing previous symlink, if existent
firefox_link="/usr/bin/firefox-quantum"
if [ -f "$firefox_link" ]; then
    rm $firefox_link
else
    echo "$firefox_link doesn't exist."
fi

# copying the tar to /opt
rsync -ah --progress $firefox_path /opt/$firefox_file

# unpacking the tar if successfully changed directory
if cd /opt; then
    tar -jxvf $firefox_file
else
    error_exit "Could not change directory! Aborting."
fi

# if unpack was successful, set permissions, create symlink, and remove tar
if [ "$?" = "0" ]; then
    chmod 755 /opt/firefox
    ln -s /opt/firefox/firefox /usr/bin/firefox-quantum
    rm $firefox_file
else
    error_exit "Could not extract file! Aborting."
fi
exit 0


texts: Finding palindromic numbers most efficiently

texts:
After reading why is my project euler #4 program not working?, I was contemplating the most efficient way to approach this (finding the target palindrome as early as possible).

Is this snippet about as efficient as it gets?  I am only considering the merits of the logic, not the choice of language.  It would be easier (but not as efficient) to brute-force it with two nested loops.

Also, is this logic common enough for it to have a name?

#!/usr/bin/perl
use strict;
$^W = 1;
$\ = "\n";

my ($n) = @ARGV;
$n = 3 if (! defined $n || $n < 2 || $n > 8);
my ($lo,$hi,$lm);
$lo = substr('10000000000',0,$n);
$hi = substr('99999999999',0,$n);
$lm = substr('100000000000000000000',0,$n*2);

my ($a,$b,$x) = ($hi,$hi);
for (;;) {
    $x = $a*$b;
    if ($x eq reverse $x) {
        print "$x is $a * $b" if ($x > $lm);
        last if ($n > 3); # show them all for small numbers
    }
    next if (!(--$a < $lo) & !(++$b > $hi)); # no short-cut operator here
    ++$a; --$b;
    print "  edge $a $b" if ($n < 3); # show edge for small numbers
    $a += $b; $b = int --$a/2; $a -= $b;
    last if ($a*$b < $lm);
}


texts: Fetching environment variables — can I use pattern matching?

texts:
I've got the following Elixir code:

defmodule Envvar do
    def exists?(env) do :os.getenv(env) != false end

    def get(env) do
        if exists?(env) do
            {env, :os.getenv(env)}
        else
            {env, nil}
        end
    end
end

Two things:

Am I using the ? correctly here?  I'm assuming that any predicate function should have the ? on the end of the name by convention.
Is there a way to code the get function as a pattern match rather than a if/else?  I'm asking here because I'm guessing that a pattern match would be more idiomatic Elixir code.


texts:
I am looking to speed up the exchange from vba to IE. The sendkeys works, but I was curious if there were a better way to do this?

The site that it routes to is a form, but there is no submit button. The only way to pull the data is to tab to the next box or click somewhere on the screen. I was hoping, however, to have all of this automated through VBA.

Thoughts?

Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long

Function FillInternetForm()
Dim HWNDSrc As Long
Dim ie As Object

Set ie = CreateObject("InternetExplorer.Application")
    'create new instance of IE. use reference to return current open IE if
    'you want to use open IE window. Easiest way I know of is via title bar.

HWNDSrc = ie.HWND

ie.Navigate "http://helppointinfo.farmersinsurance.com/OCR/Labor_Rates/laborrates.asp"
    'go to web page listed inside quotes
ie.Visible = True
While ie.Busy
    DoEvents  'wait until IE is done loading page.
  Wend
ie.Document.getElementById("DirectZip").Value = Sheets("NAT").Range("C2").Value

SetForegroundWindow HWNDSrc

Application.SendKeys "{TAB 11}", True
DoEvents
Application.SendKeys "{NUMLOCK}", True

End Function

Public Sub RunRates()

Call FillInternetForm

End Sub


texts:
surface is a pygame.surface object from the Pygame graphics library. It actually runs way faster than I thought it would for a first try. Still, have I made any obvious mistakes here? Is there any way to make it go even faster?

cdef mapped_chromatic_aberration(surface, numpy.ndarray[int,ndim=2] intensitymap):
    cdef int x,y,z,maxx,maxy,intensity
    cdef numpy.ndarray[unsigned char,ndim=3] array
    cdef numpy.ndarray[unsigned char,ndim=2] r,g,b
    r=pygame.surfarray.pixels_red(surface)
    g=pygame.surfarray.pixels_green(surface)
    b=pygame.surfarray.pixels_blue(surface)
    array=pygame.surfarray.pixels3d(surface)

    maxx,maxy=surface.get_rect().bottomright

    for x in range(maxx):
        for y in range(maxy):
            try:
                pass
                intensity=intensitymap[x,y]
                array[x,y,0]=r[x+intensity,y]
                array[x,y,1]=g[x,y+intensity]
                array[x,y,2]=b[x+intensity,y-intensity]
            except IndexError:
                pass

cdef random_chromatic_aberration(surface,int intensity=5):
    mapped_chromatic_aberration(surface,numpy.random.random_integers(-intensity,intensity,surface.get_rect().bottomright))


texts: HackerRank, Cracking the Coding Interview: Arrays - Left Rotation

texts:
I just wanted to get some constructive feedback on my solution for this problem taken from the HackerRank Cracking the Coding Interview series.

CTCI Arrays Left Rotation Problem Statement

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

vector<int> array_left_rotation(vector<int> a, int n, int k) {
    vector<int> b(a.size());
    for(int i = 0, len = a.size(); i < len; i++) {
        int swapValue = (i + len - k) % len;
        b[swapValue] = a[i];
    }

    return b;
}

int main(){
    int n;
    int k;
    cin >> n >> k;
    vector<int> a(n);
    for(int a_i = 0;a_i < n;a_i++){
        cin >> a[a_i];
    }
    vector<int> output = array_left_rotation(a, n, k);
    for(int i = 0; i < n;i++)
        cout << output[i] << " ";
    cout << endl;
    return 0;
}


texts: Binary search algorithm for non-overlapping time spans and possible gaps

texts:
I have a data structure, containing time span nodes, with the following properties:

Nodes are sorted ascending
Time spans will not overlap, but may have gaps between them
Each node will have a start datetime and a finish datetime
The last node's finish may also be null (not finished yet)

I want to be able to find the node that intersects a given datetime, or return false if no match is found — basically resembling the following sql query for a sql table with similar properties as my data structure:

SELECT t.*
FROM table t
WHERE t.start <= @probeDate AND
    ( t.finish >= @probeDate OR
      t.finish IS NULL )

I've concluded that a (variation of a) binary search is probably the most efficient search algorithm. So, this is what I have come up with so far:

<?php
class Node
{
    protected $start;
    protected $finish;

    public function __construct( DateTime $start, DateTime $finish = null )
    {
        $this->start  = $start;
        $this->finish = $finish;
    }

    public function getStart()
    {
        return $this->start;
    }

    public function getFinish()
    {
        return $this->finish;
    }

    public function __toString()
    {
        /* for easy displaying of the timespan */
        return $this->start->format( 'H:i:s' ) . ' - ' . ( null !== $this->finish ? $this->finish->format( 'H:i:s' ) : '∞' );
    }
}

class NodeList
{
    protected $nodes;

    public function __construct( array $nodes = array() )
    {
        $this->nodes = $nodes;
    }

    public function find( DateTime $date )
    {
        $min = 0;
        $max = count( $this->nodes ) - 1;

        return $this->binarySearch( $date, $min, $max );
    }

    protected function binarySearch( $date, $min, $max )
    {
        if( $max < $min )
        {
            return false;
        }
        else
        {
            $mid = floor( $min + ( ( $max - $min ) / 2 ) );
            $node   = $this->nodes[ $mid ];
            $start  = $node->getStart();
            $finish = $node->getFinish();
            if( $date < $start )
            {
                return $this->binarySearch( $date, $min, $mid - 1 );
            }
            else if( $date > $finish )
            {
                if( $finish == null )
                {
                    return $node;
                }
                else
                {
                    return $this->binarySearch( $date, $mid + 1, $max );
                }
            }
            else
            {
                return $node;
            }
        }
    }
}

I am testing it with the following:

$nodes = array(
    new Node( new DateTime( '01:01:00' ), new DateTime( '01:05:00' ) ),
    new Node( new DateTime( '01:06:00' ), new DateTime( '01:10:00' ) ),
    new Node( new DateTime( '01:11:00' ), new DateTime( '01:15:00' ) ),
    new Node( new DateTime( '01:16:00' ), new DateTime( '01:20:00' ) ),
    new Node( new DateTime( '01:21:00' ), new DateTime( '01:25:00' ) ),
    new Node( new DateTime( '01:26:00' ), new DateTime( '01:30:00' ) ),
    new Node( new DateTime( '01:31:00' ), new DateTime( '01:35:00' ) ),
    new Node( new DateTime( '01:36:00' ), new DateTime( '01:40:00' ) ),
    new Node( new DateTime( '01:41:00' ) )
);

$list = new NodeList( $nodes );

$date = new DateTime( '01:00:00' );
for( $i = 0; $i < 100; $i++, $date->modify( '+30 seconds' ) )
{
    $node = $list->find( $date );
    echo 'find: ' . $date->format( 'H:i:s' ) . PHP_EOL;
    echo ( $node !== false ? (string) $node : 'false' ) . PHP_EOL . PHP_EOL;
}

Do you see any inherent flaws and/or ways to improve this algorithm? Perhaps you even know of a more time efficient algorithm to accomplish the same?

PS.: Don't worry about the internal integrity of NodeList and Node (checking for invalid nodes, invalid min and max datetimes, checking overlaps, etc.) — this is just a quick and dirty concept. I'm primarily interested in the search algorithm in NodeList::find() and consequently NodeList::binarySearch().


texts: Multiple HTTP requests with threading and queues

texts:
Im working on a I/O bounds application where I want to learn how to use threading property as well as queues to minimize the CPU usage as well as RAM resources. My plan was to use threading queues to do it and this is what I have done so far
# System modules
import time
from queue import Queue
from threading import Thread
from loguru import logger
import requests

feed_urls = [
    'http://www.foxnews.com/',
    'http://www.cnn.com/',
    'http://europe.wsj.com/',
]

# Set up some global variables
num_fetch_threads = 5
queue_exploring = Queue()
queue_monitoring = Queue()
save_length = {}

def get_requests(url):
    return len(requests.get(url).text)

def send_notifcation(queue: Queue):
    while True:
        url = queue.get()
        logger.info(f'Sending notifications: {url}')
        # FIXME Send notifications
        queue.task_done()

def explore_links(queue: Queue):
    """This is the worker thread function.
    It processes items in the queue one after
    another.  These daemon threads go into an
    infinite loop, and only exit when
    the main thread ends.
    """
    while True:
        url = queue.get()
        get_data_length = get_requests(url)

        if save_length[url] != get_data_length:
            logger.info(f"New changes on the webpage found! -> {url}")
            queue_monitoring.put(url)

        logger.info(f"No new changes in the page found! -> {url}")
        time.sleep(60)

        # Add back to queue
        queue.put(url)
        queue.task_done()

for i in range(num_fetch_threads):
    worker_one = Thread(target=explore_links, args=(queue_exploring,))
    worker_two = Thread(target=send_notifcation, args=(queue_monitoring,))

    worker_one.setDaemon(True)
    worker_two.setDaemon(True)
    worker_one.start()
    worker_two.start()

def main():
    logger.info('*** Main thread waiting ***')
    for url in feed_urls:
        response = get_requests(url)
        save_length[url] = response
        queue_exploring.put(url)

    queue_exploring.join()
    queue_monitoring.join()
    logger.info('*** Done ***')

if __name__ == '__main__':
    main()

The idea is that we want forever loop and see if a webpage has done any changes and if they have done any changes, we want to be notified that there has been a change. Simple as that. However here I do use multiple threads as well as queues, one for monitoring to see if there has been a change in the requests and the second one is to send notification


texts: How to check minimize or make if-condition on object loop more correct?

texts:
I am looping through an object and finding whether or not the object has the "key," along with some further stuff.

I feel that there is some other correct way to do this apart from this:

var initialLocalesGen = function(data){

    var status;

    if(!$.isEmptyObject(data)){

        console.log(data);

        if(data.hasOwnProperty("username") && data.hasOwnProperty("name")){
            var headerHtml = Handlebars.compile($("#header-template").html());
            $("#userInfoBar").append(headerHtml({"username" : data["username"], "name" : data["name"]}));
        }

        if(data.hasOwnProperty("allLocales")){
            var formHtml = Handlebars.compile($("#locale-template").html());
            $("form legend").after(formHtml(data["allLocales"])).end().find("span.submit").css({display:"block"});
        }

        if(data.hasOwnProperty("status") && parseInt(data["status"]) === 0){
                currentStatus = 0;
                var object1 = {"status" : data["status"] , "userLocales": data["userLocales"]}
                userLocalesProcess(object1);
        }

        if(data.hasOwnProperty("status") && parseInt(data["status"]) === 1){
                currentStatus = 1;
                userChangeProcess({"changeLocales" : data["changeLocales"],"userLocales" : data["userLocales"] });
                popupMaker({"message":data["message"],"status":data["status"]});
        }

        if(data.hasOwnProperty("status") && parseInt(data["status"]) === 2){
                currentStatus = 2;
        }

    }

    console.log("currentStatus:", currentStatus);

}

Could anyone help me minimize the condition or show me an even better way of doing it?


texts: Merging worksheets and using find/replace

texts:
Of all the macros that I put into heavy rotation these days, this one is running the slowest. ~4-5 seconds depending on the size of the files. It's not a lot but I'd like to know why code 16x as long is running much more instantly.

The code tries to merge documents (usually 2 excel docs out of at most 5) depending on their names and then rename those to exactly what I need. Then, another big issue, is using find/replace to fix a bunch of Unicode/character issues. I cant help but think that could be handled better.

I'd like to find out where the bottlenecks in this code are, how to handle these Unicode issues, perform the Find/replace better, and all in all how to execute better VBA practices.

Option Explicit
Sub MergeBooks()
Dim wb As Workbook
Dim ws As Worksheet

On Error GoTo Handler:
Application.ScreenUpdating = False
For Each wb In Application.Workbooks
    If wb.Name <> "CompanyBook.xlsm" Then
        If FindString(wb.Name, "Report2") Then
            wb.Worksheets.Move after:=Workbooks("CompanyBook.xlsm").Sheets("Aggregate")
        ElseIf FindString(wb.Name, "Report1") Then
            wb.Worksheets.Move after:=Workbooks("CompanyBook.xlsm").Sheets("Aggregate")
        End If
    End If
Next

For Each ws In Workbooks("CompanyBook.xlsm").Worksheets
    If FindString(ws.Name, "Report2") Then
        ws.Name = "Report2"
    ElseIf FindString(ws.Name, "Report1") Then
        ws.Name = "Report1"
    End If
Next ws

'Char mishap replacements
With Workbooks("CompanyBook.xlsm")
.Worksheets("Report1").Cells.Replace What:="&amp;", Replacement:="&", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report1").Cells.Replace What:="&quot;", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="â€™", Replacement:="’", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="â€¦", Replacement:="…", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="Â£", Replacement:="£", LookAt:=xlPart, MatchCase:=False
'.Worksheets("Report2").Cells.Replace What:="â€˜", Replacement:="‘L", LookAt:=xlPart, MatchCase:=False
.Worksheets("Company").Select
End With

Application.ScreenUpdating = True
Exit Sub
Handler:
Application.ScreenUpdating = True
MsgBox "Please make sure that one and only one type of each database file is open.", vbExclamation, "Merge Documents"
End Sub
Function FindString(strCheck As String, strFind As String) As Boolean
Dim intPos As Integer
    intPos = InStr(strCheck, strFind)
    FindString = intPos > 0
End Function


texts:
I'm currently working through an exercise of Chapter 4 from Automate the Boring Stuff, which reads as follows:

"Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it."

Since I'm an absolute beginner to Python (and programming in general), I wanted to get some advice on how to make this code cleaner. It works with any size list, but I've reviewed some other solutions on SO and it seems like there are a million ways to build this out. How can I make this more straightforward?
spam = ['apples', 'bananas', 'tofu', 'cats']

def commaCode(listVar):
    if len(listVar) == 0: # condition for an empty list
        print('There are no items in this list.')

    if len(listVar) == 1: # condition for a list with 1 item
        return (str(listVar[0])+'.')

    if len(listVar) == 2: # condition for a list with 2 items
        return (str(listVar[0]) + ' and ' + str(listVar[1]) + '.')

    if len(listVar) >=3: # conditions for lists with 3+ items
        listDisp = ''
        for i in range(len(listVar[:-1])):
            listDisp = listDisp + str(listVar[i]) + ', '
        listDisp = listDisp + 'and ' + str(listVar[-1])
        return (listDisp)

commaCode(spam)


texts: Listing prime numbers up to the given number

texts:
import java.util.*;

public class PrimeNumber {
    private static ArrayList<Integer> listOfPrime = new ArrayList<Integer>();

    public static void main(String args[]) {
        Scanner userInput = new Scanner(System.in);
        System.out.print("Please enter a number to checked the list of prime number >  ");
    //Request user to input  number.
        String input = userInput.nextLine();
        int number = 0;
        boolean check = false;
    //Check if integer entered is it integer
        while(check != true) {
            try {
    // if input can be parse into integer, shows that its number so can change check into true to exit the while loop

                number = Integer.parseInt(input);
                check = true;
            }
            catch(NumberFormatException e) {
                System.out.println("Please enter numbers only  >  ");
                input = userInput.nextLine();
            }
        }

    //Check if input enter is 0 or 1, as prime number cannot be those.
        if(number < 2) {
            System.out.println("Prime number cannot be 0 or 1");
        }else {
            checkPrime(number);
        }

    }

    //Check for all prime numbers within the number user input.
    private static void checkPrime(int input) {
        boolean primeValidation = true;
    //first for loop to check from small to biggest integer in the input
        for(int i = 1; i <= input;i++) {
            if(i !=1) {

    //Second for loop to check from prime number in the small to big number.

    //If the number i is 2 or 3, the loop will exit and add into the list as the default is prime, and no option changes it to not prime number.

                for(int x = 2; x < i ; x++) {
                    if(i%x == 0) {
    //If the number is divisable by any number to 0, set it to not prime.
                        primeValidation = false;
                    }
                }
            }

//if the input is either 0 or 1 set it to false and 0 and 1 is not prime

            else {
                primeValidation = false;
            }
            if(primeValidation == true) {
                listOfPrime.add(i);
            }else {
                primeValidation = true;
            }

        }

        System.out.println("The list of prime numbers of the number " + input + " are "+listOfPrime);

    }

}


texts:
Imagine a large collection of Python dictionaries (a list of dicts just to make it simple). Each element of this list has hundreds of keys (aka attributes). More importantly not all elements share the same attributes. There is considerable overlap though. So this is a collection of semi-structured data.

I want to get a better sense of how this data looks like, so I wrote a small helper class to do what I want. More specifically, some attributes only take a small set of values. I want to know what kind of values a these keys/attributes take, and the count of each unique value. For example, for an attribute called 'color' I want to know that there are 20 reds, 5 greens, 8 blues, and 1 purple. I also want to know how many dictionaries do not have this attribute (i.e., this attribute is not defined for them).

If you are familiar with R, the information I am after is very similar to what you get when calling the built-in function summary() on a dataframe.

Here's my Python class:

class AttributeValueCount:
    '''
    A helper class to collect statistics about the different values that attributes
    (keys in dicts) take. Initialised with a list of attributes we'd like monitored.
    We can then call the update_counts method repeadedly with different dictionaries,
    to update the number of times each attribute takes specific values.
    '''
    def __init__(self, keylist):
        self._keylist = keylist
        self._counts = {key: defaultdict(int) for key in keylist}

    def update_counts(self, single_dict):
        for key in self._keylist:
            if key in single_dict:
                self._counts[key][single_dict[key]] += 1
            else:
                self._counts[key]['Non existent'] += 1

    def __repr__(self):
        s = ''
        for key in self._keylist:
            s += '-- {} --\n'.format(key)
            for value, count in self._counts[key].items():
                s += '\t {} : {}\n'.format(value, count)
        return s

Example Input

data = [
    {'name': 'apple', 'type': 'farm', 'color': 'red', 'volume': 2000},
    {'name': 'orange', 'type': 'farm', 'color': 'orange', 'volume': 5000},
    {'name': 'elderberry', 'type': 'wild', 'color': None},
    {'name': 'pythonfruit', 'type': 'extinct'}
]

value_counts = AttributeValueCount(['type', 'color'])

for fruit in data:
    value_counts.update_counts(fruit)

print(value_counts)

Example Output

-- type --
     farm : 2
     wild : 1
     extinct : 1
-- color --
     red : 1
     orange : 1
     None : 1
     Non existent : 1

Does this implementation look pythonic to you? What other ways could I achieve my result? I am mostly interested about major design decisions and  not so much about style or minor enhancements. For example, a minor enhancement would be to allow update_counts to take lists of dicts, or any kind of iterable. A major decision would be: I should not be defining a class at all, maybe a function factory would be better (idk, I am just throwing around terms). But I do not want to deter you, any feedback/observation is useful. I just realised for instance that I don't do much argument validation.

Update

The answer by Mathias provided some good points, and I also realised I should have included a bit more information: As mentioned the dictionaries contain hundreds of attributes, and I am only interested in some of them. To put the "some" in perspective, I only need to know the counts for at most 10-15 of the attributes. I also have thousands of dictionaries. For this reason I believe that flowA: specifying the attributes you want and then feed in the data, is preferable to flowB: giving all the data to the class and then ask questions on specific attributes. To my mind FlowB should just be a function definition count_values(data, key) not a class definition. Moreover, the added advantage of flowA is that you do not have to have all data present, you can increment the count incrementally.


texts: Queue over resizable array implementation

texts:
I study data structures on coursera's course, and there is an extra exercise to create a Queue data structure.

I created it:

class Queue {

  Integer[] data;
  int head, tail;

  public Queue() {
    data = new Integer[2];
    head = 0;
    tail = 0;
  }

  public int size() {
    return tail - head;
  }

  public boolean isEmpty() {
    return size() == 0;
  }

  private void realign() {
    java.util.Arrays.sort(data, new java.util.Comparator<Object>() {
      public int compare(Object o1, Object o2) {
        if (o1 == null) return 1;
        else if(o2 == null) return -1;
        else return 0;
      }
    });
    tail -= head;
    head = 0;
  }

  private void resize() {
    if (tail == data.length && size() != data.length) {
      realign();
    }
    if (data.length == size()) {
      int newLength = data.length * 2;
      //Duplication
      Integer[] newData = new Integer[newLength];
      System.arraycopy(data, 0, newData, 0, data.length);
      data = newData;
    } else if (size() == data.length / 4 && size() != 0) {
      int newLength = data.length / 2;
      //Duplication
      Integer[] newData = new Integer[newLength];
      System.arraycopy(data, 0, newData, 0, data.length);
      data = newData;
    }
  }

  public void enqueue(Integer item) {
    if (item == null) { throw new NullPointerException(); }
    resize();
    data[tail] = item;
    tail++;
    return;
  }

  public int dequeue() {
    if (isEmpty()) { throw new java.util.NoSuchElementException(); }
    int res = data[head];
    data[head] = null;
    head++;
    if (head == tail) {
      head = tail = 0;
    }
    return res;
  }
}

And a test suit for it:

import org.junit.Test;
import static org.junit.Assert.*;
import java.util.*;

public class QueueTest {

  @Test
  public void testQueueN() {
    Queue q = new Queue();
    int N = 65;
    for(int i = 0; i < N; i++) {
      q.enqueue(i);
    }
    assertFalse(q.isEmpty());
    for(int i = 0; i < N; i++) {
      assertEquals(i, q.dequeue());
      assertEquals(N - i -1, q.size());
    }
    assertTrue(q.isEmpty());
  }

  @Test
  public void testEnDeEn() {
    Queue q = new Queue();
    q.enqueue(2);
    assertEquals(1, q.size());
    assertEquals(2, q.dequeue());
    q.enqueue(5);
    assertEquals(5, q.dequeue());
  }

  @Test(expected=java.util.NoSuchElementException.class)
  public void testDeOnEmpty() {
    Queue q = new Queue();
    q.dequeue();
  }
  @Test(expected=NullPointerException.class)
  public void testEnWithNull() {
    Queue q = new Queue();
    q.enqueue(null);
  }
}

Please, review it from perspective of implementation and performance.

Update: I improved(thanks to @Vogel612) this code a little bit. Improved version


texts:
My solution for the topcoder ChessMetric challenge seems really slow. I feel like there should be a better way, but I'm not sure.

  Challenge Description

  Suppose you had an n by n chess board and a super piece called a
  kingknight. The kingknight can move either one space in any direction
  (vertical, horizontal or diagonally) or can make an 'L' shaped move.
  An 'L' shaped move involves moving 2 spaces horizontally then 1 space
  vertically or 2 spaces vertically then 1 space horizontally.

  Given the size of the board, the start position of the kingknight and
  the end position of the kingknight, your method will return how many
  possible ways there are of getting from start to end in exactly
  numMoves moves. start and finish are int[]s each containing 2
  elements. The first element will be the (0-based) row position and the
  second will be the (0-based) column position. Rows and columns will
  increment down and to the right respectively. The board itself will
  have rows and columns ranging from 0 to size-1 inclusive.

class Board:
    def __init__(self, size):
        self.size = size
        self.board = [[0 for _ in xrange(size)] for _ in xrange(size)]

    def copy(self):
        c = Board(0)
        board_copy = []
        for val in self.board:
            board_copy.append(val[:])
        c.board = board_copy
        c.size = self.size
        return c

    def is_valid(self, space):
        i, j = space
        return 0 <= i < self.size and 0 <= j < self.size

    def set(self, space, val):
        assert self.is_valid(space), "Invalid space: set()"
        i, j = space
        self.board[i][j] = val
        assert self.get(space) == val, "Problems in set"

    def get(self, space):
        assert self.is_valid(space), "Invalid space: get()"
        i, j = space
        return self.board[i][j]

    def get_adj(self, space):
        assert self.is_valid(space), "Invalid space: get()"
        i, j = space

        result = [
            (i+1, j),
            (i-1, j),
            (i, j+1),
            (i, j-1),
            (i+1, j+1),
            (i-1, j-1),
            (i+1, j-1),
            (i-1, j+1),
            (i+1, j+2),
            (i+1, j-2),
            (i-1, j+2),
            (i-1, j-2),
            (i+2, j+1),
            (i-2, j+1),
            (i+2, j-1),
            (i-2, j-1),
        ]
        result = filter(self.is_valid, result)
        return result

def chess_metric(size, start, finish, move_limit):
    board = Board(size)
    board.set(start, 1)
    aux = board.copy()
    for _ in xrange(move_limit):
        print _
        for i in xrange(size):
            for j in xrange(size):
                current_space = (i, j)
                current_val = board.get(current_space)
                if current_val == 0:
                    continue
                for neighbor in board.get_adj(current_space):
                    neighbor_val = aux.get(neighbor)
                    new_val = current_val + neighbor_val
                    aux.set(neighbor, new_val)
        board = aux.copy()
    return aux.get(finish)


texts:
After the tips from my previous review. I have come up with these changes:

Separation of Concerns
Use Delegates

I'm asking you guys if this looks good. Other then separate out the FileButton_Click(), WriteResultsToFile(), and PromtSaveAsFileName() functions to another class would you recommend any other things to improve?

public partial class StopWatchForm : Form
    {
    WatchState state;
    Stopwatch stopWatch;
    TimeSpan timeSpan;
    List<TimeSpan> times = new List<TimeSpan>();

    public event Action OnStart = () => { };
    public event Action OnStop = () => { };
    public event Action OnLap = () => { };

    public StopWatchForm()
    {
        InitializeComponent();
        state = WatchState.Stopped;
        stopWatch = Stopwatch.StartNew();
        stopWatch.Stop();
        ConfigureStopWatchBehavior();
        ConfigureTimerBehavior();
        ConfigureTimesBehavior();
        ConfigureViewBehavior();
        ConfigureViewStateBehavior();
    }

    private void StartAndLapButton_Click(object sender, EventArgs e)
    {
        if (state == WatchState.Stopped)
        {
            OnStart();
        } else if (state == WatchState.Started)
        {
            OnLap();
        }
    }

    private void StopButton_Click(object sender, EventArgs e)
    {
        if (state == WatchState.Started)
        {
            OnStop();
        }
    }

    private void FileButton_Click(object sender, EventArgs e)
    {
        if (!times.Any())
        {
            return;
        }
        var filename = PromtSaveAsFileName();
        if (filename == null)
        {
            return;
        }
        WriteResultsToFile(filename);
        times.Clear();
    }

    private void ConfigureStopWatchBehavior()
    {
        OnStart += stopWatch.Restart;
        OnStop += stopWatch.Stop;
    }

    void ConfigureTimesBehavior()
    {
        Action storeElapsedtime = () => times.Add(stopWatch.Elapsed);
        OnLap += storeElapsedtime;
        OnStop += storeElapsedtime;
    }

    void ConfigureViewBehavior()
    {
        OnStart += () =>
        {
            StartAndLapButton.Text = "Lap";
            this.Text = "Started";
        };

        OnStop += () =>
        {
            StartAndLapButton.Text = "Start";
            this.Text = "Stop Watch";
        };
    }

    void ConfigureViewStateBehavior()
    {
        OnStart += () => state = WatchState.Started;
        OnStop += () => state = WatchState.Stopped;
    }

    void ConfigureTimerBehavior()
    {
        OnStart += timer1.Start;
        OnStop += timer1.Stop;
    }

    private void WriteResultsToFile(string filename)
    {
        List<string> timesToString = new List<string>();
        foreach (var item in times)
        {
            TimeSpan newitem = new TimeSpan(item.Hours, item.Minutes, item.Seconds);
            timesToString.Add(newitem.ToString());
        }
        System.IO.File.WriteAllLines(filename, timesToString);
    }

    private string PromtSaveAsFileName()
    {
        var dialog = new SaveFileDialog
        {
            DefaultExt = "txt",
            Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
            FilterIndex = 2,
            RestoreDirectory = true
        };

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            return dialog.FileName;
        }

        return null;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        string elapsedTime;
        timeSpan = stopWatch.Elapsed;
        elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
        TimeKeeperText.Text = elapsedTime;
    }
}

This is the 3rd iteration of this code. If you would like to see the original post here is the link.


texts: remove kth last element from singly-linked list

texts:
I have implemented a code to solve following problem. I would like to improve the code efficiency.

Pardon if I just printed out the result.
Code has O(N) time and constant space complexity.

Given a singly linked list and an integer k, remove the kth last
element from the list.

k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.

I used a window with the length of k and 2 pointers to track kth last element in the list. 2 pointers are: (1): previous to the first element, (2): the last element of window:
llnode *prev = llist->head;
llnode *last = llist->head;

CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct llnode
{
    int value;
    struct llnode *next;
} llnode;

typedef struct xllist
{
    llnode * head;
    llnode * tail;
    size_t length;
} xllist;

bool create_node(xllist *list, int value)
{
    llnode *node = malloc(sizeof *node);
    if(!node)
    {
        return false;
    }
    list->length++;

    node->value = value;
    node->next = NULL;
    if(!list->head)
    {
        list->head = node;
        list->tail = node;
    }
    list->tail->next = node;
    list->tail = node;
    return true;
}

bool del_element_from_last(xllist *llist, int k)
{
    printf("len:%d \n", llist->length);
    //window with 2 pointers, length of k
    //prev is the prev node to the window
    llnode *prev = llist->head;
    llnode *last = llist->head;

    if(k > (size_t)llist->length)
    {
        return false;
    }
    else if (k == (size_t)llist->length)
    {
        llist->head = llist->head->next;
        return true;
    }

    for(int i=0; i<k; i++)
    {
        last = last->next;
    }

    //move window until last reaches end
    while(last)
    {
        prev = prev->next;
        last = last->next;
    }

    //remove first node of the window
    printf("deleted element:%d \n", prev->next->value);
    prev->next = prev->next->next;

}

int main(void)
{
    /*Given a singly linked list and an integer k, remove the kth last element from the list.
    k is guaranteed to be smaller than the length of the list.
    The list is very long, so making more than one pass is prohibitively expensive.
    Do this in constant space and in one pass.*/
    xllist llist = {NULL, NULL, 0};

    for(int i=0; i<100; i++)
    {
        if(!create_node(&llist, 100+i))
            printf("create fail\n");
    }

    del_element_from_last(&llist, 15);

}


texts: Grab the first 4 items that meet the condition from a data set with an unknown size

texts:
I was turned down for a job after a coding take-home test, and some of the feedback I received was:

  would have preferred to see more functional programming instead of
   while loops - and the while loops that were implemented weren't ideal.

Here is the while loop (there was only one) in question:

getDetails (id) {

    return this.$http.get(this.baseUrl + (this.detailPath.replace('{ID}', id)))
    .then((json) => {

        let i = 0;
        let result = [];
        while (i < json.data.length && result.length < 4) {

            if (json.data[i].profile_path) {

                result.push(json.data[i]);

            }
            i++;

        }
        return result;

    });

}

I actually considered using a reducer function instead of the while loop, but there is no way to break out of the reducer once the result length condition (i.e. result.length < 4) is no longer true. So that would mean that very large datasets would increase computation time. I created a jsperf to test this theory.

So, my question is this: am I missing something here? Is there a better, more efficient way to do this that I am overlooking?


texts:
I have been using Python to learn programming, but I am just recently beginning to utilize classes. I have a basic game below. Please review and let me know what I should improve on.

import random

class Game:

    def __init__(self):
        self.winningNumber = random.randint(0,100)
        self.humanGuess()

    def humanGuess(self):
        self.humanGuessNumber = int(input("Guess from 0-100"))
        self.comGuess()
        return self.humanGuessNumber
    def comGuess(self):
        self.comGuessNumber = random.randint(0,100)
        self.conclude()
        return self.comGuessNumber
    def conclude(self):
        if abs(self.winningNumber - self.humanGuessNumber)< abs(self.winningNumber - self.comGuessNumber):
            print("You win")
        else:
            print("You suck")

game = Game()


texts: Spawning nodes with random time interval in SpriteKit

texts:
I want to spawn objects with random time interval (from 1 to 3 seconds).

I've wrote this function:

func scheduleAddingLiquid() {
        let wait = SKAction.waitForDuration(NSTimeInterval(getRandomNumber(1, end: 3)))
        let block = SKAction.runBlock({
            [unowned self] in

            let liquidNode = LiquidNode(texture: self.liquidTexture, sceneFrame: self.frame) // It's subclass of sprite node
            self.addChild(liquidNode)

            self.scheduleAddingLiquid()
        })

        let sequence = SKAction.sequence([wait, block])
        runAction(sequence)
    }

Is it a good practice?


texts: Closeable to AutoCloseable converter utility for 3rd party java libs

texts:
I made this utility class to convert Closeable instances to AutoCloseable, so that I can make use of the try-with-resource exception handling mechanism of Java7. This is mainly useful for code which can not be altered.

public class AutoClose<T extends Closeable> implements AutoCloseable, Closeable {

    public final T instance;

    private AutoClose(T instance) {
        this.instance = instance;
    }

    public static <T extends Closeable> AutoClose<T> of(T instance) {
        return new AutoClose<>(instance);
    }

    @Override
    public void close() throws IOException {
        instance.close();
    }
}

usage can be like :

try (AutoClose<SomeType> auto = AutoClose.of(someCloseable)) {
    auto.instance.someWork();
}

feedback much appreciated.


texts: Load different table contents from mySql database using AJAX and display them

texts:
I've written a small application as a part of a much bigger project. This script grabs a bunch of tables from a MySQL database and displays them. The table that is being grabbed and displayed depends on which buttons a user clicks on. You also have the option to sort the tables from A-Z (or A-Ö as I'm Swedish) or Z-A (Ö-A). My concern is the fact that the overall project is becoming really big and I'm starting to notice some increased loading times, it's not by any means slow to the point that it's annoying but it's also not as fast as I would like it to be. This I want to improve.

Is there anything in this code that I can D.R.Y up a bit and make it execute faster?
Is there a downside to using self-invoking functions like I've done in this case? (It's not working when I call the functions manually that's why I was forced to doing it this way)
Can I change anything so that code only executes if it has to? To improve execution time further?

var administrationController = {

    bindElements: (function() {

        var wrapper = $('#table-holder');

        $('#default ul li').on('click', function() {

            $('#default span').html($(this).html());
        });

        $('.overview-nav').on('click', '.overview-btns', function() {

            var tableToGet = $(this).attr('id');

            wrapper.children('table').remove();

            var promise = administrationController.grabInfoTable(tableToGet);
                promise.done(function(data) {
                    wrapper.append(data).hide().fadeIn();
                });

            $('#default').children('span').html('A-Ö');
        });

        $('.sub-options').on('click', function() {

            var currentTable = $('#table-holder').children('table').attr('id');
            var chosenSorting = $(this).html();
            var promise = administrationController.grabInfoTable(currentTable, chosenSorting);

                promise.done(function(data) {
                    wrapper.children('table').remove();
                    wrapper.append(data).hide().fadeIn();
                });
        });

    }()),
    grabInfoTable: function(filename, sortBy) {

        return $.ajax({
                   url: 'ajax/get' + filename + '.php',
                   post: 'POST',
                   data: 'sort_by=' + sortBy
               });
    },
    showList: (function() {

        function changeBorderRadius(value) {
            $('#default').parent().css({borderBottomLeftRadius: value + 'px',
                                        borderBottomRightRadius: value + 'px'
                                       });
        }

        $('#default').on('click', function(e) {

            //Prevent the dropdown ul from reappearing on mouseenter while fading out
            e.stopPropagation();

            if ($('#default ul').is(':visible')) {
                changeBorderRadius(3);
            }
            else {
                changeBorderRadius(0);
            }

            $('#default ul').stop().fadeToggle();

        }).on('mouseleave', function() {
            changeBorderRadius(3);
            $('#default ul').fadeOut();
        });

    }())
}


texts:
This changes the IP of msloop using WMI(Win32_NetworkAdapterConfiguration), which takes about 1~2sec.

But, if I work on another computer, it works much much slower, for about 50~60sec.

My Computer:

OS: Window 7 Professional
RAM: 8GB

Another Computer:

OS: Window XP SP3
RAM: 2GB

public void setIP () {
    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMC.GetInstances();

    foreach (ManagementObject objMO in objMOC) {
        if (!(bool) objMO["IPEnabled"]) {
            continue;
        } else if ((String) objMO["ServiceName"] != "msloop") {
            continue;
        }

        try {
            ManagementBaseObject objNewIP = objMO.GetMethodParameters("EnableStatic");
            ManagementBaseObject objNewGate = objMO.GetMethodParameters("SetGateways");

            objNewIP["IPAddress"] = new string[] { "110.110.110.1" };
            objNewIP["SubnetMask"] = new string[] { "255.255.255.252" };

            objNewGate["GatewayCostMetric"] = new string[] { "1" };

            objMO.InvokeMethod("EnableStatic", objNewIP, null);
            Console.WriteLine("EnableStatic End");
            objMO.InvokeMethod("SetGateways", objNewGate, null);
            Console.WriteLine("SetGateways End");

            Console.WriteLine("Change OK");
            Console.WriteLine("==================================================================");
        } catch (Exception ex) {
            MessageBox.Show("Unable to Set IP : " + ex.Message);
        }
    }
}

The result is always "Change OK". It works on XP, but very slowly.  Is the problem with the OP or the RAM?


texts:
I created this small script to strip the data out of tables that have hyperlinks as their <th /> elements. I was hoping to get input on code clarity and possibly simplification, efficiency is not much of an issue for me as there are not any huge tables on Wikipedia.

var arr = $('tbody').children('tr').map(function(idx) {
  return(idx === 0) ?
  {
    rows: $('th', this).map(function(idx) {
      return {
        href: $('a', this).attr('href'),
        title: $('a', this).text()
      }
    }).get()
  } : {
    href: $('th a', this).attr('href'),
    title: $('th a', this).text(),
    rows: $('td', this).map(function(idx) {
      return $(this).text();
    }).get()
  }
}).get();

Here is an example of a table that this scraper can be run on.


texts:
I was working on the USACO problem arithmetic progression.

You can see the problem (and a solution) here - http://massivealgorithms.blogspot.com/2015/08/arithmeticprogressions-codetrick.html

My code successfully runs for the first 7 test cases. However, once it reaches test case 8 (22,250) it times out.
What modifications should I make to make my code more efficent? Most solutions I found online were also o(m^2*n) complexity, so I'm not sure what I need to change.

Here is my code:

 //#include "stdafx.h"
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <algorithm>
    #include <vector>
    using namespace std;

int main()
{
    ofstream fout("ariprog.out");
    ifstream fin("ariprog.in");
    int n, m;
    fin >> n >> m;
    int bisquare[125001] = {};

    for (int a = 0; a <= m; a++) {
        for (int b = a; b <= m; b++) {
            bisquare[(a*a) + (b*b)] = 1;
        }
    }
    int max = 2 * m*m;
    int value;
    bool tb = false;
    pair<int, int> all[125001];
    int yeah = 0;
    for (int s = 0; s <= max/2; s++) {
        for (int i = 1;i<=max/2; i++) {
            for (int x = 0; x < n; x++) {
                value = s + x*i;

                if (value > max) {
                    tb = true;
                    break;
                }
                if (!bisquare[value]) break;
                if (bisquare[value] && x==n-1)  {
                    all[yeah] = make_pair(i,s);
                    yeah++;
                }
            }
            if (tb) {
                tb = false;
                break;
            }
        }
    }
    sort(all,all+yeah);
    for (int i = 0; i < yeah; i++) {
        fout << all[i].second << " " << all[i].first << endl;
    }
    if (all[0].first == 0) {
        fout << "NONE" << endl;
    }
}


texts:
Sonar complains that I have too many return statements. How can I reduce the return statement count nicely?

public int compare(Sku o1, Sku o2) {
    if (o1 == null) {
        return (o2 == null) ? 0 : 1;
    } else if (o2 == null) {
        return -1;
    }

    if (o1.getSkuNumber() == null) {
        return o2.getSkuNumber() == null ? 0 : 1;
    } else if (o2.getSkuNumber() == null) {
        return -1;
    }

    return o1.getSkuNumber().compareTo(o2.getSkuNumber());
}


texts: Sum of number's quotients when divided by exact powers of 2

texts:
Problem
I have written code to solve this challenge:

Given a formula:

GCD(x,y) means the GCD (Greatest Common Divisor) of x and y.
For example: if N=2, then:

f(2) = 1/GCD(1, 4) + 2/GCD(2, 4) + 3/GCD(3, 4) + 4/GCD(4,4)
f(2) = 1/1 + 2/2 + 3/1 + 4/4
f(2) = 1 + 1 + 3 + 1
f(2) = 6

Given N, find f(N).
Output:
Value of f(N) modulo 1.000.000.007 (109 + 7)
Edit: Output should be in modulo 10^9 + 7

I found a simplified formula using Wolframalpha, by finding the first 10 elements: (4^(n + 1) + 8) / 12
Code
#include <bits/stdc++.h>
#define MOD 1000000007
using namespace std;
typedef short i16;
typedef unsigned short u16;
typedef int i32;
typedef unsigned int u32;
typedef long int i64;
typedef unsigned long int u64;
typedef float f32;
typedef double f64;

u64 pawa(u64 a, u64 b){
    u64 tot = 1;
    for (u64 i = 0; i < b; i++) {
        tot *= a;
        tot = tot % MOD;
    }
    return tot;
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    u64 n;
    cin>>n;
    cout<<(pawa(4, n + 1) + 8) / 12<<'\n';
    return 0;
}

This code scales poorly - time limit exceeded. The upper corner constraint is 10^9. How do I improve my algorithm?


texts: Ulam numbers (calculates your life expectancy if you want to)

texts:
I'm new to Java and wanted to present to you my latest project: Ulam Numbers

/**

 * This class consists of some instance variables a constructor and some getter and setter methods
 * It is supposed to implement the Ulam numbers which are named after Stanislav Ulam
 * Furthermore we will make use of the numbers to calculate/foresee how old you or me will become
 * If this made you curious just enter your own birthday or that of a relative but be warned it might
 * shock you to death.. Hehe..
 *
 * @author  Jae
 * @version 1.0
 */
public class UlamNumber {

 private int number;

 /**
  * This is a constructor which is pretty self-explaining
  *
 * @param number
 * describes the number the user can input like for example his/her birthday
 */
public UlamNumber(int number) {
     this.number = number;
 }

 /**
 * This is a method without parameters which implements the ulam algorithm
 * Furthermore it calculates your "age" by counting how many steps are needed till
 * you reach the number 1 and gives it out on the console
 */
public void ulamAlgorithm() {

     int counter = 0;

     while (number != 1) {
     if (number % 2 == 0) {
         number = number / 2;
         counter++;
         } else if (number % 2 != 0) {
             number = (number * 3) + 1;
             counter++;
         }
     }

     if (counter == 1) {
         System.out.println("Unfortunately you will only become: " + counter + "  years old >:-)");
     } else if (counter < 100) {
         System.out.println("Unfortunately you will only become: " + counter + " years old =(");
     } else {
         System.out.println("Congratulation you will become " + counter + " years old =)");
     }
 }

/**
 * This is a getter method which is pretty self-explaining
 *
 * @return number
 * is from the type integer which returns the current value of number
 */
public int getNumber() {
    return number;
}

/**
 * This is a setter method which is pretty self-explaining
 *
 * @param number
 * is from the type integer which an user can input to change the current value of number
 */
public void setNumber(int number) {
    this.number = number;
}
}

I'm sorry but I didn't write an explanation to the above stated things. You can also see this in my bad javadocs. If you have any hints/tips for improvements, please let me know.


texts: Reduce repetitive code in Lotto simulator

texts:
I'm extremely new to Java, and I had a bit of an attempt at making something that you could call lotto. I've still got a lot more to go on it, but things are becoming tedious, and I am sure there is a simpler way to do what I am doing.  How can this code be changed to have less repetitive code/optimized?

import java.util.Random;
import java.util.Scanner;

public class Lotto {

    //Pick 6 numbers from 1 to 100
    //If all of your numbers gets called out, you win

    public static void wait (int n) {
        long t0,t1;
        t0=System.currentTimeMillis();
        do{
            t1=System.currentTimeMillis();
        }
        while (t1-t0<1000);
    }

    public static void main(String[] args) {
        Random rand = new Random();
        Scanner numScan1 = new Scanner(System.in);
        Scanner numScan2 = new Scanner(System.in);
        Scanner numScan3 = new Scanner(System.in);
        Scanner numScan4 = new Scanner(System.in);
        Scanner numScan5 = new Scanner(System.in);
        Scanner numScan6 = new Scanner(System.in);
        boolean num1Cor = false;
        boolean num2Cor = false;
        boolean num3Cor = false;
        boolean num4Cor = false;
        boolean num5Cor = false;
        boolean num6Cor = false;

        System.out.print("Pick 6 numbers from 0 to 25. Pick your first number: ");
        int num1 = numScan1.nextInt();
        System.out.println();
        System.out.print("Pick your second number: ");
        int num2 = numScan2.nextInt();
        System.out.println();
        System.out.print("Pick your third number: ");
        int num3 = numScan3.nextInt();
        System.out.println();
        System.out.print("Pick your fourth number: ");
        int num4 = numScan4.nextInt();
        System.out.println();
        System.out.print("Pick your fifth number: ");
        int num5 = numScan5.nextInt();
        System.out.println();
        System.out.print("Pick your final number: ");
        int num6 = numScan6.nextInt();
        System.out.println("Numbers will now start to be drawn, if all of your numbers are called, you win.");

        while (true) {
            int random = rand.nextInt(25);
            System.out.println("Number " + random + ".");

            if (random == num1) {
                num1Cor = true;
                System.out.println("Your number, " + num1 + ", has been called.");
            }
            else if (random == num2) {
                num2Cor = true;
                System.out.println("Your number, " + num2 + ", has been called.");
            }
            else if (random == num3) {
                num3Cor = true;
                System.out.println("Your number, " + num3 + ", has been called.");
            }
            else if (random == num4) {
                num4Cor = true;
                System.out.println("Your number, " + num4 + ", has been called.");
            }
            else if (random == num5) {
                num5Cor = true;
                System.out.println("Your number, " + num5 + ", has been called.");
            }
            else if (random == num6) {
                num6Cor = true;
                System.out.println("Your number, " + num6 + ", has been called.");
            }

            if (num1Cor == true && num2Cor == true && num3Cor == true && num4Cor == true && num5Cor == true && num6Cor == true) {
                System.out.println("You win!!");
                break;
            }

            wait(100);
        }
    }
}


texts: Implementing HTTP Strict-Transport-Security via MVC action filter

texts:
HTTP Strict Transport Security (HSTS) is an opt-in security enhancement that is specified by a web application through the use of a special response header. Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS.

Currently, there is no built in support for HSTS in MVC. So I decided to create an filter attribute that I can use as part of my application. There are a few questions about the code I have written which are:

I have used an action filter for granularity, but would a module/handler been better? If so, why?
Should the default of the attribute be to include sub domains, or exclude them (currently it excludes them)
The default timeout for the header is 300 seconds. This is a randomly picked arbitrary value. Is this value too much/too little?

The attribute is designed to compliment the RequireHttpsAttribute

    using System;
    using System.Globalization;
    using System.Web.Mvc;

    public class HSTSAttribute : ActionFilterAttribute
    {
            private const string HeaderName = "Strict-Transport-Security";
            private readonly string _headerValue;
            private readonly bool _includeSubDomains;

    public HSTSAttribute(bool includeSubDomains = false)
        : this(300, includeSubDomains)
    {
    }

    public HSTSAttribute(TimeSpan duration, bool includeSubDomains = false)
        : this(duration == null ? 300 : duration.Seconds, includeSubDomains)
    {
    }

    public HSTSAttribute(int duration, bool includeSubDomains = false)
    {
        if (duration <= 0)
        {
            throw new ArgumentException();
        }

        var includeSubDomainsSuffix = includeSubDomains ? String.Empty : "; includeSubDomains";
        _headerValue = String.Format("max-age={0}{1}", duration.ToString(CultureInfo.InvariantCulture)
                                , includeSubDomainsSuffix);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        // HSTS headers should be sent via HTTPS responses only : http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-7.2
        // They should also not be duplicated
        if (filterContext.HttpContext.Request.IsSecureConnection
                && filterContext.HttpContext.Response.Headers[HeaderName] == null)
        {
            filterContext.HttpContext.Response.AddHeader(HeaderName, _headerValue);
        }

        base.OnResultExecuted(filterContext);
    }
}


texts: Implementing Python-like slice in JavaScript

texts:
Python has by far the best slice implementation I've ever used. As a quick evening project I felt like trying to implement Python's slice construct in a JavaScript function (thinking about sending a pr to a certain library with Python's slice semantics). I came up with the code below, and I'm trying to improve my code. I would love feedback or alternative implementations.

I think I hit all the edge cases, but I only briefly skimmed the Python source, so I could easily be wrong.

/**
 * Implementation of Python's `slice` function... Get a cloned subsequence
 * of an iterable (collection with length property and array like indexs).
 * Will handle both strings and array(likes).
 *
 * @param {Array|String} collection
 * @param {None|Integer} start First index to include. If negative it will be indicies from end
                             (i.e. -1 is last item). Omit or pass 0/null/undefined for 0.
 * @param {None|Integer} end Last index to include. If negative it will be indicies from end
                             (i.e. -1 is last item). Omit or pass null/undefined for end.
 * @param {None|Intger} step Increments to increase by (non-1 will skip indicies). Negative values
                              will reverse the output.
 * @returns {Array|String} sliced array
 *
 * @example
 * var list = [1, 2, 3, 4, 5]
 * slice(list) // => [1, 2, 3, 4, 5]
 * slice(list, 2) // => [3, 4, 5]
 * slice(list, 2, 4) // => [3, 4]
 * slice(list, -2) // => [4, 5]
 * slice(list, null, -1) // => [1, 2, 3, 4]
 * slice(list, null, null, 2) // => [1, 3, 5]
 * slice(list, null, null, -2) // => [5, 3, 1]
 * slice("kids a devil I tell ya", 7, -10, -1) // => "lived"
 */
function slice(collection, start, end, step) {
    var length = collection.length,
        isString = typeof collection == "string", // IE<9 have issues with accessing strings by indicies ("str"[0] === undefined)
        result = [];
    if (isString) {
        collection = collection.split("");
    }
    if (start == null) {
        start = 0;
    } else if (start < 0) {
        start = length + start;
    }
    if (end == null || end > length) {
        end = length;
    } else if (end < 0) {
        end = length + end;
    }
    if (step == null) {
        step = 1;
    } else if (step === 0) {
        throw "Slice step cannot be zero";
    }
    if (step > 0) {
        for (; start < end; start += step) {
            result.push(collection[start]);
        }
    } else {
        for (end -= 1; start <= end; end += step) {
            result.push(collection[end]);
        }
    }
    // Return a string for input strings otherwise an array
    return isString ? result.join("") : result;
}