texts: Given 4 vertices representing a quadrilateral, divide it into N parts

texts:
I am attempting to, given two dimensions (width and height) which represent a quadrilateral, partition that quad in to N parts where each part is as proportionally similar to the other as possible.

For example, imagine a sheet of paper. It consists of 4 points A, B, C, D. Now consider that the sheet of paper has the dimensions 800 x 800 and the points:

A: {0, 0}
B: {0, 800}
C: {800, 800}
D: {800, 0}

Plotting that will give you 4 points, or 3 lines with a line plot. Add an additional point E: {0, 0} to close the cell.

To my surprise, I've managed to do this programatically, for N number of cells.

How can I improve this code to make it more readable, pythonic, and as performant as possible?

from math import floor, ceil
import matplotlib.pyplot as plt

class QuadPartitioner:

    @staticmethod
    def get_factors(number):
        '''
        Takes a number and returns a list of factors
        :param number: The number for which to find the factors
        :return: a list of factors for the given number
        '''
        facts = []
        for i in range(1, number + 1):
            if number % i == 0:
                facts.append(i)
        return facts

    @staticmethod
    def get_partitions(N, quad_width, quad_height):

        '''
        Given a width and height, partition the area into N parts
        :param N: The number of partitions to generate
        :param quad_width: The width of the quadrilateral
        :param quad_height: The height of the quadrilateral
        :return: a list of a list of cells where each cell is defined as a list of 5 verticies
        '''

        # We reverse only because my brain feels more comfortable looking at a grid in this way
        factors = list(reversed(QuadPartitioner.get_factors(N)))

        # We need to find the middle of the factors so that we get cells
        # with as close to equal width and heights as possible

        factor_count = len(factors)

        # If even number of factors, we can partition both horizontally and vertically.
        # If not even, we can only partition on the X axis
        if factor_count % 2 == 0:
            split = int(factor_count/2)
            factors = factors[split-1:split+1]
        else:
            factors = []
            split = ceil(factor_count/2)
            factors.append(split)
            factors.append(split)

        # The width and height of an individual cell
        cell_width = quad_width / factors[0]
        cell_height = quad_height / factors[1]

        number_of_cells_in_a_row = factors[0]
        rows = factors[1]
        row_of_cells = []

        # We build just a single row of cells
        # then for each additional row, we just duplicate this row and offset the cells
        for n in range(0, number_of_cells_in_a_row):
                cell_points = []

                for i in range(0, 5):

                    cell_y = 0
                    cell_x = n * cell_width

                    if i == 2 or i == 3:
                        cell_x = n * cell_width + cell_width

                    if i == 1 or i == 2:
                        cell_y = cell_height

                    cell_points.append((cell_x, cell_y))

                row_of_cells.append(cell_points)

        rows_of_cells = [row_of_cells]

        # With that 1 row of cells constructed, we can simply duplicate it and offset it
        # by the height of a cell multiplied by the row number
        for index in range(1, rows):
            new_row_of_cells = [[ (point[0],point[1]+cell_height*index) for point in square] for square in row_of_cells]
            rows_of_cells.append(new_row_of_cells)

        return rows_of_cells

if __name__ == "__main__":

    QP = QuadPartitioner()
    partitions = QP.get_partitions(56, 1980,1080)

    for row_of_cells in partitions:
        for cell in row_of_cells:
            x, y = zip(*cell)
            plt.plot(x, y, marker='o')

    plt.show()

Output:


texts:
I was working on a code challenge with the following description:

Given an array of positive or negative integers
I= [i1,..,in]
you have to produce a sorted array P of the form
[ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...]
Example: I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]]

So I created an algorithm that does exactly that, but I have some performance issues. On the code challenge website (Codewars), my algorithm times out for fairly large integers, 173471 being a specific example.
One issue I am aware of with the algorithm and want to improve is that my current method for generating primes simply takes the largest number in the input array, and generates primes up to that number, but rarely do I need that many primes. I have not found a full proof way of creating the full list of possible primes otherwise, however. A second issue is that I have a loop running within my loop, to check which numbers in the input have factors in the list of primes I generated. If I could somehow reduce it to one loop, that would reduce the complexity.
Anyway all of that aside, here is my algorithm:
// Function that returns a collection of primes up to a given number
const sieveOfEratosthenes = (int) => {
  // Initialize some values
  const primes = [...Array(int + 1).keys()].slice(2);
  const sqrtCeil = Math.sqrt(int);
  let p = primes[0];
  let pIndex = 0;
  let factor = 2;

  // Until index refers to the last element, sieve primes
  while (primes[pIndex] < sqrtCeil) {
    const productIndex = primes.indexOf(factor * p);

    if (productIndex > -1) {
      primes.splice(productIndex, 1);
    }

    factor += 1;

    if (factor * p > primes[primes.length - 1]) {
      factor = 2;
      pIndex += 1;
      p = primes[pIndex];
    }
  }

  return primes;
};

function sumOfDivided(lst) {
  // If the input is empty, return an empty list
  if (lst.length === 0) {
    return [];
  }

  // Generate primes with a ceiling of the highest number in the input,
  // accounting for negative numbers
  const primes = sieveOfEratosthenes(
    Math.max(...lst.map((int) => (int < 0 ? int * -1 : int)))
  );

  // Reduce primes array to array of tuples, value one being being the prime,
  // value two being the sum of numbers it was a prime factor for in the input
  return primes.reduce((acc, prime) => {
    // Initialize values
    let sum = 0;
    let primeFactorCount = 0;

    // Check if each integer in the input had this prime as a factor
    for (let int of lst) {
      if (prime > int && int > 0) {
        continue;
      }

      if (int % prime === 0) {
        sum += int;
        primeFactorCount += 1;
      }
    }

    // If at least one number matched, add the tuple to the array
    if (primeFactorCount > 0) {
      return [...acc, [prime, sum]];
    }

    return acc;
  }, []);
}
```


texts:
I am building my first OOP program, Tic Tac Toe.  I want to conquer it in chunks, but the first part for me is the intialization of the program and the creation of the two players.  I want to get some feedback about how I structured this before I move on to build the board and the actual gameplay logic.

For instance, should I have made the player_names assignment method part of the Player class?  Or is the parent TicTacToe class good?

class TicTacToe

    def initialize
        @player1 = Player.new
        @player2 = Player.new
        game_sequence
    end

    def game_sequence
        puts "Let us play a nice game of Tic Tac Toe!"
        player_names

    end

    def player_names
        puts "Player 1, what is your name?"
        @player1.name = gets.chomp
        puts "Thanks, #{@player1.name}!  Would you like to be X or O?"

        answer = ""

        until ["X","O"].include?(answer)
            answer = gets.chomp
            if ["X","O"].include?(answer)
                @player1.mark = answer
                break
            end
            puts "You must enter in either X or O"
        end

        case @player1.mark
        when "X"
            @player2.mark = "O"
        when "O"
            @player2.mark = "X"
        end

        puts "#{@player1.name}\'s mark is #{@player1.mark} and Player 2\'s mark is #{@player2.mark}"
        puts "Player 2, what is your name?"
        @player2.name = gets.chomp

    end

    class Player

        attr_accessor :name, :mark

        def initialize(name = nil, mark = nil)
            @name = name
            @mark = mark
        end

    end

end

TicTacToe.new


texts:
This is a simple AngularJs application with two nested controllers. We need to pass data from the parent to the child Controller.

The first thing you find when googling for a solution would be this, by calling $scope.$parent in the child controller:

angular.module("outerModule", [])
  .component('outerModule', {
      controller: function($scope) {
        $scope.innerModuleConfigData = {
          text : 'hello'
        }
      }
  })

angular.module("innerModule", [])
  .component('innerModule', {
      controller: function($scope) {
        console.log($scope.$parent.innerModuleConfigData.text);
      }
  })

The critique here is that the parent controller has to know exactly what to call its shared variable.

Another thing that comes to my mind is the thing with the nested scope when working with angular directives:

<inner-module configData="innerModuleConfigData"></inner-module>

I'm not sure if something like this works for nested controllers as well.

The consensus to a 'best practice' solution seems to be sending the data by a service, which is injected to both controllers. But this seems to be a little overheaded, if only small amounts of data are to be shared.


texts: Memory issues when copying JPEG into bmp

texts:
I am trying as a part of a bigger job to merge parts of several JPEGs into one huge BMP which will be processed further.

As a start, I tried to just copy a few JPEGs each to his own BMP file. In doing so I noticed that Visual Studio 2015 Community shows increased memory consumption if I repeat the copying of files in a single debug-run. The responsible part of the code is as follows.

Please, can you help me with this increasing memory consumption? In the future, I might need to read a few thousand JPEGs so this might be a serious issue.

private void GluePhotos(string[] files) {
    foreach (string file in files) {
        //Read original JPEG
        Stream imageSource = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
        JpegBitmapDecoder jpegDecoder = new JpegBitmapDecoder(imageSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        BitmapSource bitmapSource = jpegDecoder.Frames[0];

        //Prepare memory
        int stride = bitmapSource.PixelWidth * ((bitmapSource.Format.BitsPerPixel + 7) / 8);
        byte[] pixels = new byte[bitmapSource.PixelHeight * stride];

        //Copy JPEG into memory
        bitmapSource.CopyPixels(pixels, stride, 0);

        //Copy memory into a new BMP-to-be
        WriteableBitmap bitmap = new WriteableBitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, bitmapSource.DpiX, bitmapSource.DpiY, bitmapSource.Format, bitmapSource.Palette);
        bitmap.WritePixels(new System.Windows.Int32Rect(0, 0, bitmapSource.PixelWidth, bitmapSource.PixelHeight), pixels, stride, 0);

        //Encode it as a BMP
        BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder();
        BitmapFrame newBitmapFrame = BitmapFrame.Create(bitmap);
        bmpEncoder.Frames.Add(newBitmapFrame);

        //Prepare paths for saving, save and cleaning(?)
        string dirPath = file.Insert(file.LastIndexOf('\\'), "\\ripoffs");
        dirPath = dirPath.Remove(dirPath.LastIndexOf('\\'));
        Directory.CreateDirectory(dirPath);
        string fileName = file.Insert(file.LastIndexOf('\\'), "\\ripoffs");
        fileName = fileName.Remove(fileName.LastIndexOf('.')) + "_ripoff.bmp";
        Stream imageOutput = new FileStream(fileName, FileMode.Create);
        bmpEncoder.Save(imageOutput);
        imageOutput.Close();
        imageSource.Close();
    }
}


texts: Selecting variable amount of vector elements in C++

texts:
Suppose we are given a C++ vector. We want to specify a variable amount of indices and select elements from a vector being indexed. I have two implementation: (A) one relies on C++11 initializer lists, and the second one (B) on va_list and  macro mess. Arrangement B is however funkier to type because it requires no typing the braces comprising the initializer list.

So my main question is: which one should an adult C++ programmer use, if any?

coderodde.h:

#ifndef CODERODDE_H
#define CODERODDE_H

#include <cstdarg>
#include <iostream>
#include <vector>

#define NUM_ARGS(...) (sizeof((size_t[]){__VA_ARGS__}) / sizeof(size_t))

namespace coderodde {

    template<class T>
    std::vector<T> select(const std::vector<T>& vec,
                          const std::vector<size_t>& indices)
    {
        std::vector<T> ret;

        for (auto index : indices) {
            ret.push_back(vec.at(index));
        }

        return ret;
    }

    template<class T>
    std::vector<T> select(const std::vector<T>& vec, const size_t len, ...)
    {
        std::va_list ap;
        std::vector<T> ret;
        va_start(ap, len);

        for (size_t i = 0; i < len; ++i)
        {
            ret.push_back(vec.at(va_arg(ap, size_t)));
        }

        va_end(ap);
        return ret;
    }
}

#define SELECT(vec, ...) (select(vec, NUM_ARGS(__VA_ARGS__), __VA_ARGS__))

#endif // CODERODDE_H

The test driver main.cpp:

#include <iostream>
#include <string>
#include <vector>
#include "coderodde.h"

using std::cout;
using std::endl;
using std::string;
using std::vector;
using coderodde::select;

void test_smart(const vector<string>& input)
{
    const size_t N = input.size();

    for (size_t ca = 0; ca < N; ++ca)
    {
        for (size_t cb = 0; cb < N; ++cb)
        {
            for (size_t cc = 0; cc < N; ++cc)
            {
                for (auto s : select(input, { ca, cb, cc }))
                {
                    cout << s;
                }

                cout << endl;
            }
        }
    }

}

void test_stupid(const vector<string>& input)
{
    const size_t N = input.size();

    for (size_t ca = 0; ca < N; ++ca)
    {
        for (size_t cb = 0; cb < N; ++cb)
        {
            for (size_t cc = 0; cc < N; ++cc)
            {
                for (auto s : SELECT(input, ca, cb, cc))
                {
                    cout << s;
                }

                cout << endl;
            }
        }
    }
}

int main(int argc, char** argv)
{
    std::vector<std::string> string_vec {"A", "B", "C", "D"};
    cout << "Smart:" << endl;
    test_smart(string_vec);
    cout << "Stupid:" << endl;
    test_stupid(string_vec);
    return 0;
}


texts: Injecting SelectList objects into ViewData to enable using EditorFor on dropdown based properties

texts:
I have developed a system whereby I use an attribute to state which SelectList to use for an 'FK' property. I would appreciate some feedback mainly on by good practice, and also on any ways to do this better. Let me start my exposition with a demo view model:

public class DemoModel
{
    [DropDownList("LanguageSelect")]
    public int? LanguageId { get; set; }
    public SelectList LanguageSelect { get; set; }
}

Now when I use the Razor markup @EditorFor(m => m.LanguageId), I get a drop-down populated from the LanguageSelect list. I get this because the DropDownListAttrbute class attaches the select list name to the LanguageId model:

public class DropDownListAttribute : UIHintAttribute, IMetadataAware
{
    public DropDownListAttribute(string selectListName) : base(KnownUiHints.DropDown, KnownPresentationLayers.Mvc, selectListName)
    {
        SelectListName = selectListName;
    }
    public string SelectListName { get; set; }
    public void OnMetadataCreated(ModelMetadata metadata)
    {
        var listProp = metadata.ContainerType.GetProperty(SelectListName);
        metadata.AdditionalValues[KnowMetadataKeys.SelectListName] = SelectListName;
    }
}

All my view models derive from ViewModel, which offers a SelectListDictionary property:

private IDictionary<string, SelectList> _selectListdictionary;
public virtual IDictionary<string, SelectList> SelectListDictionary
{
    get
    {
        if (_selectListdictionary == null)
        {
            var props = GetType().GetProperties().Where(p => p.PropertyType == typeof(SelectList));
            _selectListdictionary = props.ToDictionary(prop => prop.Name, prop => (SelectList)prop.GetValue(this, null));
        }
        return _selectListdictionary;
    }
}

In my base controller, I override the View method to pull the entire select list dictionary from the view model, and insert it into the view's viewdata, making it available for the editor template:

protected override ViewResult View(string viewName, string masterName, object model)
{
    var result = base.View(viewName, masterName, model);
    if ((model is ViewModel) && (!ViewData.ContainsKey(KnowMetadataKeys.ViewDataSelectLists)))
    {
        var vm = (ViewModel)model;
        result.ViewData.Add(KnowMetadataKeys.ViewDataSelectLists, vm.SelectListDictionary);
    }
    return result;
}

The editor template then retrieves the list it requires from the select list dictionary and builds a select input element:

@using Erisia.Constants
@{
    var list = (SelectList)ViewData.ModelMetadata.AdditionalValues[ViewData.ModelMetadata.AdditionalValues[KnowMetadataKeys.SelectListName].ToString()];
    var listWithSelected = new SelectList(list.Items, list.DataValueField, list.DataTextField, Model);
}
@Html.DropDownListFor(m => Model, listWithSelected, " - select - ")

So what say you all?


texts:
My current condition is written as follows:

.Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) <= 30 && Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) > 0)

which basically says where the rounded value is less than or equal to 30 and the rounded value is greater than 0.

Is there a neater way to write this than having

Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0)

twice in the same statement?

The full expression is:

List<Meeting> finalList = initialList.Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) <= 30 && Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0) > 0).ToList();


texts: Readability concerns with literal dictionary lookup vs if-else

texts:
I'm having concerns about the readability of this piece of code:
    messages_dict = {'error':errors, 'warning':warnings}[severity]
    messages_dict[field_key] = message

and I'm to use this instead:
    if severity == 'error':
        messages_dict = errors
    elif severity == 'warning':
        messages_dict = warnings
    else:
        raise ValueError('Incorrect severity value')
    messages_dict[field_key] = message

But it looks too verbose for such a simple thing.
I don't care too much if it's more efficient than constructing a dictionary for just two mappings. Readability and maintainability is my biggest concern here (errors and warnings are method arguments, so I cannot build the lookup dictionary beforehand and reuse it later).


texts:
if(env['REQUEST_METHOD'] == 'POST')
  $post = {}
  post = env['rack.input'].read.split('&')
  post_split = Array.new
  post.each{|x| post_split << x.split('=')}
  post_split.each{|x|
    $post[x[0]] = x[1]
  }
end

What would be a nice way to do this? I have a string like:

"a=b&c=d"

and i'm trying to get it into a hash like

{:a=>'b',:c=>'d'}

This code works but it is just terrible, and I can't access the keys with

$post[:a]

only

$post['a']


texts: Checking for a palindrome in any sub-range of a range

texts:
This is my attempt at answering "Palindrome from all the substrings" which asks to detect if a string contains a palindrome as a substring.

The algorithm implemented here is the one described in its accepted answer.

First, here is the main function (based on the corresponding main in the initial question):

int main()
{
    size_t n_str;
    std::cin >> n_str;

    for (size_t i = 0; i < n_str; ++i)
    {
        std::string str;
        std::cin >> str;

        std::cout << (contains_palindrome(str) ? "YES" : "NO") << std::endl;
    }

    return EXIT_SUCCESS;
}

Second, I decided to extend contains_palindrome from exclusively accepting an std::string to taking any container (e.g. std::vector<char>, std::array<int,N>, ...) as an argument:

template <class T>
bool contains_palindrome(const T& s)
{
    if (s.size() < 2) return false;

    for (auto it = s.cbegin(),
            next = std::next(it),
           nnext = std::next(next);
         nnext != s.cend();
         it = next, next = nnext, std::advance(nnext, 1))
        if (*it == *next || *it == *nnext)
            return true;

    return *std::prev(s.cend()) == *std::prev(s.cend(), 2);
}

NB: <cstdlib>, <iostream>, <iterator> and <string> are required.

QUESTION(S):

Is there any instance of bad practice in the code? In particular,

is the template correct according to the desired behaviour? Am I
right in assuming that contains_palindrome will work as expected on
any class implementing the methods size(), cbegin() and cend()?
is the use of iterators done correctly? In particular, I made sure to
call the "c versions" of begin() and end() (after declaring s
as const) and used std::prev(it), std::next(it) and
std::advance(it,1) instead of, respectively, it-1, it+1 and
it++: is this, as I was told, good practice? Are there other
instances of good practice related to iterators that I overlooked?
I used iterators because I learned that it is "the [right]
way to do it in C++" but what do I gain over the following C-like
approach?

for (size_t i = 0; i < s.size()-2; ++i)
    if (s[i] == s[i+1] || s[i] == s[i+2])
        return true;

return s[s.size()-1] == s[s.size()-2];


texts:
The below logic is working fine. But is there any way to optimize this logic ?

I have a string1, string2,...,stringn
and values of each strings are

string1 = "s1k1-s1k2-s1k3-....-s1kn | s1v1-s1v2-s1v3-....-s1vn";

string2 = "s2k1-s2k2-s2k3-....-s2kn | s2v1-s2v2-s2v3-....-s2vn";

                .............

stringn = "snk1-snk2-snk3-....-snkn | snv1-snv2-snv3-....-snvn";

Now, I want to populate the Dictionary<string, string>() with the key and values as follows.

var dict = new Dictionary<string, string>();
dict.Add(s1k1, s1v1);
dict.Add(s1k2, s1v2);
         :
         :
dict.Add(snkn, snvn);

Below is my sample code:

        string string1 = "s1k1-s1k2-s1k3-s1kn|s1v1-s1v2-s1v3-s1vn";
        string string2 = "s2k1-s2k2-s2k3-s2kn|s2v1-s2v2-s2v3-s2vn";
        string stringn = "snk1-snk2-snk3-snkn|snv1-snv2-snv3-snvn";

        var dict = new Dictionary<string, string>();

        new List<string> { string1, string2, stringn }.ForEach(str =>
        {
            var strSplit = str.Split('|');
            var strKeys = strSplit[0].Split('-');
            var strValues = strSplit[1].Split('-');
            strKeys.Zip(strValues, (key, value) => new { key, value }).ToList().ForEach(filed => dict.Add(filed.key, filed.value));
        });

Is it possible to optimize this code interms of Speed and Readability.


texts: All arithmetic operator functions (+, -, *, /, %) coded only using bitwise operators in C

texts:
Here's all the functions in C that does all the arithmetic operators without using arithmetic operators themselves, mostly using bitwise operators.  Recursive functions and comparison operators are also allowed.

int add ( int augend, int addend )
{
    return addend ? add ( augend ^ addend, ( augend & addend ) << 1 ) : augend;
}

int subtract ( int minuend, int subtrahend )
{
    return add ( minuend, add ( ~subtrahend, 1 ) );
}

int multiply_recursive ( int multiplicand, int multiplier, int product )
{
    if ( !multiplier ) return product;
    if ( multiplier & 1 ) product = add ( multiplicand, product );
    return multiply_recursive ( multiplicand << 1, (int)( (unsigned) multiplier >> 1 ),
                                product );
}

int multiply ( int multiplicand, int multiplier )
{
    return multiply_recursive ( multiplicand, multiplier, 0 );
}

int divide_recursive ( int dividend, int divisor, int size, int quotient, int remainder )
{
    if ( !size ) return quotient;
    int position = subtract ( size, 1 );
    remainder <<= 1;
    remainder |= ( dividend >> position ) & 1;
    if ( remainder >= divisor ) {
        remainder = subtract ( remainder, divisor );
        quotient |= 1 << position;
    }
    return divide_recursive ( dividend, divisor, position, quotient, remainder );
}

int abs ( int integer )
{
    int const mask = integer >> subtract ( multiply ( sizeof(int), 8 ), 1 );
    return add ( integer, mask ) ^ mask;
}

int divide ( int dividend, int divisor )
{
    int quotient = divide_recursive ( abs ( dividend ), abs ( divisor ),
                                      multiply ( sizeof(int), 8 ), 0, 0 );
    return ( dividend ^ divisor ) < 0 ? add ( ~quotient, 1 ) : quotient;
}

int mod ( int dividend, int divisor )
{
    return subtract ( dividend, multiply ( divide ( dividend, divisor ), divisor ) );
}


texts: function to check if anchor tags contain href attributes with 301

texts:
I made this function to test if the content has 301 redirections.. Please can you help me optimize it better because it's too slow
function contains_http_301_link($content, $current_site){
$pattern = '~<a(.*?)href="([^"]+)"(.*?)>~';
$links = array();
// Check if there is a url in the content
if(preg_match_all($pattern, $content, $urls)) {
    foreach($urls[0] as $url){
        // get external links

        if ( !strpos( $url, $current_site )) {                                   // Is an external link
            $vowels = array('"' ,"<a", " ", "href", "=", ">");
            $links[] = str_replace($vowels, "", $url);
        }
    }
}
foreach ($links as $link) {
    $_headers = @get_headers($link,1);
    if($_headers && strpos( $_headers[0], '301')) {
        return true;
    }
}
return false;
}


texts:
How can I write this OR statement better, allowing for growth in number of values?

var isNewFile = (progressID == 10 || progressID == 20 || progressID == 21);

I was thinking of this:

var isNewFile = progressID.Contains (10,20,21)

OR using Linq:

.Select or .Contains

Any thoughts?


texts: How to reduce responsibility of the main function in strategy pattern (python)

texts:
I am trying to make an example of Strategy design pattern in Python 3.x. Below is my code. I feel like this can be improved but I don't know how. The run methods seem to take more responsibilities for testing and executing. So does __init__ function. The class takes an external function to create an object but also:

checks if input arguments for the function process are None
loads an object if exists to avoid re-calculations
checks if user wants to create an object regardless conditions
tests if an object to return is None
returns an object.

I am wondering how this can be improved. This is the code:

class Strategy(object):
    def __init__(self, filename, forcecreate=False):
        if (filename is None) or (not isinstance(filename, str)) or (filename == ""):
            raise ValueError("File name is not set")
        self.filename = filename
        self.forcecreate = forcecreate
        self.t = None
        self.output = None

    def run(self, process, *inputs):
        if not self.forcecreate:
            self.output = self.__pre()
        if not self.output is None:
            return self.output
        # Check if objects provided are defined
        if len(inputs) > 0:
            if any([i is None for i in inputs]):
                raise ValueError("One of the objects is not set")
        self.output = process(*inputs)
        self.__post()
        return self.output

    def __pre(self):
        if (Path(self.filename).is_file()):
            print("File exists")
            with open(self.filename, 'rb') as f_handler:
                return pickle.load(f_handler)
        return None

    def __post(self):
        with open(self.filename, 'wb') as f_handler:
            pickle.dump(self.output, f_handler)

I have a set of functions which process data and return objects which contain some structured data. I also save objects in order to avoid re-calculations. If a file exists, I can just load an object and return it. The number of functions is getting higher and I end up with copy-pasting. I thought that would slightly improve my code.


texts:
Code is a countdown timer.

Should I keep this update function separate as is or can I save 3 lines of code and embed this.setState({newDeadline: event.target.value}) directly in the callback function below? eg. onChange={event => this.setState({newDeadline: event.target.value}}

import React, { Component } from 'react';
import './App.css';
import Clock from './Clock';
import {FormGroup, FormControl, Button} from 'react-bootstrap';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deadline: 'December 25 2017',
      newDeadline: ''
    }
  }

  updateDeadline() {
    if (isNaN(Date.parse(this.state.newDeadline)) || this.state.newDeadline === '') {
      this.setState({deadline: this.state.deadline});
    } else {
      this.setState({deadline: this.state.newDeadline})
    }
  }

  updateNewDeadline(event) {
    this.setState({newDeadline: event.target.value})
  }

  render() {
    return (

Countdown To {this.state.deadline}

        <Clock deadline={this.state.deadline} />
        <form className="app-form">
          <FormGroup>
            <FormControl className="deadline-input"
              placeholder='Enter a new date'
              onChange={event => this.updateNewDeadline(event)}
            />
            <Button bsStyle="primary" block onClick={() => this.updateDeadline()}>Submit</Button>
          </FormGroup>
        </form>

    )
  }
}

export default App;


texts: Script to store, search, and delete IPFS data with description in JSON file

texts:
Here is the script that I would like reviewed for the following:

Best practices and design pattern usage
Correctness in unanticipated cases
Better dictionary access

The script is made to store (IPFS) Interplanetary File System hash objects. If you would like to know more check out https://ipfs.io

Script:

#!/usr/bin/python
# PHT - Personal Hash Tracker
#
import json
import os

hashjson_global = "/Users/troywilson/testing/pht/hash.json"

choice = raw_input("What do you want to do? \n a)Add a new IPFS hash\n s)Seach stored hashes\n d)Delete stored hash\n >>")

if choice == 'a':
    # Add a new hash.
    description = raw_input('Enter hash description: ')
    new_hash_val = raw_input('Enter IPFS hash: ')
    new_url_val = raw_input('Enter URL: ')
    entry = {new_hash_val: {'description': description, 'url': new_url_val}}

    # search existing hash listings here
    if new_hash_val not in data['hashlist']:
    # append JSON file with new entry
        data['hashlist'].update(entry) #must do update since it's a dictionary
        with open(hashjson_global, 'w') as file:
            json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False)
        print('IPFS Hash Added.')
        pass
    else:
        print('Hash exist!')

elif choice == 's':
    # Search the current desciptions.
    searchTerm = raw_input('Enter search term: ')
    with open(hashjson_global, 'r') as file:
        data = json.load(file)
        hashlist = data['hashlist']
    # build dictionary map and search for description value
    d = {v['description']: h for h, v in hashlist.items()}
    print d.get(searchTerm, 'Not Found')

elif choice == 'd':
    # Search the current descriptions and delete entry.
    del_hash = raw_input('Hash to delete: ')
    with open(hashjson_global, 'r') as file:
        data = json.load(file)
    del data['hashlist'][del_hash]
    with open('hashjson', 'w') as file:
            json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False)
    print ('Hash removed')

Example JSON file:

{
"hashlist": {
"QmVZATT8jWo6ncQM3kwBrGXBjuKfifvrE": {
    "description": "Test Video",
    "url": ""
},
"QmVqpEomPZU8cpNezxZHG2oc3xQi61P2n": {
    "description": "Cat Photo",
    "url": ""
},
"QmYdWb4CdFqWGYnPA7V12bX7hf2zxv64AG": {
    "description": "test.co",
    "url": ""
}
}
}%


texts: Views Counter made in Python, Gevent and MongoDB

texts:
I've created a Views Counter in Python, Gevent and MongoDB (Flask is also included in the full stack as you can see from the context issue in the code).

My gut still tells me that it can be still somehow improved though.

What the code does is initializing a dict "buffer" (just a shelve persisted in memory [no writeback]), define a function where Mongo's bulk_op is initialized, a list comprehension that iterates over the view_count buffer and sets individual find-updates for them with their respective key values that is then ended by an execute with write concern disabled.

Then there's the run_buffer_op function that runs a loop infinitely, which checks if the buffer has over 5000 items, and in that case, flushes its content to the database (by executing the former function), otherwise it just waits 15 minutes before flushing.

This function is finally run (or better, spawned) by Gevent.

Do you see some possible further improvements?

'''
Views counter buffer
====================
'''
# Initialize vc buffer (ObjectId + Views_count pair). We don't need **writeback** as it should just be persisted in memory
view_count=shelve.open('view_count', writeback=False)

def flush_to_db():
  # Apparently you have to set the context to make the db bulk operation work, otherwise it'll return a *Working outside of context* error :(
  with app.app_context():
    bulk = mongo.db.test.initialize_unordered_bulk_op()
    # What this list comprehension does is iterating over the *view_count* buffer
    # and set individual find-updates for them with their respective key value.
    # Like: bulk.find({'_id': '7rhf3d32dh23jd78988ej8'}).update({'$set':{'count':2}})
    #       bulk.find({'_id': '7rhf3d32dh23dg48988ej8'}).update({'$set':{'count':10}})
    #       bulk.find({'_id': '7rhf3d32th23dg48988ek9'}).update({'$set':{'count':7}})
    #       ...

    [bulk.find({ '_id': k }).update({'$set':{'count': v }}) for k,v in view_count.iteritems()]

    # Execute the bulk update with no **write concern**. We can afford to lose some views count if that ever happens in change of better performance.
    bulk.execute(write_concern=None)

def run_buffer_op():
  # Run the loop infinitely
  while True:
    # If buffer has more than 5000 items flush it now to the db
    if len(view_count) > 5000:
      flush_to_db()
    # Else just wait 15 minutes
    gevent.sleep(900)
    flush_to_db()

# Spawn the loop
gevent.spawn(run_buffer_op)


texts:
The code is supposed to group start and end time logs and provide log counts and unique ID counts. The grouping will be variable 1 hour, 6 hours, 12 hours, 24 hours, etc.

What is the better way to rewrite the simpler version for this code?

Input: No of day reamins 'x' in inputs.

import pandas as pd

fn = r'Dart.csv'
df = pd.read_csv(fn)

df['m'] = df.StopTime + df.StartTime
df['d'] = df.StopTime - df.StartTime

#df.StartTime = pd.to_datetime(df.StartTime, unit='s')
#df.StopTime = pd.to_datetime(df.StopTime, unit='s')
# 'start' and 'end' for the reporting DF: `r`
# which will contain equal intervals (1 hour in this case)

start = pd.to_datetime(df.StartTime.min(), unit='s').date()
end = pd.to_datetime(df.StopTime.max(), unit='s').date() + pd.Timedelta(days=1) #change this to 'n'

# building reporting DF: `r`
freq = '1H'
idx = pd.date_range(start, end, freq=freq)
r = pd.DataFrame(index=idx)
r['start'] = (r.index - pd.datetime(1970,1,1)).total_seconds().astype(np.int64)

interval = 60*60 - 1

r['LogCount'] = 0
r['UniqueIDCount'] = 0

# counting ...
for i, row in r.iterrows():
    # intervals overlap test
    # https://en.wikipedia.org/wiki/Interval_tree#Overlap_test
    # i've slightly simplified the calculations of m and d
    # by getting rid of division by 2,
    # because it can be done eliminating common terms

    mask = np.abs(df.m - 2*row.start - interval) < df.d + interval
    r.ix[i, ['LogCount', 'UniqueIDCount']] = [len(df[mask]), df[mask].UserID.nunique()]

r['Day'] = pd.to_datetime(r.start, unit='s').dt.dayofweek
r['StartTime'] = pd.to_datetime(r.start, unit='s').dt.time
r['EndTime'] = pd.to_datetime(r.start + interval + 1, unit='s').dt.time

print(r[r.LogCount > 0])

Logs:

UserID, StartTime, StopTime, GPS1, GPS2
00022d9064bc,1073260801,1073260803,819251,440006
00022d9064bc,1073260803,1073260810,819213,439954
00904b4557d3,1073260803,1073261920,817526,439458
00022de73863,1073260804,1073265410,817558,439525
00904b14b494,1073260804,1073262625,817558,439525
00022d1406df,1073260807,1073260809,820428,438735
00022d9064bc,1073260801,1073260803,819251,440006
00022dba8f51,1073260801,1073260803,819251,440006
00022de1c6c1,1073260801,1073260803,819251,440006
003065f30f37,1073260801,1073260803,819251,440006
00904b48a3b6,1073260801,1073260803,819251,440006
00904b83a0ea,1073260803,1073260810,819213,439954
00904b85d3cf,1073260803,1073261920,817526,439458
00904b14b494,1073260804,1073265410,817558,439525
00904b99499c,1073260804,1073262625,817558,439525
00904bb96e83,1073260804,1073265163,817558,439525
00904bf91b75,1073260804,1073263786,817558,439525


texts: Computer Science glossary made with Tkinter

texts:
This is a Computer science glossary that I made with Tkinter. The user inputs the word that they want and then the code searches the text file for it and then ouputs it to the user.

#My Computer Scienece Glossary project

from tkinter import *

#key down function
def click():
    global definition
    entered_text=textentry.get() #this will collect the text from the text entry box
    output.delete(0.0, END)
    try:
        definition = my_compdictonary[entered_text]
    except:
        definition = "Sorry defintion not found"
    output.insert(END, definition)

### main:
window = Tk()
window.title("Computer Science Glossary")
window.configure(background="black")

### My Photo
photo1 = PhotoImage(file="me.gif")
Label(window,image=photo1, bg="black") .grid(row=0, column=0, sticky=W)

#create label
Label(window, text="Enter the word you want the definition for:",bg="black", fg="white", font="none 12 bold").grid(row=1, column=0, sticky=N)

#create a text entry box
textentry = Entry(window, width=20, bg="white")
textentry.grid(row=2, column=0, sticky=N)

#add a submit button
Button(window, text="SUBMIT", width=6, command=click).grid(row=3, column=0, sticky=N)

#create another label
Label(window, text="\nDefinition:", bg="black", fg="white", font="none 12 bold").grid(row=4, column=0, sticky=N)

#create a textbox
output = Text(window, width=60, height=4, wrap=WORD, background="white")
output.grid(row=5, column=0, columnspan=1, sticky=N)

#the dictionary
my_compdictonary = {}
with open("glossary.txt", "r+") as file:
    for line in file:
        word, defintions = line.strip().split(" : ")
        my_compdictonary[word] = defintions

window.mainloop()

I want suggestions on how I can make this computer science glossary better.

All suggestions will be greatly appreciated.


texts:
My AsyncDetector is internally using a Stopwatch to calculate time intervals. Because of this hardcoded dependency I am not able to write good unit-tests for it. So I must be able to use my own timestamps that I can use for assertions.

To do this I defined the IStopwatch interface that is a simplified version of the Stopwatch. Some of the properties I never use and my inteface does not provide them.

public interface IStopwatch
{
    bool IsRunning { get; }
    TimeSpan Elapsed { get; }
    IStopwatch Start();
    IStopwatch Stop();
    IStopwatch Restart();
    IStopwatch Reset();
}

Its default implementation is using of course the original Stopwatch so I provide it just for reference:

public class SystemStopwatch : IStopwatch
{
  private readonly Stopwatch _stopwatch;

  public SystemStopwatch()
  {
      _stopwatch = new Stopwatch();
  }

  public bool IsRunning => _stopwatch.IsRunning;

  public TimeSpan Elapsed => _stopwatch.Elapsed;

  public static IStopwatch StartNew()
  {
      return new SystemStopwatch().Start();
  }

  public IStopwatch Start()
  {
      _stopwatch.Start();
      return this;
  }

  public IStopwatch Stop()
  {
      _stopwatch.Stop();
      return this;
  }

  public IStopwatch Restart()
  {
      _stopwatch.Restart();
      return this;
  }

  public IStopwatch Reset()
  {
      _stopwatch.Restart();
      return this;
  }

  public override string ToString()
  {
      return _stopwatch.Elapsed.ToString();
  }
}

More interesing is the DebugStopwatch that will enumerate my timestamps on each access to the Elapsed property or it'll throw if there are not enough of them:

public class DebugStopwatch : IStopwatch
{
    private readonly IEnumerable<TimeSpan> _timestamps;
    private TimeSpan? _lastElapsed;
    private IEnumerator<TimeSpan> _enumerator;

    public DebugStopwatch([NotNull] IEnumerable<TimeSpan> elapses)
    {
        _timestamps = elapses ?? throw new ArgumentNullException(nameof(elapses));
    }

    public bool IsRunning { get; private set; }

    public TimeSpan Elapsed
    {
        get
        {
            if (IsRunning)
            {
                if (_enumerator.MoveNext())
                {
                    return (_lastElapsed = _enumerator.Current).Value;
                }

                throw new InvalidOperationException("You did not define enough timestamps.");
            }

            return _enumerator?.Current ?? _lastElapsed ?? TimeSpan.Zero;
        }
    }

    public static IStopwatch StartNew(IEnumerable<TimeSpan> elapses)
    {
        return new DebugStopwatch(elapses).Start();
    }

    public IStopwatch Start()
    {
        if (IsRunning)
        {
            return this;
        }
        _enumerator = _timestamps.GetEnumerator();
        IsRunning = true;
        return this;
    }

    public IStopwatch Stop()
    {
        IsRunning = false;
        return this;
    }

    public IStopwatch Restart()
    {
        Stop();
        Reset();
        Start();
        return this;
    }

    public IStopwatch Reset()
    {
        _enumerator = _timestamps.GetEnumerator();
        return this;
    }

    public override string ToString()
    {
        return (_lastElapsed ?? TimeSpan.Zero).ToString();
    }
}

Example Using it is very easy. I just need to provide a collection or enumeration with timestamps:

void Main()
{

    var stopwatch = DebugStopwatch.StartNew(Enumerable.Range(0, 10).Select(i => TimeSpan.FromSeconds(i)));

    stopwatch.Dump();
    stopwatch.Dump();
    stopwatch.Dump();

    stopwatch.Stop().Dump(nameof(IStopwatch.Stop));
    stopwatch.Dump();
    stopwatch.Dump();

    stopwatch.Reset().Dump(nameof(IStopwatch.Reset));
    stopwatch.Dump();
    stopwatch.Dump();
}

What do you think of the DebugStopwatch? Would you change anything about it? If so, how would you improve it?


texts:
I've just created a method that toggles menu visibility. At the moment I've gone with an if..else which checks my flag and acts appropriately. Can anyone offer any suggestions on how to make this snippet better? Maybe it shouldn't all live in the same snippet? Maybe I should be combining the show/hide logic that's duplicated in the if..else?

onNavTriggerClick: function(event) {

            var $currentTarget = $(event.currentTarget);

            if(this._navOpen) {
                Backbone.Events.trigger('hide:menu');
                $currentTarget.removeClass('is-active');
                this._navOpen = false;
            } else {
                Backbone.Events.trigger('show:menu');
                $currentTarget.addClass('is-active');
                this._navOpen = true;
            }
        }


texts: Norms, rules or guidelines for calculating and showing ETA/ETC for a process

texts:
ETC = "Estimated Time of Completion"

I'm counting the time it takes to run through a loop and showing the user some numbers that tells him/her how much time, approximately, the full process will take. I feel like this is a common thing that everyone does on occasion and I would like to know if you have any guidelines that you follow.

Here's an example I'm using at the moment:

int itemsLeft; //This holds the number of items to run through.
double timeLeft;
TimeSpan TsTimeLeft;
list<double> avrage;
double milliseconds; //This holds the time each loop takes to complete, reset every loop.

//The background worker calls this event once for each item. The total number
//of items are in the hundreds for this particular application and every loop takes
//roughly one second.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //An item has been completed!

    itemsLeft--;
    avrage.Add(milliseconds);

    //Get an avgrage time per item and multiply it with items left.
    timeLeft = avrage.Sum() / avrage.Count * itemsLeft;
    TsTimeLeft = TimeSpan.FromSeconds(timeLeft);

    this.Text = String.Format("ETC: {0}:{1:D2}:{2:D2} ({3:N2}s/file)",
        TsTimeLeft.Hours,
        TsTimeLeft.Minutes,
        TsTimeLeft.Seconds,
        avrage.Sum() / avrage.Count);

    //Only using the last 20-30 logs in the calculation to prevent an unnecessarily long List<>.
    if (avrage.Count > 30)
        avrage.RemoveRange(0, 10);

    milliseconds = 0;
}

//this.profiler.Interval = 10;
private void profiler_Tick(object sender, EventArgs e)
{
    milliseconds += 0.01;
}

As I am a programmer at the very start of my career I'm curious to see what you would do in this situation. My main concern is the fact that I calculate and update the UI for every loop, is this bad practice?

Are there any do's/don't's when it comes to estimations like this? Are there any preferred ways of doing it, e.g. update every second, update every ten logs, calculate and update UI separately? Also when would an ETA/ETC be a good/bad idea.


texts: Leaving out the max value in an Enumeration

texts:
This is part of a school assignment and I came up with the following solution to leave out the max value in a Enumeration:

static void Opdracht3()
{
    List<int> values = new List<int>();
    foreach (int value in Enum.GetValues(typeof(Opleidingen)))
    {
        values.Add(value);
    }

    foreach (int value in values)
    {
        if (value != values.Max())
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}

How could I improve this piece of (working) code?


texts: Apply smiley replacement filter to Pandoc but not in code segments

texts:
I wrote a filter for pandas that converts :-) to ☺ but not in inline code or code blocks. Pandoc makes it so the applyExceptOnCodeBlock smileyfy function trickles through the whole tree. But since I operate on Blocks and Inlines I need to handle every data constructor for Block that takes Inlines.

import Text.Pandoc.JSON
import Text.Pandoc.Walk

import Data.List (intercalate)
import Data.List.Split (splitOn)

main :: IO ()
main = toJSONFilter $ applyExceptOnCodeBlock smileyfy

smileyfy :: String -> String
smileyfy = intercalate "☺" . splitOn ":-)"

applyExceptOnCodeInline :: (String -> String) -> Inline -> Inline
applyExceptOnCodeInline f (Str s)       = Str (f s)
applyExceptOnCodeInline f (Code attr s) = Code attr s -- for code nothing shall happen
applyExceptOnCodeInline _ x = x

applyExceptOnCodeBlock :: (String -> String) -> Block -> Block
applyExceptOnCodeBlock f (Plain is) = Plain $ applyExceptOnCodeInline f <$> is
applyExceptOnCodeBlock f (Para  is) = Para  $ applyExceptOnCodeInline f <$> is
applyExceptOnCodeBlock f (LineBlock iss) = LineBlock $ (fmap . fmap) (applyExceptOnCodeInline f) iss
applyExceptOnCodeBlock f (RawBlock format s)  = RawBlock format $ f s
applyExceptOnCodeBlock f (DefinitionList [(is, bss)]) = DefinitionList [(applyExceptOnCodeInline f <$> is
                                                                        ,fmap (fmap (applyExceptOnCodeBlock f)) bss)]
applyExceptOnCodeBlock f (Header i attr is) = Header i attr $ applyExceptOnCodeInline f <$> is
applyExceptOnCodeBlock f (Table is as ds tcs tcss) = Table (applyExceptOnCodeInline f <$> is) as ds tcs tcss
applyExceptOnCodeBlock _ x = x --this covers CodeBlock as well

And thus it looks very convoluted. Is there a clearer way to express this?


texts: Counting Neighbors (Why scipy.signal.convolve2D so fast?)

texts:
Here is my Python implementation of counting neighbours of Game of Life with radius as parameter.

def neighbors_count(n2d_array, radii=1):
    assert n2d_array.ndim == 2
    row_len, col_len = n2d_array.shape
    nbrs_count = np.zeros_like(n2d_array)
    for row_idx, row_val in enumerate(n2d_array):
         for col_idx, col_val in enumerate(row_val):
             start_row = 0 if (row_idx-radii) < 0 else (row_idx-radii)
             end_row = row_len if (row_idx+radii+1) > row_len else (row_idx+radii+1)
             start_col = 0 if (col_idx-radii) < 0 else (col_idx-radii)
             end_col = row_len if (col_idx+radii+1) > row_len else (col_idx+radii+1)
             neighbor = 0
             for block_row_idx in np.arange(start_row, end_row):
                 for block_col_idx in np.arange(start_col, end_col):
                     neighbor += n2d_array[block_row_idx, block_col_idx]
             nbrs_count[row_idx, col_idx] = neighbor - n2d_array[row_idx, col_idx]
     return nbrs_count

I found out that my implementation is very slow compared to scipy.signal.convolve2d:

def neighbors_count2(n2d_array, radii=1):
    from scipy.signal import convolve2d
    diameter = 2 * radii + 1
    n2d_array = n2d_array.astype(bool)
    nbrs_count = convolve2d(n2d_array, np.ones((diameter, diameter)),
                            mode='same', boundary='fill') - n2d_array
    return nbrs_count

Here is %timeit result in my computer:

%timeit -n 10 neighbors_count(np.random.randint(2, size=(100,100)))
10 loops, best of 3: 232 ms per loop

%timeit -n 10 neighbors_count2(np.random.randint(2, size=(100,100)))
10 loops, best of 3: 963 µs per loop

How to improve/vectorize my code so it can run faster than scipy.signal.convolve2d?


texts:
I'm a noobie in programming so I've made a simple hangman game in python and I'd like someone to tell me how I could improve the code.

edit:How could I do it using classes?

from sys import exit

def makeGallow(gallow):
        for i in range(8):
            gallow.append([])
        gallow[0].append(6 * '_')
        gallow[1].append(' |   |')
        for i in range(2, 7):
            gallow[i].append('     |')
        gallow[7].append(11 * '-')

gallow = list()
secret_word = raw_input("Choose a word: ").lower()
secret_wordls = list()
letters = len(secret_word)
for c in secret_word:
    secret_wordls.append(c)
blanks = list()
for i in range(len(secret_word)):
    blanks.append('_')
lettersUsed = list()
tries = 0
makeGallow(gallow)

while True:

    for i in gallow:
        print "".join(i)
    print "".join(i for i in blanks)
    used = ", ".join(i for i in lettersUsed)
    print "Letters used: " + used
    letter = raw_input("Type a letter: ").lower()
    if letter == 'quit':
        exit(1)
    elif letter in secret_word:
        letters -= 1
        if letters == 0:
            print "You won!"
            exit("Bye!")
        else:
            switch = secret_wordls.index(letter)
            blanks[switch] = letter
    elif letter not in secret_word:
        print "Wrong!"
        tries += 1
        lettersUsed.append(letter)
        if tries == 1:
            gallow[2] = ' O   |'
        elif tries == 2:
            gallow[3] = ' |   |'
        elif tries == 3:
            gallow[3] = '/|   |'
        elif tries == 4:
            gallow[3] = '/|\  |'
        elif tries == 5:
            gallow[4] = ' |   |'
        elif tries == 6:
            gallow[5] = '/    |'
        elif tries == 7:
            gallow[5] = '/ \  |'
            print "Sorry you lost :(."
            print "The word was: " + secret_word
            exit("Bye!")
    elif letter in lettersUsed:
        print "You have already typed that letter!"
        print "Try another one."

edit2: I found a bug where if the work had 2, 3... times the same letter it would count as one and you couldn't win. I change the while loop:

while True:

    for i in gallow:
        print "".join(i)
    print "".join(i for i in blanks)
    used = ", ".join(i for i in lettersUsed)
    print "Letters used: " + used
    letter = raw_input("Type a letter: ").lower()
    if letter == 'quit':
        exit("Bye")
    elif letter in secret_word:
        for i in range(secret_wordls.count(letter)):
            switch = secret_wordls.index(letter)
            blanks[switch] = letter
            secret_wordls[switch] = '-'
            letters -= 1
    elif letter not in secret_word:
        print "Wrong!"
        tries += 1
        lettersUsed.append(letter)
        if tries == 1:
            gallow[2] = ' O   |'
        elif tries == 2:
            gallow[3] = ' |   |'
        elif tries == 3:
            gallow[3] = '/|   |'
        elif tries == 4:
            gallow[3] = '/|\  |'
        elif tries == 5:
            gallow[4] = ' |   |'
        elif tries == 6:
            gallow[5] = '/    |'
        elif tries == 7:
            gallow[5] = '/ \  |'
            print "Sorry you lost :(."
            print "The word was: " + secret_word
            exit("Bye!")
    elif letter in lettersUsed:
        print "You have already typed that letter!"
        print "Try another one."
    if letters == 0:
        print "You won!"
        exit("Bye!")


texts: RPi script to periodically collect data from Arduino through serial port

texts:
I'm not used to Python.

The script opens serial communications with an Arduino unit and send commands to and receives information from the Arduino. It is intended to run indefinitely until the system is shut down or pulled out of field deployment/laboratory testing.

The time.sleep() calls with offsets are assurances that repeated calls won't eventually result to time drifts, as mentioned in this Stack Overflow Q/A. I don't trust myself with this. I need confirmation that I placed the start_time = time.time() lines in proper locations. This time drift issue is crucial because the script shall run for months.

read_data() sends a command to the Arduino, which tells it to give the Pi new data. Data sets written by the Arduino vary in length, so I can't use serial.read(expected_bytecount). Data sent between start and stop bytes (e.g. *data1,data2,data3#) is always valid, so I don't need to do checks there. Is my algorithm here enough for my task?

wait_until_sampling() keeps the Pi from being busy around the clock. Reading data occurs every 15th and 45th minutes of an hour. I thought of using minutes % 15 != 0, but there are the 0th and 30th marks. I also tried doing away with datetime but I can't get the minutes of the system time from time. Is there a simple way to improve this algorithm by dropping datetime?

import datetime
import time
import serial

def read_data():
    data = []
    start_time = time.time()
    arduino.write(b'S')
    time.sleep(360.0 - ((time.time() - start_time) % 360.0))
    while True:
        temp = arduino.read().decode(encoding='UTF-8')
        if temp  == "*":
            while True:
                temp = arduino.read().decode(encoding='UTF-8')
                if temp == "#":
                    break
                else:
                    data.append(temp)
            break
    return data

def wait_until_sampling():
    start_time = time.time()
    dt_now = datetime.datetime.now().time()
    while (dt_now.minute != 45) and (dt_now.minute != 15):
            time_now = time.time()
            dt_now = datetime.datetime.now().time()
            time.sleep(1.0 - ((time_now - start_time) % 1.0))

arduino = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(20.0)
data_returned = []
while True:
        wait_until_sampling()
        data_returned = read_data()
        # post-process data_returned here


texts:
I have the following code for taking a date in the form of a string yyyy-MM-dd HH:mm:ss (UTC timezone) and turning it into EEEE d(st, nd, rd, th) MMMM yyyy HH:mm (devices default timezone).

However, my problem with the way I have done it is the code looks messy and inefficient. Is there a way to achieve what I want without formating and parsing the same date so many times to make it more efficient? Or any other improvements?

Preferably supporting Android API level 14.

String inputExample = "2017-06-28 22:44:55";

//Converts UTC to Device Default (Local)
private String convertUTC(String dateStr) {
    try {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date temp = df.parse(dateStr);
        df.setTimeZone(TimeZone.getDefault());
        String local = df.format(temp);
        Date localDate = df.parse(dateStr);
        SimpleDateFormat outputDF1 = new SimpleDateFormat("EEEE ");
        SimpleDateFormat outputDF2 = new SimpleDateFormat(" MMMM yyyy HH:mm");
        return outputDF1.format(temp) + prefix(local) + outputDF2.format(temp);
    } catch(java.text.ParseException pE) {
        Log.e("", "Parse Exception", pE);
        return null;
    }
}

private String prefix(String dateStr) {
    try {
        SimpleDateFormat outputDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date temp = outputDF.parse(dateStr);
        SimpleDateFormat df = new SimpleDateFormat("d");
        int d = Integer.parseInt(df.format(temp));
        if(1 <= d && d <= 31) {
            if(11 <= d && d <= 13)
                return d + "th";
            switch (d % 10) {
                case 1: return d + "st";
                case 2: return d + "nd";
                case 3: return d + "rd";
                default: return d + "th";
            }
        }
        Log.e("", "Null Date");
        return null;
    } catch(java.text.ParseException pE) {
        Log.e("", "Parse Exception", pE);
        return null;
    }
}


texts:
On the Beme app, while a video plays, the border acts a progress bar, filling from upper left to upper right to lower right to lower left.  I want to achieve that.  And I have, but my code is incredibly messy.  I don't like the repetitive checks and -='s.  Is there anyway to trim that fat from the code?  If you update the progress bar's current progress attribute, it will update how many sides has a colored border.

$(".squareProgress")
 .append("

")
 .change(function () {
  $(this).trigger("updateProgress");
 })
 .on("updateProgress", function () {
  max = $(window).width()*2 + $(window).height()*2 - 30;
  progress = max*(parseInt($(this).attr("progress"))/100);
  $(this).find("li").eq(0).width(progress > $(window).width() ? $(window).width() : progress);
  progress -= $(window).width();
  $(this).find("li").eq(1).height(progress > $(window).height() ? $(window).height() : progress);
  progress -= $(window).height();
  $(this).find("li").eq(2).width(progress > $(window).width() ? $(window).width() : progress);
  progress -= $(window).width();
  $(this).find("li").eq(3).height(progress > $(window).height() ? $(window).height() : progress);
  progress -= $(window).height();
 })
 .trigger("change");
body {
 padding:0;
 margin:0;
}

.sqaureProgress {
 position:absolute;
 width:100%;
 height:100%;
}

.squareProgress ul {
 padding:0;
 margin:0;
 list-style-type:none;
}

.squareProgress ul li {
 position:absolute;
}

.squareProgress ul li:nth-child(1) {
 left:0;
 top:0;
 width:calc(100% - 10px);
 height:10px;
 background:blue;
}

.squareProgress ul li:nth-child(2) {
 right:0;
 top:0;
 height:calc(100% - 10px);
 width:10px;
 background:red;
}

.squareProgress ul li:nth-child(3) {
 right:0;
 bottom:0;
 width:calc(100% - 10px);
 height:10px;
 background:green;
}

.squareProgress ul li:nth-child(4) {
 left:0;
 bottom:0;
 height:calc(100% - 10px);
 width:10px;
 background:yellow;
}


texts: Grouping consecutive numbers into ranges in Python 3.2 : New version for set

texts:
def range_find(pageset,upperlimit=1000):

    pagerangelist=[]

    for page in range(0,upperlimit):

        if page in pageset and previouspage in pageset:pagerangelist[-1].append(page)
        elif page in pageset and not (previouspage in pageset):pagerangelist.append([page])
        else: pass

        previouspage=page

    pagerangestringlist=[]

    for pagerange in pagerangelist:

        pagerangestringlist.append(str(pagerange[0])+('-'+str(pagerange[-1]))*((len(pagerange)-1)>0))

    return(','.join(pagerangestringlist))

print(range_find({1,2,5,7,8,11,19,25,29,30,31,39,40,41,42,43,44,56,57,59,60,70,71,72,100,101,103,104,105}))


texts: k-combinations in lexicographic order (using given algorithm)

texts:
I already solved the problem, but it seems my code is too awkward, and with a different approach there could be a more elegant solution.
Notice that the general algorithm is described in the instructions:

This is the problem description:

  Given unsigned integers 0 ≤ k ≤ n, generate all the k-combinations of
  the n objects, numbered 1, 2, ... , and n, using the following
  algorithm:

  Starting with the combination 1, 2, ..., k, the next combination is
  found by scanning the current combination from right to left so as to
  locate the rightmost element that has not yet attained its maximum
  value. This element is incremented by one, and all positions to its
  right are reset to the lowest values possible.

  Each line contains a set of n and k which separated with at least one
  space.

  For each case, the first line is a prompt as following: “case 1:”. The
  next lines are all of the combinations. Notice that one line for one
  combination and list the results in ascending order. You don’t have to
  print any thing if the result is null. The last line of each case is
  an empty line, even if the result is null.

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

int combination_find(std::vector<int> combination, int max_val);
void combination_inc(std::vector<int>& combination, const int& pos, const int& max_val);

int main()
{
    int round = 0;
    int n, k;
    while (std::cin >> n >> k)
    {
        //init
        std::vector<int> combination;
        int i = 0;
        while (i < k)
        {
            combination.push_back(++i);
        }
        std::cout << "case " << ++round << ": " << std::endl;
        while(1)
        {
            //writes (upon conditional so that the print of empty vectors doesn't mess up the text formatting0
            if (!combination.empty())
            {
                std::copy(combination.begin(), combination.end(), std::ostream_iterator<int>(std::cout, " "));
                            std::cout << std::endl;
            }
            //check
            int pos = combination_find(combination, n);
            if (pos < 0) {break;}
            //increment
            combination_inc(combination, pos, n);
        }
        std::cout << std::endl;
    }
}

int combination_find(std::vector<int> combination, int max_val)
{
    if (combination.empty()) { return -1; }
    if (combination.back() != max_val)
    {
        return (combination.size() - 1);
    }
    else
    {
        combination.pop_back();
        return combination_find(combination, --max_val);
    }
}

void combination_inc(std::vector<int>& combination, const int& pos, const int& max_val)
{
    int val = combination[pos];
    for (unsigned i = pos; i < combination.size(); ++i)
    {
        combination[i] = ++val;
    }
}


texts: Graph representation using adjacency list for BFS, DFS, and Karger's algorithm

texts:
I want to implement some graph algorithms for learning purposes (e.g BFS, DFS, Karger's min-cut algo) and before diving into them I want to make sure I have got the graph representation right (using an adjacency list). I want to keep things minimum to exactly what I need to implement these algorithms on undirected graphs for the time being.

Here's my Vertex class:

public final class Vertex {
    private final int label;
    private VertexColor color = VertexColor.WHITE;
    private int distance;
    private Vertex parent;

    public Vertex(int label, int distance, Vertex parent) {
        this(label);
        this.distance = distance;
        this.parent = parent;
    }

    public Vertex(int label) {
        this.label = label;
    }

    public int getLabel() {
        return label;
    }

    public VertexColor getColor() {
        return color;
    }

    public void setColor(VertexColor color) {
        this.color = color;
    }

    public Vertex getParent() {
        return parent;
    }

    public void setParent(Vertex parent) {
        this.parent = parent;
    }

    public int getDistance() {
        return distance;
    }

    public void setDistance(int distance) {
        this.distance = distance;
    }

    @Override
    public String toString() {
        return "Vertex{" +
                "label=" + label +
                ", color=" + color +
                ", distance=" + distance +
                ", parent=" + parent +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Vertex vertex = (Vertex) o;

        if (label != vertex.label) return false;
        if (distance != vertex.distance) return false;
        if (color != vertex.color) return false;
        return !(parent != null ? !parent.equals(vertex.parent) : vertex.parent != null);

    }

    @Override
    public int hashCode() {
        int result = label;
        result = 31 * result + (color != null ? color.hashCode() : 0);
        result = 31 * result + distance;
        result = 31 * result + (parent != null ? parent.hashCode() : 0);
        return result;
    }
}

My VertexColor enum:

public enum VertexColor {
    WHITE, GREY, BLACK
}

My adjacency list implementation:

public class SimpleAdjacencyList {
    private Map<Integer, List<Vertex>> adjacencyList = new HashMap<>();

    /**
     * Initializes a new graph from a file.
     * @param file format should be:
     * 1    2   4
     * 2    3   1
     * 3    2   4
     * 4    3   1
     */
    public SimpleAdjacencyList(String file) {
        String line;
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                String[] numbers = line.trim().split("(\\s)+");
                int key = Integer.parseInt(numbers[0]);
                List<Vertex> vertices = new ArrayList<>(numbers.length);
                Vertex parent = new Vertex(key);
                vertices.add(parent);
                for(int i = 1; i < numbers.length; i++){
                    int label = Integer.parseInt(numbers[i]);
                    vertices.add(new Vertex(label, 0, null));
                }
                adjacencyList.put(key, vertices);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "SimpleAdjacencyList{" +
                "adjacencyList=" + adjacencyList +
                '}';
    }

    public Map<Integer, List<Vertex>> getAdjacencyList() {
        return adjacencyList;
    }

    // TODO: remove this
    public static void main(String[] args) {
        SimpleAdjacencyList list = new SimpleAdjacencyList("/Users/orestis/Documents/test.txt");
        System.out.println(list);
    }
}


texts: Webpack loader for Phaser.io asset files

texts:
The following is a webpack loader for Phaser asset files.  The way this is supposed to work is that it looks at the json string, and finds all of values with "url" keys in the json object, and transforms that value to a function call with that value as the parameter.  I need to assume any level of nesting of the json values.

module.exports = function(source){
  this.cacheable();  //comment this line out to run standalone outside webpack loader context
  var s = source;
  var re = /"url":\s*\".*,/g;
  var m;
  do {
    m = re.exec(source);
    if (!!m) {
      var path = m[0].split(':')[1].trim().slice(0, -1);
      s = s.replace(path, 'require(' + path + ')');
   }
  } while (m);
  return s;
}

For example, the source could be the following as the parameter to the function (as a string)

{
    "level1": [{
            "type": "image",
            "key": "starwars",
            "url": "assets/pics/unknown-the_starwars_pic.png",
            "overwrite": false
        },{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ],
    "level2": [{
            "type": "image",
            "key": "spaceship",
            "url": "assets/pics/spaceship.png",
            "overwrite": false
        }
    ]
}

and the return value would be a string of the following

{
    "level1": [{
            "type": "image",
            "key": "starwars",
            "url": require("assets/pics/unknown-the_starwars_pic.png"),
            "overwrite": false
        },{
            "type": "image",
            "key": "spaceship",
            "url": require("assets/pics/spaceship.png"),
            "overwrite": false
        }
    ],
    "level2": [{
            "type": "image",
            "key": "spaceship",
            "url": require("assets/pics/spaceship.png"),
            "overwrite": false
        }
    ]
}

How might I implement this in a more clear way that accounts for any nesting of the json objects?


texts:
Having a view (grid control) that provides some functionallity via methods (primary SerializeView / DeserializeView) that should be called from the view model which is bound to the view.

One point to consinder is, that the view model may not be bound to the view during the deserialization process. Therefore, the serialization state of the view must be buffered in the view model and applied when the view model will be bound to the view.

The following solution can handle such use cases in general:

Implementation

IViewAwareViewModel interface that must be implemented by the view model:

public interface IViewAwareViewModel<TView> where TView : class
{
    ViewConnection<TView> ViewConnection { get; }
}

ViewConection that encapsulates the view and provides "delayed access".

public class ViewConnection<TView> where TView : class
{
    private TaskCompletionSource<TView> taskCompletionSource = new TaskCompletionSource<TView>();

    public Task<TView> View => this.taskCompletionSource.Task;

    public bool IsConnected => this.taskCompletionSource.Task.IsCompleted;

    public void Release()
    {
        this.taskCompletionSource = new TaskCompletionSource<TView>();
    }

    public void RunOnView(Action<TView> action)
    {
        this.View.ContinueWith(task => action(task.Result));
    }

    internal void SetView(TView view)
    {
        if (this.IsConnected)
        {
            throw new InvalidOperationException("Unable to connect to a view twice.");
        }
        this.taskCompletionSource.SetResult(view);
    }
}

ViewConnector that provides a helper method for connecting the view with the view model.

public static class ViewConnector<TView> where TView : class
{
    public static void Register(FrameworkElement target)
    {
        if (target == null)
        {
            throw new ArgumentNullException(nameof(target));
        }

        if (!typeof(TView).IsInstanceOfType(target))
        {
            throw new InvalidOperationException($"Object of type '{target.GetType()}' is not compatible to type '{typeof(TView)}'.");
        }

        target.DataContextChanged += TargetDataContextChanged;
    }

    private static void TargetDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var oldViewModel = e.OldValue as IViewAwareViewModel<TView>;
        var newViewModel = e.NewValue as IViewAwareViewModel<TView>;

        if (oldViewModel != null)
        {
            oldViewModel.ViewConnection?.Release();
        }

        if (newViewModel != null)
        {
            newViewModel.ViewConnection.SetView(sender as TView);
        }
    }
}

Usage

View Registration

var dataGrid = new MyDataGrid(); // implements: IDataGridAbstractionForViewModel
ViewConnector<IDataGridAbstractionForViewModel>.Register(dataGrid);

ViewModel Implementaion

public class DataGridViewModel : ViewModelBase, IViewAwareViewModel<IDataGridAbstractionForViewModel>
{
    public ViewConnection<IDataGridAbstractionForViewModel> ViewConnection { get; } = new ViewConnection<IDataGridAbstractionForViewModel>();

    protected override string SerializeState()
    {
        if (this.ViewConnector.IsConnected)
        {
            var view = this.ViewConnection.View.Result;
            return view.SaveLayout();
        }

        return string.Empty;
    }

    protected override void DeserializeState(string state)
    {
        base.DeserializeState(state);

        if (string.IsNullOrEmpty(state))
        {
            return;
        }

        this.ViewConnection.RunOnView(view => view.RestoreLayout(state));

    }

    protected override void OnRemoved()
    {
        base.OnRemoved();

        this.ViewConnection.Release();
    }
}

Questions

Are there other cleaner solutions / approaches?
Do you see any risk of memory leaks?
General feedback? :)


texts:
How many different ways can 200 be made using any number of coins? The possible denominations are 1, 2, 5, 10, 20, 50, 100, 200.

-module(coins).
-export([coins/2]).

coins(_, 0) -> 1;
coins([], _) -> 0;
coins(_, Goal) when Goal < 0 -> 0;
coins([H|T], Goal) ->
  coins([H|T], Goal-H) + coins(T, Goal).

The call is:

1> c(coins).
2> coins:coins([1, 2, 5, 10, 20, 50, 100, 200], 200).
73682


texts:
I have been working with Ruby for about a week or two now, and I wanted to create a dice-rolling application that intakes any string (e.g. 1d4 + 1 or 3d20 + 4) and outputs the correct dice rolling.

def roll(amount = 0, sides = 0)
    #this is the function that gets a random roll with the amount of sides and the amount of dice inputted.
    srand
    total = 0
    (amount.to_i).times do
        total += rand(1..sides.to_i)
    end
    return total
end

while true
    raw_input = gets.chomp.to_s
    if raw_input == "exit"
        abort("May your rolls be ever natural.")
    end
    proc_input = raw_input.tr("^0-9", " ")
    #this keeps all the numbers from the string input.
    output = proc_input.split()
    if (output[2]) == nil
        mod = 0
    else
        mod = output[2]
    end
    fin = roll(output[0], output[1]) + mod.to_i
    puts "#{fin.to_s}"
end


texts:
I tried looking up some good example init scripts, but all that I found were excessively complicated. So I wrote my own simple init script targeting CentOS 6. I tried to follow LSB where I understood what it says. CentOS uses chkconfig instead of the LSB comment block.

This is my first serious shell script ever. What do you guys think?

#!/bin/sh
# chkconfig: 2345 80 20
# description: Perforce server

. /etc/profile.d/p4d.sh

command_line='p4d -d'

running() {
    pgrep -fx "$command_line" > /dev/null
}

start() {
    if ! running; then
        $command_line > /dev/null
    fi
}

stop() {
    if running; then
        p4 admin stop > /dev/null
    fi
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart|force-reload)
        stop
        start
    ;;
    status)
        if running; then
            echo "Running"
        else
            echo "Stopped"
            exit 3
        fi
    ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|status}"
        exit 1
    ;;
esac

exit 0


texts: Attempting to utilize OOP with a user-management class

texts:
Originally, this isn't how I would have done this at all. I was told by someone I know who is a programmer that I needed to include several functions: one for removing and adding users, one for searching for users information etc.

I would have made it so you can pass a username into the constructor and then get all the user info and leave it to another UserManagement class to take care of things like adding and removing users, but I was told (very very forthrightly) that, that was NOT the way of going about doing what I'm doing.

Am I using OOP correctly? I have asked 2 people and their opinions are almost directly opposite to each others.  The code below works fine, performs well and does what I want it to just fine, but I'm worried that I'm not quite getting when and when not to use OOP.

class User{
    public $username;
    public $uid;
    public $date;
    public $location;

    public function __construct(){
    }

    public function getUser($user){

        $getUserInfo = new Database;
        $getuserInfo("SELECT * FROM users WHERE username = ?", array($user));
        $result = $getUserInfo->result;

        foreach ($result as $value) {
            $this->username = $value['username'];
            $this->uid = $value['uid'];
            $this->date = $value['date'];
            $this->location = $value['location'];
        }
    }

    public function getUserByUID($uid){
        $getUserInfo = $GLOBALS['databaseUserManagement']->prepare("SELECT * FROM users WHERE uid = ?");
        $getUserInfo->execute(array($uid));
        $result = $getUserInfo->fetchAll();

        foreach ($result as $value) {
            $this->username = $value['username'];
            $this->uid = $value['uid'];
            $this->date = $value['date'];
            $this->location = $value['location'];
        }
    }

    public function deleteUser($username){
        $deleteSpecifiedUser = $GLOBALS["databaseUserManagement"]->prepare("DELETE FROM users WHERE username = ?");
        $deleteSpecifiedUser->execute($user);
    }

    public function addUser($username, $password, $email, $ip){
        $cryptOptions = [
            'cost' => 11,
            'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
        ];

        $passwordCrypted = password_hash($password, PASSWORD_BCRYPT, $cryptOptions);
        $email = $_POST['email'];
        $date = date("y-m-d h:m:s");

        $registerQuery = $GLOBALS["databaseUserManagement"]->prepare("INSERT INTO  `users` (`id` , `uid`, `username`, `password`, `date`,`ip`, `email`) VALUES (NULL,  ?, ?, ?,  ?,  ?, ?, ?)");
        $registerQuery->execute(array(uniqid(), $username, $passwordCrypted, $date, $ip, $email));
    }

}


texts:
I'm trying to make a market depth chart with data from a exchange and a Google JS chart.

The good news is I got it working, but the bad news is the code to prepare the data to be used by google charts is just bad. I know there should be far better ways to do this but I can't come to a proper solution.

The original data is as following:

{bids: [[price, amount], [price, amount], ...],
 asks: [[price, amount], [price, amount], ...]}

Google chart needs it like this:

[[price, bid, ask], [price, bid, ask], ...]

I have the following (ugly) code:

var newData = [['price', 'bid', 'ask']];
var t = 0;
var tt = [];
var p = [];
for (var i = data.bids.length -1; i > -1; i--) {
    t += data.bids[i][1];
    tt.push(t);
    p.push(data.bids[i][0])
}
var ii = 0;
for (var i = tt.length - 1; i >= 0; i--) {
    newdData.push([p[ii], tt[i],null])
    ii++;
};
t = 0;
for (var i = data.asks.length -1; i > -1; i--) {
    t += data.asks[i][1];
    newData.push([data.asks[i][0], null, t]);
}

If I create a google chart with the newData it works as expected. How can I make the code better or more efficient?


texts: Ugly optimized caching of SimpleDateFormat

texts:
Concerning the optimization of this simple function

String formatDate(String format, Locale locale, Date date) {...}

formatting a Date using a SimpleDateFormat created with the arguments format and locale. I'm curious  what you thing about the code below. I know it's terrible, but let's assume two things

The code must be as fast as possible.
There's no suitable object to hold the cache.
It must not cause any memory leaks.

Because of 1., a thread local cache should be used. However, the passed format and arguments may differ from those used in the cache and this must be checked. Funnily, although SimpleDateFormat is mutable (which is the cause of all problems), there seem to be no way how to change its format or locale. Actually, the parameters hardly ever change, but there's no guarantee.

Because of 2., the cache must be a static field.

Because of 3., no ThreadLocal.initialValue can be used as it'd lead to memory leaks just like in this question. For the same reason no custom class may be put into the ThreadLocal.

This all is pretty restrictive. So I wrote the following ugliness

private String toString(Date obj, String format, Locale locale) {
    return getSimpleDateFormat(format, locale).format(obj);
}

private SimpleDateFormat getSimpleDateFormat(String format, Locale locale) {
    Object[] list = SDF.get();
    // An identity check is faster and correct as missing an entry is allowed.
    // It's surely good enough as passing equals but not same parameters hardly ever happens.
    if (list!=null && list[0] == format && list[1] == locale) {
        return (SimpleDateFormat) list[2];
    }
    final SimpleDateFormat result = new SimpleDateFormat(format, locale);
    list = new Object[] {format, locale, result};
    SDF.set(list);
    return result;
}

/** Contains triples (String format, Locale locale, SimpleDateFormat sdf) */
private static final ThreadLocal<Object[]> SDF = new ThreadLocal<Object[]>();

I don't care about naming and such, as this was just a quick implementation of an idea. I'm curious if there's a substantially better solution satisfying all the above conditions.

If you say, it's premature optimization, I'll fully agree, but let's assume for a while it must be done. If you say, that's hardly faster than no caching, then show me your figures.

Obviously, I'm caching just one value per thread. It should be enough in many cases like producing a CSV with one one or more dates per row as I haven't yet see them to be formatted differently.

However, time is "date" too (at least in Java), and a CSV line containing both date and time in separate columns is rather common and this would render my poor man's cache fully ineffective.


texts: Long arithmetic addition implemented in functional style

texts:
This implementation uses ECMA6 syntax and babel as transpiler. You can use this code to add integers which are bigger than Number.MAX_SAFE_INTEGER.

var _ = require('underscore'),
    assert = require('assert');

var strAdd = function(lnum, rnum) {
  var {rem, res} = _.chain(
    _.zip(
      lnum.split('').reverse(),
      rnum.split('').reverse()
    )
  ).reduce(
    ({rem, res}, [left, right]) => {
      var sum = Number(left || 0) + Number(right || 0) + rem;
      res.push(
        sum % 10
      );
      return {
        res,
        rem: ~~(sum/ 10)
      };
    },
    {
      rem: 0,
      res: []
    }
  ).value();
  if (rem !== 0) {
    res.push(rem);
  }
  return res.reverse().join('');
};
assert(strAdd('1', '9') === '10', strAdd('1', '9'));
assert(strAdd('1', '0') === '1', strAdd('1', '0'));
assert(strAdd('5', '5') == '10');
assert(strAdd('2', '2') === '4');
assert(strAdd('20', '202') === '222');


texts: Hash Tables: Ransom Note - Hacker Rank in Javascript

texts:
I'm preparing for an interview doing the preparation questions on Hacker Rank and I want to become better at this. Is it possible to get some feedback on this? How can I improve my code? How did you solve this question?

function getCount(array){
    let counts = {}
    for(let word of array){
        let count = counts[word]
        counts[word] = count ? counts[word] + 1: 1;
    }
    return counts
}
// Complete the checkMagazine function below.

function compareNoteMag(note,mag){
    let noteKeys = Object.keys(note)
    let string = 'Yes'
    for(let key of noteKeys){
        if(!mag[key]) string = 'No'
        if(mag[key] < note[key]){
            string = 'No'
        }
    }
     console.log(string)
}

function checkMagazine(magazine, note) {
    let magazineCount = getCount(magazine);
    let noteCount = getCount(note);
    compareNoteMag(noteCount,magazineCount)
};


texts: Binary tree from given Inorder and Preorder traversal

texts:
This builds a BinaryTree from given Inorder and Preorder lists.

class TreeNode(object):
  """Node of a Binary tree."""
  def __init__(self, key, left=None, right=None):
      self.key = key
      self.left = left
      self.right = right

  def __str__(self):
    return "{0}".format(self.key)

  def __repr__(self):
    return "<TreeNode>"

def insert_left(parent, node):
  parent.left = node
  return parent

def insert_right(parent, node):
  parent.right = node
  return parent

def level_order(node):
  """Given Binary Tree gives list nodes in each level."""
  if node is None:
    return
  current_level = [node]
  res = []
  while current_level:
    res.append(current_level)
    next_level = []
    for node in current_level:
      if node.left:
        next_level.append(node.left)
      if node.right:
        next_level.append(node.right)
    current_level = next_level
  return res

def build_tree(inorder, preorder):
  """Builds a Binary Tree from given inorder and preorder traversal.
  Steps:
    1. Take the first element from the preorder list.
    2. Get the index of the element from inorder list.
    3. Set the element as root.
    4. Take all elements left to root from inorder list.
    5. Take all elements right to root from inorder list.
    6. Calculate preorder list for left and right subtree respectively.
    7. Repeat from step 1 for each subtree.
  """
  def recurse(node, inorder, preorder):
    if len(preorder) == 1:
      return TreeNode(preorder)
    key  = preorder[0]
    root_index    = inorder.find(key)
    inorder_left  = inorder[:root_index]
    inorder_right = inorder[root_index+1:]
    preorder_left = preorder[1:len(inorder_left)+1]
    preorder_right = preorder[root_index+1:]
    node = TreeNode(key)
    if len(inorder_left):
      insert_left(node, recurse(None, inorder_left, preorder_left))
    if len(inorder_right):
      insert_right(node, recurse(None, inorder_right, preorder_right))
    return node
  return recurse(None, inorder, preorder)

import unittest

class TestBinaryTree(unittest.TestCase):
  def setUp(self):
    self.root = build_tree('DBEAFC', 'ABDECF')

  def test_build_tree(self):
    expected = [['A'], ['B', 'C'], ['D', 'E', 'F']]
    actual = []
    for level in level_order(self.root):
      actual.append([node.key for node in level ])
    self.assertEqual(actual, expected)

if __name__ == '__main__':
  unittest.main()

Output

A
B C
D E F

Although the code passes given test case I have to shamefully admit that it took me nearly the whole day to figure out the recursive build_tree method. I had a hard time to debug my recursive code by pen and paper as I was unable to track the progress of each recursive call (hope I could use version control and show the code progress). Anyway, as a last resort I started putting random code here and there finally putting None in this call insert_left(node, recurse(None, inorder_left, preorder_left)) worked.

So, I am here with some fundamental questions:

How can I structure the code to reduce the cognitive overload (I was literally stuck juggling with all those variables)?
How can I debug these kinds of recursive calls?


texts:
I have to write a program that changes a string's vowels, consonants and other symbols into C, V respectively 0. I've done this but I wonder if there is a more efficient and elegant way to do it. Would appreciate input.

(defun string-to-list (string)
(loop for char across string collect char))

(defun is-vowel (char) (find char "aeiou" :test #'char-equal))

(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))

(defun letter-type (char)
(if (is-vowel char) "V"
(if (is-consonant char) "C"
"0")))

(defun analyze-word (word-string)
(loop for char across word-string collect (letter-type char)))

Moreover, I would like to make it a string, how could I do that? Should I define a function that would iterate through the list and make it a string or is it an easier way to do it?

I've got it, for the ones interested, the code is below. Used map to do it.

(defun string-to-list (string)
(loop for char across string collect char))

(defun is-vowel (char) (find char "aeiou" :test #'char-equal))

(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))

(defun analyze_word (word-string)
(loop for char across word-string collect (letter-type char)))

(defun letter-type (char)
  (cond ((find char "aeiou" :test #'char-equal) #\V)
        ((alpha-char-p char) #\C)
        (t #\0)))

(defun change_string (string)
(map 'string #'letter-type "analyze-word")
)


texts: Universal CSS template for global styles

texts:
I 'm trying to create a universal CSS template for global styles. I can not find unambiguous recommendations. After inspecting various sites, I have compiled the following template . I ask your advice . Thank you!

*,
*:after,
*:before {
    box-sizing: border-box;
}

html,
body {
    overflow-x: hidden;
    overflow-y: hidden;
    width: 100%;
    height: 100%;
}

html {
    font-size: 62.5%;
    // background-color: x;
}

body {
    position: relative;
    z-index: 0;
    min-height: 100%;
    color: x;
    background-color: x;
    font-family: x;
    font-size: 1.6rem;
    font-weight: x;
    font-style: normal;
    line-height: x;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
}

.wrapper {
    margin: 0 auto;
    min-width: 320px;
    padding: x;
}


texts: Simple function to generate an HTML-safe string

texts:
Sometimes, we have to do some fixing to insert a string into an HTML property. Or just to display it.

But not everything is safe! Consider the following example:

document.getElementById('name').innerHTML = prompt('What is your name?');

This allows to introduce HTML vulnerabilities quite easily. Specially when you want to do HTML > X/HTML conversions.

So, I've came up with the following:

var safetext = function(text){
    var div = document.createElement('div');
    div.innerText = div.textContent = text;
    var safetext = div.innerHTML;
    div = null;
    return safetext.replace(/^\s+|\s+$/g, '');
};

But then I realized that it could be optimized a little. That div is created and destroyed every single time you need a cleanup. So, I've optimized to the following:

var safetext = (function(text){
    this.innerText = this.textContent = text;
    return this.innerHTML.replace(/^\s+|\s+$/g, '');
}).bind(document.createElement('div'));

The this will always be the div we created, and will always be the same one, so, no unnecessary cleanups or anything. It is always kept in memory, since it is bound to the this in the anonymous function. Or isn't it?

The resulting text is a string that is safe to use in your HTML. Using the example from before:

document.getElementById('name').innerHTML = safetext(prompt('What is your name?'));

This should show &lt;script&gt; if your name (for some bizarre reason) is <script>. Or it leaves unsafe characters behind, bound to break everything?

To the best of my knowledge, and based on the 200 tests where I've used it, I didn't had a single problem or hiccup.

Am I missing something? Is my code indeed returning safe HTML strings? Is the 2nd iteration really more performant?


texts: Await on a Task constructed with an async lambda

texts:
While looking at some C# WiFi helper code, we had a discussion about this code:

async Task JoinNetwork(WiFiProfile profile)
{
    var success = new Task(async () =>
    {
        var ret = await DoSomethingSlow();
        if (ret)
        {
            await Succeed();
        }
        else
        {
            await Fail();
        }
    });
    var failure = new Task(async () =>
    {
        await Fail();
    });

    await Util.JoinNetwork(profile, success, failure, 3 * 60 * 1000);
    await Task.WhenAny(success, failure);
}

I was initially concerned about the final await on the last line of the method, but the the programmer explained that the method that calls JoinNetwork wants to do something after either Succeed() or Fail() has finished.  The code that calls it looks something like this:

try {
    await JoinNetwork(profile);
} catch (Exception e) {
    // exception logic
}
ReportJoinNetworkResults();

But, looking at it some more, I'm not sure that Succeed() or Fail() from JoinNetwork is guaranteed to happen before ReportJoinNetworkResults(). Is everything going to happen in the right order with this code, and can it be written with less await keywords?


texts: Rendering JSON arrays of unequal length as a table

texts:
I have a website where my users can create "table-like" layout dynamically. So imagine that my users can upload a text document, and then append columns to the document, and the output will then be parsed into a table-like layout.

For example:

My text document              Date: 20-06-2019                Created by: OJN

Content                       Nice Document                   Very!

Content                       Indeed!

                              Even more!

Now imagine that this is a word document for example, and my users have defined two columns on above (right between each block of text). This would output:

{
   "1":[
      {
         "row":"My text document"
      },
      {
         "row":"Content"
      },
      {
         "row":"Content"
      }
   ],
   "2":[
      {
         "row":"Date: 20-06-2019"
      },
      {
         "row":"Nice Document"
      },
      {
         "row": "Indeed!"
      },
      {
         "row": "Even more!"
      }
   ],
   "3":[
      {
         "row":"Created by: OJN"
      },
      {
         "row":"Very!"
      }
   ]
}

As you can see, this will ultimately generate three array objects with unequal elements.

0: Array(3)
1: Array(4)
2: Array(2)

Now when presenting this for the user in the frontend, I wish to show the parsed text content in a table, like: this

        {{cell["row"]}}

However, as said, the arrays are of unequal length - so if I "just" transpose them, it will not generate the desired output. Instead, in above example, it will only create 3 rows in my table, because the first array contains 3 elements.

So in order to overcome this, I check the arrays to find the largest one:

// Transform object in array of its values
let data = Object.values(content);
let colsLength = data.map(r => r.length);
let maxNumCols = Math.max.apply(Math, colsLength);
let recordArraySchema = Array.apply(null, Array(maxNumCols)).map((r, i) => i);

this.dataTable = recordArraySchema.map((col, i) => data.map(row => row[i]));

This way, the array transposing will transpose all "rows", and fill the "empty"/non-existing will null, resulting in a full table.

I was wondering if this approach is acceptable in terms of performance and readability? I do have the option to change the JSON string format all together on the backend if that is more appropriate. However, I do have other backend functions that relies on the current schema, so those would have to be updated as well.


texts: Calling a function every 40 second inside a while loop

texts:
This code invokes a function for every 40 seconds inside a loop. I am doubtful about this condition:

if ((time_left <= 0 || time_left > interval))

Is only checking (time_left <= 0) fine? I referred to some websites and they have also added a check for time_left > interval. Is this check required?

int print_timed_op()
{
    time_t        time_now;
    time_t        time_left;
    time_t        time_next_interval;
    int           interval = 40, hit_count =10; //40 second interval, 10 times
    time_next_interval = time(0) + interval;

   //tight loop
   while (1) {
         sleep(1);
         time_now = time(0);
         time_left = time_next_interval - time_now;
         /* here time_left > interval check required ? */
         if ((time_left <= 0 || time_left > interval)) {
              call_my_fuc();
              time_next_interval = time(0) + interval;
              time_left = interval;
              hit_count--;
         }

         if(hit_count< 0)
            break;
  }
  return 0;
}

Note: I don't want to use a Linux timer system call or any other method to invoke the function periodically.


texts:
From the section called Nested Mappings

  Exercise 2.40

  Define a procedure
  unique-pairs that, given an integer n,
  generates the sequence of pairs (i,j)
  with 1 < j < i < n. Use unique-pairs to
  simplify the definition of
  prime-sum-pairs given above.

I wrote the following:

(define (prime-sum-pairs n)
  (filter (lambda (seq)
            (prime? (+ (car seq) (cadr seq))))
          (unique-pairs n)))

(define (enumerate-integers start end)
  (if (>= start end)
      (list end)
      (cons start (enumerate-integers (+ 1 start) end))))

(define (unique-pairs n)
  (flat-map (lambda (i)
              (map (lambda (j) (list i j))
                   (enumerate-integers 1 (- i 1))))
            (enumerate-integers 2 n)))

(define (filter test-fn seq)
  (if (null? seq) null
      (if (test-fn (car seq))
          (cons (car seq)
                (filter test-fn (cdr seq)))
          (filter test-fn (cdr seq)))))

(define (accumulate op initial seq)
  (if (null? seq)
      initial
      (op (car seq)
          (accumulate op initial (cdr seq)))))

(define (flat-map f seq)
  (accumulate append
              null
              (map (lambda (x) (f x)) seq)))

(define (prime? n) (= (smallest-divisor n) n))
(define (divisible? n i) (= 0 (remainder n i)))
(define (square x) (* x x))
(define (smallest-divisor n)
  (define (rec i)
    (cond ((> n (square i)) n)
          ((divisible? n i) i)
          (else (rec (+ 1 i)))))
  (rec 2))

Can this be improved in any way?