texts: Canvas in Tkinter app for Conway's Game of Life updates so slowly

texts:
This is Conway's Game of Life written in Python and using Tkinter for GUI.

Problems are:

The "Play" button works so slowly. I can see how the canvas is redrawing from top to bottom. But when I quickly click on the "step" button - I see that I want to get from "play" button: I don't see redrawing process. How can I make it faster and proper?
The __init__ method confuses me as it's so large. Are there a ways to reorganize methods or have I done it right?
How can I make this code more pythonic?

gui.py

# -*- coding: utf-8 -*-
from Tkinter import *
from processor import *
from functools import partial
import threading

class LifeGUI:
    def __init__(self, height, width):
        self.height = height
        self.width = width
        self.prev_x = self.prev_y = None
        self.root = Tk()
        self.field = init_field(height=self.height, width=self.width)
        self.canvas = Canvas(self.root, width=10 * len(self.field[0]), height=10 * len(self.field))
        self.clear()
        self.next_button = Button(self.root, bg="blue", text="step", command=self.step)
        self.next_button.pack()
        self.clear_button = Button(self.root, bg="yellow", text="clean", command=self.clear)
        self.clear_button.pack()
        self.clear_button = Button(self.root, bg="green", text="play", command=partial(self.step, {'repeat': True}))
        self.clear_button.pack()
        self.clear_button = Button(self.root, bg="red", text="stop", command=self.stop)
        self.clear_button.pack()
        self.canvas.bind("<Button-1>", self.switch_cell)
        self.canvas.bind("<B1-Motion>", self.switch_cell)
        self.canvas.bind("<ButtonRelease-1>", self.forget)
        self.canvas.pack()
        self.timer = threading.Timer(0.1, partial(self.step, {'repeat': True}))
        self.root.mainloop()

    def switch_cell(self, event):
        x = event.x / 10
        y = event.y / 10
        if (self.prev_x, self.prev_y) != (x, y):
            self.field[y][x] = not self.field[y][x]
            self.redraw()
        self.prev_x, self.prev_y = x, y

    def forget(self, event):
        self.prev_y = self.prev_x = None

    def step(self, repeat=False):
        self.field = next_step(self.field)
        self.redraw()
        if repeat:
            self.timer = threading.Timer(0.1, partial(self.step, {'repeat': True}))
            self.timer.start()

    def stop(self):
        self.timer.cancel()
        self.timer = None

    def clear(self):
        self.field = init_field(height=self.height, width=self.width)
        self.redraw()

    def redraw(self):
        self.canvas.delete("all")
        for i in range(len(self.field)):
            for j in range(len(self.field[0])):
                self.canvas.create_rectangle(j * 10, i * 10, (j + 1) * 10 - 2, (i + 1) * 10 - 2, fill="blue" if self.field[i][j] else "orange")

def main():

    LifeGUI(40, 40)

if __name__ == '__main__':
    main()

processor.py

# -*- coding: utf-8 -*-
def init_field(height=10, width=10, alives=()):
    fld = [[False] * width for _ in range(height)]
    for alive in alives:
        fld[alive[0]][alive[1]] = True
    return fld

def alive_neighbours(field, x, y):
    result = []
    for i in range(-int(y != 0), int(y != len(field[0]) - 1) + 1):
        for j in range(-int(x != 0), int(x != len(field) - 1) + 1):
            if (i or j) and field[x + j][y + i]:
                result.append((x + j, y + i))
    return result

def next_step(fld):
    result = [row[:] for row in fld]
    for i in range(len(fld)):
        for j in range(len(fld[1])):
            if fld[i][j] and len(alive_neighbours(fld, i, j)) not in (2, 3):
                result[i][j] = False
            elif len(alive_neighbours(fld, i, j)) == 3:
                result[i][j] = True
    return result


texts:
I have an array to have a maximum of 10 elements. Whenever I add a new element, if it already has 10, it would remove the first and push a new one.

I made this:

Array.prototype.pushMax = function(value,max){

     if (this.length >= max){
           this.shift();
     }
     this.push(value);

}

Which seems to work fine, however, I'm just wondering if there is a better way to do it (perhaps some native JavaScript function)


texts:
Algorithm to find pair with max sum from two arrays

A[0 ... n] and B[0 ... n]
A[i] + B[j] = max (A[i] + B[j], with i < j)
i,j < 99999; n < 99999

My best result is this:

int[] testArrayA = { 7, 1, 4, 5, 1};
int[] testArrayB = { 3, 2, 1, 5, 3};
String res = "";
int maxSum = 0;
for (int i = 0; i < testArrayA.length; i++)
{
    int i1 = testArrayA[i];
    for (int j = i; j < testArrayB.length; j++)
    {
        int j1 = testArrayB[j];
        if((j1 + i1) > maxSum)
        {
            maxSum = j1 + i1;
            res = i + " " + j;
        }
    }
}
System.out.println(res);

Expected answer "0 3"
Current complexity \$O(n^2)\$ I think it must be much lower. Can we do it better?


texts: Flattening a List containing Empty Lists

texts:
As part of a text buffer implemented as a piece table, there is an often called procedure to flatten a nested list of character lists. The function is part of constructing substrings of the buffer for display, copying, and cutting.
I have been using a procedure based on Dan D.'s StackOverflow answer here: https://stackoverflow.com/a/33338608/193509. It has worked admirably except for one corner case.
If the user deletes all of the text in the buffer, the list of characters presented to the flatten function consists of a single element list. The single element is the empty list '().
The "stock" version of flatten does not handle this correctly. I've added a special case to the cond that recognizes the condition and responds appropriately (to my mind any way.) So,
(flatten '(())) ;=> '()

Here's what I have for flatten.
(define (flatten lst)
  (letrec ((helper (lambda (lst acc stk)
                     (cond ((null? lst)
                            (if (null? stk) (reverse acc)
                                (helper (car stk) acc (cdr stk))))

                           ((pair? (car lst))
                            (helper (car lst) acc (if (null? (cdr lst))
                                                      stk
                                                      (cons (cdr lst) stk))))
                           ;; Special case for a list containing just empty lists.
                           ((null? (car lst)) '())

                           (else
                            (helper (cdr lst) (cons (car lst) acc) stk))))))
    (helper  lst '() '())))

But the special case feels clunky and not very general. Is there a better way to do this?
More generally, what should a flattened list containing empty lists look like? I have just assumed that reducing to a single empty list is correct. Likewise, it seems to me that flattening a list containing a mixture of empty lists and non-empty should just return a list of the non-empty elements.
(flatten '(() () ())) ;=> '()
(flatten '((a) (b (x y) c) () (d) () ())) ;=> (a b x y c d)

Any thoughts on that?


texts:
My code needs to take two ints and then check those ints to see if their binary representations have any differences. The function convertBits returns the number of differences between the two binary forms of the ints.

For example, you can change 31 to 14 by flipping the 4th and 0th bit:

31:  0 0 0 1 1 1 1 1
14:  0 0 0 0 1 1 1 0
---  ---------------
bit  7 6 5 4 3 2 1 0

Thus 31 and 14 should return 2.

My code works, but it is failing the time test. In short, it needs to be more efficient. I welcome any suggestions as to how to do this.

    import java.util.ArrayList;

    public class BinaryChecker {
        public static void main(String[] args){
             b call = new b();
             System.out.println(call.convertBits(31, 14));
        }

     public static int convertBits(int a, int b){
         int counter = 0;

         String A = Integer.toBinaryString(a);
         String B = Integer.toBinaryString(b);

         System.out.println("The binary value of " + a + " " + "is " +   A +"." + "The binary value of " + b + " " + "is " + B);
         //add to arraylist 1 and 2

         ArrayList<Character> String1 = new ArrayList<Character>();

         ArrayList<Character> String2 = new ArrayList<Character>();
         int size = 0;

         for(int i = 0; i < A.length(); i++){
             char Aa = A.charAt(i);
             String1.add(Aa);
         }
         for(int x = 0; x < B.length(); x++){
             char Bb = B.charAt(x);
             String2.add(Bb);
         }
         //check if String1 is 8 chars long and add 0 to beginning if not
         while (String1.size() != 8){
             String1.add(0, '0');
         }
         while (String2.size() != 8){
             String2.add(0, '0');
         }

         for (int i =0; i < String1.size(); i++){
             char biteA = String1.get(i);
             char biteB = String2.get(i);
             if(biteA != biteB){
                 counter++;
             }
         }

         return counter;
     }
}


texts: Bash script for tagging the current git workspace including uncommitted changes

texts:
I use the following script to autotag the current workspace while building even if there are changed (not committed) files:

#!/bin/bash

tagname="autobuild-test1"
commitname="autocommit for tag $tagname"

set -e
head="`git rev-parse HEAD`"
test -n "$head"
git commit -m "$commitname" -a
taghead="`git rev-parse HEAD`"
git tag "$tagname" "$taghead"
#or just `git tag "$tagname" HEAD` for the 2 lines above
git reset "$head"

The idea: I commit everything which is not committed to a 'temporary commit' and tag its hash. After doing this, I revert to the original state by resetting to the previous HEAD.

In other words: I try to do git commit -a without touching HEAD, staging, stashing and workspace.

Pros:

this also works if the workspace is dirty
the script is very flexible
the script doesn't touch any files, doesn't do any checkout or remove operations

Cons:

the staging state is completely cleared after running the script
probably more state modifications which I didn't find yet
it is a script. I would prefer a single command for this use case
no proper error handling. if the script fails, HEAD might be changed

This script was inspired by cvs2git which uses the same strategy in cases where it's not clear to which revision a tag belongs to.

Is there anything you would change to make this script more rubust and/or to remove some of the cons?


texts: Code to measure the length of binary numbers in terms of English nomenclature

texts:
"ONE" and "ZERO".

The basis of this project is in this
video -> links to his code can be found in description

In it the speaker asks you to check his math; I wrote my own code and then compared it against his.

It is also in the other GIST i am adding to stack-exchange -> Credit for that code goes to MATT PARKER.

TL;DR This code loops through all the numbers between 0 and the value in "maximum" it calculates how many letters are in the binary form of the word "One" or "Zero" -> 13 (1101) and 18 (10010) are the only two values if spelled with the number of letters it equals its value! In this all variables loop around until they reach either 13 or 18 (explained in video) I counted how many of them go to either 18 (99.9909%) or 13 (the rest).

Please rate my code and how efficient it is: especially as compared to the original code and also how it can be improved!
Code
My code is in main.py and his is in binarychain.py

#Creating Variables
Count18 = 0
Count13 = 0
#Change maximum if you don't want to break your computer
maximum = 1000000

#Iterates over each letter and adds to a variable called "letter" for each letter in "one" -> 3 or "Zero" -> 4
def letters(position=0):
    letter = 0
    binary = str('{0:b}'.format(position))

    for ch in binary:
        if ch == '1':
            letter += 3
        if ch == '0':
            letter += 4
    return int(letter)

#Checks if the number reaches 13 or 18
def check(number=0):
    global Count13
    global Count18
    if number == 13:
        Count13 += 1
        return 0
    if number == 18:
        Count18 += 1
        return 0
    if number != 13 or 18:
        return number

running = True
counter = 0
while running:
    checker = check(letters(counter))
    if checker == 0:
        pass
    else:
        #Loops through over and over again until a number reaches either 13 or 18
        while checker != 0:
            checker = check(letters(checker))

    #I could have used a "for" loop but it just wasn't working with this :(
    counter += 1
    if counter > maximum:
        running = False

#Calcualtions for percentage
PerCent18 = (Count18 / maximum)*100
PerCent13 = (Count13 / maximum)*100
print("\nCount 18:", Count18, PerCent18, "Count13:", Count13, PerCent13)

#Just incase it is not being run in an IDE
input()


texts:
I am doing Project Euler problem #6. This is the question it asks:

  The sum of the squares of the first ten natural numbers is,

  $$1^2 + 2^2 + \ldots + 10^2 = 385$$

  The square of the sum of the first ten natural numbers is,

  $$(1 + 2 + \ldots + 10)^2 = 55^2 = 3025$$

  Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

My implementation in Python is as follows:

def sum_of_squares(n):
    return sum([i**2 for i in range(1, n+1)])

def square_of_sum(n):
    return sum(range(1, n+1)) ** 2

print square_of_sum(100) - sum_of_squares(100)

It works but I was wondering if my implementation is good and fast enough?


texts: Correct approach to wait for multiple async methods to complete

texts:
I have an IWorkflow interface defined as follows:

public interface IWorkflow
{
    Task ConfigureAsync();
    Task StartAsync();
    Task StopAsync();
}

And I have an Engine class:

public sealed class Engine : IEngine
{
    private readonly List<IWorkflow> workflows = new List<IWorkflow>();

    public Engine(IEnumerable<IWorkflow> workflows)
    {
        this.workflows.AddRange(workflows);
    }

    public void Start()
    {
        var configureTasks = this.workflows.Select(w => w.ConfigureAsync()).ToArray();
        Task.WaitAll(configureTasks);

        var startTasks = this.workflows.Select(w => w.StartAsync()).ToArray();
        Task.WaitAll(startTasks);
    }

    public void Stop()
    {
        var stopTasks = this.workflows.Select(w => w.StopAsync()).ToArray();
        Task.WaitAll(stopTasks);
    }
}

Is this the correct way for the Engine to invoke in parallel the configure method on all workflows and then once all are completed, invoke in parallel the start method on all workflows?


texts:
A split-string function seems to be missing in R7RS.

I came up with the following implementation today:

(define (split-string delim str)
  (let ((add (lambda (current output)
               (cons (list->string (reverse current)) output))))
    (let loop ((input (string->list str))
               (output #f)
               (current #f))
      (if (null? input)
          (if output
              (reverse (if current
                           (add current output)
                           output))
              '())
          (let ((char (car input))
                (input (cdr input)))
            (if (char=? char delim)
                (loop input (add current output) '())
                (loop input output (cons char current))))))))

Is there anything which can be optimized due to run time or memory usage?

This test case I have used:

(import (scheme write))

(define-syntax test
  (syntax-rules ()
    ((test function index (predicate (argument ...) result))
     (let ((value (function argument ...)))
       (let ((test-result (predicate value result)))
         (display 'function)
         (if index
             (begin
               (display " ")
               (display index)))
         (display ": ")
         (if test-result
             (display "ok")
             (begin
               (display "FAILURE")
               (newline)
               (display "  Expression: ")
               (write '(function argument ...))
               (newline)
               (display "  returns: ")
               (display value)
               (newline)
               (display "  expecting: ")
               (write result)))
         (newline)
         test-result)))
    ((test function index ((argument ...) result))
     (test function index (equal? (argument ...) result)))
    ((test function (predicate (argument ...) result))
     (test function #f (predicate (argument ...) result)))
    ((test function ((argument ...) result))
     (test function #f (equal? (argument ...) result)))))

(define-syntax test*
  (syntax-rules ()
    ((test* function definition ...)
     (let ((counter (let ((value 1))
                      (lambda ()
                        (let ((this value))
                          (set! value (+ value 1))
                          this)))))
       (and (let ((index (counter)))
              (test function index definition))
            ...)))))

(test* split-string
       ((#\space "abc def") '("abc" "def"))
       ((#\space " ") '("" ""))
       ((#\space "") '())
       ((#\space " a") '("" "a"))
       ((#\space "a ") '("a" ""))
       ((#\space "  ") '("" "" "")))


texts:
I just finished learning about move semantics and realized that a nice practical example for this concept is unique_ptr (it cannot be copied, only moved).

For learning purposes, and as a personal experiment, I proceed to try to create my implementation for a smart unique pointer:

template<typename T>
class unique_ptr {
private:
    T* _ptr;
public:
    unique_ptr(T& t) {
       _ptr = &t;
    }
    unique_ptr(unique_ptr<T>&& uptr) {
       _ptr = std::move(uptr._ptr);
       uptr._ptr = nullptr;
    }
    ~unique_ptr() {
       delete _ptr;
    }
    unique_ptr<T>& operator=(unique_ptr<T>&& uptr) {
       if (this == uptr) return *this;
       _ptr = std::move(uptr._ptr);
       uptr._ptr = nullptr;
       return *this;
    }

    unique_ptr(const unique_ptr<T>& uptr) = delete;
    unique_ptr<T>& operator=(const unique_ptr<T>& uptr) = delete;
};

For a small set of test cases, this is working like the real unique_ptr.

However, it just seems too simple enough.

I have two questions regarding this code:

Is it well-formed? i.e. does it follow common C++ standard and patterns (for example, should private members be declared before public ones?
Am I missing something regarding functionality? Is there maybe a bug in my code that I'm not seeing?


texts: How can I improve CreateGenre()  function?

texts:
I use this function in my wordpress site to add genres to an album:
What is it that makes this code so bulky?
Is it have for the server or it just looks like?

/**
 * Creates a genere. If one already exists it will return an error
 * @author Junaid Qadir Baloch <shekhanzai.baloch@gmail.com>
 * @global type $wpdb
 * @param type $genreName
 * @param bool $returnFalse Return False if genre already exists insted of
 * returning setatus and message. Defaults to FALSE
 * @return type
 */
function createGenre($genreName, $returnFalse = FALSE) {
    $funtionName = __FUNCTION__;
    global $wpdb;
    $genreName = trim($genreName);
    if (empty($genreName)) {
        $status = ReturnValue::STATUS_ERROR;
        $value = "";
        $message = 'Genere name cannot be empty';
        return ReturnValue::doReturn($funtionName, $status, $value, $message);
    } elseif (!is_string($genreName)) {
        $status = ReturnValue::STATUS_ERROR;
        $value = "";
        $message = 'Genere name must be a text string';
        return ReturnValue::doReturn($funtionName, $status, $value, $message);
    }
    $genreName = ucwords($genreName);
    $genreSlug = text2Slug($genreName);
    $query = "SELECT COUNT (*) as count FROM `genres` WHERE `name`='" . $genreName . "' AND  `slug`='" . $genreSlug . "' ";
    $result = $wpdb->get_results($query);
    if ($result[0]->count <= 0) {
        $formData = array(
            'name' => $genreName,
            'slug' => $genreSlug
        );
        $result = $wpdb->insert('genres', $formData);
        if ($result) {
            $status = ReturnValue::STATUS_SUCCESS;
            $value = "";
            $message = 'Genere ' . $genreName . ' has been created.';
            return ReturnValue::doReturn($funtionName, $status, $value, $message);
        } else {
            $status = ReturnValue::STATUS_ERROR;
            $value = "";
            $message = 'Failed to create a genere as ' . $genreName . '.';
            return ReturnValue::doReturn($funtionName, $status, $value, $message);
        }
    } else {
        if ($returnFalse) {
            return FALSE;
        }
        $status = ReturnValue::STATUS_ERROR;
        $value = "";
        $message = 'Genere ' . $genreName . ' already exists.';
        return ReturnValue::doReturn($funtionName, $status, $value, $message);
    }
}

This a static class to handle return values. It provides a unified way for other functions to return values.

/**
 * ReturnValue is an helper class to handle
 * return values, status codes and messages
 * returned from different functions
 *
 * @author JQ
 */
class ReturnValue {

    const STATUS_SUCCESS = "SUCCESS";
    const STATUS_FAIL = "FAILED";
    const STATUS_OK = "OK";
    const STATUS_ERROR = "ERROR";

    public static function doReturn($funtionName, $status = NULL, $value = NULL, $message = NULL) {
        if ($status == NULL) {
            $status = self::STATUS_FAIL;
        }
        $return = array(
            action => $funtionName,
            status => $status,
            message => $message,
            returnValue => $value
        );
        return (object) $return;
    }

}


texts: Returning a different but similar "increasing" string depending on instance argument

texts:
I have to work with a function that takes an instance of a class as an input, and depending on that instance, I have to return a specific string. It works, but it has a lot of repetitive code. How can I make it more efficient?

private getDescription(ScreenViewer o) {
    String output = "";
    if(Utils.isTotalPagesVisible()) {
       String total = 5;
       if(o instance of ScreenViewerPage1) {
           output = " 1 out of " + total;
       }
       if(o instance of ScreenViewerPage2) {
           output = " 2 out of " + total;
       }
       if(o instance of ScreenViewerPage3) {
           output = " 3 out of " + total;
       }
       if(o instance of ScreenViewerPage4) {
           output = " 4 out of " + total;
       }
       if(o instance of ScreenViewerPage5) {
           output = " 5 out of " + total;
       }
    }
    else {
        String total = 3;
       if(o instance of ScreenViewerPage1) {
           output = " 1 out of " + total;
       }
       if(o instance of ScreenViewerPage2) {
           output = " 2 out of " + total;
       }
       if(o instance of ScreenViewerPage3) {
           output = " 3 out of " + total;
       }
    }
   return "Description:" + output;
}


texts: Red implementation of Rock, Scissors, Paper

texts:
I have implemented the Rosetta Code Rock Paper Scissors game in Red, but I'm sure that there are better ways to do every thing that I did. I would appreciate any feedback on this code, which does work according to spec:

  Implement the classic children's game Rock-Paper-Scissors, as well as
  a simple predictive AI (artificial intelligence) player.

  Rock Paper Scissors is a two player game.

  Each player chooses one of rock, paper or scissors, without knowing
  the other player's choice.

  The winner is decided by a set of rules:

  Rock beats scissors
  Scissors beat paper
  Paper beats rock

  If both players choose the same thing, there is no winner for that
  round.

  For this task, the computer will be one of the players.

  The operator will select Rock, Paper or Scissors and the computer will
  keep a record of the choice frequency, and use that information to
  make a weighted random choice in an attempt to defeat its opponent.

Red [
    Problem: %http://www.rosettacode.org/wiki/Rock-paper-scissors
    Code: %https://github.com/metaperl/red-rosetta/blob/master/rock-paper-scissors.red
]

help1: %https://stackoverflow.com/questions/54272942/how-to-find-the-first-element-of-a-block-of-strings-whose-first-character-matche
help2: %https://stackoverflow.com/questions/54272956/how-to-increment-element-of-block-after-found-element
help3: %https://stackoverflow.com/questions/54273057/two-dimensional-dispatch-table-with-templated-response
help4: %https://stackoverflow.com/questions/54273161/in-red-how-do-i-search-through-a-block-for-a-string-matching-a-pattern/54275072#54275072

games-played: 0

weapons: ["rock" "scissors" "paper"]
matching-weapon: func [abbrev][
    foreach weapon weapons [
        if (first weapon) = first abbrev [
            return weapon
        ]
    ]
]
player-choices: ["rock" 0 "scissors" 0 "paper" 0 ]
player-choice-tally: func [choice][player-choices/(choice): player-choices/(choice) + 1]

player-choice: "x"
valid-choice: func [c][find "rpsq" c]

player-wins: [
    ["rock" "scissors"] "breaks"
    ["paper" "rock"] "covers"
    ["scissors" "paper"] "cut"
]

player-wins?: function [player1 player2] [
    game: reduce [player1 player2]
    winning: player-wins/(game)
]

report-win: func [player1 player2][rejoin [player1 " " (player-wins? player1 player2) " " player2]]

draw: func [player computer][player = computer]

update-stats: func [player-choice][
    player-choice-tally player-choice
    games-played: games-played + 1
]

make-computer-choice: func [][
    either games-played >= 3 [
        tmp: random games-played
        tally: select "rock" player-choices
        either tmp <= tally [return "rock"][
            tally: tally + select "scissors" player-choices
            either tmp <= tally [return "scissors"][
                return "paper"
            ]
        ]
    ][random/only weapons]
]

while [not player-choice = "q"][
    player-choice: ask "(r)ock, (s)cissors, (p)aper or (q)uit? "
    either (player-choice = "q") [][
        if (valid-choice player-choice) [
            computer-choice: random/only weapons
            player-choice: matching-weapon player-choice
            update-stats player-choice
            print rejoin ["Player choice: " player-choice "tally" player-choices "Computer choice:" computer-choice]
            either draw player-choice computer-choice [print "Draw"][
                tmp: player-wins? player-choice computer-choice
                print either tmp [rejoin ["Player wins: " report-win player-choice computer-choice]]
                    [rejoin ["Computer wins: " report-win computer-choice player-choice]]
            ]
        ]
    ]

]


texts: What is a better (more testable) way to structure this page-specific JS?

texts:
I've created this (very) contrived example that demonstrates how we currently organize page specific JS in our app. Basically each page has a matching JS file that uses the module pattern to enclose page specific behaviors. Each module has an init() function that takes control IDs and wires up events, etc.

This has worked fairely well for us, however now we are wanting to add unit tests. Since many of our modules store state in private variables our unit tests end up stomping all over each other.

I think we need to stop using these singleton modules and instead use instances so that we can write better tests. What are some ways we could restructure this type of code so that it would be testable?

JS Fiddle here...

HTML

  <input type="file" />

  <input type="file" />

  <input type="file" />

  <input id="btnUpload" type="button" value="Upload Files" />
  or Clear files

JS

MyPage = (function() {
    // private members
    var _files = [];
    var _initOptions;

    // public members
    return {
        init: function(options) {
            _initOptions = options;

            $(function() {
                // wire up the events
                $(options.clearLink).click(MyPage.clear);
                $(options.uploadBtn).click(MyPage.doUpload);
                $(options.fileCtrls).change(MyPage.addFile);
            });
        },

        addFile: function() {
            _files.push($(this).val());
        },

        doUpload: function() {
            alert('uploading ' + _files.length + ' files...');
        },

        clear: function() {
            _files = [];
            $(_initOptions.fileCtrls).val('');
        }
    }
})();


texts:
I am doing Kickstart's problem Wiggle Walk. I have tried to code with matrix, dictionary and nested dictionary but the time exceeds the limit in each submition. Can anyone help me optimize it better or is there any algorithm which I may have overlooked.
The problem statement is

  Problem
  Banny has just bought a new programmable robot. Eager to test his coding skills, he has placed the robot in a grid of squares with R rows (numbered 1 to R from north to south) and C columns (numbered 1 to C from west to east). The square in row r and column c is denoted (r, c).

  Initially the robot starts in the square (SR, SC). Banny will give the robot N instructions. Each instruction is one of N, S, E or W, instructing the robot to move one square north, south, east or west respectively.

  If the robot moves into a square that it has been in before, the robot will continue moving in the same direction until it reaches a square that it has not been in before. Banny will never give the robot an instruction that will cause it to move out of the grid.
  Input
  The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with a line containing the five integers N, R, C, SR and SC, the number of instructions, the number of rows, the number of columns, the robot's starting row and starting column, respectively.

  Then, another line follows containing a single string of N characters; the i-th of these characters is the i-th instruction Banny gives the robot (one of N, S, E or W, as described above).

My code is as follows:

for j in range(int(input())):
instructions,rows,cols,startRow,startCol = map(int,input().split())
a=input()
dict={}
startRow-=1
startCol-=1
dict[startRow]={startCol:1}
i=0
while i <len(a):
    if a[i]=="N":
        if startRow-1 not in dict:
            dict[startRow-1]={startCol:1}
            i+=1
        elif startCol not in dict[startRow-1]:
            dict[startRow-1][startCol]=1
            i+=1
        startRow-=1

    elif a[i]=="S":
        if startRow+1 not in dict:
            dict[startRow+1]={startCol:1}
            i+=1
        elif startCol not in dict[startRow+1]:
            dict[startRow+1][startCol]=1
            i+=1
        startRow+=1

    elif a[i]=="W":
        if startRow not in dict:
            dict[startRow]={startCol-1:1}
            i+=1
        elif startCol-1 not in dict[startRow]:
            dict[startRow][startCol-1]=1
            i+=1
        startCol-=1
    elif a[i]=="E":
        if startRow not in dict:
            dict[startRow]={startCol+1:1}
            i+=1
        elif startCol+1 not in dict[startRow]:
            dict[startRow][startCol+1]=1
            i+=1
        startCol+=1

print("Case #{0}: {1} {2}".format(j+1,startRow+1,startCol+1))


texts:
Challenge can be found here

  People connect with each other in a social network. A connection
  between Person I and Person J is represented as M I J. When two persons
  belonging to different communities connect, the net effect is the
  merger of both communities which I and J belongs to.

  At the beginning, there are N people representing N communities. Suppose
  person 1 and 2 connected and later 2 and 3 connected, then 1,2, and 3 will
  belong to the same community.

  There are two type of queries:

  M I J => communities containing person I and J merged (if they belong to
  different communities).

  Q I => print the size of the community to which person  belongs.

  Input Format

  The first line of input will contain integers N and Q, i.e. the number
  of people and the number of queries. The next Q lines will contain the
  queries.

  Constraints :

  1 <= N <= 100000

  1 <= Q <= 200000

My code times out for 6 / 9 test-cases, so obviously this can be improved a lot.

Any suggestions would be much appreciated.

import java.io.*;
import java.util.*;

class Solution {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        int Q = s.nextInt();
        DisjointSet ds = new DisjointSet();

        for(int i = 1; i <= N; i++) {
            ds.makeSet(i);
        }

        for(int i = 0; i < Q; i++) {
            int command = s.next().charAt(0);
            if(command == 'Q') {
                System.out.println(ds.getSetSize(s.nextInt()));
            } else {
                ds.union(s.nextInt(), s.nextInt());
            }
        }
    }
}

class DisjointSet {
    private List<Map<Integer, Set<Integer>>> disjointSet;

    DisjointSet() {
        disjointSet = new ArrayList<Map<Integer, Set<Integer>>>();
    }

    public void makeSet(int element) {
        Map<Integer, Set<Integer>> map = new HashMap<>();
        Set<Integer> set = new HashSet<>();
        set.add(element);
        map.put(element, set);
        disjointSet.add(map);
    }

    public void union(int a, int b) {
        int first = find(a);
        int second = find(b);
        Set<Integer> firstSet = null;
        Set<Integer> secondSet = null;

        for(int i = 0; i < disjointSet.size(); i++) {
            Map<Integer, Set<Integer>> map = disjointSet.get(i);
            if(map.containsKey(first)) {
                firstSet = map.get(first);
            } else if(map.containsKey(second)) {
                secondSet = map.get(second);
            }
        }

        if(firstSet != null && secondSet != null) {
            firstSet.addAll(secondSet);
        }

        for(int i = 0; i < disjointSet.size(); i++) {
            Map<Integer, Set<Integer>> map = disjointSet.get(i);
            if (map.containsKey(first)) {
                map.put(first, firstSet);
            } else if (map.containsKey(second)) {
                map.remove(second);
                disjointSet.remove(i);
            }
        }
    }

    public int find(int n) {
        for(int i = 0; i < disjointSet.size(); i++) {
            Map<Integer, Set<Integer>> map = disjointSet.get(i);
            Set<Integer> keySet = map.keySet();
            for(Integer key : keySet) {
                Set<Integer> set = map.get(key);
                if(set.contains(n)) {
                    return key;
                }
            }
        }
        return -1;
    }

    public int getSetSize(int n) {
        for(int i = 0; i < disjointSet.size(); i++) {
            Map<Integer, Set<Integer>> map = disjointSet.get(i);
            Set<Integer> keySet = map.keySet();
            for(Integer key : keySet) {
                Set<Integer> set = map.get(key);
                if(set.contains(n)) {
                    return set.size();
                }
            }
        }
        return -1;
    }
}


texts: Undo Framework Design (Revert the changes in the collection)

texts:
Requirement is to monitor the changes in a List<T>, possible changes are Add / Remove / Update, which are registered in an Audit log, which I do in the code underneath using a Dictionary. Now user can take an action to revert each of the operations, using an integrated Action delegate. Each operation runs its respective Revert operation. Please note here undo is not about notification, like ObservableCollection<T> but removal at the later time based on user discretion.
Following is my design, please suggest, what shall be done to further improvise.

public class ActionWrapper<T>
{
    public int Index {get;set;}
    public T OriginalValue {get;set;}
    public T NewValue {get;set;}
    public Action<int,T> Action {get;set;}
}

public class ChangeList<T> : List<T>
                             where T:class,IEquatable<T>
{
    public Dictionary<T,ActionWrapper<T>> ActionMap {get;set;}

    public ChangeList()
    {
        ActionMap = new Dictionary<T,ActionWrapper<T>>();
    }

    public new void Add(T item)
    {
        base.Add(item);

        var actionWrapper = new ActionWrapper<T>
        {
            Action = new Action<int,T>(RevertAdd),
            Index = this.FindIndex(x => x.Equals(item)),
            NewValue = item,
            OriginalValue = null
        };

        ActionMap[actionWrapper.NewValue] = actionWrapper;
    }

    public new void Remove(T item)
    {
        var actionWrapper = new ActionWrapper<T>
        {
            Action = new Action<int, T>(RevertRemove),
            Index = this.FindIndex(x => x.Equals(item)),
            NewValue = null,
            OriginalValue = item
        };

        if(actionWrapper.Index < 0)
           return;

        base.Remove(actionWrapper.OriginalValue);

        ActionMap[actionWrapper.OriginalValue] = actionWrapper;
    }

    public void Update(T actualValue,T newValue)
    {
        var actionWrapper = new ActionWrapper<T>
        {
            Action = new Action<int, T>(RevertUpdate),
            Index = this.FindIndex(x => x.Equals(actualValue)),
            NewValue = newValue,
            OriginalValue = actualValue
        };

        if (actionWrapper.Index < 0)
            return;

        base[actionWrapper.Index] = newValue;

        ActionMap[actionWrapper.NewValue] = actionWrapper;
    }

    public void RevertAdd(int index, T actual)
    {
        base.Remove(actual);
    }

    public void RevertRemove(int index,T actual)
    {
        base.Add(actual);
    }

    public void RevertUpdate(int index,T actual)
    {
        base[index] = actual;
    }
}

Use Case

void Main()
{
    var changeList = new ChangeList<string>();
    changeList.Add("Person1");
    changeList.Add("Person2");
    changeList.Add("Person3");
    changeList.Add("Person4");
    changeList.Add("Person5");
    changeList.Add("Person6");
    changeList.Add("Person7");
    changeList.Dump(); // Print statement

    var actionMapUpdateAdd = changeList.ActionMap["Person5"];
    actionMapUpdateAdd.Action(actionMapUpdateAdd.Index, actionMapUpdateAdd.NewValue);
    changeList.Dump(); // Print statement

    changeList.Update("Person7","Person77");
    changeList.Dump(); // Print statement

    var actionMapUpdate = changeList.ActionMap["Person77"];
    actionMapUpdate.Action(actionMapUpdate.Index,actionMapUpdate.OriginalValue);
    changeList.Dump(); // Print statement

    changeList.Remove("Person6");
    changeList.Dump(); // Print statement

    var actionMapRemove = changeList.ActionMap["Person6"];
    actionMapRemove.Action(actionMapRemove.Index, actionMapRemove.OriginalValue);
    changeList.Dump(); // Print statement
}


texts:
It's not finished yet, but I want to know if the structure and the classes are ok and what can I change. Feel free to say anything.

To be more specific, I want to know what you think about the login function in the Login_Controller class:

public function login() {
            if (!empty($_POST['username']) && !empty($_POST['password'])) {
                    $user = new Users_Model;

                    $username = $_POST['username'];
                    $password = $_POST['password'];

                    if ($iduser = $user->is_registered($username, $password)) {
                            $_SESSION['user'] = $username;
                            $_SESSION['iduser'] = $iduser;
                            if ($_POST['keep']) {
                                    $user->save_cookie($username);
                            }
                            header('Location: ' . SITE_ROOT);
                            exit();
                    } else {
                            $error = 'El usuario o el password no son correctos.';
                            $this->main($error);
                    }
            } else {
                    $error = 'No ingreso el usuario o el password.';
                    $this->main($error);
            }
    }

And the router as well:

class Router {
    static function init($request)
    {
            $parsed = explode('/', $request);
            if ($parsed[0] == 'admin') {
                    $page = array_shift($parsed).ucfirst(array_shift($parsed));
            } else {
                    $page = array_shift($parsed);
            }
            if (empty($page)) {
                    $page = 'index';
            }
            $action = array_shift($parsed);
            if (empty($action)) {
                    $action = 'main';
            }
            if (empty($parsed)) {
                    $arguments = 0;
            } else {
                    $arguments = $parsed;
            }
            $target = SERVER_ROOT . '/controllers/' . $page . '.php';
            if (file_exists($target)) {
                    include_once $target;
                    $class = ucfirst($page) . '_Controller';
                    if (class_exists($class)) {
                            $controller = new $class;
                    } else {
                            die('la clase no existe');
                    }
            } else {
                    die('la pagina no existe');
            }
            $controller->$action($arguments);
    }
}


texts: Skeleton for a command-line tool to scan domains for vulnerabilities

texts:
I'm working on a new command line application in GO and was hoping I could get feedback on my design pattern, or suggestions on a better one to use. I'm still new to GO, only having used it for a handful of projects, and would value any suggestions to take better advantage of the "GO" way of doing things.

The intent of the application will be to either scan a single domain, or a list of domains and then output results in either a normal format (depending on flags) containing information about vulnerable domains and suggestions, or a file only showing the domains in the initial input that are vulnerable.

main.go

package main

import (
    "flag"
    "fmt"
    "./libprojectstart"
    "os"
)

func Banner() {
    fmt.Printf("%s%sprojectstart - SSL Mass Renegotiation Tester\n%s",
        libprojectstart.OKBLUE, libprojectstart.BOLD, libprojectstart.RESET)
}

func ParseCmdLine() (state *libprojectstart.State) {
        s := libprojectstart.InitState()

        flag.StringVar(&s.Domain, "d", "", "Domain to scan")
        flag.StringVar(&s.DomainList, "dL", "", "List of domains to scan")
        flag.StringVar(&s.OutputNormal, "oN", "", "File to write normal output to")
        flag.StringVar(&s.OutputDomains, "oD", "", "File to write successful domains to")
        flag.IntVar(&s.Threads, "t", 20, "Number of threads (Default: 20)")
        flag.BoolVar(&s.NoColour, "--no-colour", true, "Don't Use colors in output")
        flag.BoolVar(&s.Silent, "--silent", false, "Output successful scans only")
        flag.BoolVar(&s.Verbose, "v", false, "Verbose output")
        flag.BoolVar(&s.Usage, "h", false, "Display this message")
        flag.Parse()

        return &s
}

func main() {
    state := ParseCmdLine()
    if state.Silent != true {
        Banner()
    }

    if libprojectstart.IsUnchanged(*state) || state.Usage {
        Banner()
        flag.PrintDefaults()
        os.Exit(1)
    }

    if validated, error := libprojectstart.ValidateState(state); validated != true {
        fmt.Printf("%s[!] %s%s", libprojectstart.FAIL, libprojectstart.RESET, error)
        flag.PrintDefaults()
        os.Exit(1)
    }
}

state.go

package libprojectstart

// Contains state read in from the command line
type State struct {
    Domain          string  // Domain to check for
    DomainList      string  // File location for a list of domains
    OutputNormal    string  // File to output in normal format
    OutputDomains   string  // File to output domains only to
    Verbose         bool    // Verbose prints, incl. Debug information
    Threads         int     // Number of threads to use
    NoColour        bool    // Strip colour from output
    Silent          bool    // Output domains only
    Usage           bool    // Print usage information
}

func InitState() (s State) {
    return State { "", "", "", "", false, 20, false, false, false }
}

func ValidateState(s *State) (result bool, error string) {
    if s.Domain == "" && s.DomainList == "" {
        return false, "You must specify either a domain or list of domains to test"
    }

    return true, ""
}

func IsUnchanged(s State) bool {
    return s == InitState()
}

colour.go

package libprojectstart

var (
    HEADER      = "\033[95m"
    OKBLUE      = "\033[94m"
    OKGREEN     = "\033[92m"
    WARNING     = "\033[93m"
    FAIL        = "\033[91m"
    BOLD        = "\033[1m"
    UNDERLINE   = "\033[4m"
    RESET       = "\033[0m"
)

The intent of this application is that the command line options, as well as the feedback being printed will grow significantly over time. I've aimed to demonstrate some of that error checking in ValidateState() as that function will grow with the project, as will the printing of colours. Open to any and all suggestions for improvements!


texts: Creating a wrapper function for jQuery Ajax

texts:
I am creating a few functions that wrap around jQuery's Ajax function to make it a bit quicker and easier to perform a request. For this I have this JavaScript file:

$( document ).ready( function ()
{
    var ajax = {
        url: "", type: "", success: "", beforeSend: "",
        preform: function ( $url, $type, $success, $beforeSend )
        {
            $.ajax( {
                url: this.url = $url,
                type: this.type = $type,
                success: setSuccess(this.success = $success),
                beforeSend: setBeforeSend(this.beforeSend = $beforeSend)
            } );
        }
    };

    function setSuccess( $selector )
    {
        return function ( $r )
        {
            $( $selector ).html( $r );
        };
    }

    function setBeforeSend( $selector )
    {
        return function ()
        {
            $( $selector ).html( "Loading..." );
        };
    }
} );

And this is used with the following line of code:

ajax.preform( "script/javascript/ajaxfiles/print.php", "GET", "#success", "#before" );

This is working brilliantly, but is there a better way to do this?


texts:
I just wrote this fuzzy snippet to identify any 2-byte character in my data file which assumes only 1-byte characters (ANSI). Please review and suggest me any better solution!

File.open('data.txt', 'r') do |f|
    line_number = 0
    while line = f.gets
        line_number = line_number + 1
        line.each_byte do |c|
            if c & 0xff80 != 0
                puts 'A non-ascii character is found at line ' + line_number.to_s
                break
            end
        end
    end
end


texts:
I have an Excel Worksheet consisting of two columns, one of which is filled with strings and the other of which is empty.  I would like to use VBA to assign the value of the cells in the empty column based on the value of the adjacent string in the other column.

Dim regexAdmin As Object
Set regexAdmin = CreateObject("VBScript.RegExp")
regexAdmin.IgnoreCase = True
regexAdmin.Pattern = "Admin"

Dim i As Integer
For i = 1 To 10 'let's say there is 10 rows
    Dim j As Integer
    For j = 1 To 2
        If regexAdmin.test(Cells(i, j).Value) Then
            Cells(i, j + 1).Value = "Exploitation"
        End If
    Next j
Next i

The problem is that when using this loop for a big amount of data, it takes way too long to work and, most of the time, it simply crashes Excel.

Does anyone know a better way of doing this?


texts:
I'm coding a "encryption" algorithm for learning and and don't know how good is it or how could I make it better:

private static byte[] encrypt(byte[] data, int session_id, byte[] password)
    {
        int session_key = (session_id & 0xFF);
        if (session_key == 0) session_key = (session_id << 4);
        byte[] output = new byte[data.Length];
        for (int i = 0; i < output.Length; i++)
        {
            int index = getIndex(i, password.Length);
            int num001  = session_key << 2;
            int num002 = (session_id | i) >> (i+1);
            int num003 = function(i, session_key, password[index]);
            byte encrypted = XorByte(data[i], password);
            output[i] = (byte)((encrypted ^ num003) + (num002 % num001) );
        }
        return output;
    }

    private static byte[] decrypt(byte[] data, int session_id, int length, byte[] password)
    {
        int session_key = (session_id & 0xFF);
        if (session_key == 0) session_key = (session_id << 4);
        byte[] output = new byte[data.Length];
        for (int i = 0; i < output.Length; i++)
        {
            int index = getIndex(i, password.Length);
            int num001 = session_key << 2;
            int num002 = (session_id | i) >> (i + 1);
            int num003 = function(i, session_key, password[index]);
            byte decrypted = (byte)(data[i] - (num002 % num001) ^ num003);
            output[i] = XorByte(decrypted, password);
        }
        return output;
    }
    private static int function(int index, int a, int b)
    {
        if (a > b)
            if ((b + index) < a) return a - b - index;
            else return a - b + index;
        else
            if ((a + index) < b) return b - a - index;
        else return b - a + index;
    }

    public static int getIndex(int a, int b) => (a + b) >> 2;

    private static byte XorByte(byte input, byte[] password)
    {
        byte output = input;
        for (int i = 0; i < password.Length; i++) output ^= password[i];
        return output;
    }

Basically, this code takes a byte[] (data) which will be encrypted. The session_id is a randomly-generated number (this is supposed to be used in a client-server app, and every client is assigned an ID), and a password, which is a random generated byte[].

The main functions are encrypt and decrypt, and they call another 3:

function(int index, int a, int b) - this creates a number based on another 3 that is used to XOR each byte the input of the encryption and decryption functions.
getIndex(int a, int b) - this returns the "middle" number (I don't know how to say it in English) of 2 numbers, that are the number of iterations and the password length. This is used to get a byte within the password.
XorByte(byte input, byte[] password) - this applies XOR to a byte recursively for each byte of the password, so the longer the password the harder to break.

Outputs:

Using a 32 byte random password, a random ID between 1000 and 10000, and the input data: "testing string":

UTF-8 bytes:
116  101  115  116  105  110  103   32  115  116  114  105  110  103

encrypted result: ?`R?o1?zqnrjb

UTF-8 bytes:
160   96   82   15  237  111   49  205  122  113  110  114  106   98

Time: 112 ticks, less than 1 ms (encryption and decryption)

With the same inputs done 100.000 times:

Time: 0,08009ms each encryption/decryption, 8009ms overall


texts:
I am formatting a data result from the array of objects that looks like this:

const data = {
  periods: [{
    month: 'January',
    sickLeave: {
        differance: '-12000',
        revision: '6000',
        paid: '18000',
    },
    holidayLeave: {
        differance: '10000',
        revision: '22000',
        paid: '12000',
    },
    received: '-2000',
    taken: '2000',
    result: '0',
  },
  {
    month: 'Februar',
    sickLeave: {
        differance: '-8000',
        revision: '6000',
        paid: '18000',
    },
    holidayLeave: {
        differance: '10000',
        revision: '22000',
        paid: '12000',
    },
    received: '-2000',
    taken: '2000',
    result: '0',
  }],
};

What I want to do with this is to make a new array that looks like this:

[{
  name: "sickLeaveDifferance",
  result:  ["-12000", "-8000"]
},
{
  name: "sickLeaveRevision",
  result: ["6000", "6000"]
},
{
  name: "sickLeavePaid",
  result: ["18000", "18000"]
},
{
  name: "holidayLeaveDifferance",
  result: ["10000", "10000"]
},
{
  name: "holidayLeaveRevision",
  result: ["22000", "22000"]
},
{
  name: "holidayLeavePaid",
  result: ["12000", "12000"]
},
{
  name: "received",
  result: ["-2000", "-2000"]
},
{
  name: "taken",
  result: ["2000", "2000"]
},
{
  name: "result",
  result: ["0", "0"]
}]

I am achieving this with this function:

const formattedResult = perioder => {
  let resultArray = [];
  const pushNewValue = (key, value) => {
    const objectExists = resultArray.find(e => e.name === key);
    if (objectExists) {
      objectExists.result.push(value)
    } else {
      resultArray.push({
        name: key,
        result: [value]
      })
    }
  };

  perioder.map(el =>
   Object.entries(el).forEach(([key, value]) => {
     if (key != 'month') {
       if (key === 'sickLeave' || key === 'holidayLeave') {
         const prop = key;
         Object.entries(value).forEach(([key, value]) => {
           const name = `${prop + key[0].toUpperCase() + key.slice(1)}`;
           pushNewValue(name, value);
         })
       } else {
         pushNewValue(key, value);
       }
     }
   }))

   return resultArray;
}

But, I feel like there is a better, more elegant way of achieving this, just not sure how to do this?

Here is the fiddle.


texts:
I have built real-time markdown editor in order to learn AngularJS by practice. I think what I'm trying to do can be done a better way. Any suggestions appreciated. Here's my code:

var myApp = angular.module('myApp',[]);
myApp.factory('Data',function ($window) {
    return {message: $window.localStorage['stuff']}
});

function FirstCtrl($scope,$window,Data){
    $scope.data = Data;
    $scope.$watch(
        "data.message",
        function (newval,oldval){
            $window.localStorage['stuff'] = newval;
        })
}

function SecondCtrl($scope,$location,$element,$compile,Data){
    $scope.data = Data;
    $scope.location = $location;
    $scope.compile = function( newHTML ) {
        newHTML = $compile(newHTML)($scope);
        $element.html('').append(newHTML);
    };

    $scope.$watch("data.message", function (newval, oldval) {
        var $http = angular.injector(["ng"]).get("$http");
        $http.post('http://api.github.com/markdown/raw?access_token=' + $scope.location.$$absUrl.substring($scope.location.$$absUrl.indexOf("=")+1),
            newval,
            {headers:{'Content-Type':'text/plain'}})
        .then(function(res){
            $scope.data.dddd = res.data;
            //console.log($scope.data.dddd);
            if(!$scope.data.dddd) return;
            $scope.compile($scope.data.dddd);
        });
    })
}


texts:
I'm new to OOP, so I tried to learn from tutorials how to create a class in JavaScript/jQuery. But tutorials don't give you feedback from experienced coders. Is the approach to create a pop-up OK (see below)? I know it works (it's tested), but is it prone to errors or does it have redundancies?

var Popup = function (){
    /// PROPERTIES
    var new_id="div"+Date.now();
    var defaults = {
        id: new_id,
        container: "body",
        height: 200,
        width: 200,
        text: "
 created with \"id\" = "+new_id,
        x: 100,
        y: 100,
        position: "absolute",
        bgcolor: "red"
    };
    this.settings=defaults;
    /// METHODS
    this.create=function (options){
        $.extend(this.settings,options);
        var html= "
"+
                this.settings.text+
                "
";
        $(this.settings.container).append(html);
        this.update();
    };
    this.update=function (options) {
        $.extend(this.settings,options);
        $("#"+this.settings.id).css({
            "height":this.settings.height+"px",
            "width":this.settings.width+"px",
            "position":this.settings.position,
            "top":this.settings.y,
            "left":this.settings.x,
            "background-color":this.settings.bgcolor
        });
    };
};

/* Popup use:

var pop=new Popup(); // new popup is declared
pop.create({bgcolor:"green"}); // popup appears green instead of read
pop.update({bgcolor:"blue"}); // popup changes to blue

*/

(I know there are a tons of Popup plugins that I could use, but that's irrelevant for my learning goals)

For example, I've realized that this line will cause problems:

this.settings=defaults;

because when "settings" are changed, "defaults" change too (!). Thus, the better alternative is:

this.settings=$.extend(defaults);

or a JavaScript "clone" function like this.


texts:
In SQL Server, there is two tables: Houses, and their images.

I need a list with 20 houses with the first of their images (only one). I tried:

SELECT top 20 h.id, h.name, im.id, im.name
        FROM image im
        INNER JOIN house h ON im.house_id = h.id
        WHERE 1=1 AND im.id=(SELECT TOP (1) im2.id FROM image im2 WHERE im.id=im2.id ORDER BY image_code)

but that runs very slowly. There is any way to improve this query?

EDIT:

With the query:

SELECT   h.id, h.name, im.id, im.name  --  What you want to select
FROM     _house h, _image im              --  Tables in join
WHERE    h.id = im.id_house            --  The join (equivalent to inner join)
GROUP BY h.id                          --  This compresses all entries with the
                                       --  same h.id into a single row
HAVING   im.id =  min(im.id)           --  This is how we select across a group
                                       --  (thus compressing the image table per house)

I'm getting a error message:

_image.id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

Then, I change to:

SELECT   h.id, h.name, im.id, im.name  --  What you want to select
FROM     _house h, _image im              --  Tables in join
WHERE    h.id = im.house_id            --  The join (equivalent to inner join)
GROUP BY h.id,im.id, h.name, im.name                          --  This compresses all entries with the
                                       --  same h.id into a single row
HAVING   im.id =  min(im.id)

And then I get this result:

How can I take out the repeated values?

EDIT2:

If somebody want to test the queries, this is the script to create the tables and the data that I'm using now (the real data is about 1Million rows):

CREATE TABLE _house(
    [id] [int] NOT NULL,
    [name] [varchar](50) NULL
)

CREATE TABLE _image(
    [id] [int] NULL,
    [name] [varchar](50) NULL,
    [house_id] [int] NULL
)

insert into _house (id, name) values (1,'house1');
insert into _house (id, name) values (2,'house2');

insert into _image (id, name, house_id) values (31,'img1',1);
insert into _image (id, name, house_id) values (32,'img2',2);
insert into _image (id, name, house_id) values (33,'img3',2);
insert into _image (id, name, house_id) values (34,'img4',2);


texts: Iterating and fetching values from dictionary

texts:
Here is my dictionary:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"finance": "10.54%"}}

I want extract, first key value of 1 i.e. time, length of the dictionary may vary.

My code:

c_result1 = {"1": {"time": "89.46%"}, "2": {"date": "10.54%"}}
c_result2 = {"1": {"money": "89.46%"}, "2": {"date": "10.54%"}}
flag = 0
result = []
result1 = ''
result2 = ''
for k,v in c_result1.iteritems():
    for k1,v1 in v.iteritems():
        result1 = k1
        result.append(result1)
        print 'result = ', result1
        flag = 1
        if flag == 1:
            break
    if flag == 1:
        break
for k,v in c_result2.iteritems():
    for k1,v1 in v.iteritems():
        result2 = k1
        result.append(result2)
        print 'result = ', result2
        flag = 1
        if flag == 1:
            break
    if flag == 1:
        break
print 'REsult is : , ', result

What is the standard way to do this, rather then using flag?

After that I want to extract time and money from each result and pack them into list like ['time','money'], but due to flag I have used here, I was not able to do this.


texts:
I sometimes need an object that caches some data but only for the specified amount of time. So I created a class that should handle this. The main goal was to make it generic unlike the MemoryCache and be a single object cache and not a general all-pupose cache.
ObjectCache
public class ObjectCache<T>
{
    private readonly object _valueExpiredMutex = new object();

    private T _value;

    public ObjectCache(TimeSpan expiration)
    {
        Expiration = expiration;
    }

    public EventHandler<ObjectCacheEventArgs<T>> ValueExpired { get; set; }

    public TimeSpan Expiration { get; set; }

    public DateTime? LastUpdate { get; internal set; }

    public bool IsExpired
    {
        get { return !LastUpdate.HasValue || DateTime.Now - LastUpdate.Value > Expiration; }
    }

    public T GetValue()
    {
        if (!IsExpired)
        {
            return _value;
        }

        lock (_valueExpiredMutex)
        {
            _value = OnValueExpired();
            LastUpdate = DateTime.Now;
        }

        return _value;
    }

    private T OnValueExpired()
    {
        if (ValueExpired == null)
        {
            throw new InvalidOperationException("ValueExpired event handler not set.");
        }

        var e = new ObjectCacheEventArgs<T>();
        ValueExpired(this, e);
        return e.Value;
    }
}

LastUpdate has an internal setter so that I can set it in tests
I tried to implement it to be thread-safe but I'm not sure if I did it correctly with only one mutex for getting a new value.
Any kind of feedback is welcome ;-)

EventArgs
public class ObjectCacheEventArgs<T> : EventArgs
{
    public T Value { get; set; }
}

Test
[TestMethod]
public void TestObjectCache()
{
    var number = 1;

    var objectCache = new ObjectCache<int>(
        new TimeSpan(hours: 0, minutes: 21, seconds: 0));
    objectCache.ValueExpired += (sender, e) =>
    {
        e.Value = number++;
    };

    Assert.IsTrue(objectCache.IsExpired);
    Assert.AreEqual(1, objectCache.GetValue());
    Assert.IsFalse(objectCache.IsExpired);

    objectCache.LastUpdate = DateTime.Now.AddMinutes(-30);
    Assert.IsTrue(objectCache.IsExpired);
    Assert.AreEqual(2, objectCache.GetValue());
}


texts: Find Invalid User Relationships in User to Manager Map (validate map as valid tree structure with no circular relationships)

texts:
We have a new service where an admin can upload a spreadsheet of new users they want to add to our application. During our processing we make a union map of all the users both existing and new additions, and check to make sure that the users will still be in a valid tree structure(s) after the update goes through.
Requirements:
For the user relationship tree structure to be valid,

There can be no circular references (ex. Users cannot be each other's manager)
A single branch of the tree cannot exceed 50 users (ex. There should not be 50 middle-management managers between CEO and Janitor).
Its ok if the tree is severed into multiple trees when a user does not have a manager. Separate warnings are generated for that circumstance.

This may need to scale to up to 1,000,000 user relationships, so far, the current solution supports at least 10,000 user relationships in a reasonable amount of time (less than 1 minute running locally).
FYI this is Groovy/Java
Solution So Far:
I have a method that takes a HashMap of user relationships and it returns a list of invalid users ids.
Map<String, String> userRelationships = [["userId1": "userId2"], ["userId2": "userId3"], ...]
def invalidRelationships = findInvalidRelationships(userRelationships)

.
/**
 * Takes a map of user relationships (user with corresponding manager)
 * For each relationship, climb up the tree and look to see if the user is repeated in their branch
 * If user is found again up the tree branch, that is a bad circular reference
 * If the current branch goes on past 50 users, that is too long and also invalid
 * Report all users that are part of that bad relationship
 * userRelationship.key is the user
 * userRelationship.value is the manager
 */
def findInvalidUserRelationships(Map<String, String> userRelationships) {
    Set<String> invalidUserRelationshipUsers = []
    userRelationships.each { Entry<String, String> currentUserRelationship ->
        Set<String> usersInCurrentBranch = []
        Entry<String, String> nextIterationRelationship = currentUserRelationship
        while (
                nextIterationRelationship?.value && //while not top of tree (not null manager)
                        !invalidUserRelationshipUsers.contains(nextIterationRelationship.key) && //while user not part of circular relationship
                        !usersInCurrentBranch.contains(nextIterationRelationship.key) //while user not connected to other circular relationship
        ) {
            usersInCurrentBranch << nextIterationRelationship.key
            //if bad circular relationship found or branch has more than max users, report users as invalid
            if (nextIterationRelationship.value == currentUserRelationship.key || usersInCurrentBranch?.size() > 50) {
                invalidUserRelationshipUsers += usersInCurrentBranch
            }
            //set next user relationship to check in next iteration (manager's manager) - (go upline)
            nextIterationRelationship = new MapEntry(
                    nextIterationRelationship.value, //manager of current iteration user will be next user
                    userRelationships[nextIterationRelationship.value as String] //manager's manager
            )
        }
    }
    return invalidUserRelationshipUsers as List<String>
}

I have already made lots of optimizations, at least compared to how bad it was before using only Lists instead of Maps and Sets, but I was wondering if there would be a more efficient solution to this problem. I wondered if a Java TreeMap would be appropriate somewhere here, but could not figure out how it could improve performance.


texts:
This is my first attempt at writing a c++ program, so bear with me. I tried to use as many methods as I learned in about a week-long period.

#include <iostream>
#include <stdlib.h>
#include <time.h>

void generator(char tree, char water, char land)
{
    const char tileList[] = {tree, water, land};
    int tileIndex = rand() % 3;

    std::cout << tileList[tileIndex] << " ";
}

int main()
{
    srand(time(NULL));

    while(true)
    {
        generator('T', '~', '.');
    }
}

I took out comments to improve code readability. What can be improved? What needs to be changed?


texts:
I'm exceeding the time limit for a 10,000 word test case provided on LeetCode:

  Given an array of strings, group anagrams together.

  For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
  Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

  Note: All inputs will be in lower-case.

Any suggestions on how I could speed this up a little bit?

public HashMap<String, List<Integer>> createMap(String[] strs)
{
  HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();

    for(String s: strs)
    {
     char[] charArray = s.toCharArray();
     Arrays.sort(charArray);
     String sortedString = new String(charArray);

     if(map.containsKey(sortedString))
     {
        List<Integer> pos = map.get(sortedString);
        pos.add(Arrays.asList(strs).indexOf(s));
        map.put(sortedString, pos);
     }

    else
    {
        List<Integer> pos = new ArrayList<Integer>();
        pos.add(Arrays.asList(strs).indexOf(s));
        map.put(sortedString, pos);
    }
  }

  return map;
}

public List<List<String>> groupAnagrams(String[] strs) {

  HashMap hm = createMap(strs);

  List<List<String>> anagrams = new ArrayList<List<String>>();

  for(Object k: hm.keySet())
  {
    String key = k.toString();
    ArrayList pos = (ArrayList)hm.get(key);

    List<String> a = new ArrayList<String>();
    for(Object p : pos)
    {
      int idx = Integer.parseInt(p.toString());
      a.add(strs[idx]);
    }
    anagrams.add(a);
  }
  return anagrams;
}


texts: Paginating blog posts from SQL server using nested LINQ statements

texts:
I made an ASP.NET MVC application using Entity Framework for code-first migrations to the SQL Server database. I also use Unity (DI/IoC) for managing the services and repositories.

I made an overview page but I'll limit the items on that page to 10, 50 or 100 (variable named pagecount) items as selected by the user. The rest of the items are on other pages (variable named page). The result is something similar to what Code review has:

Each Blog has a Category. I'll also that the user can see one, more, or all categories (variable named categories). This contains a list of integers with the categories that the user will see.

using System.Data.Entity;

public class BlogRepo : GenericRepo<Blog>
{
    public List<Blog> GetByPage(int page, List<int> categories, int pagecount)
    {
        return (from b1 in ((from b2 in ((from b3 in dbSet.Include(b3 => b3.Category).Include(b3 => b3.User)
                                          orderby b3.CreationDateStamp ascending
                                          where categories.Contains(b3.CategoryId)
                                          select b3).Take<Blog>(page * pagecount)).Include(b2 => b2.Category).Include(b3 => b3.User) // step one
                             orderby b2.CreationDateStamp descending
                             select b2).Take<Blog>(pagecount)).Include(b1 => b1.Category).Include(b3 => b3.User) // step two
                orderby b1.CreationDateStamp ascending
                select b1).ToList<Blog>(); // step tree
    }
}

Here is my way of working:

I take the first items calculated by the formula page * pagecount sorted in ascending order by CreationDateStamp where categories.Contains(b3.CategoryId) is true.
Form that items I sort it in descending order on the same property, and take the value of pagecount.
Finally, sort it again (ascending), and call ToList<Blog>() to materialize the results.

Note one: I'll always include the properties Category (type of Category) and User (type of ApplicationUser).

Note two: the variable dbSet comes from a generic repository and is declared as follows:

public class GenericRepo<TEntity> : IGenericRepo<TEntity> where TEntity : class
{
    internal DbSet<TEntity> dbSet;
    // other basic linq statements for get basic stuff like GetAll, Delete, Insert, SaveChanges and Update
}

The code works, but I wondering if I can improve its performance and readability. In other words, can I combine some steps and can I reduce the code to make it shorter or simpler?


texts:
My code right now look like this

@contextmanager
def smtp_connection(host, user=None, passwd=None, timeout=5):
    conn = None # smell here
    try:
        conn = SMTP(host=host, timeout=timeout)
        conn.ehlo_or_helo_if_needed()
        if user and passwd:
            conn.login(user=user, password=passwd)
        logger.debug('SMTP connected')
        yield conn
    except Exception as e:
        raise e
    finally:
        if conn: # and here
            conn.quit()

In recipes for ExitStack there is a suggestion to replace try-finally and flag variables with this

with ExitStack() as stack:
    stack.callback(cleanup_resources)
    result = perform_operation()
    if result:
        stack.pop_all()

But this doesn't use result in cleanup_resources. So in my case it still would be

with ExitStack() as stack:
    result = None
    stack.callback(lambda conn: conn.quit())
    result = POP3() # code from above here
    if result:
        stack.pop_all()


texts:
I have been following this question on SO, copied below.  I put together a solution, but which is \$O(n^2)\$. In order to get a more efficient \$O(n \log n)\$ or \$O(\log n)\$ solution, I tried to sort that array, but could not get it solved hence would like to ask here how to optimize this solution to get it in less time complexity in C?

  Given an array A of N integers we draw N discs in a 2D plane,
  such that i-th disc has center in (0,i) and a radius A[i]. We
  say that the k-th disc and j-th disc intersect if they have at
  least one common point.

  Write a function

int number_of_disc_intersections(int[] A);

  which given an array A describing N discs as explained above, returns
  the number of pairs of intersecting discs. For example, given N=6 and

A[0] = 1
A[1] = 5
A[2] = 2
A[3] = 1
A[4] = 4
A[5] = 0

  there are 11 pairs of intersecting discs:

  0th and 1st
  0th and 2nd
  0th and 4th
  1st and 2nd
  1st and 3rd
  1st and 4th
  1st and 5th
  2nd and 3rd
  2nd and 4th
  3rd and 4th
  4th and 5th

  so the function should return 11. The function should return -1 if the
  number of intersecting pairs exceeds 10,000,000. The function may
  assume that N does not exceed 10,000,000.

C language solution:

int disc_intersecn(int *A,int N)
{
    int i,j,cnt=0;
    /*
    qsort(A,N,sizeof(A[0]),sort_fn_ascend);
    for(i=0;i<(N-1);i++)
    {
        if(i+A[i] > (i+1-A[i+1]))
        {
            cnt++;
        }
    }
    */

    for (i = 0; i < N; i++)
    {
        for (j = i+1; j < N; j++)
        {
            if (i + A[i] >= j - A[j]) cnt++;
        }
    }

    return cnt;
}


texts:
I solved FizzBuzz using tail recursion. Is it efficient enough?

(defun mod-3 (n)
   (zerop (mod n 3)))

(defun mod-5 (n)
  (zerop (mod n 5)))

(defun analyzer (n)
  (if (mod-3 n)
  (if (mod-5 n)
      'fizzbuzz
      'fizz)
  (if (mod-5 n)
      'buzz
      n)))

(defun fizzbuzz (limit)
  (fizzbuzz-helper limit nil))

(defun fizzbuzz-helper (limit result)
  (cond ((zerop limit) result)
    (t (fizzbuzz-helper (- limit 1)
            (cons (analyzer limit) result)))))


texts:
The following code:

import random

def keygen():
    l = list('abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" ')
    random.shuffle(l)
    return l

def encrypt(x):
    key = keygen() #or a static key for consistency
    y = list('abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" ')
    z = dict(zip(y, key))
    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))
    print('key: '+ ''.join(key))
    print('content: '+ ''.join(l))

def decrypt(key, x):
    key = list(key)
    y = list('abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" ')
    z = dict(zip(key, y))
    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))
    print(''.join(l))

is just a simple self made encrypter that I made for fun, and works like so:

>>> encrypt('hello world how are you')
key: ^lps1|dv)({t&hk#w;=@!6bjrx$4 \[m~"q*i+:-a73?u/5zf%gc9}yn"8_oe]`2
content: v1ttk2bk;ts2vkb2^;12rk!
>>> decrypt('^lps1|dv)({t&hk#w;=@!6bjrx$4 \[m~"q*i+:-a73?u/5zf%gc9}yn"8_oe]`2', 'v1ttk2bk;ts2vkb2^;12rk!')
hello world how are you
>>>

This works pretty well, but I did see one time where there was a single letter that was misplaced. This could have just been due to me not copy/pasting the key in right for decoding, but I am not so sure. Basically does this code look sound? And are there any other methods of doing something like this in a more elegant way?


texts: Caching a JS selector then only using it once

texts:
I have this code:

var submit = document.getElementById('submit');
var error = document.getElementById('error');
var url;

submit.onclick = function(){
    url = document.getElementById('url').value;
    if(url == ''){
        error.style.display = 'block';
        return false;
    }
};

Now, it's very simple in functionality. But I'm wondering if caching the error selector, for example, is worth caching or not? is it a perf hit to cache a selector if its only accessed once?


texts: Updating 3 columns conditionally on a database table

texts:
I need to run this script to update the value of 3 columns based on certain conditions. Right now, this is what I have:

UPDATE dbo.Roles
SET DisplayName = Name
WHERE DisplayName LIKE '';

UPDATE dbo.Roles
SET Name = CONCAT(Tenant, '_', DisplayName)
WHERE Name NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%');

UPDATE dbo.Roles
SET NormalizedName = CONCAT(Tenant, '_', UPPER(DisplayName))
WHERE NormalizedName NOT LIKE ('%' + Convert(varchar(200), Tenant) + '%');

I'm doing this with 3 separate update statements. I can't help but think there's probably a better way, but maybe I'm overthinking. Any suggestions?


texts:
I am working on a puzzle to find the minimum number of coins needed to buy a product.

I am given three coins:

1
3
5

and also a number representing the price of a product:

11

The answer here would be three, since it takes at least three coins to reach this number.

5, 5, 1

I decided it was best to use Ruby's repeated_permutation method. I tested my method in irb and it seems to work for smaller inputs, but when I submitted it to the online grader, I got a Memory Allocation Error.

File.open(ARGV[0]).each_line do |line|
    number = line.to_i
    coins = [1,3,5]
    coin_combos = []
    i = 1
    until coin_combos.flatten(1).any? { |c| c.inject(:+) >= number }
        coin_combos << coins.repeated_permutation(i).to_a
        i += 1
    end
    puts i - 1
end

Here was my thought process:

Store the different types of coins in a coins array
Initialize an empty array for storing sequences of coins
Use a loop. It will be finished once the sum of one of the sequences is equal to or surpasses the product's price.
Push to my array the number of repeated permutations of length equal to my counter
Increment my counter and test for the condition again

This seems to be a problem with my algorithm and I'm using up too much space here.

Is there a different algorithm I should use?


texts: Retrieving a certain amount of data from a socket

texts:
I'm trying to retrieve a certain amount of data from a socket, both Unix domain and TCP, but I've no control over its format or length.

I discussed this with someone who told me to set my receiving buffer to a specific length, use async_read_some to read the first few bytes off the socket and then loop until the OS buffer is empty.

I decided to write the following code instead:

void read() noexcept {
      buffer_.resize(0);
      asio::async_read(*socket_, asio::buffer(buffer_), asio::transfer_all(),
                       [&](const std::error_code &ec, const size_t size) {
                         buffer_.resize(socket_->available());
                         asio::read(*socket_, asio::buffer(buffer_));
                         delegate_.on_read(ec, buffer_);
                       });
      service_.run();
      service_.reset();
    }

Is there anything obviously wrong with my method? Setting the buffer to 0 before calling the read method means the buffer will never be populated and calling a synchronous read() on the callback so async_read() means the blocking will take as long as it takes to copy data from the OS buffer to my local buffer.

Am I missing something else here?

Update:

The code for the socket:

struct Socket : public std::enable_shared_from_this<Socket> {
    explicit Socket(const std::string &socket) : endpoint_{socket} {
      socket_.reset(new asio::generic::stream_protocol::socket(service_));
      socket_->connect(endpoint_, delegate_.error_code);
      socket_->non_blocking(true);
      service_.run();
      service_.reset();
    }

    virtual ~Socket() noexcept = default;

    void write(const std::vector<uint8_t> &data) noexcept {
      asio::async_write(*socket_, asio::buffer(data),
                        [&](const std::error_code ec, const size_t length) {  });
      service_.run();
      service_.reset();
    }

    void read() noexcept {
      buffer_.resize(0);
      asio::async_read(*socket_, asio::buffer(buffer_), asio::transfer_all(),
                       [&](const std::error_code &ec, const size_t size) {
                         buffer_.resize(socket_->available());
                         asio::read(*socket_, asio::buffer(buffer_));
                       });
      service_.run();
      service_.reset();
    }

   private:
    asio::io_service service_;
    std::unique_ptr<asio::generic::stream_protocol::socket> socket_;
    asio::local::stream_protocol::endpoint endpoint_;

    std::string host_;
    std::string port_;
    std::vector<uint8_t> buffer_;
  };

But I was hoping to have someone with asio knowledge as I was told this could fail on specific scenarios like when the client sends more than 1GB of data.


texts: Python program that obfuscates an email address

texts:
I decided to resume my (limited) Python skills after not coding for a long time.

Here's a very simple self-contained program to convert the characters of an email address into their HTML entities (the purpose is to make the email invisible to spamrobots).

Any comment for improvement? (e.g. args parsing, code style, etc.)
Apart from the -h option in argparse, what is the standard way to add some documentation for it, such as a manpage or some embedded help?

#!/usr/bin/python

#
# mung - Convert a string into its HTML entities
#

import argparse

parser = argparse.ArgumentParser(description = 'Convert a string into its HTML entities.')
parser.add_argument('string_to_mung', help = 'String to convert')
parser.add_argument('-l', '--link', action = 'store_true', help = 'Embed the munged string into a mailto: link')
args = parser.parse_args()

def mung(plain):
    munged = ''
    for c in plain:
        munged = munged + '&#' + str(ord(c)) + ';'
    return munged

string_munged = mung(args.string_to_mung)

if (args.link):
    print('')
    print(string_munged + '')
else:
    print(string_munged)


texts:
I posted this answer recently. OP in the StackOverflow question mentioned that it was for educational use, but I can imagine it being used as a debugging aid. Then I decided to improve it slightly and make it a compile-time function. Code:

#include <cassert>
#include <iostream>
#include <string_view>
#include <type_traits>
#include <vector>

#ifndef __GNUC__
static_assert(false, "GCC specific");
#endif // !__GNUC__

// Finds a character in a nul terminated string.
// Returns the last character if sought one isn't found.
// Notes:
// 1. Using this because std::strchr isn't constexpr.
// `PChr` is a separate typename instead of just using Chr* to allow `Chr*` and
// `Chr const*` as the pointer.
// 2. pstr shall not be nullptr.
template <typename PChr, typename Chr>
[[gnu::pure, gnu::nonnull, gnu::returns_nonnull, nodiscard]]
static constexpr auto*
constexpr_strchr(PChr pstr, Chr const value) noexcept {
    // PChr must be a raw pointer type because of gnu::nonnull and
    // gnu::returns_nonnull
    static_assert(std::is_pointer_v<PChr>, "PChr must be a raw pointer type");
    auto constexpr nul = Chr{};
    while (*pstr != value && *pstr != nul) {
        ++pstr;
    }
    return pstr;
}

// Returns distance from ptr to the end of the array.
// Notes:
// 1. ptr shall not be nullptr
// 2. ptr shall be inside the array (arr)
template <typename T, auto size>
[[gnu::const, gnu::artificial, gnu::nonnull, gnu::always_inline, nodiscard]]
inline static constexpr auto
distance_to_end(const T (&arr)[size], T const* const ptr) noexcept {
    return arr + size - ptr;
}

// Returns type T as a string_view.
// Ex: std::string -> "std::string"
template <typename T>
[[gnu::const, nodiscard]]
static constexpr auto type_name_finder() noexcept {
    // __PRETTY_FUNCTION__ means "$FUNCTION_SIGNATURE [with T = $TYPE]".

    // +2 here to skip "= "
    auto const* const begin = constexpr_strchr(__PRETTY_FUNCTION__, '=') + 2;

    // -2 meaning up to "]\0"
    auto const size =
            static_cast<std::size_t>(distance_to_end(__PRETTY_FUNCTION__, begin) - 2);
    return std::string_view{begin, size};
}

// Inline string_view with the type name.
template <typename T>
inline constexpr auto type_name = type_name_finder<T>();

// Example Class
template <typename T1, typename T2>
class my_class {};

int main() {
    // Example use-case
    my_class<int&, std::vector<double>> my_arr[20];
    std::cout << type_name<decltype(my_arr)>;
}

Code uses __PRETTY_FUNCTION__ in GCC and Clang to get a variable's type as a string. I would appreciate any comments on correctness and readability. I used a lot of GCC specific attributes, because __PRETTY_FUNCTION__ is GCC specific and for this reason the code can't be portable anyway.


texts: GetCommonBaseClass: Readabiliy and Functionality

texts:
I have two pieces of they which do almost the same thing. They both return the most common base class of two types. They differ in two aspect:

If one of the arguments is null, code A returns null and code B returns object.
If one of the arguments is an interface type, code A returns null and code B returns object.

My two questions for you:

Which code is more readable?
When it comes down to those differences, should the code:

a. return null.
b. return object.
c. throw an exception?

Code A:

    /// <summary>
    /// Returns the most common type of two types.
    /// If no common type can be found, null is returned.
    /// </summary>
    static public Type GetCommonBaseClass(Type a, Type b)
    {
        if ((a == null) || (b ==null))
            return null;
        if (a.IsInterface || b.IsInterface)
            return null;
        if (a.IsAssignableFrom(b))
            return a;
        while (true)
        {
            if (b.IsAssignableFrom(a))
                return b;
            b = b.BaseType;
        }
    }

    /// <summary>
    /// Returns the most common type of one or more types.
    /// If no common type can be found, null is returned.
    /// </summary>
    static public Type GetCommonBaseClass(params Type[] types)
    {
        if ((types == null) || (types.Length == 0))
            return null;
        Type type = types[0];
        for (int i = 0; i < types.Length; i++)
            type = GetCommonBaseClass(type, types[i]);
        return type;
    }

Code B:

    /// <summary> Finds the most derived common base class of all the provided types, or System.Object if there is no common base class  </summary>
    public static Type CommonBaseClass(params Type[] types)
    {
        if(ReferenceEquals(types,null)) return typeof(object);
        types = types.Where(x => !ReferenceEquals(x,null)).Distinct().ToArray();
        switch (types.Length)
        {
            case 0: return typeof(object);
            case 1: return types[0].IsInterface ? typeof(object): types[0];
            default:
                IEnumerable<IEnumerable<Type>> hierarchies = types.Select(ClassHierarchy).OrderBy(x => x.Count());
                Queue<Type> smallest = new Queue<Type>(hierarchies.First().Reverse());
                hierarchies = hierarchies.Skip(1);
                do
                {
                    int maxPossible = smallest.Count;
                    hierarchies = hierarchies.Select(each => each.Take(maxPossible));
                    Type candidate = smallest.Dequeue();
                    if (hierarchies.All(each => each.Last() == candidate))
                        return candidate;
                } while (smallest.Count > 1);
                return typeof(object);
        }
    }

    ///<summary>Gets the class hierarchy of the provided type, in order of derivation, e.g. : (System.Object,CustomBaseType,CustomConcreteType,...), or the singleton of System.Object type if the provided type is an interface or null </summary>
    public static IEnumerable<Type> ClassHierarchy(this Type type)
    {
        if (type == null || type.IsInterface) type = typeof(object);
        var stack = new Stack<Type>();
        do
        {
            stack.Push(type);
            type = type.BaseType;
        } while (type != null);
        return stack;

    }


texts:
I have a jQuery function using a series of if and else statements. I am wondering if there is a more elegant way I can code this. I am thinking I could create an array with my "hashtag names" and then loop it through a function. However, I am not quite sure how to go about doing that.

setTimeout(function() {
    var i = 0;
    if(window.location.hash == "#" + "somename"){
        var i = 0;
        return scroll(i);
    }

    else if(window.location.hash == "#" + "somethingelse"){
        var i = 1;
        return scroll(i);
    }

    else if(window.location.hash == "#" + "someotherword"){
        var i = 2;
        return scroll(i);
    }

    else if (window.location.hash == "#" + "sometext"){
        var i = 3;
        return scroll(i);
    }
}, 500 );

function scroll(i){
    var title = $('.title').eq(i);
    var top =  $(title).offset().top - 50 ;
    $('html,body').animate({ scrollTop: top }, 'slow');
}

I'm checking to see what hashtag is in the URL, and then scrolling to the part of the page that is related to that hashtag. This method works, but I would like to optimize the if/else part of my code if possible. An array with a loop may not be the best approach. I am open to any ideas.


texts:
Using the wine quality dataset, I'm attempting to perform a simple KNN classification (w/ a scaler, and the classifier in a pipeline). It works, but I've never used cross_val_scores this way and I wanted to be sure that there isn't a better way. For me, it became a little less straightforward using the cross_val_scores inside the pipeline, including the n range

I've included my entire code, as it's fairly short.

import pandas as pd

import pylab as pl

from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline, Pipeline, FeatureUnion
from sklearn.cross_validation import cross_val_score

X = pd.read_csv("https://s3.amazonaws.com/demo-datasets/wine.csv")
y = X.pop('high_quality')

le = LabelEncoder()
X.color = le.fit_transform(X.color)

results = []

for n in range(1, 50, 2):
   pipe = make_pipeline(StandardScaler(),
   KNeighborsClassifier(n_neighbors=n))
   c_val = cross_val_score(pipe, X, y, cv=5, scoring='accuracy').mean()
   results.append([n, c_val])

print results

results = pd.DataFrame(results, columns=["n", "accuracy"])

pl.plot(results.n, results.accuracy)
pl.title("Accuracy with Increasing K")
pl.show()


texts:
I have been learning Python 3 for about a year now. I have been looking for a project to do instead of just going through tutorials and completing some Code Wars challenges. One website suggested that a text game would be something good to work on. So, I tried to come up with a story line and did a basic map design. But, as soon as I started coding I realized that I had better just try something simple first to learn how to break things up so the game could be manageable as it got bigger.

The three small files listed below are what I have so far. You should be able to just copy and paste the code, and then run it. (To run through all the possibilities/options you want to try "N", "S", "E", "e" and then "W".)

I quickly found that using modules is essential. For this simple project I am using a separate file for storage of health and wealth.

I have tried to use descriptive names for variables and functions. I think the "page_01.py" should have a more descriptive name. But, this first little project is basically an experiment for learning. I would also use comments for a bigger game. For now, I think the variable names and function names will allow you to easily figure out what is going on in the code listed below.

Here is main.py

import page_01
import storage

page_01.instructions()
print("You have " + str(storage.health) + " health points and " + str(storage.wealth) + " coins.")

action = input("What do you want to do now?")
page_01.player_move(action)

Here is page_01.py

import storage

def instructions():
  print("You can move N, S, E or W.")

def ask_player_for_move():
  react = input("\nWhat is your next move?")
  player_move(react)

def player_update():
  print("\nYour health is now: " + str(storage.health))
  print("You now have " + str(storage.wealth) + " coins.\n")

def player_move(action):
  if action == "N":
    print("You stepped on a bear trap.")
    storage.health -= 10
    player_update()
    ask_player_for_move()
  elif action == "S":
    print("You tripped over a pengiun!")
    print("But, you found a small bag of 15 coins.")
    storage.health -= 3
    storage.wealth += 15
    player_update()
    ask_player_for_move()
  elif action == "E":
    print("Err...I wouldn't go that way if I were you!")
    ask_player_for_move()
  elif action == "W":
    print("You ride off into the sunset")
    player_update()
  else:
    print("That is not a valid entry.")
    ask_player_for_move()

Here is storage.py

health = 100

wealth = 10


texts:
Is this the correct implementation of a singleton using enum?

public class Item3 {

public static void main(String[] args) {

    Singleton s=Singleton.Single.INSTANCE.getInstance();
    Singleton s2=Singleton.Single.INSTANCE.getInstance();
    System.out.printf("%b",s==s2);
}
}

class Singleton {
    enum Single{
    INSTANCE;
    Singleton s=new Singleton();
    public Singleton getInstance(){
        if(s==null)
            return new Singleton();
        else return s;
    }
    }
}


texts:
I have a function to check if a character is a delimiter and I wonder if it is consistent or can be improved:

int chDelimit(int ch)
{
    return
        (ch == '\n' || ch == '\t') ||
        (ch >= ' ' && ch <= '/') ||
        (ch >= ':' && ch <= '@') ||
        (ch >= '[' && ch <= '`') ||
        (ch >= '{' && ch <= '~') ||
        (ch == '\0');
}


texts:
This is my command interface:

public interface IConverter {
    void convert();
}

This is my Receiver class:

public class Ogg extends Audio{

    private File src;
    private File trgt;

    public static final String CODEC = "libvorbis";
    public static final String FORMAT = "ogg";

    public Ogg(File src, File trgt){
        this.src = src;
        this.trgt = trgt;
    }

    public void convertToOgg(){
        audioAttr.setCodec(CODEC);
        encoAttrs.setFormat(FORMAT);
        encoAttrs.setAudioAttributes(audioAttr);
        try {
            encoder.encode(src, trgt, encoAttrs);
        } catch (IllegalArgumentException e) {
             e.printStackTrace();
        }
    }
}

And this is my Concrete Command:

package org.hitplay.audio.converters;

public class OggConverter implements IConverter {

    private Ogg ogg;

    public OggConverter(Ogg ogg){
        this.ogg = ogg;
    }
    @Override
    public void convert() {
        ogg.convertToOgg();
    }
}

This is my Invoker class:

public class AudioConverter {
    IConverter audio;

    public AudioConverter(IConverter audi){
        this.audio = audi;
    }
    public void setAudio(IConverter audio){
        this.audio = audio;
    }
    public void convert(){
        audio.convert();
    }
}

I have currently studied the command design pattern on this link and I was wondering if I have implemented the design pattern correctly. f I do not, please tell me why, and how else I can improve this code. Also, I have other classes besides Ogg and OggConverter; I also have Mp3 and Mp3Converter.


texts:
Looking around for modern Crypto libraries.
Could not find anything good.
I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:

Hashing
Hashed Key
Password Key
Salted Challenge Response

The data structures and implementation presented in these questions are based on RFC2104 and this post on codeproject.
This review is for an implementation of HMAC. This is a technique for hashing password using a Key.
Usage Exmple:
Digest<HMac<Sha1>>      digest;
HMac<Sha1>              hasher;

hasher.hash("This is the Key", "This is the message", digest);

hmac.h
#ifndef THORS_ANVIL_CRYPTO_HMAC_H
#define THORS_ANVIL_CRYPTO_HMAC_H

#include "hash.h"

// HMAC: Keyed-Hashing for Message Authentication RFC-2104
namespace ThorsAnvil::Crypto
{

// Look in hash.h for good examples of THash
// ThorsAnvil::Crypto::Sha1
template<typename THash>
struct HMac
{
    static constexpr std::size_t digestSize = THash::digestSize;
    using Hash        = THash;
    using DigestStore = typename Hash::DigestStore;

    void hash(std::string_view key, std::string_view message, DigestStore& digest)
    {
        Hash    hasher;

        enum { BLOCK_SIZE     = 64 };

        /* STEP 1 */
        std::array<Byte, BLOCK_SIZE>   SHA1_Key{'\x00'};
        if (key.size() > BLOCK_SIZE)
        {
            hasher.hashUnsafe(key, &SHA1_Key[0]);
        }
        else
        {
            std::copy(std::begin(key), std::end(key), &SHA1_Key[0]);
        }

        /* STEP 2 */
        std::string     ipad;
        std::string     opad;

        ipad.reserve(BLOCK_SIZE + std::size(message));
        opad.reserve(BLOCK_SIZE + digestSize);
        ipad.resize(BLOCK_SIZE, '\x36');
        opad.resize(BLOCK_SIZE, '\x5c');

        for (int i=0; i< BLOCK_SIZE; i++)
        {
            ipad[i] ^= SHA1_Key[i];
            opad[i] ^= SHA1_Key[i];
        }

        /* STEP 3 */
        std::copy(std::begin(message), std::end(message), std::back_inserter(ipad));

        /* STEP 4 */
        opad.resize(BLOCK_SIZE + digestSize);
        hasher.hashUnsafe(ipad, reinterpret_cast<Byte*>(&opad[BLOCK_SIZE]));

        /* STEP 5 */
        // Moved XOR of opad to STEP 2

        /* STEP 6 */
        // Don't need to copy the hash of ipad onto opad as we hashed
        // into the correct destination.

        /*STEP 7 */
        hasher.hash(opad, digest);
    }
};

}

#endif