texts: Convert ISO 8601 week to American-formatted date

texts:
Requirements:

Implement a function that, given a standard date and an indicator
whether or not the output should be in american standard (weeks start
on sundays, the first week of the year is the week containing the
first day of the year) or in ISO8601 standard (weeks start on mondays,
the first week of the year is the week containing the first thursday
of the year) outputs the calendar week and year of the input date in
the following format as a string.
[calendar week] / [year]

Further requirements:

camelCase is to be used for function names
variables are to be underscore-seperated / lower_snake_case
option explicit is mandatory

This is my implementation:
Option Explicit
Public Function convertDateToFormattedCalendarWeek(input_date As Date, mode As Integer) As String

Dim week As String
Dim year As String
If mode = 0 Then 'mode 0 = standard american timekeeping
    week = CStr(DatePart("ww", input_date, vbSunday, vbFirstJan1))
    year = CStr(DatePart("yyyy", input_date, vbSunday, vbFirstJan1))
ElseIf mode = 1 Then 'mode 1 = ISO8601 business timekeeping
   'using the thursday in the given week instead for calculation to avoid the datepart leap year bug
    week = CStr(DatePart("ww", input_date - Weekday(input_date, vbMonday) + 4, vbMonday, vbFirstFourDays))
    year = CStr(DatePart("yyyy", input_date - Weekday(input_date, vbMonday) + 4, vbMonday, vbFirstFourDays))
Else
    convertDateToFormattedCalendarWeek = "error"
    Debug.Print ("function convertDateToFormattedCalendarWeek called with invalid parameter mode " & mode)
    Exit Function
End If

convertDateToFormattedCalendarWeek = week & " / " & year

End Function

Runs fine from what I've tested (a lot of dates)


texts: Calculating pi with Monte Carlo using OpenMP

texts:
I'm a C noob and I'm learning about concurrency using C. I came across an exercise in a book asking me to find the approximate value of Pi using the Monte Carlo technique with OpenMP. I came up with the following:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <omp.h>

int in_circle = 0;
int total = 10000;
int thread_numb = 4;

void calculate_in_circle_random_count() {
  srand((unsigned int)time(NULL));
  for (int i = 0; i < total / thread_numb; i++) {
    float x = (float)rand()/(float)(RAND_MAX);
    float y = (float)rand()/(float)(RAND_MAX);

    float val = (x * x) + (y * y);

    if (val < 1.0) {
      #pragma omp critical
      {
        in_circle++;
      }
    }
  }
}

int main(int argc, char const *argv[]) {
  #pragma omp parallel num_threads(thread_numb)
  {
    printf("Hello from process: %d\n", omp_get_thread_num());
    calculate_in_circle_random_count();
  }

  float pi_approx = 4 * (float)in_circle / (float)total;

  printf("In circle: %d\n", in_circle);
  printf("Total: %d\n", total);
  printf("Pi approximation: %.6f\n", pi_approx);

  return 0;
}

I have the sample count of 10000 to calculate approximation and I want to dedicate 4 threads to be parallel for the calculation. So since I want 4 threads, I make sure the for loop is run until total / 4 for each thread. And whenever (val < 1.0) is true I increase the in_circle variable in a critical section.
Does this approach make sense? If not, how could it be improved?


texts: Graph and Node classes with BFS and DFS functions

texts:
I've created a Node class and a Graph class

class Node:
    def __init__(self, val):
        self.val = val
        self.edges = []

class Graph:
    def __init__(self, nodes=[]):
        self.nodes = nodes

    def add_node(self, val):
        newNode = Node(val)
        self.nodes.append(newNode)

    def add_edge(self, node1, node2):
        node1.edges.append(node2)
        node2.edges.append(node1)

I have also added functions to the Graph class for performing breadth first search and depth first search on a given graph.

def bfs(self):
    if self.nodes is None:
        return []
    visited, toVisit = [], [self.nodes[0]]
    while toVisit:
        node = toVisit.pop()
        visited.append(node)
        print(node.val)
        for nd in node.edges:
            if nd not in visited and nd not in toVisit:
                toVisit.insert(0,nd)
    return visited

def dfs(self):
    if self.nodes is None:
        return []
    visited, toVisit = [], [self.nodes[0]]
    while toVisit:
        node = toVisit.pop()
        visited.append(node)
        print(node.val)
        for nd in node.edges:
            if nd not in visited and nd not in toVisit:
                toVisit.append(nd)
    return visited

Here is an example implementation

graph = Graph()
graph.add_node(5)
graph.add_node(3)
graph.add_node(8)
graph.add_node(1)
graph.add_node(9)
graph.add_node(2)
graph.add_node(10)

#            2
#           /
# 5 - 3 - 8 -  9 - 10
#  \    /
#     1

graph.add_edge(graph.nodes[0], graph.nodes[1])
graph.add_edge(graph.nodes[0], graph.nodes[3])
graph.add_edge(graph.nodes[1], graph.nodes[2])
graph.add_edge(graph.nodes[0], graph.nodes[1])
graph.add_edge(graph.nodes[2], graph.nodes[3])
graph.add_edge(graph.nodes[2], graph.nodes[5])
graph.add_edge(graph.nodes[2], graph.nodes[4])
graph.add_edge(graph.nodes[4], graph.nodes[6])

graph.dfs()
graph.bfs()

The depth first search returns 5,1,8,9,10,2,3

The breadth first search returns 5,3,1,8,2,9,10

From what I can tell, this is a correct implementation.  However, I'm curious if there are more efficient ways to do some of these things.  Or maybe ways that make more logical sense.  For example, am I storing the edge list in a reasonable way?  Is this generic enough that it could easily be extended to work with directed vs undirected graphs?  Any feedback would be much appreciated.


texts: cake pattern object assembly - using a builder function in combination with the cake pattern

texts:
I am new to the cake pattern, this is my first attempt at using it.

Am I doing something wrong if I use the apply method in object OrderedLineListResourceImpl to create a specific version of OrderedLineListResource?

In this sense the apply method is a builder method that creates OrderedLineListResource.

Am I overcomplicating something ?  I cannot find any simpler way of creating an OrderedLineListResource (and still using the cake pattern).

Is there any simpler, more elegant, more idiomatic way of writing this code (and still using the cake pattern to inject dependencies into OrderedLineListResource, such as the abstract val member lineService )?

So, in my understanding, the cake pattern is a way to declare and inject dependencies into traits. So in some sense, self type annotations in traits are akin to function parameters in functions, and calling that "function" is the same as calling the apply method in OrderedLineListResourceImpl. So the apply method turns the trait OrderedLineListResource into a traditional function (apply).

Does this make sense ? What is your opinion ?

object OrderedLineListResourceImpl{
  def apply(ec:ExecutionContext,actorRefFactory: ActorRefFactory):OrderedLineListResourceImpl= {
    trait ExecutionContextProvider extends HasExecutionContext {
      override implicit val executionContext: ExecutionContext = ec
    }
    trait ARF extends HasActorRefFactory {
      override val arf: ActorRefFactory = actorRefFactory
    }

    object LL extends OrderedLineListResourceImpl with ExecutionContextProvider with ARF
    LL
  }
}

trait OrderedLineListResourceImpl extends OrderedLineListResource {
    self :HasExecutionContext with HasActorRefFactory =>

    trait MapContainerComponentImpl extends MapContainerComponent[OrderedList[Line]] {
       object MapContainerImpl extends MapContainer with HasExecutionContext { implicit val executionContext=self.executionContext}
       override val mc = MapContainerImpl
    }

    object OrderedListCRUDImpl extends OrderedListCRUD[E] with MapContainerComponentImpl with
      HasExecutionContext { implicit val executionContext=self.executionContext}

    val lineService: OrderedListCRUD[E] = OrderedListCRUDImpl

    override implicit val executionContext: ExecutionContext = self.executionContext

    override implicit def actorRefFactory=self.arf

    ...
}

class RestInterface(implicit val executionContext: ExecutionContext) extends HttpServiceActor {

  val ll=OrderedLineListResourceImpl(executionContext,actorRefFactory)

  def routes: Route = ll.lineRoutes

  ...
}

trait OrderedLineListResource  extends MyHttpService {
...
  val lineService: OrderedListCRUD[E]
...
}


texts:
I'm posting my C++ code for LeetCode's Expressive Words. If you have time and would like to review, please do so. Thank you!

Sometimes people repeat letters to represent extra feeling, such as
"hello" -> "heeellooo", "hi" -> "hiiii".  In these strings like
"heeellooo", we have groups of adjacent letters that are all the same:
"h", "eee", "ll", "ooo".
For some given string S, a query word is stretchy if it can be made to
be equal to S by any number of applications of the following extension
operation: choose a group consisting of characters c, and add some
number of characters c to the group so that the size of the group is 3
or more.
For example, starting with "hello", we could do an extension on the
group "o" to get "hellooo", but we cannot get "helloo" since the group
"oo" has size less than 3.  Also, we could do another extension like
"ll" -> "lllll" to get "helllllooo".  If S = "helllllooo", then the
query word "hello" would be stretchy because of these two extension
operations: query = "hello" -> "hellooo" -> "helllllooo" = S.
Given a list of query words, return the number of words that are
stretchy.
Example: Input:  S = "heeellooo" words = ["hello", "hi", "helo"]
Output: 1 Explanation:  We can extend "e" and "o" in the word "hello"
to get "heeellooo". We can't extend "helo" to get "heeellooo" because
the group "ll" is not size 3 or more.
Notes:
0 <= len(S) <= 100.
0 <= len(words) <= 100.
0 <= len(words[i]) <= 100.
S and all words in words consist only of lowercase letters

Accepted C++
class Solution {
public:
    int expressiveWords(std::string base_string, std::vector<string> &words) {
        int count = 0;

        for (auto &word : words)
            if (is_stretchable(base_string, word))
                count++;

        return count;
    }

protected:
    bool is_stretchable(std::string base_string, std::string words) { // 4 pointers
        int base_length = base_string.size();
        int words_length = words.size();
        int left_a = 0, right_a = 0;

        for (int left_b  = 0, right_b = 0; left_a < base_length && right_a < words_length; left_a = left_b, right_a = right_b) {
            if (base_string[left_a] != words[right_a])
                return false;

            while (left_b < base_length && base_string[left_b] == base_string[left_a])
                left_b++;

            while (right_b < words_length && words[right_b] == words[right_a])
                right_b++;

            if (left_b - left_a != right_b - right_a && left_b - left_a < std::max(3, right_b - right_a))
                return false;
        }

        return left_a == base_length && right_a == words_length;
    }
};

Reference
On LeetCode, there is an instance usually named Solution with one or more public functions which we are not allowed to rename those.

Solution
Discussion
Question


texts:
To get a feel of Monty Hall problem, I've implemented Monty Hall simulator in Python, using only two strategies: never switch the door or always switch the door. Please review it with an eye towards any problem with the code you can think of, things like better design, flaws in code, etc.

#!/usr/bin/env python3

import random
import sys

def available_doors():
    return [1, 2, 3]

class MontyHallBox(object):
    def __init__(self):
        self.__doors = {1: None, 2: None, 3: None}
        self.__init_doors()

    def reinitialize(self):
        self.__init_doors()

    def __init_doors(self):
        self.__doors = {n: 'goat' for n in range(1, 4)}
        car = random.choice(available_doors())
        self.__doors[car] = 'car'

    def _get_rand_doornum_item(self):
        door_num = random.choice(available_doors())
        item = self.__doors[door_num]
        return door_num, item

    def reveal_noncar(self, initial_door):
        door_num, item = self._get_rand_doornum_item()
        while item == 'car' or door_num == initial_door:
            door_num, item = self._get_rand_doornum_item()
        return door_num

    def reveal_selected(self, door):
        return self.__doors[door]

def run_sim_always_switch(mhb):
    mhb.reinitialize()
    initial_door = random.choice(available_doors())
    noncar_door = mhb.reveal_noncar(initial_door)
    switch_door_set = set(available_doors()) - set([initial_door, noncar_door])
    switch_door = list(switch_door_set)[0]
    item = mhb.reveal_selected(switch_door)
    if item == 'car':
        return 'success'
    return 'fail'

def run_sim_never_switch(mhb):
    mhb.reinitialize()
    initial_door = random.choice(available_doors())
    # this is pointless really as this info is not used by game participant
    _ = mhb.reveal_noncar(initial_door)
    item = mhb.reveal_selected(initial_door)
    if item == 'car':
        return 'success'
    return 'fail'

def run_simn(num, simn_fun):
    mhb = MontyHallBox()
    results = []
    for i in range(num):
        results.append(simn_fun(mhb))
    successes = len(list(filter(lambda x: x == 'success', results)))
    return successes / num

def main():
    num = 10000
    if num < 1:
        print('Simulation has to be ran at least 1 time')
        sys.exit(1)
    print('Always switch, run simulation {} times.'.format(num))
    print('Success ratio: {}'.format(run_simn(num, run_sim_always_switch)))
    print()
    print('Never switch, run simulation {} times.'.format(num))
    print('Success ratio: {}'.format(run_simn(num, run_sim_never_switch)))

if __name__ == '__main__':
    main()


texts: Opinions/Improvements on a run periodically/timer function in Python 2.7

texts:
I'm looking for some opinions on this bit of code that I wrote and if there are any ways it can be improved.

The scripts aim is to run the function runme() every 60 seconds with a random interval anywhere between -20 seconds to +40 seconds so it could run randomly anywhere between 40 seconds and 100 seconds.

import sched, time
import random

s = sched.scheduler(time.time, time.sleep)

def periodically(runtime, intsmall, intlarge, function):
    runtime += random.randrange(intsmall, intlarge)
    s.enter(runtime, 1, function, ())
    s.run()

def runme():
    print "hi"

while True:
    periodically(60, -20, +40, runme)


texts:
I need to add quotes to each word in a string.  Here is something that works but it looks ugly to me;

"this is a test".split.to_s.delete("[],")

produces

"\"this\" \"is\" \"a\" \"test\""

split adds the quotes, to_s turns the array back to a string, then the delete removes the array stuff.  The downside is the case where the data includes [] or ,

I welcome your responses!


texts: Any way to make this recursive function better/faster?

texts:
Is there anything that can be done differently for this function?  Any way to make it faster?

public List<Channel> ChildrenOf(Channel startingChannel)
{
    List<Channel> result = new List<Channel>();

    foreach (Channel child in startingChannel.Children)
    {
        result.Add(child);
        result.AddRange(ChildrenOf(child));
    }

    return result;
}


texts:
I have a working solution for this problem that was accepted in LeetCode:

  Given an array, rotate the array to the right by k steps, where k is non-negative."

function rotate(nums, k) {
  for (let i = 1; i <= k; i += 1) {
    const poppedNum = nums.pop();
    nums.unshift(poppedNum);
  }

  return nums;
}

// rotate([1, 2, 3, 4, 5, 6, 7], 3) -> [5, 6, 7, 1, 2, 3, 4]

Questions:

Would the time complexity be \$O(k)\$ and space complexity be \$O(1)\$?
Is there a better way to solve this? The question asked to rotate the elements in-place if possible, but I am not sure how to accomplish this at the moment.


texts: Flatten to get all child controls of certain type in a UIView

texts:
extension Array {
    func flatten<TResult>(transform: (T) -> TResult?, childArray: (T) -> [T]) -> [TResult] {
        var result = [TResult]()

        for original in self {
            let transformed = transform(original)
            if transformed != nil {
                result.append(transformed!)
            }
            result += childArray(original).flatten(transform, childArray: childArray)
        }

        return result
    }
}

Example usage to get all UILabels in a view (including it's subviews) :

let labels = someView.subviews.flatten(
                        { $0 as? UILabel },
                        childArray: { $0.subviews })

The code can probably be simplified/optimized, but how?


texts: My take at OOP module/prototyping JavaScript

texts:
The last month I've been reading up on how to take my JavaScript code to the next level. I am a Java programmer at heart, so it feels nice when everything is encapsulated in classes/objects, and these are ready to be instantiated or inhertid or whatever.

I wrote a simple test project with the purpose to refine my techniques, and I'm feeling I can't do anything more with it. Would you guys and gals take a look at it?

var People = People || {};

People = (function() {
    function People() {
        this.people = [];
    }

    People.prototype.addGentleman = function (name) {
        this.people.push(new People.Gentleman(name));
    }

    People.prototype.addLady = function (name, isMarried) {
        this.people.push(new People.Lady(name, isMarried));
    }

    People.prototype.getList = function () {
        var temp = [];

        for (var i = 0; i < this.people.length; i++) {
            temp.push(this.people[i].toString());
        }

        return temp;
    }

    return People;
})();

People.Human = (function () {
    function Human(name, hasLadyParts) {
        this.name = name;
        this.hasLadyParts = hasLadyParts;
    }

    Human.prototype.hasLadyParts = function () {
        return this.hasLadyParts;
    }

    Human.prototype.toString = function () {
        var str = this.name + ' has ';
        if (!this.hasLadyParts) str += 'no ';
        return str + 'lady parts.';
    }

    return Human;
})();

People.Gentleman = (function () {
    function Gentleman (name) {
        People.Human.call(this, name, false);
    }

    Gentleman.prototype = Object.create(People.Human.prototype);

    Gentleman.prototype.toString = function () {
        return 'Mr. ' + People.Human.prototype.toString.call(this);
    }

    return Gentleman;
})();

People.Lady = (function () {
    function Lady(name, hasWeddingRing) {
        People.Human.call(this, name, true);
        this.hasWeddingRing = hasWeddingRing;
    }

    function isNotMarried() {
        return !this.hasWeddingRing;
    }

    Lady.prototype = Object.create(People.Human.prototype);

    Lady.prototype.toString = function () {
        var str = !isNotMarried.call(this) ? 'Mrs. ' : 'Ms. ';
        return str + People.Human.prototype.toString.call(this);
    }

    return Lady;
})();

$(function () {
    var people = new People();
    people.addGentleman('Viktor');
    people.addGentleman('Joakim');
    people.addLady('Mattias', true);
    var list = people.getList();
    var $ul = $('#people');

    for (var i = 0; i < list.length; i++) {
        $ul.append('<li>' + list[i] + '</li>');
    }
});

One question: can I create protected (or public) variables that my child instance can change? Besides that question I only want my code reviewed with regards to my Java context. It feels nice to have it like this, but what can I do better?

The code should be a pretty straight-forward OOP example, and here's a fiddle.


texts: Rating tennis players in a database, taking days to run

texts:
I have this project in data analysis for creating a ranking of tennis players. Currently, it takes more than 6 days to run on my computer.

Can you review the code and see where's the problem?

Project steps:

I have a database of 600,000 tennis matches called matchdatabase.The database fileds are a) winner name, b) loser name, c) tournament, d) other fields for the winner and loser.
From that database, I create a playerdatabase with every player in the matchdatabase.
For each match in the matchdatabase it goes into the playerdatabase, retrieves the ranking/elo and computes the expected result.
It updates the ranking after the match into the playerdatabase

This for loop ends up running 1 match/second, so the whole database takes several days to run!

import pandas as pd
import glob
import numpy as np
import math

all_data = pd.read_csv('tennisdatabase.csv')
all_data = all_data.sort(['date'], ascending=[0])
all_data = all_data.reindex(index = np.arange(1, len(all_data) + 1))

#it checks every player in the matchdatabase and creates a database of players

playerdatabase = pd.DataFrame()
list_winners = pd.pivot_table(all_data,index=["winner_name"],values=["tourney_id"],aggfunc=np.count_nonzero)
list_losers =  pd.pivot_table(all_data,index=["loser_name"],values=["tourney_id"],aggfunc=np.count_nonzero)
firstloss =  pd.pivot_table(all_data,index=["loser_name"],values=["date"],aggfunc=np.min)
firstwin =  pd.pivot_table(all_data,index=["winner_name"],values=["date"],aggfunc=np.min)
playerdatabase = pd.concat([list_winners, list_losers, firstloss, firstwin], axis=1)
playerdatabase['NumberOfGames'] = 0

#defines a elo calculator for expectations and modified ratings

def getExpectation(rating_1, rating_2):
    "calculator for the expected result to player 1 based on the rating of both players"
    calc = (1.0 / (1.0 + pow(10, ((rating_2 - rating_1) / 400.0))))
    return calc

def modifyRating(rating, expected, actual, kfactor):
    "gives the new rating given the current rating, expected results, actual results and k factor"
    calc = (rating + kfactor * (actual - expected));
    return calc

#Elo calculation for the database
#sets initial rating for everyone at 2100

playerdatabase['Rating'] = 2100

loser_k_factor = 30
winner_k_factor = 30

#loop  for the calculations

for i in xrange(0, 616242):

    #gets the rating for both players from the playerdatabase
    winner_rating = playerdatabase.loc[all_data.iloc[i]['winner_name'], 'Rating']
    loser_rating = playerdatabase.loc[all_data.iloc[i]['loser_name'], 'Rating']
    all_data['winner_elo'][i+1] = winner_rating
    all_data['loser_elo'][i+1] = loser_rating

    #gets the expected result for both players
    winner_expectation = getExpectation(winner_rating, loser_rating)
    loser_expectation = getExpectation(loser_rating, winner_rating)

    #gets the updated result for both players
    winner_new_rating = modifyRating(winner_rating, winner_expectation, 1, winner_k_factor)
    loser_new_rating = modifyRating(loser_rating, loser_expectation, 0, loser_k_factor)
    #updates the results for both players in the playerdatabase
    playerdatabase.loc[all_data.iloc[i]['winner_name'], 'Rating'] = winner_new_rating
    playerdatabase.loc[all_data.iloc[i]['loser_name'], 'Rating'] = loser_new_rating
    #updates the number of games for both players in the playerdatabase
    playerdatabase.loc[all_data.iloc[i]['winner_name'], 'NumberOfGames'] = playerdatabase.loc[all_data.iloc[i]['winner_name'], 'NumberOfGames'] + 1
    playerdatabase.loc[all_data.iloc[i]['loser_name'], 'NumberOfGames'] = playerdatabase.loc[all_data.iloc[i]['loser_name'], 'NumberOfGames'] + 1

    #records the rating list every 500 calculations

    if i%500 == 0:
        playerdatabase[i] = playerdatabase['Rating']
        print i
    print i

playerdatabase = playerdatabase.sort(['Rating'], ascending=[1])


texts: Implementing String to int (atoi) in Java

texts:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

I'm not sure about my checks against integer overflow, but here is my implementation:
public int myAtoi(String str) {
    int i = 0;
    while (i < str.length() && Character.isWhitespace(str.charAt(i))) {
        ++i;
    }
    if (i == str.length()) {
        return 0;
    }

    boolean isNegative = false;
    if (str.charAt(i) == '+' || str.charAt(i) == '-') {
        isNegative = str.charAt(i) == '-';
        ++i;
    }

    int result = 0;
    while (i < str.length() && Character.isDigit(str.charAt(i))) {
        try {
            result = Math.multiplyExact(result, 10);
            result = Math.addExact(result, Character.getNumericValue(str.charAt(i)));
        } catch (ArithmeticException e) {
            return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
        ++i;
    }

    if (isNegative) {
        result = -result;
    }

    return result;
}


texts: Pushing all non empty items to the end of a list

texts:
I have a list like this

list_ = [" ", " ", "X", " ", " ", "Z", " ", "Y", " "]

I am writing a function that will result in

list_ = [" ", " ", " ", " ", " ", " ", "X", "Z", "Y"]

Basically it will push all the non-empty (I'll call " " as empty here for simplicity) to the end of the list while retaining their orders

My solution as follow

def push(list_):
    def find_current_element(list_, from_):
        for i in range(from_+1, len(list_)):
            if list_[i] != " ":
                return i
        return None

    list_ = list_[::-1]
    good_index = list_.index(" ")
    current_element_index = find_current_element(list_, 0)
    while(current_element_index is not None):
        for i in range(good_index, len(list_)):
            if list_[i] != " ":
                list_[good_index], list_[i] = list_[i], " "
                good_index += 1
                current_element_index = find_current_element(list_, current_element_index)
    return reversed(list_)

It works, but it seems too long and using too much resource (reverse the list twice and bunch of for loops). I wouldn't care if the items were just simple character, but I plan to have some big objects as items of the list. I am wondering is there a simpler approach


texts: Security of simple client/server desktop app

texts:
I am writing an application aimed at the desktop but using web technologies. It will have an HTML interface and a server written in Python using Flask will do all of the filesystem interaction. It will have the ability to edit user settings so I want to make it impossible for other users to interfere. This is a little tricky because the server and client communicate using HTTP over a localhost port.

The program is split between 3 files:

run.py - controls the start up and shut down of the server and client.

import os
import json
import time
import signal

secret_file = os.path.join(os.environ['HOME'], '.myapp.secret')
if os.path.exists(secret_file):
    os.remove(secret_file)

os.system("python server.py &")

while not os.path.exists(secret_file):
    time.sleep(0.1)

f = open(secret_file)
secret = json.load(f)

url = 'http://localhost:' + str(secret['port']) + '/' + secret['key']

os.system("python client.py " + url)

os.kill(secret['pid'], signal.SIGINT)

server.py

from flask import Flask, request, Response
import socket
import random
import json
import sys
import os

app = Flask(__name__)
key = ''.join(random.sample(
    "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM",
    random.randint(8, 24)
))
port = 0
secret_file = os.path.join(os.environ['HOME'], '.myapp.secret')

@app.route('/<authkey>')
def hello(authkey):
    if authkey == key:
        return 'Hello, world!'
    else:
        return Response('Access Denied', 401)

def broadcast(port):
    s = json.dumps({
        'key' : key,
        'port' : port,
    'pid' : os.getpid()
    })
    f = open(
        secret_file,
        'w'
    )
    f.write(s)
    os.chmod(secret_file, 0400)
    f.close()

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 0))
    port = sock.getsockname()[1]
    broadcast(port)
    sock.close()
    app.run(port=port)

client.py

This is a simple GTK window with a webkit widget that renders the page. It renders the URL passed to it by the first argument.

Is this sufficiently secure? Also, are there any other problems that I have not considered?


texts:
I wrote a simple AJAX request that performs a random select in two MySQL tables. My current script involves connecting to the database and creating a new PDO every time the #generate button is clicked.

Can it be considered a bad practice? Could it lead to performance issues? If not, how could it still be optimized?

PHP (generator.php)

$host = "localhost";
$dbname = "generator";
$user = "root";
$password = "";
$utf8 = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");

try {
    $database = new PDO("mysql:host=$host; dbname=$dbname", $user, $password, $utf8);
    $database->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    die();
}

$query = "SELECT * FROM (
    (SELECT * FROM homemade WHERE validation = 1 ORDER BY RAND() LIMIT 0,1)
    UNION ALL
    (SELECT * FROM user_generated WHERE validation = 1 ORDER BY RAND() LIMIT 0,1)
)
AS foo
ORDER BY RAND()
LIMIT 0,1";

$statement = $database->prepare($query);
$statement->execute();
$content = $statement->fetch();

$data = array();

if($query) {
    $data["pickedName"] = $content["name"];
    $data["pickedBaseline"] = $content["baseline"];
}

echo json_encode($data);

JS

var $name = $("#content h2");
var $baseline = $("#content h3")

$("#generate").click(function() {
    $.ajax({
        type: "POST",
        url: "generator.php",
        dataType: "json"
    }).done(function(data) {
        $name.text(data.pickedName);
        $baseline.text(data.pickedBaseline);
    }).fail(function(data) {
        $name.text("Something went wrong !");
        $baseline.text("Please try again.");
    });
});


texts:
I created the following service for the purpose of sending in a file for parsing. I'm using the generics so that when I call parse() I can pass a custom type conforming to Codable. I'm not a huge fan of the repetition of do {} catch {} but I don't see any other way to avoid this.
import Foundation

enum JSONError: Error {
    case read,
         parse
}

struct JSONService {
    let fileName: String

    func parse<T: Decodable>(type: T.Type) -> T? {
        do {
            let fileContents = try self.getJsonContents()
            return try self.parseJson(data: fileContents, type: T.self)
        } catch {
            fatalError("\(error.localizedDescription)")
        }
    }

    private func getJsonContents() throws -> Data {
        if let file = Bundle.main.path(forResource: self.fileName, ofType: "json") {
            if let data = try String(contentsOfFile: file).data(using: .utf8) {
                return data
            }
        }

        throw JSONError.read
    }

    private func parseJson<T: Decodable>(data: Data, type: T.Type) throws -> T {
        do {
            return try JSONDecoder().decode(type.self, from: data)
        } catch {
            throw JSONError.parse
        }
    }
}


texts:
I'm trying to select a grand child from an array in an array.

If it was C# I would have wrote something like below

SubSteps.Select(item => item.First(subitem => subitem == 1)).First();

I have code that works, but I'm not sure it is the best way to do it:

ko.utils.arrayFirst(ko.utils.arrayFirst(self.SubSteps(),
        function (item) {
            return ko.utils.arrayFirst(item.SubSteps(),
                function (subItem) { return subItem.InternalName == localStorage.getItem('lastWizardPage'); });
        }).SubSteps(), function (item) {
            return item.InternalName == localStorage.getItem('lastWizardPage');
        })

Is there a method I can use that I've never heard of perhaps?


texts:
I wrote the following code to read the config/property files. I will be exposing my api as jar to multiple application teams.

Functionality:

Reads the property files and returns the resource bundle object. I am returning the resource bundle object as, there can be multiple config files in the application.
Getting the properties or the configs as variables from the resource bundle and use it across the application.

public class FileConfigLoader {

    private static final Logger LOGGER = Logger.getLogger(FileConfigLoader.class);

    private static String EMPTY = "";

    public static ResourceBundle getBundle(String basePath, String baseName) throws MalformedURLException {

        File file = new File(basePath);
        URL[] uris = { file.toURI().toURL() };
        ClassLoader loader = new URLClassLoader(uris);
        ResourceBundle rb = ResourceBundle.getBundle(basePath, Locale.getDefault(), loader);
        return rb;
    }

    public static String getValue(ResourceBundle rb, String key) {
        String value = EMPTY;

        try {
            value = rb.getString(key);
        } catch (MissingResourceException mREx) {
            LOGGER.error("Missing Resource : " + key);
        }

        return value;
    }

}

I need code reviews on the following lines

Does my code looks reusable?
Do you think i am using the variable names and class names as per the java sandards?
If my code does not seems to be reusable, Please provide suggestions.

The below code is the demonstration of how my code used by applications in the realtime.

The config is the name of my config file.The file is located in the classpath.

import java.net.MalformedURLException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public class MainApp {

    private static final Logger LOGGER = Logger.getLogger(MainApp.class);
    public static void main(String[] args) {

        ResourceBundle resource = null;

        try {
            resource = FileConfigLoader.getBundle("config", "");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        String hive_db = FileConfigLoader.getValue(resource, "hive_db");
        String EDGE_HIVE_CONN = FileConfigLoader.getValue(resource, "EDGE_HIVE_CONN");
        String target_dir = FileConfigLoader.getValue(resource, "target_dir");
        String somekey = FileConfigLoader.getValue(resource, "somekey");

        LOGGER.info(hive_db);
        LOGGER.info(EDGE_HIVE_CONN);
        LOGGER.info(target_dir);
        LOGGER.info(somekey);
    }

}


texts: Exercising in copy constructors and assignment operators

texts:
I've just created an implementation of array to train myself in copy constructors, assignment operators, and exception safety.  Please look at this code and tell me what is wrong here.

class DumbArray {
public:
  DumbArray(size_t sz)
    : _size(sz), _buf(new int[_size])
  {
    memset(_buf, 0, _size * sizeof(int));
  }

  DumbArray(const DumbArray& arr)
    : DumbArray(arr._size)
  {
    int* newMem = new int[arr._size];

    if(newMem) {
      std::copy(arr._buf, arr._buf + arr._size, newMem);
      delete [] _buf;
      _buf = newMem;
      _size = arr._size;
    }
  }

  DumbArray(DumbArray&& arr) {
    swap(arr);
  }

  DumbArray(std::initializer_list<int> ilist)
    : DumbArray(ilist.size())
  {
    std::copy(ilist.begin(), ilist.end(), _buf);
  }

  DumbArray& operator=(const DumbArray& arr) {
    if(this != &arr) {
      DumbArray tmp(arr);
      swap(tmp);
    }

    return *this;
  }

  DumbArray& operator=(DumbArray&& arr) {
    swap(arr);
    return *this;
  }

  ~DumbArray() {
    // _size = 0;   // should this be done? object is being destroyed anyway, yup?
    delete [] _buf;
  }

  void swap(DumbArray& arr) {
    std::swap(_buf, arr._buf);
    std::swap(_size, arr._size);
  }

  int& operator[](int idx) {
    if(idx < 0 || idx >= _size) {
      throw std::out_of_range("Incorrect index");
    }

    return _buf[idx];
  }

  size_t size() const {
    return _size;
  }

private:
  size_t _size;
  int* _buf;
};


texts: Verify that a CSV file contains a backup job for every prod job

texts:
This is a list of jobs in autosys. What I have to do is make sure that every job in PROD has a accompanying job in BACKUP.

The jobs are formatted as CAPSER_JOB_01_PP. I read the list into a while loop, not sure if I should take an -r.

I take off the last two characters of the job name, and then grep twice for each area, if both are successful it prints a yes at beginning of line, otherwise it is a no.

Frankly I can't find matching documentation for the ${job%??}. I don't know what the two question marks stand for.

I tried using grep -q but it did not work. the > 2>&1 /dev/null did not work either, I had to reverse it to > /dev/null the redirect 2>&1 (as shown). The script works, it is just a clunky way of getting it done. There has to be a better way.

#!/bin/bash
#bash, version 3.2.25

IFS=,

while read area job machine script
do
if grep  ${job%??} /home/first_spreadsheet.txt | grep BACKUP >/dev/null 2>&1 && grep  ${job%??} /home/first_spreadsheet.txt | grep PROD  >/dev/null 2>&1 ; then
echo " YES $area $job $machine $script "
else
echo " NO $area $job $machine $script "
fi
sleep 1
done < /home/first_spreadsheet.txt

cat /home/first_spreadsheet.txt
BACKUP, CAPSER_JOB_01_PP, usa-penguin.com, /bin/bash -lc '/usr/bin/run.sh'
PROD, CAPSER_PROD_JOB_01_PS, usa-penguin.com, /bin/bash -lc '/usr/bin/run.sh'
BACKUP, CAPSER_JOB_02_PP, usa-penguin.com, /bin/bash -lc '$HOME/run/script02'
PROD, CAPSER_PROD_JOB_02_PS, usa-penguin.com, /bin/bash -lc '$HOME/run/script02'
BACKUP, CAPSER_JOB_03_PP, usa-penguin.com, /bin/bash -lc '$HOME/run/script03'
PROD, CAPSER_PROD_JOB_03_PS, usa-penguin.com, /bin/bash -lc '$HOME/run/script03'
BACKUP, CAPSER_JOB_04_PP, usa-penguin.com, /bin/bash -lc '$HOME/run/script04'
PROD, CAPSER_PROD_JOB_04_PS, usa-penguin.com, /bin/bash -lc '$HOME/run/script04'
PROD, CAPSER_PROD_JOB_05_PS, usa-penguin.com, /bin/bash -lc '$HOME/run/script05'
PROD, CAPSER_PROD_JOB_06_PS, usa-penguin.com, /bin/bash -lc '$HOME/run/script06'
BACKUP, CAPSER_JOB_07_PP, usa-penguin.com, /bin/bash -lc '$HOME/run/script07'
PROD, CAPSER_PROD_JOB_07_PS, usa-penguin.com, /bin/bash -lc '$HOME/run/script07'


texts: Simple singleton database connection pool

texts:
I'm studying design patterns, and to demonstrate a singleton, I've implemented a primitive database connection pool.

ConnectionPool.java

package com.levent.connpool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionPool {

    private final static int MAX_CONNECTIONS = 8;
    private static ConnectionPool instance = null;  // lazy loading
    private static Connection[] connections = new Connection[MAX_CONNECTIONS];
    private static String dbUrl = "jdbc:derby://localhost:1527/memory:levoDB/singletonDemo;create=true";
    private static int counter;

    private ConnectionPool() { }

    public static ConnectionPool getInstance() {
        if(instance == null) {
            synchronized(ConnectionPool.class) {
                if(instance == null) {
                    instance = new ConnectionPool();
                    initializeConnections();
                    counter = 0;
                }
            }
        }

        return instance;
    }

    private static void initializeConnections() {
        for(int i = 0; i < MAX_CONNECTIONS; i++) {
            try {
                connections[i] = DriverManager.getConnection(dbUrl);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static Connection getConnection() {
        counter++;
        if(counter == Integer.MAX_VALUE)
            counter = 0;

        return connections[counter%MAX_CONNECTIONS];
    }

}

ConnectionPoolDemo.java

package com.levent.connpool;

import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionPoolDemo {

    public static void main(String[] args) {
        ConnectionPool pool = ConnectionPool.getInstance();

        Connection[] connections = new Connection[17];

        for(int i = 0; i < connections.length; i++)
            connections[i] = pool.getConnection();

        int preIndex = connections[0].getClass().getCanonicalName().length();
        for(int i = 0; i < connections.length; i++)
            System.out.printf("Connection %2d : %s\n", i+1, connections[i].toString().substring(preIndex));

        for(int i = 0; i < connections.length; i++)
            try {
                connections[i].close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

}

The output is as follows:

Connection  1 : @27f8302d
Connection  2 : @6438a396
Connection  3 : @e2144e4
Connection  4 : @6477463f
Connection  5 : @3d71d552
Connection  6 : @1cf4f579
Connection  7 : @18769467
Connection  8 : @46ee7fe8
Connection  9 : @27f8302d
Connection 10 : @6438a396
Connection 11 : @e2144e4
Connection 12 : @6477463f
Connection 13 : @3d71d552
Connection 14 : @1cf4f579
Connection 15 : @18769467
Connection 16 : @46ee7fe8
Connection 17 : @27f8302d

Explanation

The aims is to have distributed connections that's why on each getConnection() method call, on of the each connections are returned with the use of mod. The maximum connection size is determined by the MAX_CONNECTIONS which is set to 8 in this example and all 17 connections retrieved from the singleton pool class are recurring instances of the 8 connections stored in the ConnectionPool class.

I know that this code is not a big shot, but my aim was to demonstrate a simple singleton in a real world example. I'm waiting for your ideas and your criticism.


texts: Drawing sets of boxes to display contents of arrays

texts:
This code draws two sets of 9 boxes on the screen to display the contents of two arrays.

How can I speed up, shorten and make the code more efficient?

    for (int x=0;x<3;x++){
        for (int y=0;y<3;y++){
            if (pattern[x][y]==1){
                g.setColor(colorrange.colb());
                g.fillRect(actlo+(x*size),actlo+(y*size),size,size);
            }
                g.setColor(Color.yellow);
                g.drawRect(actlo+(x*size),actlo+(y*size),size,size);

            if (patternb[x][y]==1){
                g.setColor(colorrange.colb());
                g.fillRect(actlo+(x*size),inlo+(y*size),size,size);
            }
                g.setColor(Color.yellow);
                g.drawRect(actlo+(x*size),inlo+(y*size),size,size);
        }
    }


texts: Report on user-input chacters by their type

texts:
I'm a first year student at a college that focuses heavily on self learning (SCRUM) without any classical lessons. Because of this, I basically learned everything I know from websites like this. I don't want to get any bad habits or wrong understandings. So, is this code any good? I'm not looking for optimization (wouldn't mind any tips though ;) ) since I'll be learning that through time, but rather if the general structure and my way of thinking is right.

The purpose of my code is to ask the user for a string of characters of his liking (for example a sentence) and displays the amount of vowels, consonants, numbers and other symbols it contains.

static void Main(string[] args)
{
    string repeat;
    //do while loop for if the user wants to run the program again
    do
    {
        //asigns variables
        string text;
        int vowels, consonants, numbers, otherSymbols;
        var hsVowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
        var hsConsonants = new HashSet<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'};
        var hsNumbers = new HashSet<char> { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

        //asks for input
        Console.WriteLine("Input anything and the program wil tell you how many vowels, consonants, numbers and other symbols you gave.");
        text = Console.ReadLine().ToLower();

        //calculates
        vowels = text.Count(c => hsVowels.Contains(c));
        consonants = text.Count(c => hsConsonants.Contains(c));
        numbers = text.Count(c => hsNumbers.Contains(c));
        otherSymbols = text.Length - (vowels + consonants + numbers);

        //shows the result
        Console.WriteLine("Your input has {0} vowels, {1} consonants, {2} numbers and {3} other Symbols.", vowels, consonants, numbers, otherSymbols);

        //asks if the user wants to run the program again
        Console.WriteLine("Would you like to try again? (yes/no)");
        repeat = Console.ReadLine();
        //tests if the users input was valid (yes/no)
        while (!(repeat.ToLower().Contains("yes") || repeat.ToLower().Contains("no")))
        {
            Console.WriteLine(@"Invalid input. Please answer ""yes"" or ""no"" .");
            repeat = Console.ReadLine();
        }
    } while (repeat.ToLower().Contains("yes"));
}

Reposted from Stack Overflow to Stack Exchange as recommended by sellotape


texts:
I am building a map editor to easily create 2d levels. To visualize how my level looks like I am using a canvas. On this canvas I can select which block is filled with a certain type ( like solid ). I did add click and drag but because I am live drawing on the canvas it goes very slow and if you draw at a decent speed it skips several block which needs to be drawn.

I already have tried several options ( doing it in another thread. Putting it first in a queue ) but none had a good result. It works now but not with the perfomance I prefer. Because it skips blocks it needs to draw.

I use the following code to draw my rectangles:

 if (currentMap != null)
    {
        mapCanvas.Children.Clear();
        mapCanvas.Width = (currentMap.Breedte * blockScale);
        mapCanvas.Height = (currentMap.Hoogte * blockScale);
        for (int i = 0; i < currentMap.Hoogte; i++)
        {
            for (int j = 0; j < currentMap.Breedte; j++)
            {
                Rectangle blok = new Rectangle();

                blok.Stroke = new SolidColorBrush(Colors.Black);
                blok.StrokeThickness = 0.3;
                blok.Width = blockScale;
                blok.Height = blockScale;
                switch (currentMap.GetElement(j, i))
                {
                    case 0:
                        blok.Fill = new SolidColorBrush(Colors.LightGray);
                        break;
                    case 1:
                        blok.Fill = new SolidColorBrush(Colors.Red);
                        break;
                    case 2:
                        blok.Fill = new SolidColorBrush(Colors.Green);
                        break;
                    case 3:
                        blok.Fill = new SolidColorBrush(Colors.Orange);
                        break;
                    case 4:
                        blok.Fill = new SolidColorBrush(Colors.Yellow);
                        break;
                    default:
                        blok.Fill = new SolidColorBrush(Colors.Black);
                        break;

                }
                blok.SetValue(Canvas.LeftProperty, (double)(blockScale * j));
                blok.SetValue(Canvas.TopProperty, (double)(blockScale * i));

                mapCanvas.Children.Add(blok);
            }
        }
    }

I did came across a solution to draw faster on a canvas on this link: https://stackoverflow.com/questions/23976163/speed-up-adding-objects-to-canvas-in-wpf

But the problem I cannot seem to get it working in my current project or a test project.

I hope you guys can help me to speed the drawing up or at least that it can recognize every block it needs to draw.

For further question please ask I will try to give as much detail as needed


texts:
I have written a custom method to use StringBuilder in java. My Requirement is to create a method which accepts any number of arguments of any type and return String by concatenating the arguments.

eg. msgBuilder("Hello ",0," how"," are"," you ",2.5) return "Hello 0 how are you 2.5"

Here is my java code. Please Someone review my code and suggest If I did anything is wrong or Can I use this further in my projects.

        public class Test {
            public static void main(String[] args ){
                String msg = msgBuilder("Hello ",5," How ","are ","you");
                System.out.println(msg);
            }

            private static String msgBuilder(Object... params){
                StringBuilder sb = new StringBuilder();
                for(Object obj:params){
                    sb.append(obj);
                }
                return sb.toString();
            }
        }


texts: Bash Shell Script uses Sed to create and insert multiple lines after a particular line in an existing file

texts:
This code seems to work, but I'd like someone with shell-fu to review it.

Is the temp file a good idea?  How would I do without?
Is sed the right tool?
Any other general advice for improving my shell script

Script/Code to Review:

# Grab max field lengths from each .hbm.xml file and
# put them into the corresponding .java file
for myFile in $(find generatedSchema/myApp/db/ -name *.hbm.xml)
do
    # Calculate the java file name
    javaFile=${myFile/%\.hbm\.xml/.java}
    echo $javaFile

    # Find each field name and length and format it for the java file.
    # Save result lines to temp.txt
    sed -n '/<property name="[^"]\+" type="string">/{
        N
        s/ \+<property name="\([^"]\+\)" type="string">\n \+<column name="[^"]\+" length="\([0-9]\+\)".*/    @SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_\1 = \2;/p}' $myFile >temp.txt

    # Load results from temp file into a shell variable
    str=""
    while read line
    do
        echo $line
        str="$str\n    $line"
    done < temp.txt

    # Put new lines after the serialVersinUID line in the existing Java file.
    sed -i -e "s/^    private static final long serialVersionUID = [0-9]\+L;$/\0\n$str/" $javaFile

    # clean up
    rm temp.txt
done

Existing Input .hbm.xml file excerpt:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.myCo.CodeReview" table="code_review" catalog="stackexchange">
        <!-- ... -->
        <property name="address1C" type="string">
            <column name="address1_c" length="50" />
        </property>
        <property name="address2C" type="string">
            <column name="address2_c" length="50" />
        </property>
        <!-- etc. -->

Existing Input Java File:

// ... preserve java code above

private static final long serialVersionUID = 20130318164201L;

// ... preserve java code below

Desired Output Java File:

// ... preserved java code above

private static final long serialVersionUID = 20130318164201L;

@SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_address1C = 50;
@SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_address2C = 50;

// ... preserved java code below

Background

This script generates Java objects that represent database tables.  It modifies the output of the Hibernate Database Reverse-Engineering tools to add maximum field length tokens to my Java objects that match the length of those columns in the database.


texts: Caching image thumbnail web-application based on rocket

texts:
This is my first rocket web-app. It serves images from a directory and thumbnails from a sub-directory. if no thumbnail is found for an existing image it is created on the fly.

Before I launch this thing into production/space, it would be calming to have some experts' eyes on it and be made aware of any glaring holes as well as things that would work, but can be optimized.

Question

In particular I am not sure what happens, if the app is run in multiple workers and multiple requests to thumbnail the same image are handled simultaneously.

Would I have to place locks on files and how would i do that?

Code

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;
extern crate image;

use std::fs::File;
use std::path::PathBuf;
use rocket::{Request, response::content, response::NamedFile};
use self::image::{FilterType, JPEG};

const IMAGE_DIR: &str = "images/";

pub fn resize_and_crop_to(filename: &PathBuf, cached: &PathBuf, width: u32, height: u32) -> Option<()> {
    let i = image::open(filename);
    match i {
        Ok(img) => {
            let scaled = img.resize_to_fill(width, height, FilterType::CatmullRom);
            let mut output = File::create(cached).expect("Could not open cache file");
            scaled.write_to(&mut output, JPEG).ok()
        },
        Err(_error) => None
    }
}

pub fn get_filename(name: &str) -> PathBuf {
    let filename: PathBuf = [ IMAGE_DIR, name ].iter().collect();
    filename
}

pub fn get_cache_filename(name: &str, format: &str) -> PathBuf {
    let filename = [ IMAGE_DIR, format, name ].iter().collect();
    filename
}

#[get("/<image>")]
fn original(image: String) -> Option<NamedFile> {
    let filename = get_filename(image.as_str());
    NamedFile::open(filename.as_os_str()).ok()
}

#[get("/thumb/<image>")]
fn scaled(image: String) -> Option<NamedFile> {
    let format = "thumb";
    let cached = get_cache_filename(image.as_str(), format);
    let f = NamedFile::open(&cached);
    match f {
        Ok(file) => Some(file),
        Err(_error) => {
            let filename = get_filename(image.as_str());
            resize_and_crop_to(&filename, &cached, 280, 180)?;
            NamedFile::open(cached).ok()
       }
    }
}

#[catch(404)]
fn not_found(request: &Request) -> content::Html<String> {
    let html = format!(
        "<p>{} not found</p>",
         request.uri()
    );
    content::Html(html)
}

fn main() {
    rocket::ignite()
        .mount("/", routes![original, scaled])
        .register(catchers![not_found])
        .launch();
}

(I could not add tags #rocket, nor #rust-rocket for lack of reputation points)


texts: Microservice unit testing database script insert Error - H2

texts:
For unit testing my ProductList service, I tried run a script to insert some data and then try to get this data and compare the list size.
But my database insert script is not running and returns null.
The related code is below.
Looking forward to your evaluation.
Thanks.
 @Test
    public void getProductsList() throws Exception {

        initDatabase();

        RequestBuilder request = MockMvcRequestBuilders
                .get ("http://localhost:8080/products")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(request).andReturn();

        String content = result.getResponse().getContentAsString();

        Product[] productList = super.mapFromJson(content, Product[].class);
        assertEquals(3, productList.length);
    }

InitDatabase method :
private static String connection_url = "jdbc:h2:file:C:/data/sample/product;DB_CLOSE_DELAY=-1";
private static String username = "";
private static String password = "";

 public static void initDatabase() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(connection_url, username, password);
            ResultSet rs = RunScript.execute(connection, new FileReader("src/test/resources/testDataProduct.sql"));
            System.out.println(rs.toString());
        } catch (Exception e) {
            throw new TransactionException("Error creating test data :" + e.getMessage());
        } finally {
            //DbUtils.closeQuietly(connection);
        }
    }

SQL:
-- Test data initialization

DROP TABLE IF EXISTS PRODUCT;

CREATE TABLE PRODUCT (ID LONG PRIMARY KEY AUTO_INCREMENT NOT NULL,
                      CATEGORY VARCHAR(30) NOT NULL,
                      NAME VARCHAR(30) NOT NULL,
                      DESCRIPTION VARCHAR(30) NOT NULL,
                      UNITPRICE DECIMAL(19,4) NOT NULL,
                      INVENTORY VARCHAR(10) NOT NULL,
                      PAYMENT_OPTIONS VARCHAR(30) NOT NULL,
                      DELIVERY_OPTIONS VARCHAR(30) NOT NULL);

CREATE UNIQUE INDEX idx_acc on PRODUCT(ID,NAME);

INSERT INTO PRODUCT (ID, CATEGORY, NAME, DESCRIPTION, UNITPRICE, INVENTORY, PAYMENT_OPTIONS, DELIVERY_OPTIONS)
VALUES (101,'ELECTRONICS','TV','LG Smart TV',1000.0000,20,'DIRECT','X');

INSERT INTO PRODUCT (ID, CATEGORY, NAME, DESCRIPTION, UNITPRICE, INVENTORY, PAYMENT_OPTIONS, DELIVERY_OPTIONS)
VALUES (102,'FASHION','Skirt 101','Black Skirt',20.0000,10,'INSTALLMENT','X');

INSERT INTO PRODUCT (ID, CATEGORY, NAME, DESCRIPTION, UNITPRICE, INVENTORY, PAYMENT_OPTIONS, DELIVERY_OPTIONS)
VALUES (103,'FOOD','Bread','Whole Wheat Bread',5,5,'DIRECT','X');

I am getting error:
org.hibernate.TransactionException: Error creating test data :null

    at com.merchant.springjwtmerchant.ProductServiceControllerTest.initDatabase(ProductServiceControllerTest.java:77)
    at com.merchant.springjwtmerchant.ProductServiceControllerTest.getProductsList(ProductServiceControllerTest.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)


texts: Python: is answer grader program secure?

texts:
I am creating my own problems that people have to solve and I want to make a grader check if a user put in the right answers and then reward them with a flag.

My code for one particular problem:

from Crypto.Cipher import AES
from binascii import hexlify
from binascii import unhexlify

password = input("What is the answer to the first question? ")

passwordtwo = input("What is the answer to the second question? ")

message = input("What is the answer to the third question? ")

obj = AES.new(password, AES.MODE_CFB, 'This is an IV456')

ciphertext = obj.encrypt(message)

obj2 = AES.new(passwordtwo, AES.MODE_CFB, 'This is an IV456')

answer = b'c557774c4e5bd1745319b15226e078ef30abcb50f1bd371946ddadffc39a1f56'
flag = b'a2c8b65cda513befb8134c7960bc977946655d485f9ad2'

if (hexlify(ciphertext) == answer):
    print(obj2.decrypt(unhexlify(flag)))

#first question: I took a major language exam in 2018 - what did I get due to my score? The answer is two words. Format should be ans:<question 1 answer>

#second question: I partook in a competition in my district in 2017 - what was the name of the competition? The answer is three words. Format should be ans: <answer to question 2>

#third question: I was in a competitive club around the time I wrote a book. What did I place and for what event? The answer is four words. Format should be <place>: <event>. Write it out in words

#note that the format is EXTREMELY particular - it has to be exactly the same. Also, everything is lowercase.

This code works as long as users abide exactly to the format I specify. I'm not sure, however, if a user can just find the flag without actually answering the questions. I would think that by making them figure out the passwords themselves it would be impossible to trick the grader. Is this code secure? If not, how can I make this more secure?


texts: Is it possible to remove variable repetition here?

texts:
/**
    * Class stringHelperK
    * Helper Class to deal with small string manipulations.
*/
class stringHelperK {

    public function normalizeStringK($string) {
        return $this->removeAccents(
            $this->replaceSpacesWithSlashes($string)
        );
    }

    /**
     * @param $string
     * @return string
     */
    public function removeAccents($string){
        return strtr($string,'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
    }

    /**
     * @param $string
     * @return string
     */
    public function replaceSpacesWithSlashes($string) {
        return strtolower(str_replace(" ", "-",$string));
    }
}

I have several questions regarding this code:

$string is used across all class methods. Should it be a property?  If so, how can I transform this accordingly? I mean, I see $string everywhere and it feels isn't correct.

Is it, something like this, better:

/**
    * Class stringHelperK
    * Helper Class to deal with small string manipulations.
*/
class stringHelperK {

    public $string;

    public function normalizeStringK($string) {
        return $this->removeAccents(
            $this->replaceSpacesWithSlashes($this->string)
        );
    }

    /**
     * @param $string
     * @return string
     */
    public function removeAccents($string){
        return strtr($this->string,'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
    }

    /**
     * @param $string
     * @return string
     */
    public function replaceSpacesWithSlashes($string) {
        return strtolower(str_replace(" ", "-",$his->string));
    }
}

Or should it be, private $_string, and we should use getters and setters?


texts:
Let's say I have a plain text string that I want to split into a string array, using an integer array containing the indexes of this string where I want it to be cut.

Example:

Input string: "001ABCD2T"

Indexes array: {3, 7, 8}

Expected resulting string array: {"001", "ABCD", "2", "T"}

Here's how I do it for now:

string line = "001ABCD2T";
int[] markers = new int[] {3, 7, 8};

for (int i = -1; i < markers.Length; i++)
{
    string value = String.Empty;
    if (i == -1)
        value = line.Substring(0, markers[0]);
    else if (i == markers.Length - 1)
        value = line.Substring(markers[i], line.Length - markers[i]);
    else
        value = line.Substring(markers[i], markers[i + 1] - markers[i]);

    Console.WriteLine(value);
}

The result is as expected, yet it is pretty eye-soring. Is there a cleaner way to write it, or even better, an already implemented method I didn't find?


texts:
I have been trying to make this code go faster by trying to write it more efficiently and I don't know what else to do. I got it to 30 seconds but I have seen 23 and 24 and I have no idea on how to do it.

public class Main {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        for(long n = 1; n <= 100000000; n+=2){
            long value = cycleLength(n);
            if(value > (n*n)){
                System.out.println(n + " " + value);
            }
        }

        long endTime = System.currentTimeMillis();

        System.out.println("Runtime = " + (endTime - startTime) + " milliseconds");

    }//main

    public static long cycleLength(long n) {
        long hi = n;

        while (n > 1) {
            if((n&1)==0)  // bitwise AND
                n = n >> 1;  // n even
            else {
                n = 3*n+1; // n odd

                if(hi < n)
                    hi = n;
                n = n >> 1;
            }
        }

        return hi;
    }

}


texts: Returning largest product of longest subsequence between min and max

texts:
This function returns the largest product of all elements of a list between the leftmost and rightmost min and max elements. Is there more readable and maybe compact way to rewrite the elif chain in this code:
from operator import mul
from functools import reduce

prod = lambda iterable: reduce(mul, iterable, 1)

def prod_between_min_and_max(arr):
    l_min, r_max = arr.index(min(arr)), len(arr)-1 - arr[::-1].index(max(arr))
    l_max, r_min = arr.index(max(arr)), len(arr)-1 - arr[::-1].index(min(arr))
    if len(range(l_min, r_max+1)) > len(range(l_max, r_min+1)):
        sl = slice(l_min, r_max+1)
    elif len(range(l_min, r_max+1)) < len(range(l_max, r_min+1)):
        sl = slice(l_max, r_min+1)
    elif prod(arr[l_min:r_max+1]) >= prod(arr[l_max:r_min+1]):
        sl = slice(l_min, r_max+1)
    else:
        sl = slice(l_max, r_min+1)
    return prod(arr[sl])

than this:
from operator import mul
from functools import reduce

cmp = lambda a, b: (a > b) - (a < b)
prod = lambda iterable: reduce(mul, iterable, 1)

def prod_between_min_and_max(arr):
    l_min, r_max = arr.index(min(arr)), len(arr)-1 - arr[::-1].index(max(arr))
    l_max, r_min = arr.index(max(arr)), len(arr)-1 - arr[::-1].index(min(arr))
    sl = [
        [
            slice(l_max, r_min+1),
            slice(l_min, r_max+1)
        ][
            prod(arr[l_min:r_max+1]) >= prod(arr[l_max:r_min+1])
        ],
        slice(l_min, r_max+1),
        slice(l_max, r_min+1)
    ][
        cmp(len(range(l_min, r_max+1)), len(range(l_max, r_min+1)))
    ]
    return prod(arr[sl])

Note: The code works in both Python 2 and Python 3.


texts: Validating username, password, and email in PHP

texts:
Let's pretend the following:

 <?php
 // Functions to validate/sanitize user input
 function validateUsername() {
    // If accepted, return true, else return false
 }
 function validatePassword() {
    // If accepted, return true, else return false
 }
 function validateEmail() {
    // If accepted, return true, else return false
 }

This is how I handle user input:

// Getting all user input
$values = $_POST['values'];

$error = false;

if (!validateUsername($username) && $error === false) {
    $errorMessage = "Username can't contain special characters";
    $error = true;
}
if (!validatePassword($password) && $error === false) {
    $errorMessage = "Password is'nt secure enought";
    $error = true;
}
if (!validateEmail($email) && $error === false) {
    $errorMessage = "Email is not correctly formatted";
    $error = true;
}

if ($error === true) {
    echo $errorMessage;
} else {

    // Do something

}
?>

But I'm sure there is a better approach. What is the best (or a good) way to handle user input messages/errors?

Also I've read a tutorial (which unfortunately I can't find anymore) where it was recommended to give the users hints and tips about their input, instead of giving them a big bold red warning.

For example to accept not only 1234 AB (Dutch postcodes), but also 1234ab, 1234AB and 1234 ab and let the script convert it to the official notation 1234 AB.


texts: Check if a linked list is a palindrome in O(n) time and O(1) space

texts:
I liked this problem because there are so many sub-problems that are interview problems in their own right-- (reverse linked list, find midpoint)

var Node = function(val) {
  this.val = val;
  this.next = null;
}

var a = new Node('r');
var b = a.next = new Node('a');
var c = b.next = new Node('c');
var d = c.next = new Node('e');
var e = d.next = new Node('c');
var f = e.next = new Node('a');
var g = f.next = new Node('r');

function checkOdd(linkedList) {
  var count = 0;
  var curr = linkedList;
  while (curr) {
    count++;
    curr = curr.next;
  }
  return count % 2 === 1;
}

function findMidPoint(linkedList) {
  var slow = linkedList;
  var fast = linkedList;

  while (fast && fast.next) {
    fast = fast.next.next;
    slow = slow.next
  }

  if (checkOdd(linkedList)) {
    return slow.next
  } else {
    return slow;
  }
}

function checkPalindrome(linkedList) {
  var midpoint = findMidPoint(linkedList);

  var firstHead = linkedList;
  var secondHead = reverseLL(midpoint);

  var flag = true;

  while (secondHead) {
    if (secondHead.val !== firstHead.val) {
      flag = false;
    }
    secondHead = secondHead.next;
    firstHead = firstHead.next;
  }
  return flag;
}

function reverseLL(root) {
  var prevNode = null;
  var currNode = root;
  var nextNode;
  while (currNode) {
    nextNode = currNode.next;
    currNode.next = prevNode;
    prevNode = currNode;
    currNode = nextNode;
  }
  return prevNode;
}

console.log(checkPalindrome(a)); = true


texts: Have I gone too far in factoring out repeated code in this example?

texts:
In a controller (PHP, CodeIgniter) I'm adding scripts & css to variables to be used in the view output. My initial coding looked like this:

private function _add_script($path, $where = self::ADD_LAST) {
    $html = "<script src='$path'></script>\n";
    switch($where) {
        case self::ADD_LAST:
            array_push($this->_data['script'], $html);
            break;
        case self::ADD_FIRST:
            array_unshift($this->_data['script'], $html);
            break;
    }
}

private function _add_css($path, self::ADD_LAST) {
    $html = "    <link rel='stylesheet' href='$path'>\n";
    switch($where) {
        case self::ADD_LAST:
            array_push($this->_data['css'], $html);
            break;
        case self::ADD_FIRST:
            array_unshift($this->_data['css'], $html);
            break;
    }
}

Well, I noticed that these two are basically just repeating themselves, so I immediately rewrote them into this format:

private function _add_script($path, $where = self::ADD_LAST) {
    $html = "<script src='$path'></script>\n";
    $this->_add_external('script', $html, $where);
}

private function _add_css($path, $where = self::ADD_LAST) {
    $html = "<link rel='stylesheet' href='$path'>\n";
    $this->_add_external('css', $html, $where);
}

private function _add_external($type, $html, $where) {
    switch($where) {
        case self::ADD_LAST:
            array_push($this->_data[$type], $html);
            break;
        case self::ADD_FIRST:
            array_unshift($this->_data[$type], $html);
            break;
    }
}

Does the second version seem like the way to go? Or perhaps a 3rd alternative. The requirements call for being able to add elements to the list either before or after all other elements already in the list.


texts: The best way for inserting multiple objects into array

texts:
I have a transformer helper function. It reduces over the array and transform key/value pairs. At the end of the loop there is the key 'EXAMPLE1' exists and I should insert two objects after the first and the second array(result) items. Right now, it works as expected, but I have concerns - is it a good approach for using splice inside reduce in my case?

 const commonData = Object.entries(settings).reduce((result, [currentKey, currentValue]) => {
        if (currentKey === SETTINGS_FIELDS.EXAMPLE1) {
            const type = {
                key: myKey,
                value: myValue,
            }
            const code = {
                key: myKey,
                value: myValue,
            }

            const insertedData = result.splice(2, 0, type, code)

            return [...result, ...insertedData]
        }

        return result.concat({ key: transformToUpperCase(currentKey), value: currentValue })
    }, [])

    return [...commonData]
}
```


texts: Dispatches an event to detect a camera - Once the camera has initialised resolve a promise to say the camera is detected

texts:
I am relatively new to redux - I wanted to keep the actions in the same detectJsCamera function which is why I decided to resolve a promise to detectCamera - hence the set timeout.

I am not sure how I would go about testing this.

xport function detectJsCamera() {
     return async(dispatch) => {
        dispatch({type: types.JS_DETECTING_CAMERA});
        try {
            await detectCamera();
            await dispatch({type: types.JS_CAMERA_DETECTED});
        } catch (error) {
            throw error;
        // this.props.history.push('/setup/positioning')
    };
    }
}

const detectCamera = () => new Promise((resolve, reject) => {
    const checkIfReady = () => {
        if (webgazer.isReady()) {
          resolve('success');
        } else {
          setTimeout(checkIfReady, 100);
        }
      }
      setTimeout(checkIfReady,100);
  });


texts:
I'm building a virtualised grid in JS/HTML and finding browser performance with large grids fairly slow, particularly in IE10/11.  The following jsfiddle roughly represents my worst case scenario, approx 1000 cells:

http://jsfiddle.net/FGr7g/1/

function test(count) {
var self = window;
var limit = 25;

if (count < limit) {
    //settimeout to give ui chance to render
    setTimeout(function () {
        self.render(count);
        count++;
        test(count);
    }, 0);
}

if (count >= limit) {
    alert((1000 / ((performance.now() - self.startTime) / limit)) + " fps");
}
}

function render(count) {
for (var x = 0; x < this.cellCount; x++) {
    this.cells[x].textContent = count + " _c_" + x;
}
}

window.render = render;

$().ready(function () {
var self = window;

self.cellCount = 1000;
self.cells = [];
self.grid = document.createElement("div");
self.grid.style.position = "relative";
self.grid.style.height = "100%";
self.grid.style.overflow = "hidden";

for (var c = 0; c < cellCount; c++) {
    var cell = document.createElement("div");

    cell.style.width = "49px";
    cell.style.height = "24px";
    cell.style.padding = "10px";
    cell.style.position = "absolute";
    cell.style.overflow = "hidden";
    cell.style.borderTop = "1px solid lightgray";
    cell.style.borderLeft = "1px solid lightgray";
    cell.style.backgroundColor = "whitesmoke";
    cell.style.left = (c % 28) * 50 + "px";
    cell.style.top = (Math.floor(c / 28) * 25) + "px";
    cell.className = cell.className += " test_cell";

    var span = document.createElement("span");
    cell.appendChild(span);

    self.grid.appendChild(cell);

    self.cells.push(span);
}

document.getElementById("grid").appendChild(self.grid);

self.startTime = performance.now();
self.count = 0;
test(self.count);
self.totalTime = 0;
 });

 .test_cell {
 text-align: right;
 font: 8pt Segoe UI, Tahoma, Arial, Verdana;
 width: 49px;
 height: 24px;
 border-left: 1px solid lightgray;
 border-top: 1px solid lightgray;
 position: absolute;
 overflow: hidden;
}

I get around 10fps in IE at full screen, and around 30 in Chrome, assuming my performance measurement code is correct, it is consistent with the fps tools in Chrome so I think it is.

So far I've tried different methods of DOM manipulation - building a HTML string of the whole grid and inserting into the DOM (slower), using DOM fragments (slower), using a table instead of an array of absolute divs (slower), various ways of setting the span's content - innerHTML, textContent etc (made little difference), using different fonts/sizes (no difference).

Based on profiling I suspect that the majority of the time is painting rather than any java script code so I think any large improvements would like come from optimising the HTML/CSS so it is quicker to render, but any suggestions/modifications would be hugely appreciated.

If it makes any difference I am not targeting older browser versions.


texts:
I found this code in our project and it just feels like the wrong way to do what it seems to be doing

id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for (symbol in results) {
    // this just selects the first symbol in the results
}

Presumably it actually doesn't select the first symbol - instead it selects the last one!

But there must be a better way. I don't quite know what

[info objectForKey: ZBarReaderControllerResults]

returns, but I'm not too bothered either. Is there a way that I can do the above code without having to loop through all possible results?


texts:
Integer permutation using Heap's algorithm:

import java.util.Arrays;

public class IntegerPermutation {

    private static void swap(Integer[] integerArray, int i, int j) {
        Integer temp = integerArray[i];
        integerArray[i] = integerArray[j];
        integerArray[j] = temp;
    }

    private static void permutationHelper(Integer[] integerArray,
            int currentPosition) {

        if (currentPosition == 1) {
            System.out.println(Arrays.toString(integerArray));
        } else {
            for (int i = 0; i < currentPosition; i++) {
                permutation(integerArray, currentPosition - 1);

                if (currentPosition % 2 == 0) {
                    swap(integerArray, i, currentPosition - 1);
                } else {
                    swap(integerArray, 0, currentPosition - 1);
                }
            }
        }
    }

    public static void permutation(Integer[] integerArray, int lengthOfTheArray) {
        permutationHelper(integerArray, lengthOfTheArray);
    }

    public static void main(String[] args) {

        Integer[] a = new Integer[] { 1, 2, 3 };
        IntegerPermutation.permutation(a, a.length);
    }
}

Can you please critique my code and provide your thoughts on where I should improve my code?


texts:
Is this an ideal use of if..else or can this code be simplified/beautified further?

    // If any image found and bigger than thumbnail settings, get that one
    if ( isset( $matches ) && !empty( $matches[1][0] ) ) {
        $image_found = $matches[1][0];
        $image_dimensions = getimagesize($image_found);
        if ( ( $image_dimensions[0] > $width ) && ( $image_dimensions[1] > $height ) ) {
            $thumbnail_img = $matches[1][0];
        }
        // Check 2nd image found
        else if ( !empty( $matches[1][1] ) ) {
            $image_found = $matches[1][1];
            $image_dimensions = getimagesize($image_found);
            if ( ( $image_dimensions[0] > $width ) && ( $image_dimensions[1] > $height ) ) {
                $thumbnail_img = $matches[1][1];
            }
            // Check 3rd image found
            else if ( !empty( $matches[1][2] ) ) {
                $image_found = $matches[1][2];
                $image_dimensions = getimagesize($image_found);
                if ( ( $image_dimensions[0] > $width ) && ( $image_dimensions[1] > $height ) ) {
                    $thumbnail_img = $matches[1][2];
                }
            }
        }
    }


texts: Refactoring a series of if-return statements.

texts:
In my model, I have things called Reports that have known workflow associated with them.

I've got a requirement to output at which state a report currently is.

public abstract partial class Report{
   public virtual string StateStatus(){
     if (Check.IsSuccessful) return "Approved";
     if (Check.AreClarificationsSent) return "Clarifications";
     if (Check.IsInProgress) return "Check in progress";
     if (IsTemplateSent) return "Sent";
     if (IsReceived) return "Received";
     return "Not received";
   }
  ...
}

I dislike this method. It won't break, but leaves some nausea in my head, just doesn't feel right.

Got any recommendations for improvement?


texts:
The data structure question I was trying to solve is as follows:

  Stack of Plates:

  Imagine a (literal) stack of plates. If the stack gets too high, it
  might topple. Therefore, in real life, we would likely start a new
  stack when the previous stack exceeds some threshold. Implement a data
  structure SetOfStacks that mimics this. SetOfStacks should be
  composed of several stacks and should create a new stack once the
  previous one exceeds capacity. SetOfStacks.push() and
  SetOfStacks.pop() should behave identically to a single stack (that
  is, pop() should return the same values as it would if there were
  just a single stack).

I am trying to practice better data structure design, so I was looking for some feedback on my code as well as tips for going forward:

import java.util.*;

 public class StackOfPlates {

   public class StackNode {
     private int data;

     public StackNode(int d){
       data = d;
     }

     public int getData(){
       return data;
     }
   }

   List<ArrayList<StackNode>> setOfStacks;
   private int stackCapacity;

   public StackOfPlates(int c){
     setOfStacks = new ArrayList<ArrayList<StackNode>>();
     stackCapacity = c;
   }

   void push(int item){
     StackNode s = new StackNode(item);

     if(setOfStacks.isEmpty()){
       ArrayList<StackNode> st = new ArrayList<StackNode>();
       st.add(s);
       setOfStacks.add(st);
     }
     else{
       int index = setOfStacks.size() - 1;
       int currStackSize = setOfStacks.get(index).size();
       if(currStackSize == stackCapacity){
         ArrayList<StackNode> st = new ArrayList<StackNode>();
         st.add(s);
         setOfStacks.add(st);
         setOfStacks.get(index + 1).add(s);
       }
       else{
         setOfStacks.get(index).add(s);
       }
     }
   }

   StackNode pop(){
     int setOfStacksSize = setOfStacks.size();
     if(setOfStacksSize == 0) return null;

     ArrayList<StackNode> lastStack = setOfStacks.get(setOfStacksSize - 1);
     int lastElmtIndex = lastStack.size() - 1;
     StackNode end = lastStack.get(lastElmtIndex);
     lastStack.remove(lastElmtIndex);
     return end;
   }
 }


texts: auto-fold deeply nested parts of a file (vimscript)

texts:
Folding in vim has bugged me for a while. What I intuitively want is for the details to be folded, but the overall structure of a file to remain unfolded. This way I can navigate around a file to see the structure quickly, and open folded sections when I need to dive into the details.

What I have been doing before today was to set the default fold level per filetype, in the ftplugin. For example bash.vim will have foldlevel=1 whereas python.vim will be 2 or 3. But what I really want is for my editor to autodetect the complexity of the code and adjust the fold level accordingly.

My first attempt was just to calculate the maximum fold level for a file and just fold the most deeply nested parts:

:let &foldlevel = max(map(range(1, line('$')), 'foldlevel(v:val)'))-1

But this code has 2 problems:

If there is one complex part that is deeply nested it only folds that part. I'd prefer folding of anything that is nested deeper than the average for the file.
I scans the whole file. This may be a concern for very large files

After a lot of fiddling and trial and error I came up with this

function setfolds()
    " default fold level to slightly higer than the average fold level
    let b:fl_lines = min([line('$'), 250])
    let b:fl_levels = map(range(1, b:fl_lines), 'foldlevel(v:val)')
    exe 'let b:fl_sum = ' . join(b:fl_levels, '+')
    let b:fl_avg = b:fl_sum / (b:fl_lines * 1.0) " convert to float
    let b:fl_ceil = 0 + string(ceil(b:fl_avg)) " convert to int
    let &foldlevel = max([b:fl_ceil, 2])
endfunction

This is my first real (not copypasted) vimscript and I find it is super hacky and ugly.

is exe on a concatenated string really the best way to sum an array of integers in vimscript? Is there some kind of reduce pattern I could use instead?
conversion: multiply by 1.0 to convert to float. +string() to convert back to int?
Is it necessary to prefix vars with b: scope? Good practice or just superfluous?
Seems like setting folding will cause the whole file to be iterated over anyway. Should I just not worry about it?


texts: Selecting a subset of the data from a list

texts:
I have a list called all_dates which contains timestamps for a number of days (hourly). I wanted to select each day (i.e every 24 items in the list) and pass it to a function.

Here is my implementation that works:

count = 0
while count < len(all_dates)-1:
    day_list = [all_dates[count]]
    for i in xrange(23):
        count += 1
        day_list.append(all_dates[count])
    print_dates(day_list)
    count += 1

I know this is probably not the best way it can be done in Python so I wanted some help to improve my implementation.


texts: Porting python's 'with' construct to TypeScript

texts:
Now that async generators are available in the platforms I care about, I figured I'd try porting Python's ingenious with construct to JS as a utility. My first stab looks like this:

type Index = string | symbol | number;
function isIndex(obj: any): obj is Index {
    return (
        typeof obj === 'string' ||
        typeof obj === 'symbol' ||
        typeof obj === 'number'
    );
}
type Disposable<TDisposerKey extends Index> = {
    [k in TDisposerKey]: DisposerMethod
};
type DisposerMethod = () => void | Promise<void>;
type DisposerCallback<TDisposable> = (res: TDisposable) => void | Promise<void>;

function using<
    TDisposerKey extends Index,
    TDisposable extends Disposable<TDisposerKey>
>(resource: TDisposable, key: TDisposerKey): AsyncIterable<TDisposable>;
function using<TDisposable>(
    resource: TDisposable,
    disposer: DisposerCallback<TDisposable>
): AsyncIterable<TDisposable>;
async function* using<
    TDisposerKey extends Index,
    TDisposable extends Disposable<TDisposerKey>
>(
    resource: TDisposable,
    keyOrDisposer: TDisposerKey | DisposerCallback<TDisposable>
): AsyncIterable<TDisposable> {
    try {
        yield resource;
    } finally {
        if (typeof keyOrDisposer === 'function') {
            await keyOrDisposer(resource);
        } else if (isIndex(keyOrDisposer)) {
            await resource[keyOrDisposer]();
        }
    }
}

async function main(): Promise<any> {
    for await (const db of using(new PouchDB('zz-data\\foo'), 'close')) {
        console.dir(await db.info());
        return await db.get('qwertyuiop');
    }
}

Does anything jump out at anybody? A for..await..of loop with only one iteration is odd, but it's the only way to handle this lexically, and it saves me having to juggle types for a callback-based alternative which was fiddly to make generic. The overloads are also a mouthful, but that's TS for you.


texts: Update any controls' Text for the specified language

texts:
I would like to optimize the below code The only difference is the datatypes RadioButton, Label, and Button. Outside the method I have an loop that iterates over all the controls in the aspx-page. I have the limitation of .NET 3.5. The code is intended to set language relevant strings on the controls of a certain type in a aspx-page without having to name each control.

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
...
public partial class MyUserControl : UserControl
...

    private static void SetTextOnControls(MyLanguageTexts keys, ControlCollection theControls)
    {
        foreach (Control control in theControls)
        {
            SetTextOnControl(keys, control);
        }
    }

    private static void SetTextOnControl(MyLanguageTexts keys, Control control)
    {

        if (control is RadioButton)
        {
            try
            {
                (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
                    DataBinder.Eval(keys.en, control.ID).ToString() :
                    DataBinder.Eval(keys.sv, control.ID).ToString();
            }
            catch (Exception)
            {
                (control as RadioButton).Text = "Key not found: " + control.ID;
            }
        }
        else if (control is Label)
        {
            try
            {
                (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
                DataBinder.Eval(keys.en, control.ID).ToString() :
                DataBinder.Eval(keys.sv, control.ID).ToString();
            }
            catch (Exception)
            {
                (control as Label).Text = "Key not found: " + control.ID;
            }
        }
        else if (control is Button)
        {
            try
            {
                (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
                DataBinder.Eval(keys.en, control.ID).ToString() :
                DataBinder.Eval(keys.sv, control.ID).ToString();
            }
            catch (Exception)
            {
                (control as Button).Text = "Key not found: " + control.ID;
            }
        }

        SetTextOnControls(keys, control.Controls);
    }


texts:
Here you find some code that returns the value of a multivariate Bernoulli density function - for a dice with n faces, where each face has its weight (weight must be positive reals, not necessarily sum = 1) it provides the result of the tossing.

function face = weighted_dice(faces, weight)
    % face = dice(faces, weight)
    % input: row vector. Faces and weight of the same dimension!
    % output: face is the discrete face after tossing a virtual dice with given
    % faces and weight.
    if size(faces, 2) ~= size(weight, 2) || size(weight, 2)<= 1
        error('Input of function dice not well defined. See help')
    end

    num_weight = size(weight, 2);
    % weight = [w1,w2,w3, .. ,w_n]
    % cumulative_weight = [0, w1, w1+w2, w1+w2+w3, ... , sum(weight)]

    cumulative_weight = zeros(1, num_weight + 1);
    for j=1:num_weight
       cumulative_weight(j+1) = sum(weight(1:j));
    end

    % pick a random value unif. distrib. betw. 0 and the sum of the weights.
    rand_w = unifrnd(0, cumulative_weight(end));
    % check in which interval of the cumulative_weight is this element
    for j=1:num_weight
       if rand_w >= cumulative_weight(j) && rand_w < cumulative_weight(j+1)
           break
       end
    end

    % assign the interval found to the value of the face
    face = faces(j);

E.g.

disp(weighted_dice(['a','b','c','d','e','f'], [0.1, 0.1, 0.5, 0.1, 0.1, 0.1]))

beans = zeros(1,6);
for i=1:1000
    val = weighted_dice(['a','b','c','d','e','f'], [0.1, 0.1, 0.5, 0.1, 0.1, 0.1]);
    if val == 'a'
        beans(1,1) = beans(1,1) + 1;
    elseif val == 'b'
        beans(1,2) = beans(1,2) + 1;
    elseif val == 'c'
        beans(1,3) = beans(1,3) + 1;
    elseif val == 'd'
        beans(1,4) = beans(1,4) + 1;
    elseif val == 'e'
        beans(1,5) = beans(1,5) + 1;
    elseif val == 'f'
        beans(1,6) = beans(1,6) + 1;
    end
end

disp(beans)

Any idea how to vectorise the two for-cycle in the function?


texts: Check if the given string has duplicates

texts:
Description:

Given a string find if it contains duplicate characters. The string contains only ASCII characters.

Code:

import java.util.Arrays;

class Main {
  /**
   * Given a string check if it duplicate characters.
   * []        -> true
   * [f, o, o] -> false
   * [b, a, r] -> true
   *
   * @param {String} str
   *
   * @return false if string contains duplicate else true
   */
  public static boolean isUnique(String str) {
    if (str.length() == 0) {
      return true;
    }
    boolean[] seen = new boolean[25];
    for (int i = 0; i < str.length(); i++) {
      int index = Character.toLowerCase(str.charAt(i)) - 'a';
      if (seen[index]) {
        return false;
      }
      else {
        seen[index] = true;
      }
    }
    // invariant
    return true;
  }

  public static void main(String[] args) {
    System.out.println(isUnique(""));       // true
    System.out.println(isUnique("a"));      // true
    System.out.println(isUnique("foo"));    // false
    System.out.println(isUnique("bar"));    // true
    System.out.println(isUnique("hello"));  // false
    System.out.println(isUnique("Hello"));  // false
  }
}

The above algorithms runs in O(n), the alternate solution is to sort the string and the check the adjacent elements but it would be O(nlogn). I need to understand if I am using Java correctly, any other styles related comments are most welcome.

PS: I would like to know if I need to include more tests to cover all cases.


texts: A simple implementation of the principle of RSA encryption

texts:
Inspired by a Numberphile video I made a little program that shows the principles of RSA encryption and decryption. To calculate the keys I used the explanation in this link: rsa public private key encryption explained. Fascinating what you can do in a few lines of code and how Python can handle to powering of large numbers.

One observation is that with large prime numbers encryption goes relatively fast starting with ascii code numbers that are relatively small less than 200 or so, but the decryption goes much slower as the encrypted numbers are magnitudes larger. How is this solved in practice? and how is this all working with really large primes?

Comments, suggestions welcome.

'''  RSA encryption
     inspired on: https://www.youtube.com/watch?v=M7kEpw1tn50
     and http://jcla1.com/blog/rsa-public-private-key-encryption-explained

     some conditions:
        - prime numbers must be > 1 and not equal
        - prime factor must sufficiently large to accommodate the ascii numbers, let's say > 150
        - so for example (2, 191) will do as well as (11, 17)
'''

class RSA():
    ''' methods for calculating keys, encrypt and decrypt ascii messages
    '''
    @staticmethod
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a

    @classmethod
    def encrypt(cls, message):
        message_letters = [ord(letter) for letter in message]
        message_encrypted = ''.join([chr(letter**cls.public_key % cls.prime_factor) for letter in message_letters])
        return message_encrypted

    @classmethod
    def decrypt(cls, message_encrypted):
        message_encrypted_letters = [ord(letter) for letter in message_encrypted]
        message = ''.join([chr(letter**cls.private_key % cls.prime_factor) for letter in message_encrypted_letters])
        return message

    @classmethod
    def calc_keys(cls, prime_1, prime_2):
        cls.prime_factor = prime_1 * prime_2
        totient = (prime_1 - 1) * (prime_2 - 1)

        # calculate the possible public keys where gcd(public_key, totient) == 1, then select the 5th one (this is abritary, any
        # of the public_keys could have been selected
        # (Note above link has an error that the gcd of public_key and totient must be 1, not public_key
        #  and the prime_factor as suggested in the article)
        public_keys = []
        for i in range(totient):
            if cls.gcd(i, totient) == 1:
                public_keys.append(i)
        cls.public_key = public_keys[4]

        # calculate the private key based on public key and totient when (public_key * private_key - 1) % totient == 0
        cls.private_key = 0
        x = -1
        while x != 0:
            cls.private_key += 1
            x = (cls.public_key * cls.private_key - 1) % totient

        return (cls.prime_factor, cls.public_key, cls.private_key)

def main():
    rsa = RSA()
    print(rsa.calc_keys(61, 53))

    message = 'hello this is my encrypted message'
    encrypted_message = rsa.encrypt(message)
    decrypted_message = rsa.decrypt(encrypted_message)

    if message == decrypted_message:
        print('Hurray!!')
        print(f'message: {message}\nencrypted message: {encrypted_message}'
              f'\ndecrypted message: {decrypted_message}')
    else:
        print('Ough, someting wrong here  ... !')

if __name__=="__main__":
    main()


texts: Am I using copy ctors/move ctors/shared_ptr correctly?

texts:
Here is my simple example: there is a class A with few primitive members and a class B with few primitive members but also a collection of objects of type A.

This is my A class:

#pragma once

#include<string>

class Hero
{
private:
    long id;
    std::string name;
    int level;
    static long currentId;
public:
    Hero();
    Hero(std::string name, int level);
    Hero(const Hero &hero);
    Hero(Hero &&hero);
    Hero& operator=(const Hero &hero);
    Hero& Hero::operator=(const Hero &&hero);
    long GetId() const { return this->id; }
    std::string GetName() const { return this->name; }
    int GetLevel() const { return this->level; }
    void SetName(const std::string &name);
    void SetLevel(const int &level);
};

#include"Hero.h"

long Hero::currentId = 0;

Hero::Hero(std::string name, int level):name(name), level(level), id(++currentId)
{

}

Hero::Hero():name(""), level(0), id(++currentId)
{

}

Hero::Hero(const Hero &hero):id(hero.id), name(hero.name), level(hero.level)
{

}

Hero::Hero(Hero &&hero):id(hero.id), name(hero.name), level(hero.level)
{

}

Hero& Hero::operator=(const Hero &hero)
{
    this->id = hero.id;
    this->name = hero.name;
    this->level = hero.level;
    return *this;
}

Hero& Hero::operator=(const Hero &&hero)
{
    this->id = hero.id;
    this->name = hero.name;
    this->level = hero.level;
    return *this;
}

void Hero::SetName(const std::string &name)
{
    this->name = name;
}

void Hero::SetLevel(const int &level)
{
    this->level = level;
}

This is my B class:

#pragma once

#include"Hero.h"
#include<vector>
#include<memory>

class Race
{
private:
    static long currentId;
    long id;
    std::string name;
    std::vector<std::shared_ptr<Hero>> heroes;
    Race(const Race &race); //disable copy constructor
    Race& operator =(const Race &race); //disable assign operator
public:
    Race();
    explicit Race(std::string name);
    std::string GetName() const { return this->name; }
    void SetName(std::string name);
    void AddHero(Hero &&hero);
    std::vector<std::shared_ptr<Hero>> GetHeroes() const { return heroes; }
};

   #include "Race.h"

long Race::currentId = 0;

Race::Race(std::string name):name(name), heroes(std::vector<std::shared_ptr<Hero>>()), id(++currentId)
{

}

Race::Race():name(""), heroes(std::vector<std::shared_ptr<Hero>>()), id(++currentId)
{

}

void Race::SetName(std::string name)
{
    this->name=name;
}

void Race::AddHero(Hero &&hero)
{
    heroes.push_back(std::make_shared<Hero>(hero));
}

And this is my main:

#include "stdafx.h"

#include"Race.h"

int _tmain(int argc, _TCHAR* argv[])
{
    Hero elvesHero1("Demon hunter", 8);
    Hero elvesHero2("Warden", 4);
    Race nightElf("Night elf");
    nightElf.AddHero(std::move(elvesHero1));
    nightElf.AddHero(std::move(elvesHero2));
    std::vector<std::shared_ptr<Hero>> heroes=nightElf.GetHeroes();
    return 0;
}

One remark: When the debugger hits nightElf.AddHero(std::move(elvesHero1)); it enters Hero's copy constructor. Shouldn't it go through move constructor?

I just want start on the right foot, so I am waiting for your tips.

LE: If I modify the AddHero method like this:

void Race::AddHero(Hero &&hero)
{
    heroes.push_back(std::make_shared<Hero>(std::move(hero)));
}

it gives the parameter std:move(hero) instead of hero.  It enters move constructor instead of copy constructor.