texts: Convert list of parameters to a string that can be invoked

texts:
My PowerShell scripting skills are pretty poor, but I've managed to hobble together got this script:

function Create-Process() {
    param([string] $fileName, [string] $arguments)

    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.FileName = $fileName
    $pinfo.Arguments = $arguments

    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo

    return $p
}

function Pack {
    param(
        [string] $nuspec,

        [string] $OutputDirectory,

        [string] $BasePath,

        [ValidateSet("normal", "quiet", "detailed", IgnoreCase = $true)]
        [string] $Verbosity,

        [switch] $Symbols
    )
    # format parameters for NuGet.exe
    If ($BasePath) {
        $basePathParam = "-BasePath ""$BasePath"""
    }
    If ($OutputDirectory) {
        $outputDirParam = "-OutputDirectory ""$BasePath"""
    }
    If ($Verbosity) {
        $verbosityParam = "-Verbosity $Verbosity"
    }
    If ($Symbols) {
        $symbolsParam = "-Symbols"
    }

    Write-Log "Creating package..." -ForegroundColor Green
    $packageTask = Create-Process .\NuGet.exe ("pack $nuspec $basePathParam $outputDirParam $verbosityParam $symbolsParam")
    $packageTask.Start() | Out-Null
    $packageTask.WaitForExit()

    $output = ($packageTask.StandardOutput.ReadToEnd() -Split '[\r\n]') |? {$_}
    $error = (($packageTask.StandardError.ReadToEnd() -Split '[\r\n]') |? {$_})
    Write-Log $output
    Write-Log $error Error

    $global:ExitCode = $packageTask.ExitCode
}

So that I can call it elsewhere like this:

Pack .\Package.nuspec -BasePath $TargetDir -OutputDirectory $TargetDir -Verbosity Detailed

How can I clean up the process for formatting the arguments string? It seems pretty ugly at the moment, and if I have to add any more parameters, it's just going to get uglier. Is there an easy way to convert a list of parameters to a string that's suitable for invoking another function?

Note: Simply passing in the parameters as a single string (e.g. Pack .\Package.nuspec "-Verbosity Detailed") doesn't really solve my issue, it just moves it back one step. I'd like to create the string within Pack itself.


texts:
x = int(input("Choose the number of times you want to spam. "))

y = input("What message do you want to spam? ")

w = x + 1

for i in range(1,w):
    print(y)

Any way to make this program better? I'm currently learning Python.


texts: Finding the balancing point of a subsequence

texts:
This is a little tricky to explain, so bear with me.
Suppose you have an integer X and a list of integers A.  Let A` be a copy of A where all values A[i] != X are replaced by -X.  For example,
X = 5
A = [1, 3, 5, 5, 1, 5, 4, 1, 8]

would result in
A` = [-5, -5, 5, 5, -5, 5, -5, -5, -5]

The task is to find a subsequence B of A` that sums to 0 when the middle
item of B is removed from the summation.  With the previous example we would have
B = [-5, 5, 5, -5, 5, -5, -5]

where the middle item is -5 at index 4 (of A`).  Splitting that into two lists generates
[-5, 5, 5] | [5, -5, -5]

which clearly sum to 0.  If such a subsequence B exists then the program should return the index of that middle value, plus 1.  In this case the return value would be 5.
I have a working solution, however it has pretty bad time complexity:

4.64179955720276e-05 for 15 elements
0.003033149677870525 for 115 elements
0.15060318663344355  for 1015 elements
13.662074328908023   for 10015 elements

It is supposed to scale up to 100,000 elements, and I think that would take about 19 minutes in the current state.  I'd greatly appreciate any suggestions on how I could simplify, improve, and speed up my algorithm.
from collections import deque

def equi ( trim_list ):
    popped_total = sum(trim_list)
    j = popped_total
    k = 0
    center = 0
    for elem in trim_list:
        j = j - elem
        if j+k == 0:
            return center + 1  # list index of sequence middle index
        k = k + elem
        center += 1
    return -1  # no match found

def solution(X, A):
    # Break from function because list too small
    if not len(A) > 5:
        return -1

    # zero out non X values into reciprocal for equality approach
    # use deque for efficient 0 index removal Lifo queue also works
    equi_deque = deque(X if elem is X else 0 for elem in A)

    # iterate through deque and pop values if they fail an equality check
    while len(equi_deque) > 4:
        # is_sequence = equality_point(X, equi_deque)
        is_sequence = equi(list(equi_deque))
        # if value did not fail return index
        if is_sequence != -1:
            # use offset to account for prior elements popped
            return len(A) - len(equi_deque) + 1
        equi_deque.popleft()
    return -1


texts:
I have one complex method with 1890 paths.  I don't know how can be this refactored. Can somebody add some tips about it?  Maybe the MySQL table structure is wrong.

public function fetchClubChallengeState()
{
    $c = $this->caller->in_club;
    $o = $this->opponent->in_club;

    if (!$c || !$o) {
        return false;
    }

    $last = Yii::app()->db->createCommand()
        ->select('*')
        ->from('challenge')
        ->where('(caller=:caller OR caller=:opponent) AND winner=0', [':caller'=>$c, ':opponent'=>$o])
        ->limit(1)
        ->queryRow();

    if ($last['caller']==$c and $last['opponent']==$o or $last['caller']==$o and $last['opponent']==$c) {
        $created = strtotime($last['created']);

        if ($this->isBetweenDates($created + 1800, $created + 3600)) {
            $this->challengeID = (int)$last['id'];
            $this->callersClubRole = $last['caller'] == $c ? 'caller' : 'opponent';
            $this->callersClub = $last['caller'] == $c ? $last['name_caller'] : $last['name_opponent'];
            $this->opponentsClubRole = $last['opponent'] == $o ? 'opponent' : 'caller';
            $this->opponentsClub = $last['opponent'] == $o ? $last['name_opponent'] : $last['name_caller'];
        }
    }
}

Edit:
The structure of the challenge table:

CREATE TABLE `challenge` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `caller` mediumint(7) unsigned NOT NULL DEFAULT '0',
 `opponent` mediumint(7) unsigned NOT NULL DEFAULT '0',
 `name_caller` varchar(20) NOT NULL DEFAULT '',
 `name_opponent` varchar(20) NOT NULL DEFAULT '',
 `winner` tinyint(1) unsigned NOT NULL DEFAULT '0',
 `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 //...
PRIMARY KEY (`id`),
KEY `c_o` (`caller`,`opponent`),
KEY `winner` (`winner`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

If the challenge was started by Player1's club, that clubs ID goes to the caller field and the ID of the opponents club goes to the opponent field. These two IDs are checked here:
if ($last['caller']==$c and $last['opponent']==$o or $last['caller']==$o and $last['opponent']==$c) {
This means, that the found challenge is between the clubs of the 2 players.

The code is also here.


texts:
I'm working on a password brute-forcer that takes in a password from the user and brute-forces solutions until it finds a match. I was wondering if there is any way to improve performance or readability?

import itertools
import time

Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXiuYZ1234567890-_.")

Password = input("What is your password?\n")

start = time.time()

counter = 1

CharLength = 1

for CharLength in range(25):

    passwords = (itertools.product(Alphabet, repeat = CharLength))

    print("\n")

    print("Currently working on passwords with ", CharLength, " characters.")
    print("We are currently at ", (counter / (time.time() - start)), "attempts per second.")
    print("It has been ", time.time() - start, " seconds.")
    print("We have tried ", counter, " possible passwords.")

    for i in passwords:

        counter += 1

        i = str(i)

        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")

        if i == Password:

            end = time.time()

            timetaken = end - start

            print("\nPassword found in ", timetaken, " seconds and ", counter, "attempts.")

            print("That is ", counter / timetaken, " attempts per second.")

            print("\nThe password is \"%s\"." % i)

            input("\nPress enter when you have finished.")

            exit()

Thanks.


texts: BinarySearch Tree implementation & traversals

texts:
I am practicing various tree algorithms and that require code review for it's efficiency, clarity and also if it can be made better etc.

Is there a better way to call parent.findMin(parent)

TreeNode.java

package binarytree;

public class TreeNode
{
    TreeNode left;
    TreeNode right;
    int data;
    TreeNode parent;
    int size=0;

    TreeNode(int data)
    {
        this.data = data;
        size = 1;
    }

    int size()
    {
        return size;
    }

    void setLeftChild(TreeNode left)
    {
        this.left = left;
        if(left == null)
        {
            left.parent = this;
        }
    }

    void setRightChild(TreeNode right)
    {
        this.right = right;
        if(right == null)
        {
            right.parent =  this;
        }
    }

    void insertInOrder(int d)
    {
        if(d <= data)
        {
            if(left == null)
            {
                setLeftChild(new TreeNode(d));
            }
            else
            {
                left.insertInOrder(d);
            }
        }
        else{
            if(right == null)
            {
                setRightChild(new TreeNode(d));
            }
            else{
                right.insertInOrder(d);
            }
        }
        size++;
    }

    void postOrderTraversal(TreeNode parent)
    {
        if(parent == null) return;

        postOrderTraversal(parent.left);
        postOrderTraversal(parent.right);
        printVal(parent);
    }

    void preOrderTraversal(TreeNode parent)
    {
        if(parent == null) return;

        printVal(parent);
        preOrderTraversal(parent.left);
        preOrderTraversal(parent.right);
    }

    void inOrderTraversal(TreeNode parent)
    {
        if(parent == null) return;

        inOrderTraversal(parent.left);
        printVal(parent);
        inOrderTraversal(parent.right);
    }

    void printVal(TreeNode parent)
    {
        System.out.print(parent.data + "\t");
    }

    /* binary tree find Minimum */
    int findMin(TreeNode parent)
    {
        if(parent == null) return 0;

        int min = parent.data;
        if(parent.left !=null)
        {
            min = Math.min(min, findMin(parent.left));
        }

        if(parent.right != null)
        {
            min = Math.min(min, findMin(parent.right));
        }

        return min;
    }

     /* binary tree find Maximum */
    int findMax(TreeNode parent)
    {
        if(parent == null) return 0;

        int max = parent.data;
        if(parent.left !=null)
        {
            max = Math.max(max, findMax(parent.left));
        }
        if(parent.right != null)
        {
            max = Math.max(max, findMax(parent.right));
        }
        return max;
    }
}

Traversal.java

package binarytree;

import binarytree.TreeNode;
public class Traversals {

    public static void main(String[] args)
    {
        TreeNode parent = new TreeNode(1);
        TreeNode left = new TreeNode(2);
        TreeNode right = new TreeNode(3);
        TreeNode next = new TreeNode(5);

        parent.insertInOrder(left.data);
        parent.insertInOrder(right.data);
        parent.insertInOrder(next.data);

        System.out.println("Pre-order traversal");
        parent.preOrderTraversal(parent);
        System.out.println();

        System.out.println("Post-order traversal");
        parent.postOrderTraversal(parent);
        System.out.println();

        System.out.println("In-order traversal");
        parent.inOrderTraversal(parent);
        System.out.println();

        System.out.println("min element:"+parent.findMin(parent));
        System.out.println("max element:"+parent.findMax(parent));
    }

}


texts:
I have a 2 dimension matrix :

public struct Matrix2D
{
    private double[,] matrix;

    public Matrix2D(double[,] matrix)
    {
        if (matrix == null) throw new ArgumentNullException(nameof(matrix));

        this.matrix = matrix;
    }

    private double[,] Matrix => matrix ?? (matrix = new double[0, 0]);
    public int RowLength => Matrix.GetLength(1);
    public int ColumnLength => Matrix.GetLength(0);
    public double this[int row, int column] => Matrix[row, column];

    public double[,] AsArray() => (double[,])Matrix.Clone();
}

And a method to sum them :

/// <summary>
/// Sums multiple matrices togheter
/// </summary>
/// <param name="matrices">Matrices to add</param>
/// <returns>New matrix with the summated values</returns>
public static Matrix2D Sum(params Matrix2D[] matrices)
{
    if (matrices == null) throw new ArgumentNullException(nameof(matrices));
    if (matrices.Length == 0) return new Matrix2D();
    if (matrices.Length == 1) return matrices[0];

    int rowLength = matrices[0].RowLength;
    int columnLength = matrices[0].ColumnLength;
    double[,] matrix = matrices[0].AsArray();

    for (int matrixIndex = 1; matrixIndex < matrices.Length; matrixIndex++)
    {
        var matrix2D = matrices[matrixIndex];

        if (matrix2D.RowLength != rowLength || matrix2D.ColumnLength != columnLength)
            throw new ArgumentException("Matrixes must have the same size");

        for (int row = 0; row < rowLength; row++)
        {
            for (int column = 0; row < columnLength; row++)
            {
                matrix[row, column] += matrix2D[row, column];
            }
        }
    }

    return new Matrix2D(matrix);
}

At the moment, the complexity is of \$O(mnp)\$, \$m\$ being the number of matrices and \$n\$ being the row length of matrices and \$p\$ the column length.

I'm wondering if there are edge cases that might crash my method, is it a good decision to make my Matrix2D a struct and is there a way to make this more performant? Obviously any other comments are welcomed.


texts: Run time complexity of printing a binary tree level by level

texts:
I have some doubts about running time of following question. The problem is printing a binary tree level by level. For example if tree is like

            5
           / \
          2   6
         / \   \
        7   1   8

Then the output should be like

5
2 6
7 1 8

TreeNode structure is very simple and looks like below;

public class TreeNode {

    public TreeNode left;
    public TreeNode right;
    public int      value;

    public TreeNode(int value) {
        this.value = value;
    }
}

And the code is shown below:

public void printByLevel(TreeNode root) {

    if (root == null) {
        throw new IllegalArgumentException();
    }

    Queue<TreeNode> current = new LinkedList<>();
    current.add(root);

    while (!current.isEmpty()) {

        Queue<TreeNode> parents = current;
        current = new LinkedList<>();

        // print parents
        for (TreeNode parent : parents) {
            System.out.print(parent.value + "  ");
        }

        System.out.println();

        // construct next level by adding children of each parent
        for (TreeNode parent : parents) {

            if (parent.left != null) {
                current.add(parent.left);
            }

            if (parent.right != null) {
                current.add(parent.right);
            }
        }
    }
}

Now can I say running time of this algorithm is \$O(N)\$ because every is node processed only once? Or should I say it is \$O(m*N)\$, where \$m\$ refers to number of nodes at the current level because I am printing nodes at each level?


texts:
Problem statement for finding given substring:

  Given a random string S and another string T with unique elements,
  find the minimum consecutive sub-string of S such that it contains all
  the elements in T.

  Example:

S='adobecodebanc'
T='abc'
answer='banc'

How could I have improved the code from construction of code? Should I have created one more compare function? Did I use too many variables? Could I have optimized the code further and much more?

#include <iostream>
#include <stdio.h>

int min(int a, int b, int c);
int max(int a, int b, int c);

int main(void)
{
    char string1[] = "adobecodebanc";
    char *pstring = string1;
    int first_char = -1;
    int second_char = -1;
    int third_char = -1;
    int final_distance = 1000;
    int final_min = 0;
    int final_max = 0;
    int counter = 0;

    /* iteratre over the string and compare each characeter*/
    while (*pstring != '\0')
    {
        /* if any character matches substring condition
           assign index value of the string to that variable  */
        if (*pstring == 'a' || *pstring == 'b' || *pstring == 'c')
        {
            if (*pstring == 'a')
            {
                first_char = counter;
            }
            else if (*pstring == 'b')
            {
                second_char = counter;
            }
            else
            {
                third_char = counter;
            }

            if (first_char != -1 && second_char != -1 && third_char != -1)
            {
                /* get the min and max index value difference*/
                int min_1 = min(first_char, second_char, third_char);
                int max_1 = max(first_char, second_char, third_char);
                int distance = max_1 - min_1;

                /*track the minimum substring so far*/
                if (distance < final_distance)
                {
                    final_distance = distance;
                    final_min = min_1;
                    final_max = max_1;
                }
            }
        }
        pstring++;
        counter++;
    }

    int temp = final_min;

    while (final_max >= temp)
    {
        std::cout << string1[temp];
        temp++;
    }
    std::cout << std::endl;
    return 0;
}

/* Find the min index value*/
int min(int first_char, int second_char, int third_char)
{
    if (first_char < second_char)
    {
        if (first_char < third_char)
        {
            return first_char;
        }
        else
        {
            return third_char;
        }
    }
    else
    {
        if (second_char < third_char)
        {
            return second_char;
        }
        else
        {
            return third_char;
        }
    }
}

/* Find the max index value*/
int max(int first_char, int second_char, int third_char)
{
    if (first_char > second_char)
    {
        if (first_char > third_char)
        {
            return first_char;
        }
        else
        {
            return third_char;
        }
    }
    else
    {
        if (second_char > third_char)
        {
            return second_char;
        }
        else
        {
            return third_char;
        }
    }
}


texts:
I am putting together an animated drawer from scratch for use but also as a learning experience as I am not very strong with jQuery and would really like to get better.

I am hoping that someone here might take a moment to look over my JSFiddle and give me some direction/tips to help me continue to progress?

For example: Is what I put together clean and correct way of doing things? Is creating a function to init the elements for users who have JavaScript as I have done correct? Will what I wrote function well across browsers or are there better ways of achieving this?

jsFiddle

$(document).ready(function() {

    //Hide message if user has javascript
    function initPage() {
        $('#message').css('marginTop', '-60px');
        $('#message').find('.droid').css('bottom', '-60px');
    }

    function slideMessage() {
        var message = $('#message');
        var tab = $('#tab');
        var margin = $('#message').css('marginTop');
        var speed = 300;

        if (margin != "0px") {
            tab.animate({top: "-90px"}, speed);
            message.delay(speed).animate({marginTop: "0px"}, speed);
            message.find('.droid').delay(1000).animate({bottom: "0px"}, 100);
        } else {
            message.find('.droid').delay(1000).css({bottom: "-60px"}, 100);
            message.animate({marginTop: "-60px"}, speed);
            tab.delay(speed).animate({top: "0px"}, speed);
        }
    }

    initPage();

    setTimeout(function() {
        slideMessage();
    }, 1000);

    $('#message .close, #tab').click(function() {
        slideMessage();
    });
});


texts:
I don't like how this config has so much duplication. Any suggestions on how to at least shorten it somewhat? Normally we only have one server block as the staging server is separate from production, but the client has gotten their own server so we'll need to stage on that.

upstream upgrade-release{
    server 127.0.0.1:8000;
}

upstream upgrade-staging{
    server 127.0.0.1:8010;
}

server {
    listen 80;
    server_name www.upgrade.sg upgrade.sg;

    access_log  /var/log/nginx/upgrade.access.log;
    error_log   /var/log/nginx/upgrade.error.log;

    root /home/upgrade/npcec/release/src/npcec;

    location /media/ {
        expires max;
        access_log off;
    }

    location /static/ {
        expires max;
        access_log off;
    }

    location /robots.txt {
        alias /home/upgrade/npcec/release/src/npcec/static/robots.txt;
        access_log off;
    }

    location /favicon.ico {
        alias /home/upgrade/npcec/release/src/npcec/static/favicon.ico;
        expires max;
        access_log off;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://upgrade-release;
    }
}

server {
    listen 80;
    server_name staging.upgrade.sg;

    access_log  /var/log/nginx/upgrade.access.log;
    error_log   /var/log/nginx/upgrade.error.log;

    root /home/upgrade/npcec/staging/src/npcec;

    location /media/ {
        expires max;
        access_log off;
    }

    location /static/ {
        expires max;
        access_log off;
    }

    location /robots.txt {
        alias /home/upgrade/npcec/staging/src/npcec/static/robots.txt;
        access_log off;
    }

    location /favicon.ico {
        alias /home/upgrade/npcec/staging/src/npcec/static/favicon.ico;
        expires max;
        access_log off;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://upgrade-staging;
    }
}


texts: Formatting phone number without knowing locale

texts:
I am trying to format supplied phone numbers for a web application.  Users in general will be supplying US-based phone numbers, but it is possible for some users to input a phone number from another country.

Here are my assumptions:

Default to US if the number of digits is 7 or 10 after stripping non-digits.  If not, just return the String
Use tested external
libraries where possible since speed isn't an utmost concern (the
service can be run in the background if it is really that slow).
Prefer an external library over a custom regex.

For the first assumption, I am thinking that if there is another country that has phone numbers with 7 or 10 digits, it's not the end of the world to have it formatted in US format.

Here's my code anyway, using Google's libphonenumber:

public static String formatPhoneNumber(String phoneNumber, Locale locale) throws NumberParseException {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber usNumber = phoneUtil.parse(phoneNumber, locale.getCountry());
    return phoneUtil.format(usNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
}

public static String formatUSPhoneNumber(String phoneNumber) throws NumberParseException {

    //First strip out any non-digits
    phoneNumber = stripNonDigits(phoneNumber);

    phoneNumber = (phoneNumber == null) ? BaseConstants.EMPTY_STRING : phoneNumber;
    if ((phoneNumber.length() != 7) && (phoneNumber.length() != 10)) {
        return phoneNumber;
    }
    return formatPhoneNumber(phoneNumber, Locale.US);
}

I am adding this method to be comprehensive, but it's not directly needed for review (credit to SO):

public static String stripNonDigits(final CharSequence input){
    final StringBuilder sb = new StringBuilder(input.length());

    for(int i = 0; i < input.length(); i++){
        final char c = input.charAt(i);
        if(c > 47 && c < 58){
            sb.append(c);
        }
    }
    return sb.toString();
}

The associated JUnit tests:

@Test
public void testFormatPhoneNumber() throws NumberParseException {
  assertEquals(FormUtils.formatPhoneNumber("2122222222", Locale.US), "(212) 222-2222");
  assertEquals(FormUtils.formatPhoneNumber("2122222222", Locale.CANADA), "(212) 222-2222");
  assertEquals(FormUtils.formatPhoneNumber("(021)11111111", Locale.GERMANY), "0211 1111111");
}

@Test
public void testFormatUSPhoneNumber() throws NumberParseException {
  assertEquals(FormUtils.formatUSPhoneNumber("2122222222"), "(212) 222-2222");
  assertEquals(FormUtils.formatUSPhoneNumber("92122222222"), "92122222222");
  assertEquals(FormUtils.formatUSPhoneNumber("(212)2222222"), "(212) 222-2222");
  assertEquals(FormUtils.formatUSPhoneNumber("(212)222-2222"), "(212) 222-2222");
  assertEquals(FormUtils.formatUSPhoneNumber("(212) 222-2222"), "(212) 222-2222");
}

Is there a better way to do this?  Are there tests I should add?


texts: Stripping formatting from text - Am I using an efficient jQuery selector?

texts:
I'm making a comment box using a contenteditable div, but I want to remove formatting from text a user might copy/paste into it (also no CTRL+B or CTRL+I shortcuts allowed either). Only "approved" formatting ("tagged" names, URLs, etc).

Originally I went the regex route but was informed regex + html is not a good approach, so I then tried using jQuery/DOM manipulation and found a solution there as well.

I am worried though, that my jQuery selector used in $nodesToReplace is too long and possibly inefficient although it basically describes what I want returned. I'm just wondering if there was another more elegant/shorter/more efficient way to do this that I may have overlooked. Here's the code:

Two utility functions (for reference)

// Change an Element's type (change it's html tags) to "newType"
jQuery.fn.changeElemTypeTo = function(newType){
  // just make sure it's a plain element name
  newType.replace(/[<\/>]/ig,'');

  var newElemStr = '<' + newType + '>' + this.html() + '</' + newType + '>';
  console.log('*Nodes with tags replaced: ',newElemStr);
  return this.replaceWith(newElemStr);
};

// Remove/strip the html tags from an element
jQuery.fn.removeElemTags = function(){
  var tmp = this.replaceWith(this.html());
  console.log('*Node with tags Removed: ',this.html());
  return tmp;
};

main handler with super long selector in $nodesToReplace...

$('#input').on('paste', function() {
  var $inputDiv = $(this);
  setTimeout(function() {
    var oldHTML = '', newHTML = '';
    // look through the commentbox for headings and other (mostly) block
    // elements
    var $nodesToReplace = $inputDiv.find('h1,h2,h3,h4,h5,h6,address,article,aside,blockquote,div,p,pre,dd,dt');
    var $nodesToRemove = $inputDiv.find('*').not($nodesToReplace);

    $nodesToRemove.each(function(){
      console.log('Nodes with tags to remove: ',$(this).outerHtml());
      $(this).removeElemTags();
    });

    $nodesToReplace.each(function(){
      console.log('Nodes with tags to replace: ',$(this).outerHtml());
      $(this).changeElemTypeTo('p');
    });
  }, 10);
});

I also have a demo on JSBin: http://jsbin.com/adazel/10/edit


texts: Integrate the product of four infinite series functions

texts:
I wrote the following code to integrate the product of four functions.

Two of the functions are hypergeometric functions and the other two are incomplete gamma functions. I have written each function as an infinite series, one per nested loop. The first loop (variable k) is for time.

y1 = 0;
for k = 1:L-1
    for i = 0:N
        total1 = i*log(x) + 2*(n-m-i+k)*log(sig);
        for j = 0:N
            total2 = j*log(y) + 2*(n-m-j+k)*log(sig);
            for p = 0:100
                total3 = 0;
                for q = 0:100
                    temp = (n-m+i+k+p)*log(a);
                    temp = temp - 2*(2*n - 2*m + i + j + 2*k + p + q)*log(sig);
                    temp = temp - func1(k, j+1, q+1) + func2(i+1, j+1, p+1, q+1, k);
                    temp = temp + (i + j + 2*k + p + q)*log(sig^2/(1+a));
                    temp = temp + log(gammainc(b*(1 + x)/sig^2,i + j + p + q));
                    total3 = total3 + exp(temp);
                end
                total4 = func3(k, i+1) + (n - m + i + k + p)*log(a/sig^2);
                total4 = total4 + func5(k, i+1, p+1);
                total4 = total4 + (n - m + i + k + p + 2)*log(sig^2/a);
                total4 = total4 + log(gammainc(a*b/sig^2, i + k + p)));
                total4 = exp(total4) - total3;
                y1 = y1 + exp(total1 + total2 - func5(k, i+1, p+1) + log(total4));
            end
        end
    end
end

Thereafter, I removed the innermost loop the following way to improve speed:

y1 = 0;
for k = 1:L-1
    for i = 0:N
        total1 = i*log(x) + 2*(n-m-i+k)*log(sig);
        for j = 0:N
            total2 = j*log(y) + 2*(n-m-j+k)*log(sig);
            for p = 0:100
                q = 0:100;
                temp = (n-m+i+k+p)*log(a);
                temp = temp - 2*(2*n - 2*m + i + j + 2*k + p + q)*log(sig);
                temp = temp - reshape(func1(k, j+1, q+1),1,101)
                temp = temp + reshape(func2(i+1, j+1, p+1, q+1, k), 1, 101) ;
                temp = temp + (i + j + 2*k + p + q)*log(sig^2/(1+a));
                temp = temp + log(gammainc(b*(1 + x)/sig^2,i + j + p + q));
                total3 = total3 + exp(temp);
                total4 = func3(k, i+1) + (n - m + i + k + p)*log(a/sig^2);
                total4 = total4 + reshape(func5(k, i+1, p+1), 1, 101);
                total4 = total4 + (n - m + i + k + p + 2)*log(sig^2/a);
                total4 = total4 + log(gammainc(a*b/sig^2,i + k + p)));
                total4 = exp(total4) - total3;
                y1 = y1 + exp(total1 + total2 - reshape(func5(k, i+1, p+1),1,101) + log(total4));
            end
        end
    end
end

Can you suggest further changes to improve speed?

Basically this is the function I am trying to integrate:

\begin{eqnarray}
F &=& \sum\limits_{k=1}^{L-1}\sum\limits_{i=1}^{\infty}\sum\limits_{j=1}^{\infty}\sum\limits_{p=1}^{\infty}\left(\frac{x^i\sigma^{2\left(n-m-i+k\right)}}{\left(n-m+1\right)_ii!}\frac{y^j\sigma^{2\left(n-m-j+k\right)}}{\left(n-m+1\right)_jj!}\frac{1}{s\left(s+1\right)\cdots\left(s+p\right)}\right)\nonumber\\
&&\left[\left(\Gamma\left(n-m+j+k\right)\left(\frac{a}{\sigma^2}\right)^{n-m+i+k+p}\int_0^{b*}e^{-\frac{ab}{\sigma^2}}b^{n-m+i+k+p+1}db\right)\right]\nonumber\\
&-&\left(\sum\limits_{q=0}^{\infty}\frac{a^{n-m+i+k+p}}{\sigma^{2\left(2n-2m+i+j+2k+p+q\right)}}\frac{1}{s(s+1)\cdots(s+q)}\int_0^{b*}e^{-\frac{ab+b}{\sigma^2}b^{2n-2m+i+j+p+q+2k+2}}db\right)
\end{eqnarray}


texts: Compute power set of a given set in Python

texts:
Problem:

  Given a set (let's say of integers), return the list of all of its subsets also known as the power set.

It looks to be working, but I would like feedback on the algorithm and Python coding style and techniques as I am new to Python.

def get_power_set(s):

    empty_set = set()
    power_set = [empty_set]

    for elem in s:
        # Need this temporary list because we can't change the power_set list while iterating it. Or so I think.
        new_sets = []
        for power_set_item in power_set:
            new_set = set().union(power_set_item) # Is this the best way to copy set?
            new_set.add(elem)
            new_sets.append(new_set)
        power_set.extend(new_sets)

    return power_set


texts: Google CodeJam 2016 - Ruby - Counting Sheep

texts:
I just wrote a small Ruby class to solve the first of the challenges in the G CodeJam. I am not strong at this sort thing so very sure it can be simplified massively! The program is correct for both the small and large inputs.

Challenge

  Problem

  Bleatrix Trotter the sheep has devised a strategy that helps her fall
  asleep faster. First, she picks a number N. Then she starts naming N,
  2 × N, 3 × N, and so on. Whenever she names a number, she thinks about
  all of the digits in that number. She keeps track of which digits (0,
  1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as
  part of any number she has named. Once she has seen each of the ten
  digits at least once, she will fall asleep.

  Bleatrix must start with N and must always name (i + 1) × N directly
  after i × N. For example, suppose that Bleatrix picks N = 1692. She
  would count as follows:

  N = 1692. Now she has seen the digits 1, 2, 6, and 9. 2N = 3384. Now
  she has seen the digits 1, 2, 3, 4, 6, 8, and 9. 3N = 5076. Now she
  has seen all ten digits, and falls asleep. What is the last number
  that she will name before falling asleep? If she will count forever,
  print INSOMNIA instead.

  Input

  The first line of the input gives the number of test cases, T. T test
  cases follow. Each consists of one line with a single integer N, the
  number Bleatrix has chosen.

  Output

  For each test case, output one line containing Case #x: y, where x is
  the test case number (starting from 1) and y is the last number that
  Bleatrix will name before falling asleep, according to the rules
  described in the statement.

class CountingSheep
  def solve(input)
    return "INSOMNIA" if input == 0
    current = input
    seen_numbers = []

    loop do
      seen_numbers.concat(current.to_s.split(//))
      break if seen_numbers.uniq.size == 10
      current += input
    end
    current
  end

  def get_inputs(data_size)
    array = []
    path = "~/Desktop/counting_sheep/A-#{data_size}-practice.in"

    File.open(File.expand_path(path), 'rb') do |f|
      f.each_line do |line|
        array << line.strip
      end
    end
    array.shift
    array
  end

  #'small' or 'large' data_size input
  def output(data_size: "small")
    count = 1
    get_inputs(data_size).each do |input|
      output = solve(input.to_i)
      puts "Case ##{count}: #{output}"
      count += 1
    end
  end
end


texts:
I've recently stared learning C++ so I'm new to all of it. I've got my fourth "software" under development. Could someone have a look through and give me some constructive criticism on what should I change or keep the same?

#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>

using namespace std;

void mainmenu();

int choice;
bool cinfail;
int confirmation;
string username, password, password2;

void writetofile(string username){
    ofstream writefile;
    string file = username+".txt";
    writefile.open(file.c_str());
    writefile << password;
    writefile.close();
    mainmenu(); }

void login(){
    cout << "You are being logged in!";}

void registerpassword(){
    cout << "Please enter the password:" << endl;
    cin >> password;
    cout << "Please renter your password:" << endl;
    cin >> password2;
    if (password == password2){
        cin.clear();
        cin.ignore(10000,'\n');
        writetofile(username);
        exit(1);
    }
    else;{
        cout << "Sorry invalid" << endl;
        registerpassword();
    }}

void registerme(){
    cout << "Please enter your username: " << endl;
    getline(cin, username);
    cout << "\nUsername -  \""<< username << "\"\nConfirm? \n\n[1] Yes\n[2] No" << endl;
    cin >> confirmation;
    if (confirmation == 1){
        registerpassword();
    }

    else; {
        cout << "Sorry invalid input, Please try again" << endl;
        cin.clear();
        cin.ignore(10000,'\n');
        registerme();
    }}

void exit(){
    exit(0);}

void mainmenu(){ cout << "Hello, Would you like to log in or register\n[1] Login\n[2] Register\n[3] Exit" <<endl; cin >> choice; do{
    cinfail = cin.fail();
    cin.clear();
    cin.ignore(10000,'\n');

    }while(cinfail == true);{
        switch(choice){
            case 1:
                login();
                break;

            case 2:
                registerme();
                break;

            case 3:
                exit();}}}

main(){
mainmenu();
}


texts:
A balanced array is defined to be an array where for every value n in the array, -n also is in the array.

{-2, 3, 2, -3} is a balanced array.
So is {-2, 2, 2, 2}. But {-5, 2, -2} is not because 5 is not in the array.

I wrote the following class BalancedArray which satisfied above condition.

public class BalancedArray {
public static void main(String args[]) {
    System.out.println("The result is: " + isBalanced(new int[]{-2, 3, 2, -3}));
}
public static boolean isBalanced(int[] a){
    boolean status = false;
    for(int i = 0; i < a.length; i++) {
        if(a[i] > 0) {
            for(int j = i+1; j < a.length; j++) {
                if(a[i] == Math.abs(a[j])) {
                    status  =  true;

                }
            }

        } else if(a[i] < 0) {
            for(int k = i+1; k < a.length; k++) {
                if(Math.abs(a[i]) == a[k]) {
                    status = true;

                }
            }

        }
        System.out.println(status);
      if(status) {
          status= true;
      } else {
          status  = false;
          break;
      }
    }

    return status;
}
}

Is this proper way to check Balanced array or I am missing some conditions to check in array??


texts: std::function alternative with no dependencies

texts:
An alternative to std::function for when compile time is more important than runtime performance. Doesn't pull in any headers.

(#include <functional> pulls in 19k lines of code.)

This satisfies my needs, but I'm curious how it could be improved (without adding any dependencies).

template<typename>
class func;

// Alternative to std::function for when compile time is
// more important than runtime performance. Doesn't pull in
// any headers.
template<typename Result, typename... Arguments>
class func<Result (Arguments...)> {

  struct holder {
    virtual ~holder() {}
    virtual Result call(Arguments...) = 0;
    virtual holder* clone() = 0;
  };

  template<typename Lambda>
  struct lambda_holder : public holder {
    virtual ~lambda_holder() {}
    Lambda lambda;
    lambda_holder(Lambda l) : lambda(l) { }
    Result call(Arguments... args) override {
      return lambda(args...);
    }
    holder* clone() override {
      return new lambda_holder<Lambda>(lambda);
    }
  };

public:

  func() { }

  func(const func& f) {
    holder = f.holder->clone();
  }

  func& operator=(const func& f) {
    if(holder) { delete holder; }
    holder = f.holder ? f.holder->clone() : nullptr;
    return *this;
  }

  // Create from a lambda.
  template<class F>
  func(F f) {
    holder = new lambda_holder<F>{f};
  }

  ~func() {
    if(holder) { delete holder; }
  }

  Result operator()(Arguments... args) const {
    assert(holder);
    return holder->call(args...);
  }

  operator bool() const {
    return holder;
  }

private:

  holder *holder = nullptr;

};


texts:
I'm testing here ways to find prime number. But it looks weird because of repeating parts. Are there any options to make it prettier. Probably I should use cycle or wrap it in an interface.
        start = System.nanoTime();
        res = PoKrestyanski.letsUseit(numbers);
        duration = (System.nanoTime() - start) / 1_000_000;
        System.out.println(res);
        System.out.println("Time spent: " + duration + " ms" + "\n\n");

        //using threads
        int nthreads = 4;
        PrimeThreads<Integer> threadsHandler = new PrimeThreads<>(nthreads);
        start = System.nanoTime();
        PrimeThreads.Answer<Integer> answer = threadsHandler.runThreads(numbers, nthreads, pred);
        duration = (System.nanoTime() - start) / 1_000_000;
        res = answer.isAnswerFound();
        System.out.println(res);
        System.out.println("Time spent: " + duration +  " ms" + "\n\n");

        //using Parallel Stream
        //System.out.println("parallelStream");
        start = System.nanoTime();
        Stream<Integer> parStream = numbers.parallelStream();
        res = parStream.anyMatch(pred);
        duration = (System.nanoTime() - start) / 1_000_000;
        System.out.println(res);
        System.out.println("Time spent: " + duration +  " ms");
```


texts:
I currently have two (core) classes :

public abstract class BO<TConfig> where TConfig : BOConfigBase
{
    protected TConfig Config { get; set; }
    internal List<BC> _BCs { get; set; }

    public abstract void Init();

    public void Process() => _BCs.ForEach(bc => bc.Process());
}

public class BOOne : BO<BOConfigOne>
{
    public BOOne(BOConfigOne config)
    {
        Config = config;
    }

    public override void Init()
    {
        _BCs = new List<BC>()
        {
            BCA.Init(Config),
            BCB.Init(Config),
            BCC.Init(Config),
            BCOneA.Init(Config)
        };
    }
}

Then the code for my BCs

public abstract class BC
{
    protected BOConfigBase Config { get; set; }
    public abstract void Process();
}

public class BCA : BC
{
    private BCA()
    {
    }

    public static BCA Init(BOConfigBase config)
    {
        BCA ret = new BCA { Config = config };
        return ret;
    }

    public override void Process()
    {
        Config.Counter += 1;
    }
}

To call this, I will do this :

    static void Main()
    {
        {
            var boConfigOne = new BOConfigOne()
            {
                A = "one",
                B = "one",
                C = "one",
                One = "one"
            };
            var testBO = new BOOne(boConfigOne);
            testBO.Init();
            testBO.Process();
            Console.WriteLine(
                $"A = {boConfigOne.A}, B = {boConfigOne.B}, C = {boConfigOne.C}, One = {boConfigOne.One}, Counter = {boConfigOne.Counter}");
        }

        {
            var boConfigTwo = new BOConfigTwo()
            {
                A = "two",
                B = "two",
                C = "two",
                Two = "two"
            };

            var testBOTwo = new BOTwo(boConfigTwo);
            testBOTwo.Init();
            testBOTwo.Process();
            Console.WriteLine(
                $"A = {boConfigTwo.A}, B = {boConfigTwo.B}, C = {boConfigTwo.C}, Two = {boConfigTwo.Two}, Counter = {boConfigTwo.Counter}");
        }
        Console.ReadKey();
    }

BO stands for Business Orchestration, and BC for Business Component. A BC would perform a single function, and a BO would contain several of these re-usable BCs.

I would like to change the BO to be able to Init all the BCs generically, something like Init => BCs.Foreach(bc => bc.Init(Config));. The problem is that my BC's Init's are static, hence I can't put it in an interface, and call it on the interface, nor can I put it in the base abstract method, and override it.

Does anyone have a better solution for me?


texts: Spreading the load more evenly from a background thread

texts:
I have a background thread which runs every 5 minutes. I am using ScheduledExecutorService for this. Every five minutes, I am making a call to one of my service and parsing the response coming back from that service.

public class ThreadScheduler {

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public void startScheduleTask() {

        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                try {
                    callService();
                } catch (Exception ex) {
                    // log error
                }
            }
        }, 0, 5L, TimeUnit.MINUTES);
    }

    public void callService() throws Exception {
        // execute the service and parse the response
    }
}

Now the above code is running in 1000 machines and they all are started at the same time, so that means it will make all the 1000 calls every 5 minutes simultaneously to my service.  I'm trying to spread the load more evenly over a 5 minute window. Is this possible to do by any chance with the above code?

I am just trying to spread the load more evenly on my service over the 5 minute window so that it doesn't hit my service at the same time which will put more load once all the systems are started up  simultaneously.

I came up with the below code trying to spread the load more evenly over the five minute window:

public class ThreadScheduler {

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public void startScheduleTask() {

        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                try {
                    callService();
                } catch (Exception ex) {
                    // log error
                }
            }
        }, (int)(Math.random()*5*60), 5*60L, TimeUnit.SECONDS);
    }

    public void callService() throws Exception {
        // execute the service and parse the response
    }
}

I am opting for code review to see whether this way load will get evenly spread out over the 5 minute window or not.


texts: unique_ptr basic implementation for single objects

texts:
This is an implementation to simulate the basic functionality of unique_ptr.
This doesn't provide features like custom deleter and make_unique().

I would really appreciate any feedback to improve the below code, any other api's that I should be providing etc.

my_unique_ptr.h

#ifndef MY_UNIQUE_PTR_H_
#define MY_UNIQUE_PTR_H_

#include <utility>

namespace kapil {
  template <typename T>
  class unique_ptr final {
    private:
      T* ptr_;
      unique_ptr(const unique_ptr&) = delete;               // Make unique_ptr non copy constructible
      unique_ptr& operator = (const unique_ptr&) = delete;  // Make unique_ptr non copy assignable

    public:
      explicit unique_ptr (T* ptr = nullptr) noexcept
        : ptr_{ptr} { }

      unique_ptr(unique_ptr<T>&& rval) noexcept               // Move constructor
        : ptr_{rval.ptr_} {
        rval.ptr_ = nullptr;
      }

      unique_ptr& operator = (unique_ptr&& rhs) noexcept {   // Move assignment
        delete ptr_;
        ptr_ = rhs.ptr_;
        rhs.ptr_ = nullptr;
        return *this;
      }

      ~unique_ptr() noexcept {
        delete ptr_;
      }

      T* release() noexcept {
        T* old_ptr = ptr_;
        ptr_ = nullptr;
        return old_ptr;
      }

      void reset(T* ptr = nullptr) noexcept {
        delete ptr_;
        ptr_ = ptr;
      }

      void swap(unique_ptr& rhs) noexcept {
        std::swap(ptr_, rhs.ptr_);
      }

      T* get() const noexcept {
        return ptr_;
      }

      explicit operator bool() const noexcept {
        return (ptr_ != nullptr);
      }

      T& operator * () const {
        return *ptr_;
      }

      T* operator -> () const noexcept {
        return ptr_;
      }

      friend bool operator == (const unique_ptr& lhs, const unique_ptr& rhs) {
        return lhs.get() == rhs.get();
      }

      friend bool operator != (const unique_ptr& lhs, const unique_ptr& rhs) {
        return !(lhs == rhs);
      }
  };

  template <typename T>
  void swap(unique_ptr<T>& lhs, unique_ptr<T>& rhs) {
    lhs.swap(rhs);
  }
} //kapil

#endif


texts:
Looking to optimize this method so it will run quicker, but can't seem to find anything.  WOrking in .NET 3.5.  ExcludedWords and NewCodes are both HashSet of strings.

    private bool isValid(String code)
    {
        String pattern = "[a-zA-Z]{3}";

        if (chkLessThan2Letters.Checked && Regex.IsMatch(code, pattern))
        {
            return false;
        }

        foreach (string s in excludedWords)
        {
            if (code.Contains(s))
            {
                return false;
            }
        }

        if (newCodes.Contains(code))
        {
            return false;
        }

        return true;
    }


texts:
Link: https://leetcode.com/problems/reverse-nodes-in-k-group/
Problem description:

Given a linked list, reverse the nodes of a linked list k at a time
and return its modified list.
k is a positive integer and is less than or equal to the length of the
linked list. If the number of nodes is not a multiple of k then
left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes
themselves may be changed.
e.g. Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

My solution:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode** subHead = &head;
        int i = 0;
        for (ListNode* subTail = head; subTail != NULL; subTail = subTail->next) {
            if ((i+1) % k == 0) {
                ListNode* temp = subTail->next;
                reverse(subHead, &subTail);
                subTail->next = temp;
                subHead = &(subTail->next);
            }
            i++;
        }
        return head;
    }

    void reverse(ListNode** subHead, ListNode** subTail) {
        if (*subHead==NULL) return;
          ListNode* itHead = *subHead;
          ListNode* prev = NULL;
          ListNode* next = NULL;
          ListNode* end = (*subTail)->next;
          while (itHead != end) {
            next = itHead->next;
            itHead->next = prev;
            prev = itHead;
            itHead = next;
          }
        std::swap(*subHead, *subTail);
    }
};

This solution was accepted and seemed to do quite well in both space and time. I'm interested in how it can be optimized further, how it can be made more readable, more elegant, or better express good design principles. Note that the data definition and the signature ListNode* reverseKGroup(ListNode* head, int k) is enforced by the question. Feel free to comment on anything you'd like though. Many thanks.


texts:
I am trying to implement a thread-safe LFU cache algorithm, please review my code and would really appreciate some criticism or suggestion. (on naming, design, data structures used, anything)
Some assumptions:

capacity will be larger than 0.
If the cache is full and multiple keys have the same frequency, the least recently used will be evicted.

Here is the code:
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

public interface CacheAlgorithm<K, V> {
    public V get(K key);
    public void put(K key, V value);
}

public class LFU<K, V> implements CacheAlgorithm<K, V> {

    private final ReentrantLock lock;
    private final int capacity;
    private final TreeMap<Integer, Set<K>> frequencyToKeys;
    private final Map<K, V> entries;
    private final Map<K, Integer> frequencies;

    public LFU(int capacity) {
        this.capacity = capacity;
        lock = new ReentrantLock();
        frequencyToKeys = new TreeMap<>();
        entries = new HashMap<>();
        frequencies = new HashMap<>();
    }

    @Override
    public V get(K key) {
        try {
            V value = entries.get(key);
            if (value != null) {
                incrementFrequency(key);
            }
            return value;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void put(K key, V value) {
        try {
            if (entries.containsKey(key)) {
                incrementFrequency(key);
                entries.put(key, value);
            } else {
                if (capacity == entries.size()) {
                    removeLeastFrequentEntry();
                }
                addNewEntry(key, value);
            }
        } finally {
            lock.unlock();
        }
    }

    private void addNewEntry(K key, V value) {
        entries.put(key, value);
        setKeyFrequency(key, 1);
    }

    private void incrementFrequency(K key) {
        int frequency = frequencies.get(key);
        Set<K> keys = frequencyToKeys.get(frequency);
        keys.remove(key);
        if (keys.isEmpty()) {
            frequencyToKeys.remove(frequency);
        }
        setKeyFrequency(key, frequency + 1);
    }

    private void setKeyFrequency(K key, int frequency) {
        frequencies.put(key, frequency);
        frequencyToKeys.putIfAbsent(frequency, new LinkedHashSet<>());
        frequencyToKeys.get(frequency).add(key);
    }

    private void removeLeastFrequentEntry() {
        Map.Entry<Integer, Set<K>> entry = frequencyToKeys.firstEntry();
        Integer frequency = entry.getKey();
        Set<K> keys = entry.getValue();
        K keyToEvict = keys.iterator().next();
        keys.remove(keyToEvict);
        if (keys.isEmpty()) {
            frequencyToKeys.remove(frequency);
        }
        frequencies.remove(keyToEvict);
        entries.remove(keyToEvict);
    }
}


texts: Run multiple python codes and Check with answer data

texts:
I wrote the code for my undergraduate TA jobs, to check assignment codes of students in Python class are correct or not.

Usage of the code is

$ python [test01.py[,test02 , ...] answer.dat grade.md

It will write grades (range 0~100) to a file called grade.md.

"""
Testing Assginments
by kidkkr
03-16-2017
"""

import os
import sys
from difflib import SequenceMatcher

class ResultChecker:
    """ Check python code result with answer data """
    __slots__ = '_srcFiles', '_ansFile', '_gradeFile', '_grade', '_ans'

    def __init__(self, srcFiles, ansFile, gradeFile):
        self._srcFiles = srcFiles
        self._ansFile = ansFile
        self._ans = open(self._ansFile, 'r').read()
        self._gradeFile = gradeFile
        self._grade = "# Grade File\n"

    def _run_code(self, src):
        print('-----------running ' + src + '..-----------')
        os.system('python ' + src + ' > result.swp')
        res = open('./result.swp', 'r').read()
        ratio = int(SequenceMatcher(None, res, self._ans).ratio() * 100)
        self._grade += src + ' ' + str(ratio) + '\n'
        print('result: ' + str(ratio))

    def check(self):
        for src in self._srcFiles:
            self._run_code(src)
        open(self._gradeFile, 'w').write(self._grade) # Write _grade to a file
        print('Checking has completed.')
        print(self._gradeFile + ":")
        print(self._grade)

def __main__():
    if len(sys.argv) < 2: # Check arguments
        raise ValueError('')

    srcFiles = sys.argv[1:-2]
    ansFile = sys.argv[-2]
    gradeFile = sys.argv[-1]

    ResultChecker(srcFiles, ansFile, gradeFile).check()

if __name__ == '__main__':
    __main__()


texts: Worst case runtime analysis of a string partitioning algorithm

texts:
Give all the partitionings of  a string s such that every substring of the partition is a
  palindrome

What is the time complexity of this solution? And, how can I improve my code overall?

List<List<String>> resultLst;
ArrayList<String> currLst;
public List<List<String>> partition(String s) {
    resultLst = new ArrayList<List<String>>();
    currLst = new ArrayList<String>();
    backTrack(s,0);
    return resultLst;
}
public void backTrack(String s, int l){
    if(currLst.size()>0 //the initial str could be palindrome
        && l>=s.length()){
            List<String> r = (ArrayList<String>) currLst.clone();
            resultLst.add(r);
    }
    for(int i=l;i<s.length();i++){
        if(isPalindrome(s,l,i)){
            if(l==i)
                currLst.add(Character.toString(s.charAt(i)));
            else
                currLst.add(s.substring(l,i+1));
            backTrack(s,i+1);
            currLst.remove(currLst.size()-1);
        }
    }
}
public boolean isPalindrome(String str, int l, int r){
    if(l==r) return true;
    while(l<r){
        if(str.charAt(l)!=str.charAt(r)) return false;
        l++;r--;
    }
    return true;
}


texts:
This program adds together all elements in an array with the function parallelReduce. Includes testing on an initialization with all 1's and a calculation of the speed up. I only tried to optimize the kernel itself, not the data transfer by initializing on the GPU for example.
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <iostream>
#include <chrono>
#include <assert.h>

// To make error checking easier
inline cudaError_t checkCuda(cudaError_t result)
{
    if (result != cudaSuccess) {
        fprintf(stderr, "CUDA Runtime Error: %s\n", cudaGetErrorString(result));
        assert(result == cudaSuccess);
    }
    return result;
}

/*
Parallel reduce helper function. When run
with n/2 threads, changes array a to a' such that
the sum of the first n elements of a is equal to
the sum of the first \lceil n/2 \rceil elements of a'
*/
__global__ void reduce(int* a, int n)
{
    int i = threadIdx.x + blockDim.x * blockIdx.x;
    int stride = gridDim.x * blockDim.x;

    for (int j = i; j < n / 2; j += stride)
    {
        a[j] += a[n - 1 - j];
    }
}

/*
For an array a of length n, puts the sum of all elements in a[0]
*/
void parallelReduce(int* a, int n)
{
    // Get some information about the GPU
    cudaDeviceProp prop;
    cudaGetDeviceProperties(&prop, 0);
    int multiProcessors = prop.multiProcessorCount;

    // Repeatedly use the helper function reduce to condense
    // a to its first element
    while (n > 1) {
        int threadsPerBlock = 256;
        int numberOfBlocks = 32 * multiProcessors;
        reduce << <numberOfBlocks, threadsPerBlock >> > (a, n);
        checkCuda(cudaGetLastError());
        n = (n + n % 2) / 2; // Rounds n/2 up.
    }
}

int main()
{
    // Initialize vector with N 1's.
    int N = (2 << 27) + 1; // The array size gets too big before we would need a long or long long for N.
    size_t size = N * sizeof(int);
    int* h_a;
    checkCuda(cudaMallocHost(&h_a, size));

    for (int i = 0; i < N; i++) {
        h_a[i] = 1;
    }

    // Copy to device (can be done asynchronically to hide transfer time, but
    // that messes up the timing of the kernel).
    int* d_a;
    checkCuda(cudaMalloc(&d_a, size));
    checkCuda(cudaMemcpy(d_a, h_a, size, cudaMemcpyHostToDevice));

    // Calculate the sum sequentially and time it.
    auto tic = std::chrono::high_resolution_clock::now();
    int hostSolution = 0;
    for (int i = 0; i < N; i++)
    {
        hostSolution += h_a[i];
    }
    auto toc = std::chrono::high_resolution_clock::now();
    int duration = std::chrono::duration_cast<std::chrono::milliseconds>(toc - tic).count();

    std::cout << "The sequential function says the answer is " << hostSolution << " this took " << duration
        << " ms." << std::endl;

    // Kernel computation
    tic = std::chrono::high_resolution_clock::now();
    parallelReduce(d_a, N);
    checkCuda(cudaDeviceSynchronize());
    toc = std::chrono::high_resolution_clock::now();
    int parallelDuration = std::chrono::duration_cast<std::chrono::milliseconds>(toc - tic).count();

    // Copy result back to host
    int solution;
    checkCuda(cudaMemcpy(&solution, &d_a[0], sizeof(int), cudaMemcpyDeviceToHost));

    // Print the parallel result and speed up:
    std::cout << "The parallel function says the answer is " << solution << " this took " << parallelDuration
        << " ms." << std::endl;

    std::cout << "This means we have achieved a speed up of " << duration / parallelDuration << std::endl;
}


texts: Reading numbers from three text files in C++

texts:
This code is supposed to read some text files. What should I do in order to optimize my code. I was confused about writing a user defined function so that I can pass any text to it and it stores it in vectors. I have different types of vectors as you see below.

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

int main()
{
    unsigned short int num1;
    float num2, num3;
    vector<unsigned short int>index;
    vector<float>lenght;
    vector<float>coordinate;
    ifstream InFile1;
    ifstream InFile2;
    ifstream InFile3;
    InFile1.open("E:\\Programming Languages\\HelloC++\\Geodetic\\Index.txt");
    InFile2.open("E:\\Programming Languages\\HelloC++\\Geodetic\\Lenght.txt");
    InFile3.open("E:\\Programming Languages\\HelloC++\\Geodetic\\Coordinate.txt");
    if (!InFile1 || !InFile2 || !InFile3){
        cerr << "Sorry Couldn't Open The File\n.";
    }
    while (InFile1 >> num1) {
        index.push_back(num1);
    }
    while (InFile2 >> num2) {
        lenght.push_back(num2);
    }
    while (InFile3 >> num3){
        coordinate.push_back(num3);
    }
    for (size_t i = 0; i < coordinate.size(); i++) {
        cout << coordinate[i]<<endl;
    }
    return 0;
}


texts:
My code prints the next 20 leap years:

def loop_year(year):
    x = 0
    while x < 20:
        if year % 4 != 0 and year % 400 != 0:
            year +=1
            ##print("%s is a common year") %(year)
        elif year % 100 != 0:
            year +=1
            print("%s is a leap year") % (year)
            x += 1

loop_year(2020)

I want to use fewer lines. I thought of using a for but some people said it was a waste of time. What else can I do?


texts:
I just start learning to code in C#.
Is there any other short way to make calculator like this

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

namespace Calculator
{
   class Program
{

    static void Main(string[] args)
    {
        float result = 0;
        //Getting Input of First number
        Console.WriteLine("Enter first number");
        float num1 = float.Parse(Console.ReadLine());

        //Getting Input of second number
        Console.WriteLine("Enter second number");
        float num2 = float.Parse(Console.ReadLine());

        //Getting the math operator
        Console.WriteLine("Enter operator");
        string op = Console.ReadLine();

        switch (op) {

            case "+" : result = num1 + num2;
                break;
            case "-":
                result = num1 - num2;
                break;
            case "*":
                result = num1 * num2;
                break;
            case "/":
                result = num1 / num2;
                break;
            case "%":
                result = num1 % num2;
                break;

        }
        Console.WriteLine("Result = " + result);

    }
  }
}


texts: Linked list vs array performance for RemoveAt() function

texts:
I am trying to compare the RemoveAt() function performance in an array and linked list.

For array:

public T RemoveAt(int index)
{
    if (index >= this.count || index < 0)
    {
        throw new ArgumentOutOfRangeException(
            "Invalid index: " + index);
    }

    T item = this.arr[index];

    Array.Copy(this.arr, index + 1,

        this.arr, index, this.count - index - 1);

    this.arr[this.count - 1] = default(T);

    this.count--;

    return item;
}

For linked list:

public T RemoveAt(int index)
{
    if (index < 0 || index >= count)
    {
        throw new IndexOutOfRangeException("Invalid Index" + index);
    }
    else
    {
        int currentindex = 0;
        ListNode currentnode = this.head;
        ListNode prevnode = null;

        while (currentindex<index)
        {
            prevnode = currentnode;
            currentnode = currentnode.nextnode;
            currentindex++;
        }
        // Remove the found element from the list of nodes

        RemoveListNode(currentnode, prevnode);

        // Return the removed element

        return currentnode.element;

    }
}

private void RemoveListNode(ListNode node, ListNode prevNode)
{

                 prevNode.nextnode = node.nextnode;
}

Main program:

I have inserted 10K elements in each and I am trying to remove the 500th element.

Stopwatch s=new Stopwatch();
CustomArrayList<int> listusingArray = new CustomArrayList<int>(10000);
Console.WriteLine("Deleting 500th elements from array........\n");

s.Start();
listusingArray.RemoveAt(500);
s.Stop();

Console.WriteLine("Time taken to delete from array: " + s.Elapsed);

DynamicList<int> listusingDynamic = new DynamicList<int>();

s.Reset();
Console.WriteLine("Removing 500th elements from Link List........\n");

s.Start();
listusingDynamic.RemoveAt(500);
s.Stop();

Console.WriteLine("Time taken to remove from list: " + s.Elapsed);

Output:

Time taken to delete from array :00:00:00.0003040

Time taken to delete from list  :00:00:00.0008685

Shouldn't the linked list Remove at() function  be faster as it avoids Array.Copy in array?


texts: Automatically run doctest every time program is run

texts:
I would like this to happen every time I run a program from the command line. Is my approach Pythonic? I'm interested to know whether there is any problem with readability or correctness. Any general advice on better ways of doing things or potential problems are also welcome.

Although the main function is just an example, I'm looking for a review of the rest of the code, which I intend to append to all my existing programs and is therefore not just example code. I have included the example main function here as I used this to observe the different behaviour when including a passing or failing doctest. If any doctest fails, this will be printed to stdout and the program will not run. If all doctests pass, there is no output from the testing and the program runs as normal.

"""Auto doctest.

Code to run the doctests before the main code every time the code is run
from the command line. Uses assert so that running the code in optimised
mode will skip the testing.
"""

def main(arguments):
    """Perform the functions of the program.

    Example doctest:

        >>> 1 + 1
        2

    """
    print('The main function received the following arguments:')
    print(arguments)

def _doctests_pass():
    """Return True if all doctests pass, otherwise False."""
    import doctest
    failure_count, test_count = doctest.testmod()
    return failure_count == 0

if __name__ == '__main__':
    assert _doctests_pass()
    import sys
    main(sys.argv)


texts:
I'm trying to implement an algorithm able to search for multiple keys through ten huge files in Python (16 million of rows each one). I've got a sorted file with 62 million of keys, and I'm trying to scan each ten file in dataset to look for a key and its value.

Sorted file key:

a
b
c
d
...

Each dataset file appears like this:

a 1
d 10
g 3
...

Output (if key does not appear in file set val to 0):

<sum_vals>,a,<val_1_file>,<val_2_file>,...,<val_10_file>
<sum_vals>,b,<val_1_file>,<val_2_file>,...,<val_10_file>
....

Here it is my Python algorithm. I scan file containing key and for each match I take its value. For each line in dataset where dataset is an array containing name of files, I'm scanning and creating an output line with 0 if key is not in and <val_in_file> if it matches.  Everything is working fine on a small set of training data, but it takes long and epic time to process on real data.

import os,sys;

files = ["20140601","20140602","20140603","20140604","20140605","20140606","20140607","20140608","20140609","20140610"]

def printToFile(text):
  f = open('processed/20140601','a')
  f.write(text)
  f.close()

def getKey(line):
  data=line.split(" ")
  return data[0]+ " "+ data[1]

def getPageSource(line):
  data=line.split(" ")
  return data[0]

def getPageTitle(line):
  data=line.split(" ")
  return data[1]

def getPageClicks(line):
  data=line.split(" ")
  return data[2]

def searchWindow(dataset,key):
  isHere = 0;
  total = 0;
  acc = getPageTitle(key)
  for f in dataset:
    line_with_keyword = next((line for line in open("dataset/"+f) if key in line),None)
    if line_with_keyword is not None:
        isHere = 1
        click = getPageClicks(line_with_keyword)
    if(isHere == 1):
        acc = acc.strip('\n') + "," + click
        total += int(click)
        isHere = 0
    else:
        acc = acc.strip('\n') + "," + str(0)
        total += 0
        isHere = 0
    printToFile(str(total)+","+acc.strip('\n')+","+"\n")

with open("processed/sorted_keys") as inSortedKey:
  for line in inSortedKey:
    searchWindow(files,getKey(line).strip("\n"));


texts:
I built a testimonial slider that automatically plays on load and stops auto playing when the slider controls are used to change the active slide.

I feel like it could be optimized easily, especially the adding and removing active class seems like it could be made better but I'm not sure how.

$(document).ready(function(){
        // Check var to see if slider controls has been clicked
        var clickedSlider = false;
        // Automatically change the active Testimonial Slide
        function autoSlide(){
            // Get active Slide en corresponding Control item
            var activeSlide = $('.testimonial-slider-slides a.active');
            var activeControl = $('.testimonial-slider-controls a.active');
            // If last testimonial is active  start back from the beginning
            if(activeSlide.is(':last-child')){
                activeSlide.removeClass('active');
                activeControl.removeClass('active');
                $('.testimonial-slider-slides a').first().addClass('active');
                $('.testimonial-slider-controls a').first().addClass('active');
            } else {
                // Else go to next slide
                activeSlide.removeClass('active');
                activeControl.removeClass('active');
                activeSlide.next().addClass('active');
                activeControl.next().addClass('active');
            }
        }
        // If controls haven't been clicked, autoplay the slider
        window.setInterval(function(){
            if (clickedSlider === false) {
                autoSlide();
            }
        }, 2000);
        // Show corresponding slide when clicking on slider control
        $('.testimonial-slider-controls a').click(function(e){
            e.preventDefault();
            clickedSlider = true;
            $('.testimonial-slider-controls a.active').removeClass('active');
            $(this).addClass('active');
            var slide = ($(this).data('for'));
            $('.testimonial-slider-slides a').removeClass('active');
            $('[data-id="' + slide + '"]').addClass('active');
        });
    });

Any thoughts on this?

Update:
This is the HTML I use:

    Slide 1
    Slide 2
    Slide 3

This was updated after i first posted here but the only real change in the javascript / jquery is the slides are now selected by .testimonial-slider-slides-slide instead of .testimonial-slider-slides a

Thanks to Mike Brant's Answer the data-for and data-id attributes can be left out


texts: Longest common prefix for set of strings

texts:
Question:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example :
Input: strs = ["flower","flow","flight"]
Output: "fl"

Source: https://leetcode.com/problems/longest-common-prefix/
My Code:
public String longestCommonPrefix(String[] strs) {
        StringBuilder lcp = new StringBuilder();

        //compute min length
        int minLength = Integer.MAX_VALUE;
        for(String str:strs){

            if (str.length() < minLength) {
                minLength = str.length();
            }

        }

        for (int i = 0; i < minLength;i++){
            char cmp = strs[0].charAt(i);
        for(String str:strs){

            if (str.charAt(i) != cmp) {
                return lcp.toString();
             }

           }
          lcp.append(cmp);
        }

        return lcp.toString();
    }

Questions:

Current time complexity is O(mn) where n is number of strings and m is the min string length.
Can it be faster?
How to improve code style in general.


texts: Is this the proper way to find the subclass of a polymorphic superclass?

texts:
I came across polymorphism in the book that I'm reading and decided to do a little experiment. Essentially what I did was to create a base class called Asset and two subclasses that derive from Asset, called Property and Stock. I created instances of these two types and passed them to this function:

public static void PrintAsset(Asset theAsset)
{
    Console.WriteLine(theAsset.name);
    Console.WriteLine(theAsset.GetType().ToString());

    string x;

    if (theAsset.GetType() == typeof(Stock))
    {
        Stock theStock = (Stock)theAsset;
        x = (theStock.numShares * theStock.stockPrice).ToString();
    }
    else
    {
        Property theStock = (Property)theAsset;
        x = (theStock.value).ToString();
    }

    Console.WriteLine(x + "\n");
}

Initially, the method only consisted of the first two lines, and the output shocked me since I would've figured the incoming reference (theAsset) would've been cast to Asset, but .GetType().ToString() surprisingly produced "...Stock" and "...Property" in the Console output.

I'm assuming the fact that they allow you to see the true class of the object being passed to the method for a reason, so doing something like this should be considered acceptable, but I was wondering if perhaps you SO/SE folks might disagree. Is there some unforeseen problem that this causes?


texts: Serializing user data to send to another API

texts:
I'm trying to improve my OOP skills in PHP. One of my projects requires me to get user info from one API and send it to another API with a different structure.

I will use a simplified situation, but basically I have a big user array from one API. I need to break this into sub objects (customer and address) and serialize the data ready to be sent as a string over SOAP to another API.

I have the following user classes:

class User_customer{

    public $data;
    public $new_user_obj;

    public function __construct($data){
        $this->data = $data;
        $this->set_data();
    }

    public function set_data(){
        $this->new_user_obj->ID = $this->data->id;
        $this->new_user_obj->FirstName = $this->data->first_name;
        $this->new_user_obj->LastName = $this->data->last_name;
    }

    public function serialize_data(){
        $serializer = new XMLSerializer();

       // Notice I send a second param below - just indicating that sometimes
       // Although very similar, these params could be different per object
        return $serializer->serializeObj($this->new_user_obj, true);
    }
}

class User_address{

    public $data;
    public $new_user_obj;

    public function __construct($data){
        $this->data = $data;
        $this->set_data();
    }

    public function set_data(){
        $this->new_user_obj->ID = $this->data->id;
        $this->new_user_obj->Address = $this->data->home_address;
        $this->new_user_obj->Postcode = $this->data->postal_code;
    }

    public function serialize_data(){
        $serializer = new XMLSerializer();

        // Notice no second param below
        return $serializer->serializeObj($this->new_user_obj);
    }
}

And then in my main handling class, I'd call each section similar to:

$data = get_from_api();
$User_customer = new User_customer($data);
$User_address = new User_address($data);

send_to_other_api($User_customer->serialize_data(), $User_address->serialize_data());

Obvious alarm bells are ringing looking at this. I know that:

These classes are very similar, and there is a lot of code duplication.
I'm sending the same big data array with a lot of 'waste' to each class
I'm calling 'new XMLSerializer' so that means there is some 'coupling'
And no doubt a ton of other things

My instinct tells me I should have a parent class that these two inherit from, but it also looks like I should use an interface as both classes use the same methods. Also, maybe I should send an XMLSerializer object into the constructor when initiating each class (dependency injection?)

Any suggestions for 'the correct' way to write the above code would be helpful.


texts: Copy directories while excluding or isolating certain extensions

texts:
I often find myself wanting to copy directories around with either:

having to copy only specific extensions, or
having to exclude specific extensions.

For this task, I wrote some Python which I am calling from the cmd.

The Python script is humbly called copy_master.py and I have also set an environment variable for it called %Pcopy%.

  copy_master.py

def classify(dirs):
    return {(1, 0): dirs, (0, 1): dirs[::-1], (0, 0): [None, None], (1, 1): [1, 1]}[tuple(map(os.path.isdir, dirs))]

def include(d, files):
    return [f for f in files if not any(f.endswith('.' + x) for x in sys.argv[4].split(',')) and not os.path.isdir(os.path.join(d, f))]

def refuse(d, files):
    return [f for f in files if any(f.endswith('.' + x) for x in sys.argv[4].split(',')) and not os.path.isdir(os.path.join(d, f))]

if __name__ == '__main__':
    import shutil
    import os
    import sys

    if len(sys.argv) < 3 or sys.argv[1].lower() == 'help':
        print('\nParameters:: \n\t > Source and Destination directories: order does not matter; one of the specified '
              'directories MUST NOT exist and this is taken to be the destination. \n\t > Mode: (+) for copying specific'
              ' file extensions only OR (-) for skipping specific extensions. \n\t > Extensions: comma delimited list of'
              ' file extensions to be copied or ignored.\n\nExample Usage:\n\t{0:} {1:} + bdf  -> Copies only bdf files '
              'from {1:} to {0:}\n\t{0:} {1:} - f06,xdb  -> Copies everything but f06 & xbd files from {1:} to {0:}'.format(r'I:\do\not\exist', r'I:\have\the\files\you\want'))
    elif len(sys.argv) > 2:
        src, dst = classify(sys.argv[1:3])
        if src is None:
            raise IOError('The source directory should exist!')
        elif src == 1:
            raise IOError('The destination directory should not exist!')

        if len(sys.argv) == 5:
            mode = sys.argv[3]
            print('\rCopying...', end='')
            shutil.copytree(src, dst, ignore={'+': include, '-': refuse}[mode])
            print('\rCopying completed')
        else:
            q = input('Extensions and execution mode have not been specified. Everything is going to be copied! Proceed (Y/N)?\n::')
            if q.lower() in ['n', 'no']:
                exit()
            else:
                print('Copying...')
                shutil.copytree(src, dst)

Example usages (with the command prompt open, type):

copy only specific extension:

%Pcopy% I:\do\not\exist I:\have\the\files\you\want + txt
#                                                  ^

exclude specific extensions from the copying:

%Pcopy% I:\do\not\exist I:\have\the\files\you\want - xlsx,bat
#                                                  ^

There are a couple of things I am not so happy\sure about:

Have I sacrificed too much readability in the classify() function? Are dicts meant to be (ab)used like that? What should I be returning in the (1, 1) case (if both directories exist)?
Is the use of global sys.argv in include() and refuse() ok?
How can I handle the different ways a user might use the script in the best possible way? Not quite happy about the if statements in the __main__.

Apart from the points discussed above, feel free to suggest other changes or even an entirely different approach. And by all means, use the script if you like it ;)

Bonus Points:
Currently, directories that have to be quoted to be recognized by the cmd are not handled (e.g., C:\users\Example\This&That, note the &)


texts:
I have a own made grid system and made a jQuery function for that to check if there are not too many columns in each row. If so, delete the HTML code of the row.

Normally in my grid system, there fits 12 columns in 1 row, but I can change that.

In HTML, I've written them like this:

...

...

...

...

...

...

...

...

...

...

...

...

In this jQuery function, im checking the number of each [class*="size-"] and counting them up.

    function validateRowWidths() {
        $('.row').each(function (index) {
            var row = $(this),
                columns = 0;
            row.children('[class*="size-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            row.children('[class*="offset-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            row.children('[class*="push-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            row.children('[class*="pull-"]').each(function () {
                var eachSizeNumber = Number($(this).attr('class').match(/\d+$/)[0]);
                columns += eachSizeNumber;
            });

            console.log(columns);

            if (columns > 12) {
                $(this).remove();
                console.log("Row " + (index + 1) + " is has to many colums in it. Remove one or more columns or make them narrower.");
            }
        });
    }

For all the grid extensions such as offset, push or pull i have to write that same each function again.

The HTML markup for the grid extensions looks like this:

...

...

...

...

...

...

...

...

...

...

Can I do this in a better way?


texts:
I'm currently working on a project that involves a MySQL database. To make life a little easier, I've been working on a regex that should validate and pull apart the different sections of the connection URI. All of my testing shows that it does work correctly, but I'd like to challenge everyone to see if they can find any errors in the expression.

^(mysqlx?:\/\/)(?:([\w$_]*)(?::([\w$_]+))?@)?([\w!#$%&'()*+,\-./;=?@[\]_~]*)(?::(\d{1,5}))?(?:\/[\w$_])?$

Please note that this regular expression is using the JavaScript regex engine. It was developed in accordance with the MySQL documentation.


texts: Using a popup to display messages to the user

texts:
I am having a popup which is styled to match the page and am using that single popup to display messages to the user. My popup contains one h1 element and an ASP.NET Label.

The h1 element and Label contents and color change according to the operation: if the information was successfully inserted the h1 text becomes Success and Label's text becomes "Your information was saved".

On incorrect input it changes accordingly, and on some unexpected error it changes the same way.

Currently I am calling three different JavaScript functions on appropriate events from my code behind using RegisterClientScriptBlock.

HTML:

 <asp:Label ID="NewCustomerlblSubmitStatusMsg" runat="server" Text=""></asp:Label>

 <input class="NewCustomercmdSubmitPopUp"  type="button" value="Close" />

CSS:

#NewCustomerSubmitStatusPopUp
    {
    display:none;
    position: fixed;
    width:500px;
    height: 150px;
    top: 50%;
    left: 50%;
    margin-left:-255px;
    margin-top:-110px;
    /*background-color:#F7DFDE; */
    padding:10px;
    z-index:102;
    font-family:Verdana;
    font-size:10pt;
    border-radius:10px;
    -webkit-border-radius:20px;
    -moz-border-radius:20px;
    font-weight:bold;
    }
    #NewCustomerSubmitStatusPopUp h1
    {
        /*color:#BD494A;*/
        padding:20px 0;
        text-align:center;
    }

    .NewCustomercmdSubmitPopUp
    {
        height:30px;
        width:50px;
        margin-left:220px;
    }

    .NewCustomerSubmitPopUpImg
    {
        float:right;
        margin-top:-30px;
        margin-right:-25px;
    }

javascript:

function ShowSubmitSuccessPopUp()
 {

    $('#NewCustomerMask').show("slow");
    $('#NewCustomerSubmitStatusPopUp').show("slow");
    $('#NewCustomerSubmitStatusPopUp').show("slow");
    $('#NewCustomerSubmitStatusPopUp').css({ background: 'white' });
    $('#NewCustomerSubmitStatusPopUp').css({ border: '10px solid #9cc3f7'});
    $('#NewCustomerSubmitStatusPopUp h1').html("Success");
    $('#NewCustomerSubmitStatusPopUp h1').css({ color: '#9cc3f7' });
    $('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').css({ color: '#9cc3f7' });
}

function ShowSubmitErrorPopUp()
{

    $('#NewCustomerMask').show("slow");
    $('#NewCustomerSubmitStatusPopUp').show("slow");
    $('#NewCustomerSubmitStatusPopUp').css({ background: '#F7DFDE' });
    $('#NewCustomerSubmitStatusPopUp').css({ border:'10px solid #BD494A'});
    $('#NewCustomerSubmitStatusPopUp h1').html("Error");
    $('#NewCustomerSubmitStatusPopUp h1').css({ color: '#BD494A' });
    $('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').html("There are some errors in the page.Please rectify the errors by visiting the Errors tab.");
    $('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').css({ color: '#BD494A' });
}

function ShowSubmitUnexpectedErrorPopUp()
{
    $('#NewCustomerMask').show("slow");
    $('#NewCustomerSubmitStatusPopUp').show("slow");
    $('#NewCustomerSubmitStatusPopUp').css({ background: '#F7DFDE' });
    $('#NewCustomerSubmitStatusPopUp').css({ border: '10px solid #BD494A' });
    $('#NewCustomerSubmitStatusPopUp h1').html("Something Went Wrong");
    $('#NewCustomerSubmitStatusPopUp h1').css({ color: '#BD494A' });
    $('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').html("There was some error while submitting your information.Please re-enter the values and try again.");
    $('#ctl00_ContentPlaceHolder1_NewCustomerlblSubmitStatusMsg').css({ color: '#BD494A' });
}

As you can see, for every event, I change text text of the h1 and the label element and change the style too.

Can anybody tell me if I am doing it in a good manner or if there is something wrong?


texts: Using inputted data from vector to create two outputs

texts:
I'm trying to figure out a way to do the exercise 3.20 in the C++ primer book

I have to create a program that reads input into a vector then use that data to create 2 outputs:

one is the sum of each adjacent number
one is the sum of the first and last number moving inwards (as in the 2nd and 2nd last, 3rd and 3rd last etc)

I've created the following code, but it feels off somehow.  Can I simplify/clean up this stuff a bit?

#include <vector>
#include <string>
#include <iostream>
#include <cctype>

using std::cin; using std::cout; using std::endl; using std::vector; using std::string;

int main()
{
    vector<int> nv;
    int n;

    while (cin >> n)
    {
        nv.push_back(n);
    }

    int cnt = 0;
    int output = 0;
    int oldnum = 0;

    //output sum of adjacent
    for (int cn : nv)
    {
        output += cn;
        output += oldnum;
        ++cnt;

        if (cnt == 2)
        {
            cout << output << " ";
            cnt = 1;
            output = 0;
            oldnum = cn;
        }

    }
    cout << endl;

    //output sum of first and last
    int trigger = 1;
    for (decltype(nv.size()) i = 0; i < (nv.size()/2); ++i)
    {
        cout << (nv[trigger - 1]) + (nv[nv.size() - (1 * trigger)]) << " ";
        ++trigger;
    }
    return 0;
}


texts:
I'm looking for feedback on the actual logic of this simple Python 2.7 script.  The automated grader passed it, but I expect it could be make more 'pythonic'.  It was written for homework, and some of the constraints included basic looping constructs only and no function declarations.  This differs from a simple String.find() because it must count substrings with common characters. For example, "bobob" must match "bob" twice.

#! /usr/bin/python
s = 'azcbobobegghakl'  #2 bobs
s = 'auoeunbobnoeubobob,ntonethbobobo'  #5 bobs

seek = 'bob'
matches = 0

for i in range(0,len(s)):
    if s[i] == seek[0]:  #if any input char matches seek string
        if abs(i-len(s)) < len(seek):  #checks not closer to end of input than seek
            break
        match_maybe = True
        match = False
        seek_index = 0
        while (match_maybe):  #look ahead to see if subsequent chars match seek
            seek_index += 1
            if seek_index == len(seek):  #successful match each char of seek
                match = True
                break
            if s[i+seek_index] != seek[seek_index]: #does not match
                match_maybe = False
                break
        if match:
            matches += 1

print 'Number of times bob occurs is: ' + str(matches)


texts: Find given number by summing up integers from 2 sorted arrays

texts:
I am working on an algorithm question in which I need to find out pair of number out of 2 sorted arrays which sum up to the given number. I need to print out the indexes of those pairs rather than number itself.

I have written an algorithm which does work but I am wondering is it the best solution or is there any better way to do it (complexity-wise).

    /**
     * Finds and prints all the pairs of indexes from 2 sorted arrays which sum up to the given number
     * @param array1 The first array
     * @param array2 The second array
     * @param sum The number which needs to be constructed by summing integers of both arrays
     */
    private static void findPairs(int[] array1, int[] array2, int sum) {
        if(array1.length == 0 || array2.length == 0)
            return;

        Map<Integer, Integer> firstArrayMap = new HashMap<Integer, Integer>();

        for(int i = 0; i < array1.length; i++) {
            firstArrayMap.put(sum - array1[i], i);
        }

        for(int i = 0; i < array2.length; i++) {
            if(firstArrayMap.containsKey(array2[i]))
                System.out.println("Pair found at index : " + firstArrayMap.get(array2[i]) + " " + i);

        }

    }


texts:
I wrote an implementation of the Karp-Rabin string matching algorithm in Java 7, based on the discussion in Section 32.2 of Introduction to Algorithms (CLRS). Clearly, I need more experience with numeric programming, because I spent two days wrestling with overflow issues and floating point error, but I believe it works now.

Of course, anything goes, but I'm especially looking for feedback on the following points:

Are there any cases left where it would fail?
How can I improve the design?
How can I make the code more readable?
How can I make the code more robust?
Did I miss any glaring performance traps?

Here's the class constructor and the match method, which do the bulk of the work.

public class KarpRabin {
    final long q, b;
    public static final int NONE = -1;
    Map<Character, Integer> digitMap;

    public KarpRabin(String alphabet) {
        digitMap = new HashMap<>();
        for (int i = 0; i < alphabet.length(); ++i) {
            digitMap.put(alphabet.charAt(i), i);
        }
        q = 26900927; // A prime such that b*q can reasonably fit in
                      // a word for most values of b.
        b = alphabet.length();
        if (b >= q) {
            throw new IllegalArgumentException("b cannot be larger than " + q);
        }
    }

    public int match(String pattern, String text) {
        // Returns location of first match of pattern in text.
        if (pattern.length() > text.length()) {
            throw new IllegalArgumentException("Pattern longer than text.");
        }
        int[] T = digitValue(text);
        int[] P = digitValue(pattern);
        long h, p, t;
        p = t = 0;
        h = expt(b, pattern.length()-1).mod(BigInteger.valueOf(q)).longValue(); // See note [7].

        // Calculate fingerprint of pattern and of first
        // pattern.length-length group in text.
        for (int i = 0; i < pattern.length(); ++i) {
            p = (b*p + P[i]) % q;
            t = (b*t + T[i]) % q;
        }

        for (int s = 0; s < text.length() - pattern.length(); ++s) {
            if (p == t) {
                if (pattern.equals(text.substring(s, s+pattern.length()))) {
                    return s;
                }
            }
            assert s < T.length && s + pattern.length() < T.length :
                "s is " + s + " and s+pattern.length() is " +
                (s + pattern.length());
            t = (b * (t - T[s]*h) + T[s + pattern.length()]) % q;
            // Handle Java's modulus behavior; see note[2].
            t += q;
            t %= q;
            assert t >= 0 : "t is below 0, has value " + t;
       }
       // See note [4].
       if (p == t) {
           if (pattern.equals(text.substring(
               text.length() - pattern.length(), text.length())))
               return text.length() - pattern.length();
       }
       return NONE;
}

Here's a gist with the rest of the code, including the private helper methods.

Although the current code is Java 7, I plan to switch to Java 8 in the near future, so suggestions for where I could make good use of Java 8 features is also welcome.


texts:
This is something I am always asked by managers and clients : "make it random". More often than not, this isn't what they want.

Comments like "I had the same element twice in a row !" and "I don't see lement X often enough !" are common, even if they are part of the "true random".

I came up with the following solution using generics. It's basically a Urn with a safeguard so the last item isn't picked after a refill. I'm looking for ways to improve it. Is it readable ? Is it efficient enough ?

using System;
using System.Collections;
using System.Collections.Generic;

namespace Utils
{
    /// <summary>
    /// Implements "iTunes shuffle" that is to say, it's a random where you can't get twice the same value unless you
    /// already got all the values.
    ///
    /// To avoid having a chance to get twice the same value when refilling the pool, we store the last picked value in
    ///  `_last` and do not put it back when refilling the pool
    ///
    /// author: ray.hubert@riseup.net
    /// </summary>
    public class Shuffler<T> : IEnumerable
    {
        private readonly List<T> _allItems = new List<T>(); // All items used in the shuffler
        private readonly List<T> _pool = new List<T>(); // Remaining items for current series
        private T _last; //Last object extracted from the pool
        private Random _random = new Random();

        private int PoolCount
        {
            get { return _pool.Count; }
        }

        public Shuffler()
        {
        }

        public Shuffler(ICollection<T> allItems)
        {
            if (allItems.Count == 0) throw new ArgumentException("ERROR: initialization list cannot be empty !");
            _allItems.AddRange(allItems);
            PopulatePool();
        }

        public T GetNext()
        {
            if (IsPoolEmpty())
            {
                PopulatePool();
            }
            return PopRandomElement();
        }

        private T PopRandomElement()
        {
            if (PoolCount == 0) throw new ArgumentException("ERROR: initialization list cannot be empty !");
            int randomIndex = _random.Next(PoolCount);
            T item = _pool[randomIndex];
            _pool.RemoveAt(randomIndex);
            if (IsPoolEmpty()) _last = item;
            return item;
        }

        private void PopulatePool()
        {
            _pool.Clear();
            _pool.AddRange(_allItems);
            if (PoolCount > 1) // If _allItems is size 1 we don't remove from the pool : it would be empty
            {
                RemoveLastFromPool();
            }
        }

        private void RemoveLastFromPool()
        {
            _pool.Remove(_last);
            _last = default(T);
        }

        public List<T> GetAllPossibleValues()
        {
            return new List<T>(_allItems);
        }

        private bool IsPoolEmpty()
        {
            return PoolCount == 0;
        }

        public IEnumerator GetEnumerator()
        {
            while (PoolCount > 0)
            {
                yield return PopRandomElement();
            }
        }

        public void Add(T element)
        {
            _allItems.Add(element);
            PopulatePool();
        }
    }
}

Sample usage #1 :

// Loops on all alements and stop
Shuffler<int> shuffler = new Shuffler<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
foreach (int number in shuffler)
{
    Console.Write("Random element : " + number);
}

Sample usage #2 :

// Loops on all elements for ever
Shuffler<string> shuffler = new Shuffler<string> {"Alice", "Bob", "John", "Bill", "Scrooge"};
bool gameIsPlaying = true;
while (gameIsPlaying)
{
    Console.Write("Random element : " + shuffler.GetNext());
}

Points I'm wanting to improve :

The empty constructor seems necessary for the Add() function to work properly (see usage)
Throwing an exception in two code path is suboptimal, I'd rather have a single place to throw it
Readability, "code-cleanness"


texts: Method for getting the DataTable when having connection ID and the SQL command

texts:
I am quite new to C# and to the ASP.NET programming. When maintaining the legacy code, I have found rather terrible implementation of the method that is used on many places to get the DataTable object with the data filled by the SQL command.

Here is my first approach to rewrite it. Does using work with the return as shown below? Should the da and ds be released explicitly somehow? If ds is released, is the returned DataTable reference counted so that it will not be deleted?

public DataTable getdata2(string connection_string_id, string sqlcmd)
{
    string connstring = ConfigurationManager
        .ConnectionStrings[connection_string_id].ConnectionString;

    // Open the connection and return the first table.
    // A single one should be there, only.
    using (SqlConnection con = new SqlConnection(connstring))
    {
        SqlDataAdapter da = new SqlDataAdapter(sqlcmd, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        Debug.Assert(ds.Tables.Count == 1);
        return ds.Tables[0];
    }
}