texts: Collaborative filtering to group similar users and products

texts:
I'm doing product recommendation module based on collaborative_filtering.

The recommendation will be generated by users, products, and products view count

The recommendations can be splited into 2 types:

One is to find which user's favorites is similar to specific user (the _similar_users function)
The other is to find which products is similar to specific product (the  _similar_products function)

However, the implmentation between these two function is similar.

But finally, I got a messy code and not knowing how to make my work more readable.

  def _similar_products
    user_ids = _get_all_user_ids
    matrix = _get_view_history_by_product(user_ids)
    (matrix.keys - [@product.id.to_s] ).inject([]) do |h, other_product_id|
      h <<  [other_product_id, CollaborativeFiltering.sim_distance( matrix, @product.id.to_s, other_product_id.to_s)]
      h
    end
  end

  def _similar_users
    product_ids = _get_all_product_ids
    matrix = _get_view_history_by_user(product_ids)
    related_items = (matrix.keys - [current_user.id.to_s] ).inject([]) do |h, other_user_id|
      h <<  [other_user_id, CollaborativeFiltering.sim_distance( matrix, current_user.id.to_s, other_user_id.to_s)]
      h
    end
  end

  def _get_all_user_ids
    User.all.pluck(:id).map{|c|[c.to_s,0.to_f]}.to_h
  end

  def _get_all_product_ids
    Product.all.pluck(:id).map{|c|[c.to_s,0.to_f]}.to_h
  end

  def _get_view_history_by_product(population_items)
    view_history_group_by('product').inject({}) do |h, (product_id, raw_view_history)|
      view_history = _counting_items_by('user', raw_view_history)
      h[product_id.to_s] = union_items(view_history, population_items)
      h
    end
  end

  def _get_view_history_by_user(population_items)
    view_history_group_by('user').inject({}) do |h, (user_id, raw_view_history)|
      view_history = _counting_items_by('product', raw_view_history)
      h[user_id.to_s] = union_items(view_history, population_items)
      h
    end
  end

  def view_history_group_by(type)
    index = ('user' == type) ? 0 : 1
    Impression.where(impressionable_type: 'Product')
      .pluck(:user_id, :impressionable_id)
      .group_by{|c| c[index]}
  end

  def _counting_items_by(type, raw_list)
    index = ('user' == type) ? 0 : 1
    raw_list.collect{|c| c[index] }.each_with_object(Hash.new(0)) { |word, counts|
      counts[word.to_s] += 1.0
    }
  end

  def union_items(target_items, population_items)
    target_items.merge(population_items) { |k, v1, v2|
      [v1, v2].max
    }
  end


texts: Two icon animations — one on the left, one on the right

texts:
I have two icon animations that pretty much do the same thing, the only difference between them is positioning... one is left and the other right.

I would like to use one block of code for both left and right icon animations.

//////////// Left Icon Animation ////////////
$('.recent .left-icon').css({opacity:0, left:33});
$('.recent .controls-wrap').hover(function() {
    $(this).find('.left-icon').stop()
        .animate({left:63}, {duration:300})
        .animate({opacity:'0.99'}, {duration:400});
},function() {
    $(this).find('.left-icon').stop()
        .animate({left:33}, {duration:550})
        .animate({opacity:'0'}, {duration:300});
});

//////////// Right Icon Animation ////////////
$('.recent .right-icon').css({opacity:0, right:33});
$('.recent .controls-wrap').hover(function() {
    $(this).find('.right-icon').stop()
        .animate({right:63}, {duration:300})
        .animate({opacity:'0.99'}, {duration:400});
},function() {
    $(this).find('.right-icon').stop()
        .animate({right:33}, {duration:550})
        .animate({opacity:'0'}, {duration:300});
});


texts: Visualization showing overlays of points

texts:
I'm fairly new to d3 and am wanting to create a visualization that will allow a user to check whether or not a device will be in range of a bluetooth speaker.

I was able to hack together most of what I want, but am not sure if I'm following d3 best practices. This will be eventually integrated with React. Any feedback on style/efficiency is appreciated.

(Note: you'll want to view in the full page)

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height"),
  radius = 8,
  unitRadius = 64;

var points = d3.range(10).map(function() {
  return {
    x: Math.round(Math.random() * (width - radius * 2) + radius),
    y: Math.round(Math.random() * (height - radius * 2) + radius)
  };
});

var circle = d3.range(1).map(function() {
  return {
    x: width / 2,
    y: height / 2
  };
});

var points = svg
  .selectAll("circle.point")
  .data(points)
  .enter()
  .append("circle")
  .attr("class", "point")
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", radius)
  .style("fill", "red");

var circle = svg
  .selectAll("circle.unit")
  .data(circle)
  .enter()
  .append("circle")
  .attr("class", "overlay")
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", unitRadius)
  .style("fill", "blue")
  .call(
    d3
    .drag()
    .on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended)
  );

function dragstarted(d) {
  d3.select(this)
    .raise()
    .classed("active", true);
}

function dragged(d, i) {
  d3.select(this)
    .attr("cx", (d.x = d3.event.x))
    .attr("cy", (d.y = d3.event.y));

  var inside = d3.selectAll("circle.point").style("fill", function(p) {
    var x = d.x - p.x;
    var y = d.y - p.y;
    var dis = Math.sqrt(x * x + y * y);
    if (dis <= Math.abs(unitRadius - radius)) {
      return "green";
    } else {
      return "red";
    }
  });
}

function dragended(d) {
  d3.select(this).classed("active", false);
}
.overlay {
  fill-opacity: 0.1;
}
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<svg width="960" height="500"></svg>


texts: Get value from an async function in Outlook Web Addin

texts:
I'm working on an Outlook Web Addin that gets the email body. So in the Office API you could get the email body in two types: Simple Text and Html.

Our requirement is to get the HTML format so this is easy, however, even if the email body is empty the HTML format still returns a value which is the HTML elements but does not have contents in it. So my solution is to check first for the Simple Text version of the email body then if there is a content get the HTLM format version.

Please see the below codes:

var mailItem = Office.context.mailbox.item;

mailItem.body.getAsync(Office.CoercionType.Text, function (result) {
    if (result.status === Office.AsyncResultStatus.Succeeded) {
        var normalizeValue = null;

        if (result.value) {
            normalizeValue = result.value.trim();
        }

        if (normalizeValue !== '') {
            mailItem.body.getAsync(Office.CoercionType.Html, function (result) {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    // the value will be initialized in input value
                    $('#body').val(result.value.trim());
                }
            });
        }
    }
});

I would like to get the value from the 'Text' type and pass this in a variable then check the variable then run the getAsync for the html version separately instead of having the codes inside the method of body.getAsync. Or anything the code could improve?


texts: Sqlite.swift -- Selecting all rows and returning them in an array of tuples

texts:
Link to SQLite wrapper

func queryAll() -> [(String, String, String)]  {
    do {
        let sql = try DB?.prepare("SELECT city, zip , temp FROM weather")
        var arr : [(city : String, zip : String, temp : String)] = []
        for row in sql! {
            arr += [(city: row[0] as! String, zip: row[1] as! String, temp: row[2] as! String)]
        }
        return arr;
    }
    catch {
        print("\(error)")
    }
    return [("","","")]
}

Grabbing all the rows, and returning them as a tuple for later use.
I've read the docs but I cannot think of a more efficient way to return all the rows to a TableView

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : CustomTableViewController = self.tableView.dequeueReusableCell(withIdentifier: "Cell")! as! CustomTableViewController
    let DB : WeatherDataStorage = WeatherDataStorage()
    var arr = [(city : String, zip : String, temp : String)]()
    arr = DB.queryAll()
    cell.cityLabel.text = arr[i].city
    cell.zipLabel.text = arr[i].zip
    cell.temperatureLabel.text = arr[i].temp
    i += 1
    return cell
}

EDIT: GIST


texts:
How do I improve the below code, which takes input from a file and does some word analysis?  I find a lot of redundancy in it. I want to know a better way of implementing it.

analysis = {}
wordanalysis = {}
found = True

for line in sys.stdin:
   (n1,n2,n3,n4,n5,n6) = re.split("\t+",line.strip())
   tweet = re.split("\s+", n6.strip().lower())
   #adding tweet id to a dictionary

   for i in range(0, len(tweet)):
     print "{", n1, wordanalysis,"}"
     wordanalysis["word"] = tweet[i]
     wordanalysis["charcount"]= len(tweet[i])

     if len(tweet[i]) > 7:
        wordanalysis["longword"] = found
     else:
        wordanalysis["longword"] = not(found)
     #if 1st char is UpperCase
     if tweet[i].istitle():
        wordanalysis["title"] = found
     else:
        wordanalysis["title"] = not(found)

     if tweet[i].isupper():
        wordanalysis["uppercase"] = found
     else:
        wordanalysis["uppercase"] = not(found)


texts: Function to call a list of callables with retry

texts:
This script is designed to be run via windows task scheduler once per day.

All callables passed to this function should only return a bool. The callables are called until either the maximum number of call attempts is reached, or until they return True. If one or more callables returns False, the program will sleep for the alloted time 'attempt_interval', before attempting to calls again to those which have not yet returned True.

Function:

import time
from dateutil.parser import parse

def call_callables(callables: list,
                   max_attempts=12,
                   earliest_attempt="07:00",
                   attempt_interval=600):
    """
    Call each callable until it either returns True or max_attempts is reached

    :param callables: a list of callable functions/methods which return
                      either True or False.
    :param earliest_attempt: For the current day, don't attempt list generation
                             before this time. This is a target time for the
                             first attempt.
    :param max_attempts: The maximum number of calls to each callable
    :param attempt_interval: The number of seconds to wait between calls to each
                             callable
    """

    earliest_attempt = parse(earliest_attempt)
    current_time = datetime.datetime.now()

    # track number of attempts for each callable
    attempt_counter = defaultdict(int)

    # track return bool status for each callable
    success_tracker = defaultdict(bool)

    callable_objs = callables

    while callable_objs:
        for callable_obj in callables:
            success_tracker[callable_obj] = callable_obj()
            attempt_counter[callable_obj] += 1

            if (success_tracker[callable_obj] or attempt_counter[callable_obj]
                >= max_attempts):
                callable_objs.remove(callable_obj)
                continue

        # Unsuccessful (False returned by one or more callables) attempt. Retry.
        if callable_objs:
            time.sleep(attempt_interval)

    # return dicts to allow for testing
    return attempt_counter, success_tracker

Test (using pytest-cov; this passed):

import pytest
from unittest.mock import Mock, patch

@patch("time.sleep")
def test_call_callables(sleep):
    mock_true = Mock()
    mock_false = Mock()

    def ret_true():
        return True

    def ret_false():
        return False

    mock_true.call_method = ret_true
    mock_false.call_method = ret_false

    mocks = [mock_true.call_method, mock_false.call_method]

    attempt_tracker, success_tracker = call_callables(callables=mocks,
                                                      max_attempts=10,
                                                      attempt_interval=1)
    assert {ret_true: 1, ret_false: 10} == dict(attempt_tracker)
    assert sleep.call_count == 10
    assert {ret_true: True, ret_false: False}  == dict(success_tracker)


texts: "Algorithmic Crush" problem hitting timeout errors

texts:
This is the HackerRank problem Algorithmic Crush:

  You are given a list of size N, initialized with zeroes. You have to perform M operations on the list and output the maximum of final values of all the N elements in the list. For every operation, you are given three integers a, b and k. The value k needs to be added to all the elements ranging from index a through b (both inclusive).

  Input Format

  The first line will contain two integers N and M separated by a single space.
  The next M lines will each contain three integers a, b and k separated spaces.
  The numbers in the list are numbered from 1 to N.

  Output Format

  A single integer on a separate line line containing maximum value in the updated list.

  Constraints

  \$3 ≤ N ≤ 10^7\$
    \$1 ≤ M ≤ 2 \cdot 10^5\$
    \$1 ≤ a ≤ b ≤ N\$
    \$0 ≤ k ≤ 10^9\$

  Sample input:

5 3
1 2 100
2 5 100
3 4 100

  Sample output:

200

  Explanation

  After the first update, the list will be 100 100 0 0 0.
  After the second update, the list will be 100 200 100 100 100.
  After the third update, the list will be 100 200 200 200 100.
  So, the required answer will be 200.

This is my Python 3 solution:

tempArray = [int(n) for n in input().split(" ")]
N = tempArray[0]
M = tempArray[1]
arr = [0 for x in range(N)]
for i in range(0,M):
    tempArray = [int(n) for n in input().split(" ")]
    for j in range(tempArray[0]-1, tempArray[1]):
        arr[j] = arr[j] + tempArray[2]
print(max(arr))

It gives me running time-out error for some test cases. I know very little about time complexity but I think it's \$O(NM)\$. What am I doing wrong?


texts:
Obviously, 'select *' is never a good idea.

HOWEVER, I have taken a job with an org that allowed this cancer to spread.

They have huge queries, using select * as SUB-QUERIES, when the coder only needed 3 or 4 columns.

 select t.field1, t.field2, t.field3, x.field4 ...
   from table t
   left join (select * from table where .... ) x
     on x.field5 = t.field5
   left join (select * from table where .... ) y
     on y.field6 = t.field6
   left join (select * from table where .... ) z
     on z.field7 = t.field7

Performance on this beast is a dog.

The databases we pull from we don't own, so I don't have rights to get an estimated or actual execution plan.

Before I start rewriting these queries, is the query optimizer on the M$ SQL Server smart enough to translate the splat into just the needed columns?  Or do I start targeting one query a day at lunch?

Thank you for your time and consideration.


texts: Optimization of weightedWinner() and random() function

texts:
I have written a Lottery contract that picks winner based on the amount they contributed to the pool. I am looking if the code of weightedWinner function can be optimized. And if there is a better way to write the random function.

pragma solidity ^0.5.12;

//import "./SafeMath.sol";

contract WeightedLottery {
    //using SafeMath for uint256;

    address public owner;
    address payable[] private players;
    mapping(address => uint256) private amounts;
    uint256 totalAmount = 0;

    constructor() public {
        owner = msg.sender;
    }

    function random() private view returns (uint) {
        return uint(keccak256(abi.encodePacked(blockhash(block.number - 1 - players.length), block.difficulty, now, players)));
    }

    function weightedWinner() private view returns(address payable) {
        require(msg.sender == owner);
        require(totalAmount != 0);
        require(players.length != 0);
        uint256 val = random() % totalAmount;
        uint256 temp = 0;
        for(uint256 i = 0; i < players.length; i++) {
            temp += amounts[players[i]];
            if(val < temp) {
                return players[i];
            }
        }
        return address(0x0);
    }

    function getPlayers() public view returns(address payable[] memory) {
        return players;
    }

    function join() payable public {
        require(msg.sender != owner);
        require(msg.value != 0);
        if(amounts[msg.sender] == 0) {
            players.push(msg.sender);
        }
        amounts[msg.sender] += msg.value;
        totalAmount += msg.value;
    }

    function pickWinner() public {
        address payable winner = weightedWinner();
        require(winner != address(0x0));
        winner.transfer(totalAmount);
    }
}

How it works

Players join with an initial amount of tokens. Later s/he can increase the amount. When pickWinner is called, player with the highest amount has the height probability of winning.

Example:

player 1 joins with 10 tokens.
player 2 joins with 10 tokens.
player 1 adds 10 tokens.
player 3 joins with 10 tokens.
player 3 adds 10 tokens.
pickWinner is called.

Now we have player 1 and 3 with 20 tokens and 2 has 10 tokens. So player 1 and 3 has (20/50) probability of winning and player 2 has (10/50) probability.


texts: Performance optimization in function for datastructure mapping

texts:
I want to optimize a Perl function which is frequently used in my application. The function creates a special datastructure from the results of DBI::fetchall_arrayref which looks like:

$columns = ['COLNAME_1','COLNAME_2','COLNAME_3']
$rows    = [ ['row_1_col_1', 'row_1_col_2', 'row_1_col_3'],
             ['row_2_col_1', 'row_2_col_2', 'row_2_col_3'],
             ['row_3_col_1', 'row_3_col_2', 'row_3_col_3']
];

The new datastructure must contain the data in the following form (all row-values for every column in a single arrayref)

$retval = {
    row_count => 3,
    col_count => 3,
    COLNAME_1 => ['row_1_col_1', 'row_2_col_1', 'row_3_col_1' ],
    COLNAME_2 => ['row_1_col_2', 'row_2_col_2', 'row_3_col_2' ],
    COLNAME_3 => ['row_1_col_3', 'row_2_col_3', 'row_3_col_3' ]
}

The new datastructure is a Hash of Arrays and is used in the whole application. I cannot change the format (its too frequently used). I wrote a function for this conversion. I've already done some some performance optimization after profiling my application. But it's not enough. Now the function looks like:

sub reorganize($$) {
    my ($self,$columns,$rows) = @_;
    my $col_count = scalar(@$columns);
    my $row_count = scalar(@$rows);
    my $col_index = 0;
    my $row_index = 0;
    my $retval = {  # new datastructure
        row_count   => $row_count,
        col_count   => $col_count
    };

    # iterate through all columns
    for($col_index=0; $col_index<$col_count; $col_index++) {
        # create a arrayref for all row-values of the current column
        # set it to the correct size and assign all values to this arrayref
        my $tmp = [];
        $#{$tmp} = $row_count-1;    # set size of array to the number of rows

        # iterate through all rows
        for($row_index=0; $row_index<$row_count; $row_index++) {
            # assign values to arrayref (which has the correct size) instead of a "slow" push
            $tmp->[$row_index] = $rows->[$row_index][$col_index];
        }
        # Assign the arrayref to the hash. The hash-key is the name of the column
        $retval->{$columns->[$col_index]} = $tmp;
    }
    return $retval;
}

My Question:

Is there a way to further optimize this function (maybe using $[...])?  I found some hints here at page 18 and 19, but I don't have any experience in using $ in different contexts.

I have to say that the function listed above is the best I can do. There may be other ways to do some optimization which I have never heard of.


texts: Passing objects to functions safely and efficiently

texts:
I would like to have this code reviewed. I am learning C++ from a C background. How would I improve this code to make it more C++ like? This is a simple program that I wrote, which is a stripped down version of the actual full program I'm writing.

#include <iostream>
using namespace std;

class Doge{
public:
    Doge();
    Doge(Doge&);
    ~Doge();
    int GetAge() const { return itsAge; }
    void SetAge(int age) { itsAge = age; }

private:
    int itsAge;
};

Doge::Doge(){
    cout << "Doge Constructor" << endl;
    itsAge = 5;
}

Doge::Doge(Doge&){
    cout << "Doge Copy Constructor" << endl;
}

Doge::~Doge(){
    cout << "Doge Destructor" << endl;
}

Doge * Function( Doge * theDoge){
    cout << "In Function" << endl;
    cout << "Scott is now " << theDoge->GetAge() << endl;
}

int main(){

    cout << "Make Doge" << endl;
    Doge Scott;
    cout << "Scott is " << Scott.GetAge() << endl;
    Scott.SetAge(10);
    Function(&Scott);
    cout << endl;
    return 0;
}


texts:
I want to print a tree in a zigzag manner level-by-level. I'm wondering if there are any logic issues in my code and any further performance improvement ideas by using a smarter algorithm implementation.

class Node:

    def __init__(self, value):
            self.value = value
            self.left = None
            self.right = None

def zigzagPrint(wq, isLeft):
    if not wq:
        return
    buf = []
    if isLeft == True:
        for i in range(len(wq)):
            buf.append(wq[i].value)
    else:
        for i in range(len(wq)-1, -1, -1):
            buf.append(wq[i].value)
    print buf

def zigzag(root):

    if not root:
        return

    wq = []
    wqTemp=[]
    wq.append(root)
    isLeft = True
    while True:
        zigzagPrint(wq, isLeft)
        isLeft = not isLeft
        while len(wq) > 0:
            node = wq.pop(0)
            if node.left:
                wqTemp.append(node.left)
            if node.right:
                wqTemp.append(node.right)
        # inner while
        wq = wqTemp
        wqTemp = []
        if len(wq) == 0:
            return

if __name__ == "__main__":
    n1 = Node(1)
    n21 = Node(2)
    n1.left = n21
    n22 = Node(3)
    n1.right = n22

    n31 = Node(4)
    n32 = Node(5)
    n21.left = n31
    n21.right = n32
    n33 = Node(6)
    n22.right = n33

    n41 = Node(7)
    n42 = Node(8)
    n31.left = n41
    n31.right = n42
    n43 = Node(9)
    n32.right = n43

zigzag(n1)

Expected output

The tree in the code can be represented as

      1
     / \
    2   3
   / \   \
  4   5   6
 / \   \
7   8   9

And the associated output is

[1]
[3, 2]
[4, 5, 6]
[9, 8, 7]


texts:
In my job we use our internal CA, which runs on a Windows server. When I want to use its CRL on a Linux machine I have to do these steps:

download root CA and intermediate CAs
covert them to x509
merge into one file (CRL.pem)

For this I wrote the small script below, which I run automatically by timer unit (cron on systems without systemd) once a day.

#!/usr/bin/env bash

crls=(RootCA IntermediateCA IntermediateCA2)
new_crl="newcrl.pem"
crl_temp=$(mktemp -q -d /tmp/pullcrl.XXXXX)
crl_dir="/etc/pki/tls/misc"

for crl in ${crls[@]}; do
  if curl -s http://url_of_crls/${crl}.crl -o ${crl_temp}/${crl}.crl; then
    openssl crl -in ${crl_temp}/${crl}.crl -inform DER -out ${crl_temp}/${crl}.pem
  else
    echo "Download a crl file failed!"
    exit 1
  fi
done

cat ${crl_temp}/*.pem > ${crl_temp}/${new_crl}

mv ${crl_temp}/${new_crl} ${crl_dir}/${new_crl}

Could I do something better?


texts: How to avoid instanceof when working to fill in varying ArrayLists and table models?

texts:
I am looking for a way to improve the following method or to find out if this is the best way to do it. I have a superclass called Product and then I have Yoghurt, Crisp, etc. extending it. My Lists are declared as private static ArrayList inside of the class where this method is being executed, my main client class. I am trying to add the object to the correct list but don't know of a better way to do this. Am I going about it the long winded way or is this acceptable?

public <T> void addToTable(T obj) {

        if (obj instanceof Yoghurt) {
            yoghurtList.add((Yoghurt)obj);
            yoghurtList.sort(new IdSorter());
            yoghurtModel.fireInsert();    //this method just does fireTableDataChanged()
        } else if (obj instanceof Crisp) {
            crispList.add((Crisp)obj);
            crispList.sort(new IdSorter());
            crispModel.fireInsert();
        } else if (obj instanceof Milk) {
            milkList.add((Milk)obj);
            milkList.sort(new IdSorter());
            milkModel.fireInsert();
        } else if (obj instanceof Drink) {
            drinkList.add((Drink)obj);
            drinkList.sort(new IdSorter());
            drinkModel.fireInsert();
        } else if (obj instanceof Bar) {
            barList.add((Bar)obj);
            barList.sort(new IdSorter());
            barModel.fireInsert();
        }
    }


texts:
I am writing simple program to reverse its input and output the reversed version. I came up with this code. So how can I improve it? Something tells me that int lengthSoFar is bad in both printArray and reverse functions.

#include <stdio.h>
#include <string.h>

#define ARRSIZE 1000

//function declarations...
char *reverse(char *a, int l);

void printArray(char *a, int l);

int main(void) {
    int c = 0;
    int i = 0;
    char buff[ARRSIZE];
    while ((c = getchar()) != EOF) {
        if (i > ARRSIZE) printArray(reverse(buff, i), i);
        if (c != '\n') {
            buff[i]=c;
            i++;
        }else{
            printArray(reverse(buff, i), i);
            memset(buff, 0, sizeof buff);
            i=0;
        }
    }
    return 0;
}

char *reverse(char *array, int lengthSoFar) {
    int i = 0;
    int j = lengthSoFar - 1;
    static char arrayToReturn[ARRSIZE];
    while (i < lengthSoFar && j >= 0) {
        arrayToReturn[i] = array[j];
        i++;
        j--;
    }
    return arrayToReturn;
}

void printArray(char *array, int lengthSoFar) {
    for (int i = 0; i < lengthSoFar; i++) {
        putchar(array[i]);
    }
}


texts:
In my Python application, I am using Tarjan's algorithm to compute strongly connected components. Unfortunately, it shows up under profiling as one of the top functions in my application (at least under cPython, I haven't figured out how to profile under Pypy yet).

I've looked at the code, but I don't see any obvious performance mistakes, and I can't figure out how to make it faster. Any suggestions?

Note: The profiler reports a lot of time spent inside the function, so it's not just a matter of slow callbacks.

def tarjanSCC(roots, getChildren):
    """Return a list of strongly connected components in a graph. If getParents is passed instead of getChildren, the result will be topologically sorted.

    roots - list of root nodes to search from
    getChildren - function which returns children of a given node
    """

    sccs = []
    indexCounter = itertools.count()
    index = {}
    lowlink = {}
    removed = set()
    subtree = []

    #Use iterative version to avoid stack limits for large datasets
    stack = [(node, 0) for node in roots]
    while stack:
        current, state = stack.pop()
        if state == 0: #before recursing
            if current not in index: #if it's in index, it was already visited (possibly earlier on the current search stack)
                lowlink[current] = index[current] = next(indexCounter)
                children = [child for child in getChildren(current) if child not in removed]
                subtree.append(current)

                stack.append((current, 1))
                stack.extend((child, 0) for child in children)
        else: #after recursing
            children = [child for child in getChildren(current) if child not in removed]
            for child in children:
                if index[child] <= index[current]: #backedge (or selfedge)
                    lowlink[current] = min(lowlink[current], index[child])
                else:
                    lowlink[current] = min(lowlink[current], lowlink[child])
                assert(lowlink[current] <= index[current])

            if index[current] == lowlink[current]:
                scc = []
                while not scc or scc[-1] != current:
                    scc.append(subtree.pop())

                sccs.append(tuple(scc))
                removed.update(scc)
    return sccs


texts: Change size of elements until parent reaches certain height

texts:
I wrote this method and I would like to refactor it so it is easier to understand and looks cleaner. However, I don't know how or where to start. If you could give it your best shot and explain your approach to how you did it, it would be very helpful to me. The function reduces the size of elements until the parent container reaches a certain height (in this case 25 or less).

function _AdjustHeightOwlDots() {
    let dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height();
    if (!dotRowHeight || dotRowHeight === 25 || dotRowHeight === 0) {
      return;
    }
    this._waitFor(`#${get(this, 'elementId')} div.owl-dots > button > span`).then(() => {
      if (dotRowHeight && dotRowHeight > 25) {
        for (let index = 0; index < 10; index += 1) { // default size of dot is 10x10px
          // first the margin because it looks better
          document.querySelectorAll(`#${get(this, 'elementId')} div.owl-dots > button > span`).forEach((el) => {
            const elCopy = el;
            const elStyle = elCopy.currentStyle || window.getComputedStyle(elCopy);
            if (parseFloat(elStyle.margin, 10) > 1) {
              elCopy.style.margin = `${parseFloat(elStyle.margin, 10) - 1}px`;
            }
          });
          dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height();
          if (dotRowHeight > 25) {
            document.querySelectorAll(`#${get(this, 'elementId')} div.owl-dots > button > span`).forEach((el) => {
              const elCopy = el;

              if (el.offsetHeight > 1) {
                elCopy.style.height = `${el.offsetHeight - 1}px`;
                elCopy.style.width = `${el.offsetHeight}px`;
              }
            });
          }
          const el = document.querySelector(`#${get(this, 'elementId')} div.owl-dots > button > span`);
          const elStyle = el.currentStyle || window.getComputedStyle(el);

          if (el.offsetHeight === 1 && parseFloat(elStyle.margin, 10) <= 1) { // cant get smaller
            break;
          }
          dotRowHeight = $(`#${get(this, 'elementId')} .owl-carousel .owl-dots`).height();

          if (dotRowHeight <= 25) { break; }
        }
      }
    })
      .catch((/* e */) => {
      //
      });
  },

Edit: Follow up: Find size for elements to fit in certain width


texts: Bot-like Spring Java service for checking advertisements

texts:
I am in the middle of developing a Spring Boot application, which has a service acting like a bot.

advertisementService.update(Advertisement ad) is a method which parses some HTML. It is important that it cannot execute periodically. For now it is pseudo random, but in the future there will be some logic returning the time depending on information read in previous parsing.

Immediately after the start of the app, it invokes the method scheduleAllChecks().
If a new Advertisement comes up, then it calls scheduleCheck(0, ad);

I am wondering if the solution (I mean the whole service class) is proper and if it can be beter?

package com.gadomski.service;

import com.gadomski.model.Advertisement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by Krzysiek on 21.08.2016.
 */

@Service
public class CheckerService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final int CHECKER_THREADS = 100;
    @Autowired
    AdvertisementService advertisementService;
    private ScheduledExecutorService scheduledExecutorService;

    CheckerService() {
        this.scheduledExecutorService = Executors.newScheduledThreadPool(CHECKER_THREADS);
    }

    public void scheduleCheck(int delaySeconds, Advertisement advertisement) {
        if (advertisement.isActive()) {
            ScheduledFuture<?> check = this.scheduledExecutorService.schedule(
                    () -> {
                        scheduleCheck(getDelayInSeconds(), advertisement);
                        advertisementService.updateAdvertisement(advertisement);
                        log.info("Scheaduled next check for " + advertisement.getUrl() + " for user with id: " + advertisement.getUserId());
                    },
                    delaySeconds, TimeUnit.SECONDS);
        }
    }

    private int getDelayInSeconds() {
        Random rand = new Random();
        return (8 + rand.nextInt(10)) * 60 + rand.nextInt(60);
    }

    public void scheduleAllChecks() {
        Random random = new Random();
        advertisementService.getAllActvieAdvertisements().forEach(a -> scheduleCheck(random.nextInt(3 * 60), a));
    }
}


texts: Big O notation for quicksort implementation

texts:
I am trying to find out what would be the Big O notation of a quick sort implementation I wrote. If I can get some analysis on the code, that would be great.

public class JavaApplication1 {

public static void main(String args[]) {

    int[] input = { 23, 31, 1, 21, 36, 72};
    System.out.println("Before sorting : " + Arrays.toString(input));
    quickSort(input); // sort the integer array using quick sort algorithm
    System.out.println("After sorting : " + Arrays.toString(input));

    // input with duplicates
    int[] withDuplicates = { 11, 14, 16, 12, 11, 15};
    System.out.println("Before sorting : " + Arrays.toString(withDuplicates));
    quickSort(withDuplicates); // sort the integer array using quick sort algorithm
    System.out.println("After sorting : " + Arrays.toString(withDuplicates));
}

/**
 * public method exposed to client, sorts given array using QuickSort
 * Algorithm in Java
 * @param array
 */
public static void quickSort(int[] array) {
   if(array.length <= 1) return;
   int leftwall = 0;
   int rightwall  = array.length - 1 ;
   int pivot = array[array.length/2];
   rechelperquickSort(array,leftwall,rightwall,pivot);
}

public static void rechelperquickSort(int[] array ,int left , int right , int pivot ){

    int idx;
    idx = left;

    if(left>=right) return;

    while(idx<=right){

        if(pivot > array[idx])swapinarray(array,left++,idx);

        idx++;
    }
    if(left >= right) return;
    pivot = array[left+1];
    rechelperquickSort(array,left+1,right,pivot);
    rechelperquickSort(array,0,left,array[left/2]);
}

public static void swapinarray(int[] array,int leftelementidx, int rightelementidx){
    int tmp = array[leftelementidx];
    array[leftelementidx] = array[rightelementidx];
    array[rightelementidx] = tmp;
}

}


texts: Gradient descent for linear regression using numpy/pandas

texts:
I currently follow along Andrew Ng's Machine Learning Course on Coursera and wanted to implement the gradient descent algorithm in python3 using numpy and pandas.

This is what I came up with:

import os
import numpy as np
import pandas as pd

def get_training_data(path):    # path to read data from
    raw_panda_data = pd.read_csv(path)

    # append a column of ones to the front of the data set
    raw_panda_data.insert(0, 'Ones', 1)

    num_columns = raw_panda_data.shape[1]                       # (num_rows, num_columns)
    panda_X = raw_panda_data.iloc[:,0:num_columns-1]            # [ slice_of_rows, slice_of_columns ]
    panda_y = raw_panda_data.iloc[:,num_columns-1:num_columns]  # [ slice_of_rows, slice_of_columns ]

    X = np.matrix(panda_X.values)   # pandas.DataFrame -> numpy.ndarray -> numpy.matrix
    y = np.matrix(panda_y.values)   # pandas.DataFrame -> numpy.ndarray -> numpy.matrix

    return X, y

def compute_mean_square_error(X, y, theta):
    summands = np.power(X * theta.T - y, 2)
    return np.sum(summands) / (2 * len(X))

def gradient_descent(X, y, learning_rate, num_iterations):
    num_parameters = X.shape[1]                                 # dim theta
    theta = np.matrix([0.0 for i in range(num_parameters)])     # init theta
    cost = [0.0 for i in range(num_iterations)]

    for it in range(num_iterations):
        error = np.repeat((X * theta.T) - y, num_parameters, axis=1)
        error_derivative = np.sum(np.multiply(error, X), axis=0)
        theta = theta - (learning_rate / len(y)) * error_derivative
        cost[it] = compute_mean_square_error(X, y, theta)

    return theta, cost

This is how one could use the code:

X, y = get_training_data(os.getcwd() + '/data/data_set.csv')
theta, cost = gradient_descent(X, y, 0.008, 10000)

print('Theta: ', theta)
print('Cost: ', cost[-1])

Where data/data_set.csv could contain data (model used: 2 + x1 - x2 = y) looking like this:

x1, x2, y
0, 1, 1
1, 1, 2
1, 0, 3
0, 0, 2
2, 4, 0
4, 2, 4
6, 0, 8

Output:

Theta:  [[ 2.  1. -1.]]
Cost:  9.13586056551e-26

I'd especially like to get the following aspects of my code reviewed:

Overall python style. I'm relatively new to python coming from a C background and not sure if I'm misunderstanding some concepts here.
numpy/pandas integration. Do I use these packages correctly?
Correctness of the gradient descent algorithm.
Efficiency. How can I further improve my code?


texts:
I have been interested in trying Rust in a long time, and I finally got around to sit down and start reading "The Book". I have not finished yet, so there are probably a few features that I could have used, but I didn't know about.

Anyway, the purpose of this program is to generate a maze (using the simplest "Randomized DFS" algorithm).

Since the main goal for me was to practice the language, I tried to make the program as "idiomatic" as possible. The main thing that still bothers me is all those type conversions between the signed and unsigned types. Since this is my first Rust program, I am mainly just looking for feedback on anything that could be considered "bad code", or parts that could be improved in any way.

extern crate rand;
extern crate image;
use std::io::Write;
use rand::Rng;

#[derive(Clone, PartialEq)]
enum Cell {
    Blocked,
    Free,
}

fn make_odd(mut t: (usize, usize)) -> (usize, usize) {
    let o = |v: &mut usize| if *v%2==0{*v+=1};
    o(&mut t.0); o(&mut t.1); t
}

fn gen(s: (usize, usize)) -> Vec<Vec<Cell>> {
    let mut t = vec![vec![Cell::Blocked; s.1]; s.0];
    let mut stack = Vec::<(isize, isize)>::new();

    let c = make_odd((s.0/2, s.1/2));
    stack.push((c.0 as isize, c.1 as isize));
    t[c.0][c.1] = Cell::Free;

    let mut dirs: [(isize, isize); 4] = [(2, 0), (-2, 0), (0, 2), (0, -2)];
    let mut rng = rand::thread_rng();
    'o: while let Some(&(x, y)) = stack.last() {
        rng.shuffle(&mut dirs);
        for i in 0..4 {
            let (dx, dy) = dirs[i];
            let (nx, ny) = (x+dx, y+dy);
            if nx < 0 || ny < 0 || nx >= (s.0 as isize) || ny >= (s.1 as isize) { continue; }
            if t[nx as usize][ny as usize] != Cell::Free {
                stack.push((nx, ny));
                t[nx as usize][ny as usize] = Cell::Free;
                t[(x+dx/2) as usize][(y+dy/2) as usize] = Cell::Free;
                continue 'o;
            }
        }
        stack.pop();
    }

    t[0][1] = Cell::Free;
    t[s.0-1][s.1-2] = Cell::Free;
    t
}

fn print_usage() -> ! {
    let _ = writeln!(std::io::stderr(), "Usage: maze-gen width height [output.png]");
    std::process::exit(1);
}

fn main() {
    let args: Vec<_> = std::env::args().collect();
    if args.len() < 3 { print_usage(); }
    let mut nums = [0; 2];
    for i in 0..2 {
        match args[i+1].parse::<usize>() {
            Err(_) => { print_usage(); },
            Ok(v) => nums[i] = v,
        }
    }
    let s0 = (nums[0], nums[1]);
    let mut s = make_odd(s0);
    if s.0 < 3 { s.0 = 3; }
    if s.1 < 3 { s.1 = 3; }
    if s != s0 {
        let _ = writeln!(std::io::stderr(),
            "Warning: Adjusting sizes to {} and {}!", s.0, s.1);
    }
    let m = gen(s);
    let mut buf = image::ImageBuffer::new(s.0 as u32, s.1 as u32);
    for (x,y,px) in buf.enumerate_pixels_mut() {
        *px = image::Luma([
            match m[x as usize][y as usize] {
                Cell::Free => 255,
                Cell::Blocked => 0,
            }
        ]);
    }
    let filename = if args.len() >= 4 { args[3].as_str() } else { "out.png" };
    let ref mut file = std::fs::File::create(&std::path::Path::new(filename)).unwrap();
    image::ImageLuma8(buf).save(file, image::PNG).unwrap();
}

Sample output: (It's quite tiny, you might have to download it and zoom in to see it properly.)

(Sorry for any bad grammar, English is not my native language.)


texts:
I decided to roll out my own encryption algorithm, which I am calling "SBC" or Simple Byte Cipher. Essentially, I just take the bytes of the string data, do a Caesar cipher like shift to it, increment through an array of password bytes for each byte in the data (this enables the same letters such as "T" to not always have the same output, which would be easily crackable). And in the end I just reverse the process to glean the original data.

My code seems to work just fine; decryption works like a dream. I just want to know if there is a better way, or any hidden errors that may occur with the code as it currently stands.

I am aware that the length of the password and data are not length tested, or null tested. I will address that later.

public static class SimpleByteCipher
    {
        public static byte[] EncryptStringToByteArray( string data , string password )
        {
            byte[] bytes = Encoding.ASCII.GetBytes( data );
            byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
            int passwordShiftIndex = 0;
            for( int i = 0; i < bytes.Length; i++ )
            {
                bytes[ i ] = ( byte )( bytes[ i ] + passwordBytes[ passwordShiftIndex ] );
                passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
            }
            return bytes;
        }

        public static string DecryptByteArrayToString( byte[] data , string password )
        {
            byte[] bytes = data;
            byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
            int passwordShiftIndex = 0;
            for( int i = 0; i < bytes.Length; i++ )
            {
                bytes[ i ] = ( byte )( bytes[ i ] - passwordBytes[ passwordShiftIndex ] );
                passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
            }
            return Encoding.ASCII.GetString( bytes );
        }

        public static byte[] EncryptStringToByteArray( string data , string password , uint seed)
        {
            byte[] bytes = Encoding.ASCII.GetBytes( data );
            byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
            int passwordShiftIndex = 0;
            for( int i = 0; i < bytes.Length; i++ )
            {
                bytes[ i ] = ( byte )( bytes[ i ] + passwordBytes[ passwordShiftIndex ] + seed );
                passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
            }
            return bytes;
        }

        public static string DecryptByteArrayToString( byte[] data , string password , uint seed)
        {
            byte[] bytes = data;
            byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
            int passwordShiftIndex = 0;
            for( int i = 0; i < bytes.Length; i++ )
            {
                bytes[ i ] = ( byte )( bytes[ i ] - passwordBytes[ passwordShiftIndex ] - seed );
                passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
            }
            return Encoding.ASCII.GetString( bytes );
        }
    }

And here is a practice main:

class Program
    {
        static void Main( string[] args )
        {
            string data = "This is but a test.";
            byte[] encrypted = SimpleByteCipher.EncryptStringToByteArray( data , "Test" , 5000 );
            string decrypted = SimpleByteCipher.DecryptByteArrayToString( encrypted , "Test" , 5000 );
            Console.WriteLine( decrypted );
            Console.ReadLine();
        }
     }

The output correctly prints:

  "This is but a test."

And here is a visualization of what the encrypted bytes look like in a text file:


texts:
I'm making a Minecraft clone and have made an Object Pool. Looking for some advice on how I have implemented it.

Uses m_availableObjects as a O(1) way of searching for the next available object.

Thank you in advance.

constexpr int INVALID_OBJECT_ID = -1;

//Internal Use - Object Pool
template <class Object>
struct ObjectInPool : private NonCopyable
{
    ObjectInPool(int ID)
        : object(),
        inUse(false),
        ID(ID)
    {}
    ObjectInPool(ObjectInPool&& orig) noexcept
        : object(std::move(orig.object)),
        inUse(orig.inUse),
        ID(orig.ID)
    {
        orig.ID = INVALID_OBJECT_ID;
        orig.inUse = false;
    }
    ObjectInPool& operator=(ObjectInPool&& orig) noexcept
    {
        object = std::move(orig.object);
        inUse = orig.inUse;
        ID = orig.ID;

        orig.ID = INVALID_OBJECT_ID;
        orig.inUse = false;
        return *this;
    }
    ~ObjectInPool() {}

    Object object;
    bool inUse;
    int ID;
};

//External Use - Object Pool
template <class Object>
class ObjectPool;
template <class Object>
struct ObjectFromPool : private NonCopyable
{
    ObjectFromPool(ObjectInPool<Object>* objectInPool, std::function<void(int)> func)
        : objectInPool(objectInPool),
        m_func(func)
    {
        if (objectInPool)
        {
            objectInPool->inUse = true;
        }
    }
    ~ObjectFromPool()
    {
        if (objectInPool)
        {
            objectInPool->object.reset();
            objectInPool->inUse = false;

            m_func(objectInPool->ID);
        }
    }
    ObjectFromPool(ObjectFromPool&& orig) noexcept
        : objectInPool(orig.objectInPool),
        m_func(orig.m_func)
    {
        orig.objectInPool = nullptr;
    }
    ObjectFromPool& operator=(ObjectFromPool&& orig) noexcept
    {
        objectInPool = orig.objectInPool;
        m_func = orig.m_func;

        orig.objectInPool = nullptr;

        return *this;
    }

    Object* getObject() const
    {
        return (objectInPool ? &objectInPool->object : nullptr);
    }

private:
    ObjectInPool<Object>* objectInPool;
    std::function<void(int)> m_func;
};

using std::placeholders::_1;

//Object Pool
template <class Object>
class ObjectPool : private NonCopyable, private NonMovable
{
public:
    ObjectPool(int visibilityDistance, int chunkWidth, int chunkDepth)
        : m_objectPool()
    {
        //Added a little bit more than neccessary due to how the inifinite map generates
        int x = visibilityDistance / chunkWidth;
        x += x += 1;
        int z = visibilityDistance / chunkDepth;
        z += z += 1;

        m_objectPool.reserve(x * z);
        for (int i = 0; i < x * z; ++i)
        {
            m_objectPool.emplace_back(i);
            m_availableObjects.push(i);
        }
    }

    ObjectFromPool<Object> getNextAvailableObject()
    {
        if (!m_availableObjects.empty())
        {
            int ID = m_availableObjects.top();
            m_availableObjects.pop();
            assert(ID < m_objectPool.size());
            return ObjectFromPool<Object>(&m_objectPool[ID], std::bind(&ObjectPool<Object>::releaseID, this, _1));
        }
        else
        {
            return ObjectFromPool<Object>(nullptr, std::bind(&ObjectPool<Object>::releaseID, this, _1));
        }
    }

private:
    std::stack<int> m_availableObjects;
    std::vector<ObjectInPool<Object>> m_objectPool;

    void releaseID(int ID)
    {
        assert(ID != INVALID_OBJECT_ID);
        m_availableObjects.push(ID);
    }
};


texts:
As a learning exercise, I decided to implement a BST and add functionality to it slowly. I'd appreciate any feedback.

I should also point out that I borrowed the template from the here.

tree.h header file

typedef char treeElement;
typedef struct TreeNodeTag{
  treeElement  element;
  struct TreeNodeTag  *left, *right;
}treeNode;

typedef struct treeCDT{
  treeNode *root;
}treeCDT;

typedef struct treeCDT *treeADT;

treeNode* addTreeHelper(treeNode**, treeElement);
void addTree(treeADT, treeElement);
int destroyTree(treeADT);
int destroyTreeHelper(treeNode*);
void createTree(treeADT*);
void printTree(treeADT);
void printTreeHelper(treeNode*);

Implementation tree.c

treeNode* addTreeHelper(treeNode **root, treeElement element){

  if(!*root){
    treeNode *temp;
    temp = malloc(sizeof(treeNode));
    temp->element = element;
    temp->left = NULL;
    temp->right = NULL;

    /*
    *root =  malloc(sizeof(treeNode));
    (*root)->element = element;
    (*root)->left = NULL;
    (*root)->right = NULL;
    */
    *root = temp;
    return *root;
  }

  if( (*root)->element >= element ){
    addTreeHelper( &(*root)->left, element);
  }
  else{
    addTreeHelper(&(*root)->right, element);
  }

  return *root;
}

void addTree(treeADT tree, treeElement element){
  addTreeHelper(&(tree->root), element);
}

int destroyTree(treeADT tree){
  destroyTreeHelper(tree->root);
  free(tree);
  return 0;
}

int destroyTreeHelper(treeNode* root){
  if(root){
    destroyTreeHelper(root->left);
    destroyTreeHelper(root->right);
    free(root);
  }
  return 0;
}

void createTree(treeADT* tree){
  *tree = malloc(sizeof(treeCDT));
  if(!*tree){
    fprintf(stderr, "Problem allocating tree");
  }
}

void printTree(treeADT tree){
  printTreeHelper(tree->root);
}

void printTreeHelper(treeNode * node){
  if(node){
    printf("%c\n", node->element);
    if(node->left)
      printTreeHelper(node->left);
    if(node->right)
      printTreeHelper(node->right);
  }
}


texts:
I've been working on adding an operation like Data.Lens.At.at to Data.Map. This uses an extremely fast, extremely small, and extremely limited sort of queue of bits representing the path taken down a tree of bounded balance with delta = 3. If the word size is 64, or nearly so, then it's unlikely that the code will overflow the queue (which can hold up to 2 * bitSize (0 :: Word) - 2 bits). If the word size is closer to 32 bits, then I need to be a bit more careful about very large maps. I believe that I've calculated appropriate cutoffs based on the maximum tree depths described in the paper, but I'm not entirely confident. Furthermore, I don't really know how to test this code—it requires a setup with a small word size and a giant, badly balanced map.

#if !(WORD_SIZE_IN_BITS >= 61)
#define DEFINE_ALTERF_FALLBACK 1
#endif

...

alterF :: (Functor f, Ord k) =>
      (Maybe a -> f (Maybe a)) -> k -> Map k a -> f (Map k a)
#if DEFINE_ALTERF_FALLBACK
alterF f !k m
-- It doesn't seem sensible to worry about overflowing the queue
-- if the word size is 61 or more. If I calculate it correctly,
-- that would take a map with nearly a quadrillion entries.
  | wordSize < 61 && size m >= alterFCutoff = alterFFallback f k m
#endif
alterF f !k m = case lookupTrace k m of
  TraceResult mv q -> (<$> f mv) $ \ fres ->
    case fres of
      Nothing -> case mv of
                   Nothing -> m
                   Just old -> deleteAlong old q m
      Just new -> case mv of
                   Nothing -> insertAlong q k new m
                   Just _ -> replaceAlong q new m

#if __GLASGOW_HASKELL__
{-# INLINABLE alterF #-}
#else
{-# INLINE alterF #-}
#endif

#if DEFINE_ALTERF_FALLBACK
alterFCutoff :: Int
#if WORD_SIZE_IN_BITS == 32
alterFCutoff = 55744454
#else
alterFCutoff = case wordSize of
      30 -> 17637893
      31 -> 31356255
      32 -> 55744454
      x -> (4^(x*2-2)) `quot` (3^(x*2-2))  -- Unlikely
#endif
#endif

...

data TraceResult a = TraceResult (Maybe a) {-# UNPACK #-} !BitQueue

-- Look up a key and return a result indicating whether it was found
-- and what path was taken.
lookupTrace :: Ord k => k -> Map k a -> TraceResult a
lookupTrace = go emptyQB
  where
    go :: Ord k => BitQueueB -> k -> Map k a -> TraceResult a
    go !q !_ Tip = TraceResult Nothing (buildQ q)
    go q k (Bin _ kx x l r) = case compare k kx of
      LT -> (go $! q `snocQB` False) k l
      GT -> (go $! q `snocQB` True) k r
      EQ -> TraceResult (Just x) (buildQ q)


texts: A binary tree , its copy constructor and assignment operator

texts:
I implemented a binary tree in the following code. Its node's copy constructor and assignment operator should copy itself and all its descendents. Similarity a node's destructor should delete itself and all nodes descended from it.The print function just prints each node in a new line. How can I pretty-print it? Please point to errors(if any) and suggestions.

#include <iostream>

struct Node
{
    Node(int);
    Node(const Node&);
    Node& operator=(const Node&);
    ~Node();

    Node* left;
    Node* right;
    int value;
};

Node::Node(int v)
:left(nullptr),
right(nullptr),
value(v)
{}

Node::Node(const Node& other)
:left(nullptr),
 right(nullptr),
 value(other.value)
{
    if (other.left != nullptr )
    {
        left = new Node(*other.left);
    }
    if (other.right != nullptr)
    {
        right = new Node(*other.right);
    }
}

Node& Node::operator=(const Node& other)
{
    value = other.value;

    Node * left_orig = left;
    left = new Node(*other.left);
    delete left_orig;

    Node * right_orig = right;
    right = new Node(*other.right);
    delete right_orig;

    return *this;
}

Node::~Node()
{
    if (left != nullptr )
    {
        delete left;
    }
    if (right != nullptr)
    {
        delete right;
    }
}

Node* make_copy(Node* other)
{
    Node * new_node = new Node(*other); // copy constructor invoked
    return new_node;
}

void print(Node* n)
{
    if (n == nullptr)
    {
        return;
    }
    std::cout << n << std::endl;
    print(n->left);
    print(n->right);

}

int main()
{
    Node* n = new Node(1);

    n->left = new Node(2);
    n->right = new Node(3);

    n->left->left = new Node(4);
    n->left->right = new Node(5);

    n->right->left = new Node(6);
    n->right->right = new Node(7);

    print(n);
    auto nc =  make_copy(n);
    print(nc);
}


texts:
let reply =  ref ""

let doAuto  =
    async {
        let! resultAA =
            async { return SqlCmd.aaHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultBB =
            async { return SqlCmd.bbHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultCC =
            async { return SqlCmd.ccHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultDD =
            async { return SqlCmd.ddHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultEE =
            async { return SqlCmd.ddHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultFF =
            async { return SqlCmd.ffHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultGG =
            async { return SqlCmd.ggHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultHH =
            async { return SqlCmd.hhHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultII =
            async { return SqlCmd.iiHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultJJ =
            async { return SqlCmd.jjHits query |> Async.RunSynchronously |> List.ofSeq }
        let! resultKK =
            async { return SqlCmd.kkHits query |> Async.RunSynchronously |> List.ofSeq }

        let length1 = resultAA.Length + resultBB.Length

        if length1 > 9 then reply := "hey " + length1.ToString()
        else
            let x = resultCC.Length + resultDD.Length + resultEE.Length + resultFF.Length + resultGG.Length
                        + resultHH.Length + resultII.Length + resultJJ.Length + resultKK.Length + length1
            reply := x.ToString()

    } |> Async.StartImmediate

!reply

The typical SqlCmd.xxHits (in module SqlCmd) built using FSharp.Data.SqlCommandTypeProvider looks like this:

[<Literal>]
let sqlXX = "SELECT ...@startsWith..."

type QueryXX = SqlCommand<sqlXX, ConnectionStringName=...>

let xxHits query =
    let cmdXxHits = QueryXX(connectionString = connectionString, startsWith = query)
    cmdXxHits.AsyncExecute()

I'm pretty inexperienced at using async. Looking for feedback, especially in a couple of areas:

I couldn't think of a better way to get my results out from inside the outer async than the ref. From what I read it sounded like Async.StartImmediate was the best solution for something running in an IIS application.
From the results of the first 2 inner asyncs, I may choose to quit before waiting for any more completions. Should I really be cancelling the remaining asyncs? Does it matter?


texts:
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::vec_deque::VecDeque;
use std::ops::AddAssign;

type Vertex = u64;
type Graph = HashMap<Vertex, HashSet<Vertex>>;

/**
 * Constructs a graph from a sequence of parent child pairs
 */
pub fn from_pairs(pairs: &[(u64, u64)]) -> Graph {
    let mut graph: Graph = HashMap::new();
    for &(parent, child) in pairs {
        let children = graph.entry(parent).or_insert(HashSet::new());
        children.insert(child);
    }
    return graph;
}

#[derive(Debug)]
pub struct DFSResult {
    starting_times: HashMap<Vertex, u64>,
    finishing_times: HashMap<Vertex, u64>,
    parents: HashMap<Vertex, Option<Vertex>>,
    forest: VecDeque<HashSet<Vertex>>,
    topologically_sorted: VecDeque<Vertex>,
}

/**
 * Returns the starting and finishing times and the parents of every node
 * found with dfs as well as the dfs forest
 */
pub fn dfs(graph: &Graph) -> DFSResult {
    let mut state = DFSResult {
        // The DFS forest
        forest: VecDeque::new(),
        // all the starting times for each vertex
        starting_times: HashMap::new(),
        // the finishing times for each vertex
        finishing_times: HashMap::new(),
        // the parents of each vertex
        parents: HashMap::new(),
        // the topologically sorted list of verticies
        topologically_sorted: VecDeque::new(),
    };

    // the verticies that bave been seen so far
    let mut seen: HashSet<Vertex> = HashSet::new();
    // current time
    let mut time = 0;

    fn dfs_visit (graph: &Graph,
                  vertex: Vertex,
                  time: &mut u64,
                  seen: &mut HashSet<Vertex>,
                  state: &mut DFSResult) {

        time.add_assign(1);
        state.starting_times.insert(vertex, *time);
        seen.insert(vertex);

        let mut branch = state.forest.pop_back().expect("The Forest should not be empty!");
        branch.insert(vertex);
        state.forest.push_back(branch);

        for neighbor in graph.get(&vertex).unwrap_or(&HashSet::new()) {
            if !seen.contains(neighbor) {
                state.parents.insert(*neighbor, Option::Some(vertex));
                dfs_visit(graph, *neighbor, time, seen, state);
            }
        }

        time.add_assign(1);
        state.finishing_times.insert(vertex, *time);
        state.topologically_sorted.push_front(vertex);
    };

    for vertex in graph.keys() {
        state.parents.insert(*vertex, Option::None);
    }

    for vertex in graph.keys() {
        if !seen.contains(vertex) {
            state.forest.push_back(HashSet::new());
            dfs_visit(graph, *vertex, &mut time, &mut seen, &mut state);
        }
    }
    return state;
}

fn topological_sort(graph: &Graph) -> VecDeque<Vertex> {
    let DFSResult{topologically_sorted, ..} = dfs(graph);
    return topologically_sorted
}

fn main() {
    let pairs = [(1, 2), (2, 1)];
    let g = from_pairs(&pairs);
    println!("{:?}", g);
    println!("{:?}", dfs(&g));
    println!("{:?}", topological_sort(&g));
}

I want to make an implementation of Depth-First Search that I can use for implementing classical algorithms. I am unsure about using the DFSResult struct; It feels like I should be able to conditionally compute each one of those fields, but I don't know how to structure my code to accomplish that without repeating myself.


texts:
Based on suggestions and some thoughts I made some refactorings of my classes to hold EAN13 codes, I created a contract interface which now is extended by BarCode classes, since there will be other types of BarCodes, like DUN-14, UPC-A...

public interface BarCode {}

I decide to move all the validations to factory class, so the EAN13 class looked like this:

@Embeddable
public class Ean13 implements BarCode {

    @Column(name = "ean_code", nullable = true, length = 13)
    private String code;

    public Ean13() {
    }

    public Ean13(String code)  {
        this.code = code;
    }

    @Override
    public String toString() {
        return code;
    }
}

I changed the pre-generate exception creating a custom InvalidBarCodeException  exception.

In the first moment, this was created as a RuntimeException. But I think this is the case where checked is much better suited, because I'm forced to deal with invalid codes.

public class InvalidBarCodeException extends Exception {
    private String code;
    private static final String INVALID_EAN = "INVALID EAN CODE";

    public InvalidBarCodeException(String code) {
        super(INVALID_EAN + " "+code);
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

The validation was moved to a Predicate in a separated class:

public class BarCodePredicate {

    public static Predicate<String> isValidEan13() {
        return p -> isValid(p);
    }

    private static boolean isValid(String code) {
        if (code == null || code.length() != 13) {
            return false;
        }
        if (!CharMatcher.DIGIT.matchesAllOf(code)) {
            return false;
        }
        String codeWithoutVd = code.substring(0, 12);
        int pretendVd = Integer.valueOf(code.substring(12, 13));
        String[] evenOdd = SplitterByIndex.split(codeWithoutVd, idx -> idx % 2 == 0);
        int evenSum = sumStringDigits(evenOdd[0]);
        int oddSum = sumStringDigits(evenOdd[1]);
        int oddFator = oddSum * 3;
        int sumResult = oddFator + evenSum;
        int dv = getEanVd(sumResult);
        if (pretendVd != dv) {
            return false;
        }
        return true;
    }

    private static int sumStringDigits(String s) {
        return s.chars().map(n ->
                Character.getNumericValue(n)
        ).sum();
    }

    private static int getEanVd(int s) {
        return 10 - (s % 10);
    }

}

So I use it in a factory class:

public interface BarCodeFactory {
    BarCode create(String code) throws InvalidBarCodeException;

    default boolean isValid(String code, Predicate<String> predicate) {
        return predicate.test(code);
    }

}

public class Ean13Factory implements BarCodeFactory {
    @Override
    public BarCode create(String code) throws InvalidBarCodeException {
        if (!isValid(code, BarCodePredicate.isValidEan13())){
            throw new InvalidBarCodeException(code);
        }
        return new Ean13(code);
    }
}

In the Product class now is simply a set method (it will be changed to BarCode interface):

public class Product{

   public void setEan(Ean13 ean) {
        this.ean = ean;
   }
}

And invalid codes are treated outside:

Product p = new Product();
p.setDescription(name);
p.setUrl(url);
try {
    BarCode ean = new Ean13Factory().create(code);
    //TODO: refactoring.
    p.setEan((Ean13) ean);
} catch (InvalidBarCodeException e) {
    logInvalidCode(e, code);
}

Does anyone have other suggestions?


texts: First Python Script - Web Scraper with results saved to MySQL DB

texts:
I am working on getting more experience with Python so I made a basic Web Scraper, that saves it to MySQL.

The code is currently working, but looking at it is very frustrating because it seems extremely redundant to me.

Some fake html - This does emulate the sites tree.

World

$1.99

$1.99

World2

$2.99

$2.99

World3

$3.99

$3.99

World4

$4.99

$3.99

My Python Script

from bs4 import BeautifulSoup
import urllib2
import csv
import dbconfig as cfg
origPage = 'http://localhost'
page = urllib2.urlopen(origPage)
import sys
import MySQLdb as mdb
reload(sys)
sys.setdefaultencoding('UTF8')

def pullGames():
 soup = BeautifulSoup (page, 'html.parser')
 #(page, 'html.parser')

 #Let's pull prices
 names = []
 pricing = []
 discounts = []
 discountPct = []
 #Push items to array for saving
 for name in soup.find_all('div', attrs={'class': 'tab_row'}):
  names.append(name.h4.text)
 for price in soup.find_all('div', attrs={'class': 'discount_original_price'}):
  pricing.append(price.text)
 for discount in soup.find_all('div', attrs={'class': 'discount_final_price'}):
  discounts.append(discount.text)
 for percent in soup.find_all('div', attrs={'class': 'discount_pct'}):
  discountPct.append(percent.text)

 con = mdb.connect(cfg.mysql['host'], cfg.mysql['user'], cfg.mysql['passwd'], cfg.mysql['db']);
 cur = con.cursor()
 con.set_character_set('utf8')
 cur.execute('SET NAMES utf8;')
 cur.execute('SET CHARACTER SET utf8;')
 cur.execute('SET character_set_connection=utf8;')

 for i in range(len(names)):
  sql = 'INSERT INTO game_pricing(game_name, original_price, discount_price) \
         VALUES("%s", "%s", "%s")' % \
         (names[i],pricing[i],discounts[i])
 #print sql
  cur.execute(sql)
  con.commit()

def checkDb():
 con = mdb.connect(cfg.mysql['host'], cfg.mysql['user'], cfg.mysql['passwd'], cfg.mysql['db']);
 cur = con.cursor()
 con.set_character_set('utf8')
 cur.execute('SET NAMES utf8;')
 cur.execute('SET CHARACTER SET utf8;')
 cur.execute('SET character_set_connection=utf8;')
 sql = 'SELECT game_name, original_price, discount_price FROM game_pricing'
 cur.execute(sql)
 results = cur.fetchall()
 for row in results:
  game_name = row[0]
  original_price = row[1]
  discount_price = row[2]
  print "game_name=%s, original_price=%s, discount_price=%s" % \
         (game_name, original_price, discount_price)
#For testing
checkDb()

It currently succeeds and gets 2,800 records in just a few(~15) seconds, including DB save. I am now adding in additional code to review if an entry exists, and only update if they exist.

I wrapped both parts into functions so I can easily test them out without writing duplicates.

Welcome any feedback. While this is working, I am not even sure how to begin refactoring it for redundancy sake.


texts: Retrieving current time and computing a hash value

texts:
Can someone critique this Java code?

package javaapplication;

import java.util.Date;
import java.lang.Long;

interface infix_operator {

    public int apply(int x, int y);
}

class f implements infix_operator {

    public int apply(int x, int y) {
        return x + (2 * y);
    }
}

class g implements infix_operator {

    public int apply(int x, int y) {
        return (2*x) + y;
    }
}

class h implements infix_operator {

    public int apply(int x, int y) {
        return x + y;
    }
}

class k implements infix_operator {

    public int apply(int x, int y) {
        return x * y;
    }
}

public class JavaApplication {

    static long to_64bit_signed_integer (long value)
    {
        long bit16 = value & 65535;
        value = (bit16 << 16) | bit16;
        value = (value << 16) | bit16;
        value = (value << 16) | bit16;
        return Long.reverse(value);
    }

    public static void main(String[] args) {
        long current_time_value = new Date().getTime();
        System.out.println("Current Time: " + current_time_value);

        infix_operator[] operator_array = {new f(), new g(), new h(), new k()};

        int [] node = new int[31];
        int [] to_signed_value = new int[] {0,-2,1,-1};
        int [] to_unsigned_value = new int[] {0,2,1,3};

        long value = to_64bit_signed_integer (current_time_value);

        value = value >> 2;

        for (int leaf_index=30; leaf_index>=15; leaf_index--)
        {
            node[leaf_index] = to_signed_value [(int)(value & 3)];
            value = value >> 2;
        }

        for (int internal_index = 14; internal_index >= 0; internal_index--)
        {
            int op = to_unsigned_value [(int)(value & 3)];
            int child_index = 2*internal_index + 1;
            node [internal_index] = operator_array[op].apply(node[child_index], node[child_index+1]);
            value = value >> 2;
        }

        System.out.println("Hash Value: " + node[0]);
    }
}


texts:
I am trying to print longest consecutive element in sorted array  for that I have written following brute force algorithm

void Main()
{
    var arr = new[] { 1, 2, 4, 5, 6 ,7,8,10,11,12};

    int max = 0;
    int count = 1;
    int startIndex = 0;
    int start=0;
    int endIndex=0;
    for (int i = 0; i < arr.Length - 2; i++)
    {
        startIndex = i;
        while (i<arr.Length-1 && Math.Abs(arr[i] - arr[i + 1]) == 1)
        {
            i++;
            count++;
        }
        if (max < count)
        {
            max=count;
            start=startIndex;
            endIndex=i;
            count=1;

        }

    }
    for (int k = start; k <= endIndex; k++)
    {
        Console.WriteLine(arr[k]);

    }
}

I need some review comments on my solution( I don't want optimize solution)


texts:
I made a program that lets the user input text into a text box.
The user can choose a number to rotate each alphabetical character by that number,
and the output box will diplay the converted text.
Here is how it runs:

Among the code is
#            if event.key == pygame.K_RETURN:
#                print('\n'.join([''.join(row) for row in rot_box.text])+'\n--------------------')

If you remove the hashtags, the converted text will be printed whenever you press Enter.
Here is my entire code:
import pygame
pygame.font.init()

wn = pygame.display.set_mode((600, 600))
font = pygame.font.Font(None, 32)

class TextBox():
    def __init__(self, x, y, w, h, title='Text Box', color=(0, 0, 0), default=''):
        self.input_box = pygame.Rect(x, y, w, h)
        self.w = w
        self.h = h
        self.color_inactive = color
        self.color_active = pygame.Color('purple')
        self.color = self.color_inactive
        self.default = default
        self.text = ['']
        self.active = False
        self.title = title

    def draw(self):
        title = font.render(self.title, True, self.color)
        wn.blit(title, (self.input_box.x+5, self.input_box.y-self.h))
        txts = [font.render(''.join(t), True, self.color) for t in self.text]
        width = max(self.w, max(txts, key=lambda x:x.get_width()).get_width()+10)
        height = self.h * len(txts)
        self.input_box.w = width
        self.input_box.h = height
        if len(txts) == 1 and txts[0].get_width() == 1:
            wn.blit(font.render(self.default, True, self.color), (self.input_box.x+5, self.input_box.y+5))
        else:
            for i, txt in enumerate(txts):
                wn.blit(txt, (self.input_box.x+5, self.input_box.y+5+i*self.h))
        pygame.draw.rect(wn, self.color, self.input_box, 2)

    def check_status(self, pos):
        if self.input_box.collidepoint(pos):
            self.active = not self.active
        else:
            self.active = False
        self.color = self.color_active if self.active else self.color_inactive

    def type(self, event):
        if self.active:
            if event.key == pygame.K_RETURN:
                self.text.append('')
            elif event.key == pygame.K_BACKSPACE:
                if self.text[-1]:
                    self.text[-1] = self.text[-1][:-1]
                else:
                    if len(self.text) > 1:
                        self.text = self.text[:-1]
            else:
                self.text[-1] += event.unicode

def rot(alp, num):
    while num >= 26:
        num -= 26
    if alp in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
        n = ord(alp) + num
        if n > 122 or 97 > n > 90:
            n -= 26
        alp = chr(n)
    return alp

box = TextBox(110, 60, 140, 32, 'Input Text')
rot_num = TextBox(10, 60, 50, 32, 'Rot', default='0')
rot_box = TextBox(110, 300, 140, 32, 'Output Text')

while True:
    rt = int(rot_num.text[0]) if rot_num.text[0] else 0
    rot_box.text = [[rot(char, rt) for char in row] for row in box.text]
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            box.check_status(event.pos)
            rot_num.check_status(event.pos)
        if event.type == pygame.KEYDOWN:
            box.type(event)
            if (event.unicode.isdigit() or event.key == pygame.K_BACKSPACE) and len(rot_num.text[0]) < 6 or event.key == pygame.K_BACKSPACE:
                rot_num.type(event)
#            if event.key == pygame.K_RETURN:
#                print('\n'.join([''.join(row) for row in rot_box.text])+'\n--------------------')

    wn.fill((255, 255, 200))
    box.draw()
    rot_num.draw()
    rot_box.draw()
    pygame.display.flip()

Can you show me how to clean up my messy code?
Can also you point me at the parts of my code that should've been in a class or function, and the parts that shouldn't have been?


texts:
I'm brand new to AngularJS. I would like advice as to whether I'm approaching the design of a simple login section of an app built with Angular correctly.

The app consists of two view partials: login.html and user-admin.html. Of what I have so far, the user types their username into the login page. A controller checks if that username is listed in users.json file, if so then login is successful and the user-admin.html partial replaces login.html.

I feel that the controller which checks the typed username against the usernames in users.json could be written better. Is there a more efficient way than using the 'for' statement?

To develop this further I will want to add some way of preventing a logged in user seeing the login page and a non-logged in user seeing the admin page. My initial thought is to use cookies. But would the 'Angular' way be to create a service that perpetuates the logged in status between views? If that is the best way to implement it, what would that service look like?

app.js

angular.module('userApp', ["ngResource"]).

config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/login', {templateUrl: 'partials/login.html',   controller: LoginCtrl}).
        when('/loggedin', {templateUrl: 'partials/user-admin.html', controller: UserCtrl}).
        otherwise({redirectTo: '/login'});
}],[ '$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode = true;
}]).

factory("User", function($resource) {
    return $resource("users/:userId.json", {}, {
        query: {method: "GET", params: {userId: "users"}, isArray: true}
    });
});

controllers.js

function LoginCtrl($scope, $route, $routeParams, $location, User) {
    $scope.users = User.query();
    $scope.loginUser = function() {
        var loggedin = false;
        var totalUsers = $scope.users.length;
        var usernameTyped = $scope.userUsername;

        for( i=0; i < totalUsers; i++ ) {
            if( $scope.users[i].name === usernameTyped ) {
                loggedin = true;
                break;
            }
        }

        if( loggedin === true ) {
            alert("login successful");
            $location.path("/loggedin");
        } else {
            alert("username does not exist")
        }
    }
}

function UserCtrl($scope, $route, $routeParams, $location) {
    $scope.logoutUser = function() {
        $location.path("/login");
    }
}

users.json

[
    {
        "userId": 1,
        "name": "Tommy",
        "password": "123456",
        "log": {
            "registration": "2012.12.14",
            "lastLog": "2013.01.15"
        }
    },
    {
        "userId": 2,
        "name": "Anne",
        "password": "123456",
        "log": {
            "registration": "2012.12.24",
            "lastLog": "2012.12.29"
        }

    },
    {
        "userId": 3,
        "name": "Miles",
        "password": "abc",
        "log": {
            "registration": "2013.02.01",
            "lastLog": "2013.02.01"
        }
    }
]

login.html

Login

    <form ng-submit="loginUser();">
        Username<input type="text" id="userUsername" ng-model="userUsername">
        <input type="submit" value="Login">
    </form>


texts:
I created an example of a simple form for a last name input in React, where I can check the validation of the data at the time of input. The last name should contain only small and capital letters. If the user enters other characters, the error text is displayed. I will be grateful for tips on improving the style.

index.js:

import React from 'react'
import { render } from 'react-dom'

const ErrorOutput = props => {
  if (!(props.case).match(/^[a-zA-Z]+$/) && (props.case).length > 0) {
    return Letters only.
  }
  return
}

class App extends React.Component {
  constructor(props){
    super(props)

    this.state = { value: '' }
  }

  handleValidation(e) {
    this.setState({
      value: e.target.value
    })

  }

  render() {
    const inputValue = this.state.value

    return (
      <form>

          Last name:

        <input
          type='text'
          name ='lastName'
          value = {this.state.value}
          onChange = {this.handleValidation.bind(this)}
        />
        <ErrorOutput case={inputValue} />
      </form>
    )
  }
}

render(
  <App />,
  document.getElementById('root')
)


texts:
I have project where I will need to create lots of immutable strings. If I am using std::string, which has huge overhead - about 60-70% against const char *. On a 64-bit machine, the current implementation uses 8 bytes for the class + the const char * size. This is the same size as it would be with plain C.

I will also do optimization with union and will put small strings into the pointer itself.

I need to know if I am on right track.

#include <stdio.h>

#include <memory>
#include <string.h>

class String{
public:
    String(){};

    String(const char *s) : _data(__dup(s)){};

    String(const String & other) : String( other.c_str() ){};

    String(String && other) = default;

    String & operator=(String other){
        std::swap(_data, other._data);
        return *this;
    }

    const char *c_str() const{
        return _data.get();
    }

    int cmp(const String & other) const{
        if (c_str() == nullptr)
            return other ? -1 : 0;

        return strcmp(*this, other);
    }

    operator bool() const{
        return c_str();
    }

    operator const char *() const{
        return c_str();
    }

    bool operator == (const String & other) const{
        return cmp(other) == 0;
    }

    bool operator != (const String & other) const{
        return cmp(other) != 0;
    }

    bool operator > (const String & other) const{
        return cmp(other) > 0;
    }

    bool operator >= (const String & other) const{
        return cmp(other) >= 0;
    }

    bool operator < (const String & other) const{
        return cmp(other) < 0;
    }

    bool operator <= (const String & other) const{
        return cmp(other) <= 0;
    }

private:
    static char *__dup(const char *s){
        auto size = strlen(s);
        char *copy = new char[size];
        memcpy(copy, s, size);
        return copy;
    }

private:
    std::unique_ptr<char[]> _data;
};

void p(String &s){
    printf("%s\n", s ? (const char *) s : "[null]");
}

int main(){
    String s1;          p(s1);
    String s2  = { "hello" };   p(s2);
    String s3a = s2;        p(s3a);
    String s3  = std::move(s3a);    p(s3);
    s1 = s3;            p(s1);
    s1 = "hi";          p(s1);

    String a = "aaaa";
    String b = "bbbb";
    String c = "aaaa";

    printf("%s %s\n", a == c ? "Y" : "N", "Y");
    printf("%s %s\n", a == b ? "Y" : "N", "N");
    printf("%s %s\n", a != b ? "Y" : "N", "Y");
    printf("%s %s\n", a <  b ? "Y" : "N", "Y");
    printf("%s %s\n", a >  b ? "Y" : "N", "N");
    printf("%s %s\n", a <= b ? "Y" : "N", "Y");
    printf("%s %s\n", a >= b ? "Y" : "N", "N");
    printf("%s %s\n", a <= c ? "Y" : "N", "Y");
    printf("%s %s\n", a >= c ? "Y" : "N", "Y");

    return 0;
}


texts: Reduction of time for matrix multiplication of pixels

texts:
This part of my code is taking 30 minutes to multiple 300 RGB and Depth images pixel by pixel. How can I reduce this time? This is just a part of big code but this taking lot of time.

def depth_to_xyz_and_rgb(uu, vv, dep):
    # t1.tic()
    # get z value in meters
    pcz = dep.getpixel((uu, vv))
    if pcz == 60:
        return
pcx = (uu - cx_d) * pcz / fx_d
pcy = ((vv - cy_d) * pcz / fy_d)

# apply extrinsic calibration
P3D = np.array([pcx, pcy, pcz])
P3Dp = np.dot(RR, P3D) - TT

# rgb indexes that P3D should match
uup = (P3Dp[0] * fx_rgb / P3Dp[2] + cx_rgb)
vvp = (P3Dp[1] * fy_rgb / P3Dp[2] + cy_rgb)

# t1.toc()

# return a point in point cloud and its corresponding color indices
return P3D, uup, vvp

Sample images.


texts: Concurrent Queue with enqueue and dequeue using Stack as underlying data structure

texts:
This is a mix of data structure and multi threading concept based question. (This is only for understanding and learning purpose) The language for the solution : Java

A Queue with FIFO behavior needs to be implemented by having underlying data structure as Stack.
Enqueue and Dequeue need to be parallel and need not block each other, i.e. enqueue thread must not wait for dequeue thread.

During my search (java based solutions) I could only find the blocking version of this problem where enqueue and dequeue are blocking for each other.

Below is my attempt for this, please correct me if I am wrong or in case I missed something.

Two Stacks : addStack and removeStack with individual Lock Objects addLock and removeLock
Enqueue operation : enqueue inside synchronized block on addLock, once item added, invoke notifyAll on addLock
Dequeue operation : If removeStack is empty then addStack is checked if it is empty , if not then all the elements from addStack are popped and pushed to removeStack
pop the element from removeStack and return

Below is the java code :

import java.util.Stack;

/**
 * Queue Implementation with Stack as underlying data-structure and with
 * parallel (almost) enqueue and dequeue
 *
 * @author krishna_k
 *
 */
public class Queue {

    private Stack<Integer> addStack = new Stack<>();
    private Stack<Integer> removeStack = new Stack<>();
    private final Object addLock = new Object();
    private final Object removeLock = new Object();

    public void enqueue(int item) {
        synchronized (addLock) {
            addStack.push(item);
            addLock.notifyAll();
        }
    }

    public int dequeue(){
        int value = 0;
        synchronized (removeLock) {
            if (removeStack.isEmpty()) {
                try {
                    synchronized (addLock) {
                        while (addStack.isEmpty()) {
                            addLock.wait();
                        }
                        while (!addStack.isEmpty()) {
                            removeStack.push(addStack.pop());
                        }
                    }
                }catch(InterruptedException e) {
                    //code to log the exception e
                }
            }
            value = removeStack.pop();
        }
        return value;
    }
}


texts: Swift/iOS: Subclassing UILabel and setting properties

texts:
I'm writing this subclass to add an icon to a UILabel. It works, but I'm wondering if this is the best/cleanest way to do it. Do you see any improvements? Should maybe text and image properties be set using a init() method?

import UIKit

class IconLabel: UILabel {

    override var text: String? {
        set {
            nameLabel.text = newValue
        }
        get {
            return nameLabel.text
        }
    }

    var image: UIImage? {
        didSet {
            icon.image = image?.withRenderingMode(.alwaysTemplate)
        }
    }

    private lazy var icon: UIImageView = {
        let imageView = UIImageView()
        imageView.tintColor = .white
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = Theme.regular(size: .tiny)
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = Theme.supportLightGrayColor
        self.layer.cornerRadius = 5.0
        self.clipsToBounds = true
        self.addSubviewsAndConstraints()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func addSubviewsAndConstraints() {
        self.addSubview(icon)
        self.addSubview(nameLabel)

        self.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 5.0, leading: 5.0, bottom: 5.0, trailing: 5.0)

        icon.leftAnchor.constraint(equalTo: self.layoutMarginsGuide.leftAnchor).isActive = true
        icon.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor).isActive = true
        icon.heightAnchor.constraint(equalTo: self.layoutMarginsGuide.heightAnchor).isActive = true
        icon.widthAnchor.constraint(equalTo: icon.heightAnchor).isActive = true

        nameLabel.leftAnchor.constraint(equalTo: icon.rightAnchor, constant: 5.0).isActive = true
        nameLabel.centerYAnchor.constraint(equalTo: icon.centerYAnchor).isActive = true
        nameLabel.rightAnchor.constraint(equalTo: self.layoutMarginsGuide.rightAnchor).isActive = true
    }
}


texts: Animations when navigation items are clicked

texts:
I'm a beginner in jQuery and am wondering how I could write the following code shorter, since I'm repeating a lot.

Working example

//-----------Fullscreen overlay menu click events -----//

$('#overlay-menu').bind("click", function() {
    $(".overlay").addClass('overlay-open');
    $("#overlay-menu").fadeOut(800);
});

$(".overlay-close").bind("click", function() {
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});

//------------ Scroll function-------//

function scrollToAnchor(linkID) {
    var linkName = $("a[name='"+ linkID +"']");
    $('html, body').animate({scrollTop: linkName.offset().top}, 'slow');
}

//------------- the repeating part --------------------------------//

$("#homelink").bind("click", function() {
    scrollToAnchor('home_anchor');
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});

$("#overlink").bind("click", function() {
    scrollToAnchor('over_anchor');
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});

$("#daglink").bind("click", function() {
    scrollToAnchor('dag_anchor');
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});

$("#werkzaamhedenlink").bind("click", function() {
    scrollToAnchor('werkzaamheden_anchor');
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});

$("#contactlink").bind("click", function() {
    scrollToAnchor('contact_anchor');
    $(".overlay").removeClass('overlay-open');
    $("#overlay-menu").fadeIn(800);
});

//------------One page item (there are 5)---------------//

over

//------------Fullscreen menu overlay ------------------//

                <button type="button" class="overlay-close">Close</button>

home

over

een dag bij

werkzaamheden

contact


texts: Header only c++ singleton pattern implementation

texts:
I want to implement the singleton pattern in a header only c++ library. (Please refrain from sharing your opinion on the pattern itself!) This would be trivial if I could rely on the compiler implementing thread safe c++11 function-local static-duration object initialization. i.e.

static inline MyClass& singleTon()
{
    static MyClass instance;
    return instance;
}

Unfortunately MSVC prior to 2015 does not comply with this standard. See "Magic Statics" so I have tried to implement it through a class:

#include <mutex>
/**
 * Header only implementation of the singleton pattern.
 * Use like this:
 * MyClass& singleton = SingleTon<MyClass>().get();
 */
template<class Type>
struct SingleTon
{
    static std::unique_ptr<Type> instance;
    static std::once_flag flag;
    Type& get()
    {
        auto& capture = instance;// lambdas can't capture static members
        std::call_once(flag, [&capture] { capture.reset(new Type{}); });
        return *instance.get();
    }
};

template<class Type>
std::unique_ptr<Type> SingleTon<Type>::instance;

template<class Type>
std::once_flag SingleTon<Type>::flag;

So my function now looks like:

static inline MyClass& singleton()
{
    return SingleTon<MyClass>().get();
}

I hope that this function is thread safe given that the ctor of Typeis nothrow.


texts: Find all distinct combinations of letters in a string

texts:
I've been preparing for interviews and picking up modern C++. A recent prep question I did was to find all combinations (or distinct subsets) of letters from a string.  E.g. 'AA2'-> {'A', '2', 'A2', 'AA2'}.  Note that the order doesn't matter.  I would like feedback both on the approach and on use of C++ style/best practices.  My attempt is:

#include <string>
#include <algorithm>
#include <unordered_set>
#include <iostream>

std::unordered_set<std::string> getPermutations(std::string str){
    std::unordered_set<std::string> ret;
    if (str.length() <= 1){
        ret.insert(str);
    } else {
        char removedLetter = '\0';
        for(unsigned i = 0; i < str.length(); i++){
            if (removedLetter == str[i]){ //Already found all subsets missing this character
                continue;
            }
            removedLetter = str[i];
            std::string subString = str.substr(0, i) + str.substr(i+1, std::string::npos);
            std::unordered_set<std::string> shorter = getPermutations(subString);
            for(auto shortPerm : shorter){
                ret.insert(shortPerm);
                auto ind = shortPerm.begin();
                for(; ind < shortPerm.end(); ind++){ //Find where to insert letter so that ordering is preserved for eliminating duplicates
                    if(*ind > removedLetter){
                        break;
                    }
                }
                shortPerm.insert(ind, removedLetter);
                ret.insert(shortPerm);
            }
        }
    }
    return ret;
}

int main(int argc, char ** argv){
    std::string str;
    std::cin >> str;
    std::sort(str.begin(), str.end()); //Sort string so that method works.
    for(const auto &p :  getPermutations(str)){
        std::cout << p << ' ';
    }
    std::cout << std::endl;
}


texts: Risks related to overriding attribute access

texts:
I have written ExtendedConfigParser class that adds ability to dot access config values like ExtendedConfigParser().section_name.option_name:

from ConfigParser import SafeConfigParser

class ExtendedConfigParser(SafeConfigParser):

    def __init__(self, config_file=None, type_conversion={}, *args, **kwargs):
        self.config_file = config_file
        self.type_conversion = type_conversion
        SafeConfigParser.__init__(self, *args, **kwargs)
        self.chain = []
        self.cmap = {}
        if config_file:
            self.read(config_file)

    def section2dict(self, secname):
        opts = self.options(secname)
        def opt_conv_type(optname, value):
            if optname in self.cmap:
                return self.cmap[optname](value)
            return value
        return {o:opt_conv_type(o, self.get(secname, o)) for o in opts}

    def add_type_conversion_map(self, cmap):
        self.cmap.update(cmap)

    def __getattr__(self, attrname):
        if attrname in self.sections():
            self.chain.append(attrname)
            return self
        if len(self.chain) == 1 and attrname in self.section2dict(self.chain[0]):
            return self.section2dict(self.chain[0])[attrname]
        self.chain = []
        return getattr(SafeConfigParser, attrname)(self)

Let's have config file like this:

[globals]

webui_port = 8888

redis_host = 127.0.0.1
redis_port = 5600

Then it works like this:

cmap = {'redis_port':int, 'webui_port':int}
cfg = ExtendedConfigParser(config_file=confile, type_conversion=cmap)
print cfg.globals.webui_port

What I do not like about the code above is that I'm doing sort of manual attribute resolution in __getattr__. Is there a better (cleaner, more general) solution?

And also what will happen if a section name happens to be called like SafeConfigParser attribute? It would override it, correct? How can I avoid that?


texts: A puzzle about how to write more clean and understandability code

texts:
private function getFeatureByParam ($classname, $module, $action) {
    $needFeature = array();
    foreach ($this->featureConf as $featureIndex => $feature) {
        if ($feature['classname'] == $classname &&
            $feature['module'] == $module &&
            $feature['action'] == $action) {
                $needFeature = $feature;
                break;
        }
    }
    return $needFeature;
}
private function getFeatureByParam ($classname, $module, $action) {
    foreach ($this->featureConf as $featureIndex => $feature) {
        if ($feature['classname'] == $classname &&
            $feature['module'] == $module &&
            $feature['action'] == $action) {
                return $feature;
        }
    }
    return array();
}

The first style of writing is more understandability.

The second style of writing is more clean and efficient.

But witch one is more better? (Or they are too bad....)


texts: Fading HTML elements in and out after timed delays using jQuery

texts:
I recently launched my first website, and despite being very proud of how far I've come, I know that my code is more "I got it to work" than "It works the best that it can." I'd like some criticism, and insight into how you would accomplish the same effect.

This script shows and hides overlapping Divs to tell a story through text about myself. I want to retain the granular control over how long each div stays visible, but simplify this code.

<script>
    $(document).ready(function(){
     $("button.button").click(function(){
      $("h1.about-title").fadeOut(300, function() {
       $("div.b").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){
        $("div.c").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){
         $("div.d").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){
          $("div.e").delay(500).fadeIn(300).delay(5000).fadeOut(300, function(){
           $("div.f").delay(500).fadeIn(300).delay(5000).fadeOut(300, function(){
            $("div.g").delay(500).fadeIn(300).delay(5000).fadeOut(300, function(){
             $("div.h").delay(500).fadeIn(300).delay(4000).fadeOut(300, function(){

               });
              });
             });
            });
           });
          });
         });
        });
       });
      });
</script>

an example of this running can be found at http://www.erikgratz.com/about.html

I suspect I could have saved a lot of time and code with a loop or some variables. How would you accomplish this same effect?


texts: Calculating the difference between 2 arrays

texts:
I made this function to calculate the difference between 2 arrays and return it in a third array. I'm using this function as a part of stocktaking functionality I apply in my accounting system.

function stockdiff ($array2,$array1){
    //inputs :
    //$array2 is the stocktaking result in an array that has the format "$product_id=>$quantity"
    //$array1 is the stock according to the data in the system in an array that has the format "$product_id=>$quantity"
    foreach($array2 as $key=> $value){
        if(isset($array1[$key])){$result[$key] = $array2[$key] - $array1[$key];}
        else{$result[$key] = $array2[$key];}
    }
    $array1diff = array_diff_key($array1,$array2);

    foreach($array1diff as $key=> $value){
        $result[$key] = -1 * $array1[$key];
    }
return $result;
}

Case example

When the user do the stocktaking, its result are going to be saved in $array2 in the format $product_id=>$quantity.

This is a stocktaking result example:

$array2[2] = 500;
$array2[3] = 7;
$array2[1] = 302;
$array2[105] = 7000;
$array2[7] = 304;
$array2[8] = 20;
$array2[9] = 20;
$array2[11] = 20;
$array2[73] = 32;
$array2[21] = 35;

I then compare it against the stock quantities according to the data in the system $array1 which might be something like this:

$array1[1] = 30;
$array1[2] = 60;
$array1[3] = 202;
$array1[4] = 200;
$array1[7] = 0;
$array1[8] = 0;
$array1[9] = 0;
$array1[11] = 52;
$array1[21] = 70;
$array1[99] = 21;

I made this function to do that job. I need it to tell me the changes that happened for every product between the data in the system and the actual data come from the stocktaking, for example, let's take product_id 2.

In the system it was $array1[2] = 60; 60 units from the product 2, and the stocktaking told us no, we found 500 units from the product 2 $array2[2] = 500;. So, the function must return [2]=>440.

The function also needs to consider about these points:

If there is a product in the stocktaking array ($array2) that has no matching product in the stock-in-system array($array1), then the function will assume it's whole quantity has been increased and return it's quantity from $array2.
If there is a product in the stock-in-system array ($array1) that has no matching product in the stocktaking array ($array2), then the function will assume it's whole quantity has been decreased and return -1 * quantity.

What do you think about the function?