texts:
I've started learning Mithril framework, which looks pretty awesome. I've created a basic blog app and have a few questions about code style and structure.

var app = {};

app.PostList = function(list) {
  return m.prop(list || []);
};

app.vm = {};

app.Post = function(data) {
  var data = data || {};
  this.id = m.prop(data.id);
  this.title = m.prop(data.title);
  this.content = m.prop(data.content);
};

app.vm.init = function() {
  var self = this;
  self.posts = new app.PostList();
  m.request({method: 'GET', url: '/posts', background: true, type: app.Post})
    .then(self.posts)
    .then(m.redraw);
};

app.controller = function() {
  app.vm.init();
};

app.view = function(ctrl) {
  return m('body', [
      m('h1', 'My blog'),
      m('ul',
        app.vm.posts().map(function(el){
          return m('li', [
            m('a[href="/posts/'+el.id()+'"]', {config: m.route}, JSON.stringify(el))
          ]);
        })
      ),
      m('a[href="/posts/add/"]', {config: m.route}, 'add new post')
  ]);
};

var add = {};

add.newPost = function(data) {
  data = data || {};
  this.title = data.title || '';
  this.content = data.content || '';
};

add.controller = function() {
  var post = new add.newPost();
  this.post = post;
  this.create = function(e) {
    e.preventDefault();
    m.request({
      method: 'POST',
      url: '/posts',
      data: post
    }).then(function() {m.route('/');});
  };
};

// data binding helper function
// http://lhorie.github.io/mithril-blog/asymmetrical-data-bindings.html
function formBinds(data) {
  return function(e) {data[e.target.name] = e.target.value;};
}

add.view = function(ctrl) {
  return m('body', [
    m('form', {
      onsubmit: ctrl.create,
      onchange: formBinds(ctrl.post)
    }, [
      m('a[href="/"]', {config: m.route}, 'All Posts'),
      m('br'),
      m('input[type=text][name=title][placeholder="post title"][required]'),
      m('br'),
      m('textarea[name=content][placeholder="post content"][required]'),
      m('br'),
      m('input[type=submit][value=Post]')
    ])
  ]);
};

var details = {};

details.vm = {};
details.vm.init = function(postId) {
  var self = this;
  self.comment = {
    postId: postId,
    name: '',
    body: ''
  };
  self.post = new app.Post();
  m.request({method: 'GET', url: '/posts/'+postId, type: app.Post}).then(function(data) {
    data = data[0];
    self.post = data;
  });
  self.comments = m.request({method: 'GET', url: '/posts/'+postId+'/comments'});

  self.add = function(e) {
    e.preventDefault();
    if (self.comment.body) {
      var newComment = self.comment;
      // TODO: add request error handler (how to?)
      m.request({method: 'POST', url: '/posts/'+postId+'/comments', data: newComment}).then(function() {
        var comments = self.comments();
        comments.push(newComment);
        self.comments(comments);
      });
    }
  }.bind(self);
};

details.controller = function() {
  var postId = +m.route.param('postId');
  this.postId = postId;
  details.vm.init(postId);
};

details.view = function(ctrl) {
  return m('body', [
    m('a[href="/"]', {config: m.route}, 'All posts'),
    m('h1', details.vm.post.title()),
    m('p', details.vm.post.content()),
    m('form', {
      onsubmit: details.vm.add,
      onchange: formBinds(details.vm.comment)
    }, [
      m('input[type=text][name=name][placeholder="your name"][required]'),
      m('br'),
      m('textarea[name=body][placeholder="comment body"][required]'),
      m('br'),
      m('input[type=submit][value=Post]')
    ]),
    m('ul', details.vm.comments().map(function(comment) {
      return m('li', comment.name+': '+comment.body);
    }))
  ]);
};

//setup routes to start w/ the `#` symbol
m.route.mode = 'hash';

//define a route
m.route(document, '/', {
    '/' : app,
    '/posts/add': add,
    '/posts/:postId': details
});

You can find the complete project on my GitHub.
Please, provide some advice or comments about how to implement it with Mithril.


texts: Efficiently calculate the value of an arithmetic sequence

texts:
I need to calculate the value for the following function:
$$f(n) = -1 + 2 - 3 + ... + -1^n$$
The time limit to calculate a given value of \$n\$ is less than 1 second. My approach does not meet that requirement at large sizes, for example \$f(1000000000)\$.
My code:
program A486;
uses wincrt, sysutils;

var
    n: LongInt;

function f(n : LongInt): LongInt;
var
    i : LongInt;
    //Result : LongInt;
begin
    Result:= 0;
    for i:= 1 to n do
        if i mod 2 = 0 then
            Result += i
        else
            Result -= i;
    //f:= Result;
end;

begin
    readln(n);
    writeln(f(n));
    //readkey()
end.

Is there a better way I can do this?


texts:
I've made the following and have a few questions:

Do I have some (big) mistakes in this approach? (bad practices, 'this code is trash'...)

1.1 If I do, can you suggest what to fix?
Are appended element created in good way?
Code in success function seems to be a little long.  Any way to refactor?

CSS code

.no-display-table {
    display: none;
}

HTML code

    ...

    ...

...

 Selected options

JavaScript code

$(function() {
    $('#options-table').addClass('no-display-table');

    $('#product-option-select').change(function() {
        if($('.append-select select').length > 0)
            $('.append-select select').remove();

        var selectedOptionId = $(this).val();

        $.ajax({
            type: 'get',
            url: '../option_types/' + selectedOptionId,
            success: function(data) {
                var element = '<select id="value-select" class="form-control">';
                element += '<option selected disabled>Select value...</option>';

                for(var i=0; i<data.length; i++) {
                    element += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                }

                element += '</select>';
                $('.append-select').append(element);

                $('.append-select').on('change', '#value-select', function() {
                    $('#options-table').removeClass('no-display-table');

                    var selectedValue = $('#value-select option:selected').text();
                    var element = '
' + selectedValue + '	';
                        element += ' x
';

                    $('#options-table tbody').append(element);

                    $('#options-table').on('mouseover', '.remove', function() {
                        $('.remove').css('cursor', 'pointer');
                    });

                    $('#options-table').on('click', '.remove', function() {
                        $(this).parent().parent().remove();

                        if($('#options-table tbody tr').length == 0)
                            $('#options-table').addClass('no-display-table');
                    });
                });
            }
        });
    });
});


texts:
I am a beginner and I have made a Reservation Form in HTML. I'm pretty sure it will look horrible to any developer out there, but hey, that's why I've posted it.

I'd like a general review of this. I'm especially concerned about the quality and enhancements of this form. What should I do to add attractive looks and to upload the input data somewhere, So that I could read it?

RESERVATION FORM

NAME<INPUT TYPE="TEXT" SIZE="20" MAXLENGTH="99" />

AGE<INPUT TYPE="TEXT" SIZE="12" MAXLENGTH="99" />

ADDRESS<INPUT

<TYPE="TEXT" SIZE="42" MAXLENGTH="99" />

EMAIL<INPUT TYPE="TEXT" SIZE="30" MAXLENGTH="99" />

TELEPHONE<INPUT TYPE="TEXT" SIZE="10" MAXLENGTH="99" />

SELECT YOUR

BERTH
<SELECT NAME="CHOICES" SIZE="3">
<OPTION>TATKAL</OPTION>
<OPTION>LADIES</OPTION>
<OPTION>GENRAL</OPTION>
</SELECT>

CITY<SELECT naME="CITY"><OPTION SELECTED>

DELHI</OPTION><OPTION>MUMBAI</OPTION><OPTION>KOLKATA</OPTION><OPTION>CHENNAI</OPTION>

<input type="submit" value="click here to submit" />
<input

type="reset" value="clear this form" />


texts:
This is a task taken from Leetcode -

  Given a collection of intervals, merge all overlapping intervals.

  Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]

Output: [[1,6],[8,10],[15,18]]

/** Explanation: Since intervals `[1,3]` and `[2,6]` overlap, merge them into `[1,6]`. */

  Example 2:

Input: [[1,4],[4,5]]

Output: [[1,5]]

/** Explanation: Intervals `[1,4]` and `[4,5]` are considered overlapping. */

My imperative solution -

 /**
   * @param {number[][]} intervals
   * @return {number[][]}
   */
  var merge = function(intervals) {
    const sortedIntervals = intervals.sort((a,b) => a[0] - b[0]);
    const newIntervals = [];

    for (let i = 0; i < intervals.length; i++) {
      if (!newIntervals.length || newIntervals[newIntervals.length - 1][1] < sortedIntervals[i][0]) {
        newIntervals.push(sortedIntervals[i]);
      } else {
        newIntervals[newIntervals.length - 1][1] = Math.max(newIntervals[newIntervals.length - 1][1], sortedIntervals[i][1]);
      }
    }
    return newIntervals;
  };

My functional solution -

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
function merge(intervals) {
  const mergeInterval = (ac, x) => (!ac.length || ac[ac.length - 1][1] < x[0]
    ? ac.push(x)
    : ac[ac.length - 1][1] = Math.max(ac[ac.length - 1][1], x[1]), ac);

  return intervals
    .sort((a,b) => a[0] - b[0])
    .reduce(mergeInterval, []);
};


texts:
I'm in the middle of a project that was built around Microsoft's Message Queue service. During development all of our machines are on a domain and we were able to create a public queue accessible from the server and client.

When moving this to our test server, I discovered that both the test server and production servers are running in workgroup mode, no public queues available.

I'm experimenting with creating a webservice broker backed by a MemoryCache. Here is what I've got so far. Each key is posted into a FIFO queue due to the needs of the project.

Has anyone else done something similar? What about concurrency? Any other gotchas I should be concerned about?

UPDATED: Added suggested changes, and handled differences resulting from use of ConcurrentQueue and Lazy instantiation.

    [WebMethod]
    public bool Push(string key, string value)
    {
        if (String.IsNullOrWhiteSpace(key) || String.IsNullOrWhiteSpace(value)) return false;

        // input validation removed for brevity

        var queue = GetQueue(key);
        queue.Enqueue(value);
        return true;
    }

    [WebMethod]
    public string Pop(string key)
    {
        var queue = GetQueue(key);
        string result = "";
        if (queue.TryDequeue(out result))
        {
            return result;
        }
        return null;
    }

    [WebMethod]
    public List<string> RemoveAll(string key)
    {
        var queue = GetQueue(key);
        var list = queue.ToList();
        queue.Clear();
        return list;
    }

    private ConcurrentQueue<string> GetQueue(string key)
    {
        var cache = MemoryCache.Default;
        var queue = (Lazy<ConcurrentQueue<string>>) (cache.AddOrGetExisting(key.ToLowerInvariant(),new Lazy<ConcurrentQueue<string>>() , new CacheItemPolicy
        {
            AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration,
            SlidingExpiration = TimeSpan.FromMinutes(5)
        }) ?? cache[key.ToLowerInvariant()]);
        return queue.Value;
    }

I also added an extension for the ConcurrentQueue to clear it.

public static class ConcurrentQueueExtensions
{
    public static void Clear<T>(this ConcurrentQueue<T> queue)
    {
        T item;
        while (queue.TryDequeue(out item))
        {
            // do nothing
        }
    }
}


texts:
I am writing a lightweight JSON API, and I come from a PHP background, so I have some questions/reviews about async node.js code.

This is my code so far:

main.js

var http = require('http');
var api = require('./api.js');

api.addRoute({
    'method': 'POST',
    'url': '/users',
    'input': {
        'fullName': {
            type: String,
            required: true,
            min: 2,
            max: 64
        },
        'email': {
            type: String,
            required: true,
            match: /^(.*)@(.*).(.*)$/,
            min: 2,
            max: 64
        },
        'password': {
            type: String,
            required: true,
            min: 2,
            max: 64
        }
    },
    'description': 'Create an user account.'
});

var server = http.createServer(api.handleRequest).listen(3000);

api.js

var api = exports;
var routes = [];

var postMaxSize = 1000;
var postTotalReceived = 0;

function getInput(req, res, callback){
    if(req.method === 'POST' || req.method === 'PUT'){
        var queryString = require('querystring');
        var inputData = '';

        req.on('data', function(data){
            if(data.length < postMaxSize && postTotalReceived < postMaxSize){
                inputData += data;
                postTotalReceived += data.length;
            } else {
                res.statusCode = 413;
                res.end('max-size');
            }
        });

        req.on('end', function(){
            callback(queryString.parse(inputData));
        });
    } else {
        callback(false);
    }
};

api.addRoute = function(route){
    routes.push(route);
}

function getRoute(req, res, callback){
    for(var i = 0; i < routes.length; i++){
        if(routes[i]['method'] === req.method){ // If the request method matches.
            if(typeof(routes[i]['url'] === 'string') && routes[i]['url'] === req.url){
                callback(routes[i]);
            }
        } else {
            var matches = req.url.match(routes[i]['url']);

            if(matches){
                req.urlParameters = [];

                for(var j = 1; j < matches.length; j++){ // Skip the first match, which is the url.
                    req.urlParameters.push(matches[j]);
                }

                callback(routes[i]);
            }
        }
    }
};

api.handleRequest = function(req, res){
    res.setHeader('Content-Type', 'application/json'); // Always return JSON since this is a rest JSON api.

    getInput(req, res, function(inputData){
        getRoute(req, res, function(route){
            if(route){

                // Do something.

                res.end();
            } else {
                res.statusCode = 404;
                res.end('not-found');
            }
        });
    });
};

I am just wondering, Node.js sells itself with "Non-blocking", but if on each request I have to do a regex to match the route for example:

/^\/users\/(.*)\//$ -> /users/mike

The regex has to be executed since Node.js is single threaded.  How does it do Regex non blocking? The CPU has to execute the Regex, right?

About the code, my idea was:

I don't want to use any framework like express, since routing etc. can be done
much more lightweight and I can customize everything, full control etc.
Each route has automatic input validation, which can be combined with auto generating documentation, for example if a user would request 'GET /' he would get a list of all the routes fully documented with required parameters, optional parameters, description, authentication requirements etc.

Please take a look at the api.handleRequest function.  Am I correctly using callbacks at getInput and getRoute? Or should I only use callbacks at I/O, db calls etc?

The API I am about the build is basically a simple wrapper around Amazon Web Services, MongoDb and maybe later Redis or some other message queue.


texts:
I need to implement a decoding in the next JSONs:

First variant:

{}

Second variant:

{"user":{
    user_field_0: ""
    user_field_1: ""
    ...
}}

Third variant:

{"data":{
    data_field_0: ""
    data_field_1: ""
    ...
}}

Fourth variant:

{"datas":[
    {
        data_field_0: ""
        data_field_1: ""
        ...
    },
    {
        data_field_0: ""
        data_field_1: ""
        ...
    },
    ...
]}

To the next enum:

#[derive(Debug)]
pub enum Value {
    User(User),
    Data(Data),
    Datas(Vec<Data>),
    None,
}

#[derive(Debug)]
pub struct User {
    pub user_field_0: String,
    pub user_field_1: String,
    ...
}

#[derive(Debug)]
pub struct Data {
    pub data_field_0: String,
    pub data_field_1: String,
    ...
}

I implemented it with map:

impl Decodable for Value {
    fn decode<D: Decoder>(d: &mut D) -> result::Result<Self, D::Error> {
        d.read_map(|d, len| {
            let key: String = try!(d.read_map_elt_key(0, |d| Decodable::decode(d)));
            match &key[..] {
                "user" => Ok(Value::User(try!(d.read_map_elt_val(0, |d| Decodable::decode(d))))),
                "data" => Ok(Value::Data(try!(d.read_map_elt_val(0, |d| Decodable::decode(d))))),
                "datas" => Ok(Value::Datas(try!(d.read_map_elt_val(0, |d| Decodable::decode(d))))),
                _ => unreachable!(),
            }
        }).or(Ok(Value::None))
    }
}

But it does not look nice. Because we read the "whole" map, but use only the element at zero index. In my opinion it is not right way. Is there a proper way to perform this decoding?

Maybe something like this:

// not working code!
d.read_struct_field("user", 0, |d| {
    Ok(Value::User(try!(Decodable::decode(d))))
})
.or(d.read_struct_field("data", 0, |d| {
    Ok(Value::Data(try!(Decodable::decode(d))))
}))
.or(d.read_struct_field("datas", 0, |d| {
    Ok(Value::Datas(try!(Decodable::decode(d))))
}))
.or(Ok(Value::None))


texts: Finding the longest path, avoiding obstacles in a 2D plane

texts:
The Scenario

You are given a matrix of size m x n (width x height) with m*n spots where there are a few obstacles. Spots with obstacles are marked as 1, and those without are marked as 0. You can move vertically or horizontally, but can visit each spot only once. The goal is to cover as much area/spots as possible, avoiding obstacles.

Input

A 2D Matrix consisting of 0s and 1s and the coordinates of starting point.

Example Matrix:

0 1 0
0 0 0
1 0 0

Starting Point (0,0).
The coordinates are nothing but array indices.

Output

Output should be a line containing comma separated moves. A move is a space separated direction (n,s,e,w) and number of units of movement in the direction (range 1-1000).

Example output for the above matrix would be,

s 1,e 1,s 1,e 1,n 2

(0,0) --> (1,0) --> (1,1) --> (2,1) --> (2,2) --> (1,2) --> (0,2)

which is the longest path, visiting each coordinate only once and avoiding those coordinates with obstacles.

My algorithm

  for every vertex/coordinate, recursively choose the neighbor which
  yields the longest path

Code

def getDirections(p1, p2):
    return {(1,0):"n", (-1,0):"s", (0,1):"w", (0,-1):"e"}[(p1[0]-p2[0], p1[1]-p2[1])]

def findPath(start, mat):
    m, paths = getMax(mat, getNeighbours(mat), start, list())
    print(paths)
    if len(paths) == 1:
        return ""
    directions = ""
    prev = getDirections(paths[0], paths[1])
    current = ""
    ctr = 1
    for i in range(1, len(paths)-1):
        current = getDirections(paths[i], paths[i+1])
        if current == prev:
            ctr += 1
        else:
            directions, prev, ctr = directions + prev + " " + str(ctr) + ",", current, 1
    return directions + current+ " " +str(ctr)

#Neighbor is (-1,-1) if indices are out of range. For top and bottom rows for example.
def getNeighbours(mat):
    neighbours = dict()
    for i in range(len(mat)):
        for j in range(len(mat[i])):
            n = (i-1, j) if i-1 >= 0 else (-1, -1)
            s = (i+1, j) if i+1 < len(mat) else (-1, -1)
            w = (i, j-1) if j-1 >= 0 else (-1, -1)
            e = (i, j+1) if j+1 < len(mat[i]) else (-1, -1)
            neighbours[(i,j)] = {'n':n, 's':s, 'w':w, 'e':e}
    return neighbours

def getMax(mat, neighbours, coordinates, visited):
    if coordinates == (-1,-1):
        return -1, []
    elif mat[coordinates[0]][coordinates[1]] == 1:
        return -1, []
    elif coordinates in visited:
        return -1, []
    else:
        visited.append(coordinates)
        n, nlist = getMax(mat, neighbours, neighbours[coordinates]['n'], visited[:])
        s, slist = getMax(mat, neighbours, neighbours[coordinates]['s'], visited[:])
        w, wlist = getMax(mat, neighbours, neighbours[coordinates]['w'], visited[:])
        e, elist = getMax(mat, neighbours, neighbours[coordinates]['e'], visited[:])
        if max(n,s,w,e) == -1:
            return 0, visited
        if max(n,s,w,e) == n:
            visited = nlist
        elif max(n,s,w,e) == s:
            visited = slist
        elif max(n,s,w,e) == w:
            visited = wlist
        elif max(n,s,w,e) == e:
            visited = elist
        return 1+max(n,s,w,e), visited


texts: Advanced love calculator that generates a result based on the similarities between the two names

texts:
My love calculator gives a result from 0 to 100% based on these factors:

If the first letters of the names are the same.
If the number of vowels is the same.
If the length of the name is the same.
If the number of consonants is the same.

Also, there is an extra boost of 10-50%, so the result is also partially as a result of luck.
Can the coding below be simplified or improved to function more smoothly?:

(Edit 1: By the way, I'm very new at Python - I joined the community only yesterday.)

(Edit 2: I am using Python 3.7.3 for Mac OSX.)

name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")

total_vowel1 =0
for i in ['a','e','i','o','u']:
     total_vowel1 += name1.count(i)
total_vowel2 =0
for i in ['a','e','i','o','u']:
     total_vowel2 += name2.count(i)

love = 0
if(total_vowel1 == total_vowel2):
    import random
    love +=random.randint(10,30)

consonants1 = 0
consonants2 = 0
CONSONANTS = 'bcdfghjklmnprstvwxyz'
consonants1 = len([letter for letter in name1 if letter.lower() in
CONSONANTS])
consonants2 = len([letter for letter in name2 if letter.lower() in
CONSONANTS])

if(consonants1 == consonants2):
    import random
    love +=random.randint(20,40)

line1 = name1
line2 = name2
split1 = line1.split()
split2 = line2.split()
fl1 = [word[0] for word in split1]
fl2 = [word[0] for word in split2]

if (fl1 == fl2):
    import random
    love +=random.randint(10,30)

if (len(name1) == len(name2)):
    import random
    love+=random.randint(1,10)

import random
love +=random.randint(10,50)
if (love>100):
    love = 100

print("Calculating...")
import time
import random
time.sleep(random.randint(1,3))

print("",name1,"and",name2,"have a",love,"% relationship.")
if ((love>90) or (love == 90)):
    print("They have an unbreakable relationship that will last
    forever.")
if ((love<89) or (love == 89)) and ((love>70) or (love == 70)):
    print("They have a strong relationship that will most likely
    lead to a marriage.")
if ((love<69) or (love == 69)) and ((love>50) or (love == 50)):
    print("They have a good relationship that can lead to a
    honeymoon to Paris.")
if ((love<49) or (love == 49)):
    print("They have a weak relationship that could have been a
    'match made in heaven'.")


texts:
I am doing some online exercises, and I came across this: "Your job is to write a program for a speed camera. For simplicity, ignore the details such as camera, sensors, etc and focus purely on the logic. Write a program that asks the user to enter the speed limit. Once set, the program asks for the speed of a car. If the user enters a value less than the speed limit, program should display Ok on the console. If the value is above the speed limit, the program should calculate the number of demerit points. For every 5km/hr above the speed limit, 1 demerit points should be incurred and displayed on the console. If the number of demerit points is above 12, the program should display License Suspended."

        Console.Write("Speed Limit :");
        int speedLimit = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("SPEED LIMIT : " + speedLimit);
        Console.WriteLine("***********************");

        Console.Write("Car Speed : ");
        int carSpeed = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("CAR SPEED : " + carSpeed);
        Console.WriteLine("***********************");
        Console.WriteLine("***********************");

        int demeritPoints = 0;

        if (carSpeed < speedLimit)
        {
            Console.WriteLine("Ok. You are good to go");
        }
        else
        {
            int speedDifference = carSpeed - speedLimit;

            for (int counter = 5; counter <= speedDifference; counter += 1)
            {
                if (counter % 5 == 0)
                {
                    demeritPoints++;
                }
            }
        }
        Console.Write("Demerit Points :");
        Console.WriteLine(demeritPoints);

        if (demeritPoints >= 12)
        {
            Console.WriteLine("Your license is suspended");
        }
        else
        {
            Console.WriteLine("You are not suspened");
        }


texts: Python Time Class definition and methods, use of __init__

texts:
I've written a Time class that records the time of day and performs simple timing operations (add 2 times, convert a time object to an integer and back again,etc.) following the prompts in How to Think Like a Computer Scientist: Learning with Python.

class Time(object):
"""Attributes: hours, minutes, seconds"""
def __init__(self,hours,minutes,seconds):
    self.hours =hours
    self.minutes=minutes
    self.seconds=seconds

def print_time(self):
    """prints time object as a string"""
    print "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds)

def _str_(self):
    """returns time object as a string"""
    return "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds)

def name(self,name):
    """names an instance"""
    self.name=name
    return self.name

def after(t1,t2):
    """checks to see which of two time objects is later"""
    if t1.convert_to_seconds()<t2.convert_to_seconds():
        return "%s is later" %(t2.name)
    elif t1.convert_to_seconds>t2.convert_to_seconds:
        return "%s is later" %(t1.name)
    else:
        return "these events occur simultaneously"

def convert_to_seconds(self):
    """converts Time object to an integer(# of seconds)"""
    minutes=self.hours*60+self.minutes
    seconds=minutes*60+self.seconds
    return seconds

def make_time(self,seconds):
    """converts from an integer to a Time object"""
    self.hours=seconds/3600
    seconds=seconds-self.hours*3600
    self.minutes=seconds/60
    seconds=seconds-self.minutes*60
    self.seconds=seconds

def increment_time(self, seconds):
    """Modifier adding a given # of seconds to a time object
    which has been converted to an integer(seconds); permanently
    alters object"""
    sum=self.convert_to_seconds()+seconds
    self.make_time(sum)
    return self._str_()

def add_time(self, addedTime):
    """adds 2 Time objects represented as seconds;
       does not permanently modify either object"""
    import copy
    end_time=copy.deepcopy(self)
    seconds=self.convert_to_seconds()+addedTime.convert_to_seconds()
    end_time.make_time(seconds)
    return end_time._str_()

Usage examples:

breakfast=Time(8,30,7)
dinner=Time(19,0,0)
smokebreak=Time(19,0,0)
interval=(4,30,0)

print dinner.after(smokebreak)
print breakfast.add_time(interval)
print breakfast.increment_time(3600)

The Time Class example in the text I'm following does not use an init method, but passes straight into creating a time object and assigning attributes. Is there any advantage to including an init function, as I have done? Removing the init method seems to make it easier to adopt a terser and more functional style.
Is including a method to name instances bad form, as I suspect? Would it be better write a functional-style version of add_time without importing deepcopy?
I would appreciate any advice on best practices in Python 2.x OOP.


texts: Incrementing time in a discrete-event simulation of a supermarket queue

texts:
A method has been written that increments time in minutes that simulates how much time it takes to process item in a supermarket queue and if there is an empty queue, skip it and loops around to find the number of items processed in each interval (each time a minute has passed). I was wondering if there are ways to improve the code I have written??

private Queue[] lines;
private double time; // Time measured in minutes
private static double item_per_min;
private static double time_inc;
private static Random rand = new Random();
static int x = 0;
public static final double lambda = item_per_min * time_inc;
public static double target_Probability = rand.nextDouble();
public static final double target_ProbabilityabilityOfX = Math.pow(lambda, x) * Math.exp(-lambda) / factorial(x); // Poisson
                                                                                // distribution

public void add_time(double time_inc)
{
    for (int i = 0; i < lines.length; i++) // Loops
    {
        if (lines[i].empty())
        {
            continue;
        }

        while (true)
        {
            time += time_inc;
            if (target_ProbabilityabilityOfX > target_Probability)
            {
                break;
            }

            x++;
            target_Probability -= target_ProbabilityabilityOfX;
        }

        while (!lines[i].empty() && x > 0)
        {
            lines[i].decrement();

            x--;
        }
    }

    this.display();
}


texts:
I'm trying to properly write a card class in swift. I've been taking classes in software engineering and I need help in understanding how to take a more object-oriented approach to my class. I have seen a Class for suit and rank and I'm wondering would that approach would be better? I have also seen the suit as enums and wonder if that approach would be better.

Any help will be appreciated.

Thank you

class Card

private var rank: Int
private var suit: Int

init(n: Int) {
    self.rank = -1;
    self.suit = -1;
    if(n >= 0 && n <= 51) {
        self.rank = n % 13;
        self.suit = n / 13;
    }
}

func getRank() -> Int {
    return self.rank;
}

func getSuit() -> Int {
    return self.suit;
}

func compareRank(otherCard: Card) -> Bool {
    return self.rank == otherCard.getRank();
}

func compareSuit(otherCard: Card) -> Bool {
    return self.suit == otherCard.getSuit();
}


texts: Making a TableViewDataSource more independent of the data it utilizes

texts:
I have written an ordinary tableView to display a list of players, with the following data structure that's in place.

A Conductor (which is the user), has many
Orchestra? objects.
A Orchestra? has many Player? objects

All objects besides the Conductor are cast as Optional, meaning that a Conductor could have no Orchestra, and an Orchestra could have no player.

The Conductor is a singleton object. At anytime the currentConductor could be called (similar to how you could always call currentUser in Parse or Firebase)

Currently, I am displaying all the players for a Conductor's currentOrchestra object. My concern is that my TableViewDataSource is too tightly coupled with having to know about how my Conductor class functions, and I could like to decouple some of the logic.

For instance:

class OrchestraViewDataSource: NSObject, UITableViewDataSource {

    var isCurrentOrchestraAvaliable = false

    override init() {
        super.init()

        if let _ = User.shared.currentOrchestra {
            isCurrentOrchestraAvaliable = true
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        if isCurrentOrchestraAvaliable {
            return 2 //Shows Performers and Non-performers
        }

        return 0
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 0 {
            return User.shared.currentOrchestra?.performers.count ?? 0
        } else {
            return User.shared.currentOrchestra?.nonPerformers.count ?? 0
        }

    }

    //... Additional code omitted
}

At the moment, I call User.shared.currentOrchestra?.performers.count because the user could change the line up of the performers and non-performers. Is calling the Singleton to populate my data source ok? And if not, what are better ways to make my TableViewDataSource more independent?

Thanks!


texts: How can I layout this class to make it easier to use for API developers?

texts:
I have an application that allows the user to place a string of text into a PDF document.  I have three different ways that they can do this:

Use a Form Field. Then they have four properties to define:

Provide field name
provide instance of the field
provide an X-axis Offset
provide a Y-axis Offset

Search for a string of text. Then they have four properties to define:

Provide string of text to search for
provide instance of that string of text
provide an X-axis Offset
provide a Y-axis Offset

Define Page Coordinates. Then they have three properties to define:

Provide page number
provide an X-axis Offset
provide a Y-axis Offset

In my API, I want the object to be setup intuitively so that it is clear they are choose one of the three different methods and then whichever one they choose, they have the options for each.

In my old API, all of those options are grouped together as a list of properties like this:

Placement.FormField_FieldName
Placement.FormField_Instance
Placement.SearchText_Text
Placement.SearchText_Instance
Placement.PageCoordinates_PageNumber
Placement.XOffset
Placement.YOffset

I find this to be a little confusing for the developer using the API because you could never use all of the properties together.

You would either use Form Field like this:

Placement myPlacement = new Placement();
myPlacement.FormField_FieldName = "MyPdfFormFieldName";
myPlacement.FormField_Instance = ;
myPlacement.XOffset = 0;
myPlacement.YOffset = 0;

Or use Text Search like this:

Placement myPlacement = new Placement();
myPlacement.SearchText_Text = "My String Of Text";
myPlacement.FormField_Instance = 1;
myPlacement.XOffset = 0;
myPlacement.YOffset = 0;

Or use Page Coordinates like this:

Placement myPlacement = new Placement();
myPlacement.PageCoordinates_PageNumber = "My String Of Text";
myPlacement.XOffset = 0;
myPlacement.YOffset = 0;

Is there a better way to setup the class (or sub classes) to make it easier for the developer to understand how to use this functionality?

UPDATE

This is what I currently am using because the abstract class thing didn't work.

public class SignatureBlock
{
    public List<SignatureBlockPlacement> SignatureBlockPlacements = new List<SignatureBlockPlacement>();
}

public class SignatureBlockPlacement
{
    public Enumerations.SignatureBlock.SignatureBlockTypes Type { get; set; }
    public string FormField_FieldName { get; set; }
    public int FormField_InstanceOfField { get; set; }
    public string SearchText_TextToSearch { get; set; }
    public int SearchText_InstanceOfText { get; set; }
    public string PageCoordinates_PageNumber { get; set; }
    public int XOffset { get; set; }
    public int YOffset { get; set; }
}

Which I'm implementing like this:

SignatureBlock sigBlock = new SignatureBlock();

SignatureBlockPlacement sig = new SignatureBlockPlacement();
sig.Type = Enumerations.SignatureBlock.SignatureBlockTypes.Signature;
sig.FormField_FieldName = "SignatureField";
sig.FormField_InstanceOfField = 1;

SignatureBlockPlacement title = new SignatureBlockPlacement();
title.Type = Enumerations.SignatureBlock.SignatureBlockTypes.Title;
title.FormField_FieldName = "SignatureField";
title.FormField_InstanceOfField = 1;
title.XOffset = 0;
title.YOffset = -20;

SignatureBlockPlacement org = new SignatureBlockPlacement();
org.Type = Enumerations.SignatureBlock.SignatureBlockTypes.Organization;
org.FormField_FieldName = "SignatureField";
org.FormField_InstanceOfField = 1;
org.XOffset = 0;
org.YOffset = -40;

sigBlock.SignatureBlockPlacements = new List<SignatureBlockPlacement>() { sig, title, org };

If there's a better way to do this, please let me know.

UPDATE #2

I should have mentioned this is for a WCF SOAP web service.

UPDATE #3

Long story short on this one, I need to allow the developer three different ways to place the signature but they should only be allowed to use one of the three ways .  Each way shares the X/Y Offset properties but their other properties are unique to each way.


texts: Implement clojure-a-like comp() function in python3

texts:
With a friend some time ago we wanted to write our own implementation of comp() clojure function in python3. we ended up writing the following function:

 def comp(*fs):
     """
     Takes a set of functions and returns a fn that is the
     composition of those fns. The returned fn takes a variable number of args,
     applies the rightmost of fns to the args, the next fn (right-to-left) to
     the result, etc.
     """
     if len(fs) == 1:
         return lambda *x: fs[0](*x)
     else:
         return lambda *x: fs[0](comp(*fs[1:])(*x))

In my oppinion it's still opaque and difficult to read. But it works as in:

 # Checking for single argument
 >>> [comp(lambda x: x*10,lambda x: x+2, lambda x: x*3, lambda x: x+3)(x) for x in range(6)]
 [110, 140, 170, 200, 230, 260]
 # Checking for multiple arguments
 >>> a = lambda x: sum(x)
 >>> b = lambda x, y, z: [x*1, y*2, z*3]
 >>> comp(a, b)(1, 2, 3)
 14

How could it be written better?


texts: Remove duplicates in list of lists where an item in each list is ignored when determining duplicity

texts:
I have lines_list_copy of the form:

[['a1', 'b1', 'c1', 'd1', 'e1'], ['a2', 'b2', 'c2', 'd2', 'e2'], ... ]

I needed to remove all duplicate entries where a,b,c,d are identical. So note that I don't care about what value e has. So for example, If lines_list_copy = [['a1', 'b1', 'c1', 'd1', 'e1'], ['a2', 'b2', 'c2', 'd2', 'e2'], ['a1', 'b1', 'c1', 'd1', 'e1'], ['a1', 'b1', 'c1', 'd1', 'e2']] we have three values that are the same, namely lines_list_copy[0], lines_list_copy[2] and lines_list_copy[3] and any 2 of them need to be deleted which will give us the value of lines_list. At the end deleting any two results in a valid outputs for lines_list

lines_list_copy has lengths typically exceeding 200000 and realistically will eventually exceed 500000 with the amount of data we are collecting. Thus I needed a way to remove duplicates fast. I found a way to efficiently remove all duplicates, but the method would take e into account and thus wouldn't give me what I need. Therefore, I delete all the e values in each list first like so:

for x in lines_list_copy:
  del x[cfg.TEXT_LOC_COL]
lines_list_copy = [list(x) for x in set(tuple(x) for x in lines_list_copy)]

After which I have lines_list_copy as I need it. All I need to do is re-add any one of the e values for each list. My double for loop is admittedly naive and more so that I didn't think it would bring my program to a crawl.

    for line_copy_ind in range(len(lines_list_copy)):
        for line_ind in range(len(lines_list)):
            if lines_list_copy[line_copy_ind][cfg.TIME_COL] == lines_list[line_ind][cfg.TIME_COL] and \
                    len(lines_list_copy[line_copy_ind]) == 4:
                lines_list_copy[line_copy_ind].append(lines_list[line_ind][cfg.TEXT_LOC_COL])
    lines_list = lines_list_copy

I looked into vectorizing and using filter but just cant seem to reverse engineer solutions to other problems and make them work for my problem of adding e back on the end of each list in lines_list_copy. Maybe there's an elegant way for me to instead not delete the e column and still remove duplicates efficiently without considering the e values?


texts: Is there a better way to make a function silent on need?

texts:
I got a piece of code I'm not pleased with; Does anyone would have a better idea?

def myFunc(verbose=True):
    if not verbose:
        print = functools.partial(globals()['print'], file=open(os.devnull, 'w'))
    else:
        # Required, othewise I got the error 'local print variable was referenced before being declared' a few lines below…
        print = globals()['print']

    # Bunch of code with tons of print calls […]

I also tried the classical sys.stdout = open(os.devnull, 'w') but it can't work with my code because my print function is defined as such at the beginning of the code:

print = functools.partial(print, file=codecs.getwriter('utf8')(sys.stdout.buffer)) # Make sure the output is in utf-8

But I'm not really fan about having to use globals twice.


texts: Inject a list of processes to execute using spring DI

texts:
I have couple of MessageProcessors. One of the Processor will log the payload. Other Processor will save into an embedded database.

Here is the code I have written so far:

I am using annotation-driven configuration so I have omitted other classes which are not used in this use case.

@Component
public class ProcessorConfiguration {
    @Bean
    @Qualifier("textMp")
    public MessageProcessor textMessageProcessor() {
        return new TextMessageProcessor();
    }

    @Bean
    @Qualifier("employMp")
    public MessageProcessor employMessageProcessor() {
        return new EmployMessageProcessor();
    }

    @Bean
    private List<MessageProcessor> messageProcessorList(@Qualifier("textMp") MessageProcessor textMessageProcessor,
            @Qualifier("employMp") MessageProcessor employMessageProcessor) {
        List<MessageProcessor> list = new ArrayList<>();
        list.add(textMessageProcessor);
        list.add(employMessageProcessor);
        return list;
    }
}

This class is responsible for all the JMS messages the application receives.

public class MessageHandler {
    @Autowired
    private List<MessageProcessor> messageProcessors;

    public void handleMessage(Notification notification) {
        messageProcessors.forEach(processor -> processor.doProcess(notification));
    }
}

public interface MessageProcessor {
    void doProcess(Notification notification);
}

public class TextMessageProcessor implements MessageProcessor {
    private static final Logger logger = Logger.getLogger(TextMessageProcessor.class);
    @Override
    public void doProcess(Notification notification) {
        logger.info("The payload is " + notification.getText());
    }

}

I have created a builder which takes String as input and returns an Employ object.

@Service
public class EmployMessageProcessor implements MessageProcessor {
    @Autowired
    private EmployDao dao;

    @Override
    public void doProcess(Notification notification) {
        Employ employ = EmployBuilder.buildEmploy(notification.getText());
        dao.save(employ);
    }

}

public interface Notification {
    String getText();
}

I think, the way I am injecting the processors can be improved. Please review my code and provide your valuable feedback.


texts: replacing characters in string one by one to create target string

texts:
while doing a code clash on codingames, in which we had to replace a character in a string one by one to transform it into a target string, printing out every itteration of the new string, resulting in something like this:

"Turtle Ham"
"Hurtle Ham"
"Hartle Ham"
"Hamtle Ham"
"Ham le Ham"
"Ham Me Ham"
"Ham Ma Ham"
"Ham MakHam"
"Ham Makeam"
"Ham Makerm"
"Ham Maker!"

This is de code I came up with, in Javascript.

var source = "Turtle Ham";
var target = "Ham Maker!";
var safe = source;
String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}
console.log(source);
for(var i=0; i < source.length; i++) {
    source = source.replaceAt(i, target.charAt(i));
    if(source == safe) {

    } else {
     console.log(source);
     safe = source;
    }
}

would there be any more effective way of doing this in Javascript?


texts: C++ Dijkstra's shortest path implementation

texts:
I have created a c++ function that searches for the shortest path between two points with dijkstra's shortest path algorithmus. I'm using it right now in combination with a program that solves mazes and it works quite well on up to 15K * 15K mazes (I ran short of RAM there). But I have problems solving an 2K * 2k Braid maze (one with lots of paths and loops). Tell me what I can improve.

The function itself:

    bool dijkstra::GetShortestPath(std::deque<CNode> &vGraph, CNode *mStart, CNode *mEnd, std::deque<CNode*> *vPath)
{
    if(mStart == 0 || mEnd == 0 || vPath == 0)
        return false;

    std::vector<CNode*> vUnvisited;     //Priority Queue
    auto mCompare = [&](CNode *lhs, CNode *rhs){return (lhs->DistanceTo > rhs->DistanceTo);};

    //Set distance to start node to 0
    mStart->DistanceTo = 0;

    //Init Queue
    vUnvisited.reserve(vGraph.size());
    vUnvisited.push_back(mStart);   //At the beginning the queue is empty, besides the startnode
    //Dijkstra loop
    {CNode *mTopNode = 0;
    do{
        std::pop_heap(vUnvisited.begin(), vUnvisited.end(), mCompare);
        mTopNode = vUnvisited.back();               //Get nearest, not completed node
        vUnvisited.pop_back();                      //Remove it, it will be completed next iteration
        for(auto &it : mTopNode->Connections())     //Look at all connections
        {
            if(it.To->DistanceTo > (mTopNode->DistanceTo + it.Distance))        //If a shorter path to a node is found, overwrite DistanceTo & PreviousNode
            {
                it.To->DistanceTo = (mTopNode->DistanceTo + it.Distance);
                it.To->PreviousNode = mTopNode;
                std::make_heap(vUnvisited.begin(), vUnvisited.end(), mCompare); //Completely sort the queue
            }
            if(it.To->Completed == false)       //If an unvisited node has been found, add it to the queue and sort it in
            {
                vUnvisited.push_back(it.To->Addr());
                std::push_heap(vUnvisited.begin(), vUnvisited.end(), mCompare);
            }
            mTopNode->Completed = true; //The current node is now completed
        }
    }while(!(mEnd->Completed == true || vUnvisited.size() == 0 || mTopNode->DistanceTo == std::numeric_limits<unsigned int>::max()));}

    //Push path into array
    {CNode *mCurrentNode;
    mCurrentNode = mEnd;
    while(mCurrentNode != 0)
    {
        vPath->push_front(mCurrentNode);
        mCurrentNode = mCurrentNode->PreviousNode;  //Follow the PreviousNode pointers
    }}
    return true;
}

The CNode class:

struct SConnection
{
    SConnection(CNode *To, unsigned int Distance);
    CNode *To;
    unsigned int Distance;
};

class CNode
{
public:
    CNode();

    std::vector<SConnection> Connections()const;

    bool AddConnection(CNode *mTo, unsigned int nDistance);
    bool AddConnection(const SConnection &mConnection);
    bool RemoveConnection(CNode *mTo);

    bool operator >  (const CNode &rhs)const;
    bool operator <  (const CNode &rhs)const;
    bool operator == (const CNode &rhs)const;

    CNode* Addr();

    bool Completed = false;
    unsigned int DistanceTo = std::numeric_limits<unsigned int>::max();
    CNode *PreviousNode = 0;
    unsigned int XPos = 0;
    unsigned int YPos = 0;

private:
    std::vector<SConnection> m_vConnections;
};


texts: Function to test if exactly one of three parameters is truthy, without using equality operators

texts:
Given the following instructions I have created a function that achieves the requirements. I feel my function is a bit too complex, though it does what it's supposed to. The difficult part for myself was avoiding the equality operators. The only way I could think to solve this is with a bit of math and a comparison operator. How can I simplify this function and save some editing time?

  Write a function onlyOne that accepts three arguments of any type.

  onlyOne should return true only if exactly one of the three arguments are
  truthy. Otherwise, it should return false.

  Do not use the equality operators (== and ===) in your solution.

My function:

function onlyOne(input1, input2, input3){
output = false;
let truthy = 0;
let falsey = 0;
if (!!input1) {
    truthy++;
} else falsey++;
if  (!!input2) {
    truthy++;
} else falsey++;
if (!!input3) {
    truthy++;
} else falsey++;
if (falsey > truthy) {
    output = true;
}
if (falsey > 2) {
    output = false;
}
return output;
}

(originally asked on StackOverflow and was directed here.)


texts: Get directions for unit movement with conditions

texts:
I am developing a bot for Starcraft II.
In my code for unit movement, I often find myself doing this:

Calculate points around the current position of the unit
Check if these points are valid and can be reached
Get the best n points that fit condition A (for example, the n points that are furthest away from the closest enemy unit)
Of these n points, get the best point that fits condition B (for example, the point that is closest to the closest friendly unit)

I already made a numpy version to speed it up a bit, but would like this to run even faster. Maybe there is a way to combine the two conditions somehow.

import heapq
import math
import timeit

import numpy as np

# Point2 objects are needed here for the starcraft bot, they have .x and .y properties
# positions have 15 decimal places
from sc2.position import Point2

DIRECTIONS_AMOUNT = 16
# add [0] to have current position in points
DIRECTION_OFFSETS = (
    [0] + [round(math.cos(2 * math.pi / DIRECTIONS_AMOUNT * p), 15) for p in range(DIRECTIONS_AMOUNT)],
    [0] + [round(math.sin(2 * math.pi / DIRECTIONS_AMOUNT * p), 15) for p in range(DIRECTIONS_AMOUNT)],
)
# the current position of the unit
position = Point2((65.11906509381345, 127.15779037493655))
#  urrent position of closest enemy
closestEnemy = Point2((74.11906509381345, 112.15779037493655))
# current position of closest friend
closestFriend = Point2((68.11906509381345, 131.15312313133655))

# directions + original position for the case that standing still is the best option
retreatPoints = [
    Point2((position.x + DIRECTION_OFFSETS[0][p], position.y + DIRECTION_OFFSETS[1][p]))
    for p in range(DIRECTIONS_AMOUNT + 1)
]

# select some points which are far away from the enemy
retreatPointsChoice = heapq.nlargest(3, retreatPoints, key=lambda p: p.distance_to(closestEnemy))
# final point where the unit moves to based on distance to closest friend
retreatPoint = min(retreatPointsChoice, key=lambda p: p.distance_to(closestFriend))

# with numpy, i improved it to this:
np_retreatPoints = np.array(retreatPoints)

def numpy_distance_sort(direction_points, target_point, amount=6, sort="min"):
    if sort == "max":
        results = np.add(
            np.square(np.subtract(target_point.x, direction_points[:, 0])),
            np.square(np.subtract(target_point.y, direction_points[:, 1])),
        )
    if sort == "min":
        results = -1 * np.add(
            np.square(np.subtract(target_point.x, direction_points[:, 0])),
            np.square(np.subtract(target_point.y, direction_points[:, 1])),
        )
    return [np_retreatPoints[i] for i in np.argpartition(-results, amount)[:amount]]

np_retreatPointsChoice = numpy_distance_sort(np_retreatPoints, closestEnemy, 3, "max")
np_retreatPoint = min(retreatPointsChoice, key=lambda p: p.distance_to(closestFriend))


texts: Sum array values based on conditions in other arrays

texts:
I have the following code that sums the values in wgt_dif (a numpy array) if certain conditions in two other numpy arrays are met. It is basically the equivalent of a SUMIFS function in Excel.

sum_4s = 0

for i in range(len(pntl)):
    if pntl[i] == 4 and adj_wgt[i] != max_wgt:
        sum_4s += wgt_dif[i]

I'm wondering if there is a more Pythonic way to write this. It works fine, but I'm new to Python and numpy and would like to expand my "vocabulary".


texts:
I've created a function to return all the indices where an element is to be found in an array. If it occurs twice or more, all the respective indices will be returned, for now it returns them in natural counting (1,2,3...) and not how the computer sees them (0,1,2,...).

#include <iostream>
#include <vector>
using namespace std;

void searchList(int theArray[], int sizeOfTheArray, int findFor);

void searchList(int theArray[], int sizeOfTheArray, int findFor){
  vector<int> foundIndices;

  int j = 0;

  for (int i = 0; i < sizeOfTheArray; i++)
  {
    if (theArray[i] == findFor){
      foundIndices.push_back(i);
      j++;
    }
  }

  if (foundIndices.size()!=0){
    cout << "Found in index: ";
    for (int i = 0; i < foundIndices.size(); i++){
      cout << foundIndices[i]+1 << " ";
    }
  }
  else
    cout << "Not found in array";
}

int main(){
  int test[8] = {87, 75, 98, 100, 100, 234, 265, 9};
  searchList(test, 8, 99);
  return 0;
}


texts: Building objects in javascript, without "if(!a[k]) a[k] = []"

texts:
When building objects using reduce, I often have crappy code like this:

function mapArticlesByTagAndId(articles) {
    return articles.reduce((collector = {}, article) => {
        const { tag, id } = article;
        if(!collector[tag]) collector[tag] = {};

        collector[tag][id] = article;
        return collector;
    })
}

I would love to one line this, but I can't figure out a way to do it.
If only assigning a property to undefined created an object =P [Obviously this would cause different problems haha]


texts: Selecting multiple checkboxes to show similar but different boxes

texts:
I have 3 checkbox's with 8 different combinations and outcomes.

Selecting no checkboxes shows no divs.
Selecting one checkbox shows the colored div.
For example; clicking the red checkbox.
Selecting two checkboxes shows the color1+color2 div. But doesn't show either of the single colored divs.
For example; clicking the red and green checkboxes shows the redgreen div. But ensures both the red and green div boxes are hidden so there's only ever one div box showing.
Selecting all the checkboxes shows the rgb div. And doesn't show any other divs.

It does work I was wondering if this can be wrote more efficient?

$('input[type="checkbox"]').click(function () {
    $('.box').hide();
if ($('#red').is(':checked')) $('.red.box').show();
if ($('#green').is(':checked')) $('.green.box').show();
if ($('#blue').is(':checked')) $('.blue.box').show();

if ($('#red').is(':checked') && $('#green').is(':checked')) $('.redgreen.box').show() && $('.red.box, .green.box').hide();

if ($('#red').is(':checked') && $('#blue').is(':checked')) $('.redblue.box').show() && $('.red.box, .blue.box').hide();

if ($('#green').is(':checked') && $('#blue').is(':checked')) $('.greenblue.box').show() && $('.green.box, .blue.box').hide();

if ($('#red').is(':checked') && $('#green').is(':checked') && $('#blue').is(':checked'))  $('.rgb.box').show() && $('.red.box, .green.box, .greenblue, .redblue, .redgreen.box, .blue.box').hide();

});
.box {
    padding: 20px;
    display: none;
    margin-top: 20px;
    border: 1px solid #000;
}

.redblue .redgreen .greenblue {
    border: 1px solid black;
}
.rgb {
    border: 1px dashed black;
}
.red {
    background: #ff0000;
}
.green {
    background: #00ff00;
}
.blue {
    background: #0000ff;
}

        <input type="checkbox" id="red" name="colorCheckbox" value="red">red

        <input type="checkbox" id="green" name="colorCheckbox" value="green">green

        <input type="checkbox" id="blue" name="colorCheckbox" value="blue">blue

red

green

blue

red green

red blue

green blue

rgb


texts: Java PrintWriter not printing data to file

texts:
This program is compiling just fine, and the variables and such seem to be passing through.  However, when I open the text file there is no data.  Can anyone point me in the right direction or nudge my brain into the right process thought?

package dvdlogger;
import java.util.*;
import java.io.*;

public class DVDLogger {
public DVDLogger() throws IOException
{
    String title = null;
    double price = 0;
    storeDVDInfo(title, price);
}
private void storeDVDInfo(String title, double price) throws IOException
{
    File path = new File("C:\\users\\crazy\\desktop\\dvd.txt");
    PrintWriter output = new PrintWriter(path);
    output.printf("%1$s %2$.2f", title, price);
}

public static void main(String[] args) throws IOException{
    DVDLogger dvd;
    String title;
    double price;
    try (Scanner read = new Scanner(System.in)) {
        dvd = new DVDLogger();
        System.out.printf("%nPlease enter the title of the DVD: ");
        title = read.nextLine();
        System.out.printf("%nPlease enter the price of the DVD: ");
        price = read.nextDouble();
    }
    dvd.storeDVDInfo(title, price);
}
}


texts:
It's time for my second simple game - Tic Tac Toc. I checked it on my Linux and it's working. For compiling it I used g++ with -std=c++11. I will be glad for any advice for the future.

#include <iostream>
#include <cstdlib>
#include <unistd.h>

class Game_Board
{
public:
    Game_Board();

private:
    enum Player{cross=1, circle=2};
    Player which_player = cross;
    int table_board[3][3];
    bool end = false;

//drawing board
    void draw_board(int const table_board[3][3])
    {
        system("clear");
        for (int i = 0; i<3; i++)
        {
            std::cout << "\n";
            for (int j = 0; j<3; j++)
            {
            if(table_board[j][i]==1)
            {
                std::cout << " _X_ ";
            }
            else if(table_board[j][i]==2)
            {
                std::cout << " _O_ ";
            } else
            {
            std::cout << " ___ ";
            }
            }
            std::cout << "\n\n";
        }
    }

//reading player move
    void read_move()
    {
        int *p_moveX = new int;
        int *p_moveY = new int;
        std::cout << "\nChoose a field (Player " << which_player << "): ";
        std::cin >> *p_moveX >> *p_moveY;
        write_move(*p_moveX, *p_moveY, which_player);
        delete p_moveX; p_moveX = NULL;
        delete p_moveY; p_moveY = NULL;
    }

//saving player's move to table
    void write_move( int X, int Y, int plr_number)
    {
        if(table_board[X-1][Y-1]!=0 || X<=0 || Y<=0 || X>3 || Y>3)
        {
            std::cout << "You can't do this!";
            read_move();
        }
        else
        {
        table_board[X-1][Y-1] = plr_number;
        }
    }

//checking end of game
    void check_winner()
    {
    int *end_counter = new int;
    *end_counter = 0;
        for( int i = 0; i<3; i++)
        {
            if((table_board[i][0] & table_board[i][1] & table_board[i][2])!=0 ||(table_board[0][i] & table_board[1][i] & table_board[2][i])!=0 || (table_board[i][0] & table_board[i+1][1] & table_board[i+2][2])!=0 || (table_board[i][2] & table_board[i+1][1] & table_board[i+2][0])!=0)
            {
                switch(which_player)
                {
                    case 1:
                    draw_board(table_board);
                    std::cout << "Player 1 wins!\n";
                    end = true;
                    break;

                    case 2:
                    draw_board(table_board);
                    std::cout << "Player 2 wins!\n";
                    end = true;
                    break;
                }

            }
        }
        for( int i = 0; i<3; i++)
        {
            if(table_board[i][0]!=0 && table_board[i][1]!=0 && table_board[i][2]!=0)
            {
                    *end_counter+=1;
                    if(*end_counter==3)
                    {
                    draw_board(table_board);
                    std::cout << "Only God wins!\n";
                    end = true;
                    }
            }
        }
        delete end_counter;
        end_counter = NULL;
    }

//choosing player
    void choose_player()
    {
        if(which_player==1)
        {
            which_player = circle;
        } else {
            which_player = cross;
        }
    }

//clearing table
    void clear_table()
    {
        for(int i=0; i<3; i++)
        {
            for(int j=0; j<3; j++)
            {
                table_board[i][j]=0;
            }
        }
    }
};

Game_Board::Game_Board()
{
    clear_table();
    while(!end)
    {
    draw_board(table_board);
    read_move();
    check_winner();
    choose_player();
    }
}

int main()
{
    Game_Board game;
    return 0;
}


texts:
In preparing a solution for the CodeChef "Will India Win" challenge, I am trying to find out the xor of list of numbers.

The first line of input contains the number of test cases, 1 ≤ T ≤ 106.
Subsequent lines contain fifteen space-delimited numbers (each between 1 and 231), to be XORed together.

def main():
    t = int(raw_input())
    for i in range(t):

        input_list = [int(j) for j in raw_input().split()]
        res = input_list[0]
        for n in range(len(input_list)-1):
            res = res^input_list[n+1]
        print res

if __name__ == '__main__':
    main()

Here is my second code by implementing a 2D array through a dictionary:

def main():
    t = int(raw_input())
    for i in range(t):
        input_str = [ int(j) for j in raw_input().split()]
        d = {}
        for j in range(15):
            d[j] = bin(input_str[j])[2:].zfill(32)

        l = []#contains the final output
        for j in range(32):
            temp = 0
            for k in range(15):
                if d[k][j] == '1':
                    temp += 1

            if temp%2 == 0:
                l.append(0)
            else:
                l.append(1)
if  __name__ == '__main__':
    name()

But it turns out that both code are not optimal because I am getting time constraint problems. How can I optimize the code?


texts: Servlet filter which detects if the authenticated user is a service account

texts:
My concern with this code is that I am forcing execution repeatedly through the same pathway for the sake of a readability that I'm not convinced by.

It's a servlet filter which detects if the authenticated user is a service account (non-human) and then does some checks on them within the if clause.

import org.springframework.security.core.Authentication;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

public class ServiceAccountFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {
        if (request instanceof HttpServletRequest
            && ((HttpServletRequest) request).getUserPrincipal() != null
            && ((HttpServletRequest) request).getUserPrincipal()
                    instanceof Authentication
            && ((Authentication)
                ((HttpServletRequest) request).getUserPrincipal())
                .getPrincipal() != null
            && ((Authentication)
                ((HttpServletRequest) request).getUserPrincipal())
                .getPrincipal() instanceof MyUser
            && ((MyUser) ((Authentication)
                ((HttpServletRequest) request).getUserPrincipal())
                .getPrincipal()).getUsername() != null
            && ((MyUser) ((Authentication)
                ((HttpServletRequest) request).getUserPrincipal())
                .getPrincipal()).getUsername().length() > 6) {
            MyUser myUser = (MyUser) ((Authentication)
                    ((HttpServletRequest) request).getUserPrincipal())
                    .getPrincipal();
            // app-specific tests
        }
        chain.doFilter(request, response);
    }

Would it be better to instantiate all of these objects and create a deeply nested set of simplified if clauses?

My opinion is that it might be marginally more performant but it wouldn't be any more readable - or am I already blind to how unreadable it is?


texts:
We had to write a program that would perform rotation of elements in an array. The array size was entered by user, so it had to be in a sense, dynamic.

Rotation or Circular Shifting

Initial Array: 1 3 7 4 8 6 5 2 9

Shift by: 4

Final Array: 6 5 2 9 1 3 7 4 8

Notice, in rotation, each elements position increased by shift amount. Also, elements in the end came to the front.

My Try

I used an approach in which I had to create a new array of size = shift amount. This array stored the shift no. of elements in the end of array. Now I shifted all the elements in the beginning of array by shift amount. In the end, I copied the elements of shift sized array to beginning of original array.

I tried to use minimum memory possible so only used shift sized array. I and keep it a bit fast (shift%=n statement to reduce inefficiency if shift >= n).

// Rotation

#include <iostream>

int main() {

    int n;
    std::cout << "Array size: ";
    std::cin >> n;
    int* list = new int[n];

    std::cout << "Enter elements:\n";
    for( int i = 0; i < n; ++i) {
        std::cin >> list[i];
    }

    int shift;
    std::cout << "Shift amount: ";
    std::cin >> shift;

    shift %= n; // to reduce work if shift > n
    int* temp = new int[shift];

    for( int i = n-shift; i < n ; ++i) {
        temp[i-n+shift] = list[i];
    }

    for( int i = n-1; i >= shift; --i) {
        list[i] = list[i-shift];
    }

    for( int i = 0; i < shift; ++i) {
        list[i] = temp[i];
    }

    delete [] temp;

    // Printing
    for( int i = 0; i < n; ++i) {
        std::cout << list[i] << "  ";
    }

    delete [] list;
}

Question

My question is that all the optimization that i was able to make were a bit obvious and natural. I wanted to know if there was a significant algorithmic, or memory optimization possible for this problem.

PS

I know there's a function std::rotate available from algorithm, but we had to solve this problem on our own.


texts:
I've been working on Python for the past few weeks trying to get my head around it's syntax/naming conventions/style/etc. I decided to make a monty hall sim to see how it looks in python. For those who don't know what the Monty Hall problem is, check the second paragraph here.

I've verified the code is fully functional and gives the right results. It IS indeed best to swap every time. After spending time getting rid of duplicated effort, overly wordy statements, and many logic errors, I'd like to know how to improve my code readability and efficiency (both here and in general).

Specific to this code, here's what I'd like to know (mostly #1):

If possible, how could I make this more efficient?
Is having a function call in the first for loop a good idea? If not, where do I put it?
I keep feeling like this is longer than needed. Are there still places I can cut out code?

import random

def setup():
    # Basic greeting/explaining what to do.
    print("\n\nThere are 3 doors. One is a winner. The computer")
    print("will try guess the right one. After the first ")
    print("guess, one door is shown to be a loser. The computer ")
    print("can then change it's choice to the remaining door.\n")

    # Display choices and get input
    change_choice = input("Should the computer always change it's choice? y/n\n:> ")
    runs = int(input("How many times should this run?\n:> "))
    run(change_choice, runs)

def run(change_choice, times_to_run):
    wins = 0 #Correct door choices

    # Loop through calling the function with switching enabled or not
    for i in range(times_to_run):
        if change_choice == 'y' or change_choice == 'Y':
            wins = wins + setupDoors(True)
        else:
            wins = wins + setupDoors(False)

    # Display amount of times won/percentage of games won
    statistics(wins, times_to_run)

def setupDoors(always_change_choice):
    # Set up the winning door
    winning_door = random.randint(1,3)
    print("\nThe winning door is "+str(winning_door))

    # Get the computer's guessed door
    computer_guess = random.randint(1,3)
    print("the computer guessed door number "+str(computer_guess))
    return playGame(winning_door, computer_guess, always_change_choice)

def playGame(winning_door, computer_guess, always_change_choice ):

    # Get the right door to open.
    # Can't be the computer's door OR the winning door
    opened_door = getAvailableDoor(computer_guess, winning_door)
    print("Door number "+str(opened_door)+" was opened and shown not to be a winning door.")

    #Swap the computer's choice to last door if that was desired
    if always_change_choice:
        computer_guess = getAvailableDoor(computer_guess, opened_door)
        print("The computer changed it's guess to door number "+str(computer_guess))

    # Return a win or a loss.
    if computer_guess == winning_door:
        print("The computer won!")
        return 1
    else:
        print("The computer lost!")
        return 0

def getAvailableDoor(computer_guess, unavailable_door):
    # List of doors to choose from
    Doors = [1,2,3]

    for i in range(3):
        if Doors[i] == computer_guess or Doors[i] == unavailable_door:
            continue
        else:
            break
    return Doors[i]

def statistics(wins, times_to_run):
    print("\nThe computer won "+str(wins)+" times")
    print("This means the computer won "+str((wins/times_to_run)*100)+"% of the time")

setup()


texts: ASP.NET Core singleton acting as an HttpClient provider

texts:
I have created an ASP.NET Core singleton service class to act as an HttpClient provider after reading that reusing an instance of HttpClient is encouraged. However, I also want to be sure that the BaseAddress property is kept up-to-date with the value specified in the configuration so I added a dependency on IOptionsMonitor so that any time the configuration is updated, the BaseAddress property is re-set.

HttpClientProvider

public class MachineDatabaseHttpClientProvider
{
    public HttpClient Client
    {
        get
        {
            try
            {
                readWriteLock.EnterReadLock();
                return client;
            }
            finally
            {
                readWriteLock.ExitReadLock();
            }
        }
    }

    private readonly ReaderWriterLockSlim readWriteLock = new ReaderWriterLockSlim();
    private readonly HttpClient client;

    public MachineDatabaseHttpClientProvider(IOptionsMonitor<ApplicationConfiguration> applicationConfigurationMonitor)
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(applicationConfigurationMonitor.CurrentValue.MachineDatabase.BaseUrl);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        applicationConfigurationMonitor.OnChange(c => UpdateClientBaseAddress(c.MachineDatabase.BaseUrl));
    }

    private void UpdateClientBaseAddress(string baseUrl)
    {
        try
        {
            readWriteLock.EnterWriteLock();
            client.BaseAddress = new Uri(baseUrl);
        }
        finally
        {
            readWriteLock.ExitWriteLock();
        }
    }
}

ASP.NET Core Startup Class

public class Startup
{
    public Startup(IHostingEnvironment env) { ... }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddTypedRouting();
        services.Configure<ApplicationConfiguration>(Configuration.GetSection(ApplicationConfiguration.ConfigurationSectionKey));
        services.AddSingleton<MachineDatabaseHttpClientProvider>();
    }
}

Is the above code more complex than it needs to be? Is my use of ReaderWriterLockSlim sufficient to achieve thread-safety? Reading this answer on HttpClient thread-safety indicates that none of the properties of HttpClient are thread-safe. Should I offer Get and Post methods as a wrapper around the HttpClient so that I can control all access to the class?


texts:
I was recently talking to someone about a function I wrote to mimic (very basically) the string interpolation function String.Format() found in the C# language. They mentioned that I would have performance concerns using RegExp, and that I should try to parse the string template rune by rune. So I wrote a loop the best I could to accomplish that very task. It looks alarmingly ugly (to me) and I wanted some input on the performance considerations with the loop version. As well, maybe some better suggestions on how to accomplish this function in a more sensible/clean fashion.

Here's the two different versions of the implementation:

void main() {
  String thestring = '{0} {1} {2} {3}!';
  assert(formatStringListRegExp([thestring, 'This', 'was', 'a', 'triumph']) == 'This was a triumph!');

  assert(formatStringListloop([thestring, 'This', 'was', 'a', 'triumph']) == 'This was a triumph!');
}

String formatStringListRegExp(List<String> args)
{
  if (args == null || args.length < 2) {
    throw new ArgumentError('expected at least two paramters.');
  }
  if (args[0] is !String) {
    throw new ArgumentError('expected a string for the first paramter.');
  }
  var str = args[0];
  var inserts = args.sublist(1);
  for (var i = 0; i < inserts.length; i++) {
    str = str.replaceAll('{$i}', inserts[i].toString());
  }
  return str;
}

String formatStringListLoop(List<String> args)
{
  if (args == null || args.length < 2) {
    throw new ArgumentError('expected at least two paramters.');
  }

  if (args[0] is !String) {
    throw new ArgumentError('expected a string for the first paramter.');
  }

  var str = args[0];
  var inserts = args.sublist(1);
  StringBuffer buffer = new StringBuffer();

  for (var i = 0; i < str.length; i++) {
    if (str[i] == '{' && i < str.length + 1) {
      var value = '';
      var count = 1;
      var number;

      while(true) {
        if (i + count < str.length - 1) {
          try {
            number = int.parse(str[i + count]);
          } catch (e) {
            break;
          }
        } else {
          break;
        }

        if (number is int) {
          value += number.toString();
          count++;
        } else {
          break;
        }
      }

      if (str[i + count] == '}') {
        if (value.isNotEmpty) {
          int index = int.parse(value);
          if (index < inserts.length) {
            buffer.write(inserts[index]);
            i += count;
          } else {
            buffer.write('{');
          }
        }
      }
    } else {
      buffer.write(str[i]);
    }
  }

  return buffer.toString();
}


texts:
I wrote the following simple Perl script to read lines from stdin that are the output from a psql call that returns lines of the form key1 | key2 | long text field and create a separate output file for each line, whose name is key1_key2_NNN.txt, where NNN is just a counter to ensure unique file names.

my $count = 0;

while (<>) {
    if (/(.*)\|(.*)\|(.*)/) {
        $count++;
        my $outname = "$1_$2_$count.txt";
        my $text = $3;
        $outname =~ s/\s+//g;
        my $outfile = new IO::File("> $outname");
        $outfile->print("$text");
    }
}

This does the trick, but there are 2 things I'm not thrilled about

I'd like to be able to do the $count++ inline while putting the incremented number into the string, but I'm not sure how to not just get 0++ plugged in (i.e. how to make it know that the ++ is a command and not part of the literal string).
I don't like that I have to save $3 to another variable, but if I don't, it gets cleared out before I need it.

Anyhow, any suggestions on making this a bit more slick?


texts:
This is my .cs part code where I am calling storeprocedure in LINQ to SQL:

var rr_j_cat = db.allcategories().ToList();//its store procedure calling thousands of rows

if (rr_j_cat.Count() != 0)
 {
   DataTable dt = new DataTable();//making dynamic datatable
   dt.Columns.Add("sub_id");  //dynamic columns
   dt.Columns.Add("sibheadername");  //dynamic columns
   foreach (var it in rr_j_cat) // will rotate thousands time which makes process talking more time
   {
      DataRow dr = dt.NewRow(); // dyanamic rows
      var rr_sel_cat = db.selcategories(Convert.ToInt32(it.sub_id)).ToList(); //another storeprocedure to check a count of data present in another data or table
      int count = Convert.ToInt32(rr_sel_cat.First().Column1);
      if (count != 0)
       {
         dr["sub_id"] = it.sub_id;
         dr["sibheadername"] = it.sibheadername + " (" + count + ")"; // adding count besides subheader name which you can see in below image on dance
         count =0;
        }
        else
        {
           dr["sub_id"] = it.sub_id;
            dr["sibheadername"] = it.sibheadername;
        }
                dt.Rows.Add(dr);
     }
     dd_j_area.DataSource = dt; // binding with dropdownlist
     dd_j_area.DataTextField = "sibheadername";
     dd_j_area.DataValueField = "sub_id";
     dd_j_area.DataBind();
     dd_j_area.Items.Insert(0, "");
}

It's working fine, but taking more time.

It will show as


texts: Getting the unique identifier from a given login username

texts:
Are there any issues in this code?

/// <summary>
/// This function gets the unique identifier of a member by the given
/// login user name of that member on our web site.
/// </summary>
/// <param name="userName">The username</param>
public static string GetMemberNumberByUserId(string userName, string connectionString)
{
    try
    {
        SqlConnection database = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand("GetMemberInfoByUserID", database);

        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.AddWithValue("@userID", userName);
        database.Open();
        SqlDataReader reader = command.ExecuteReader();
        reader.Read();
        string memberNumber =
            reader.GetString(reader.GetOrdinal("memberNumber"));

        // Make sure the member number is a 11 or 12 digit number
        if (Regex.IsMatch(memberNumber, @"^(000|100)\d{6,7}(?!00)\d{2}$"))
        {
            return memberNumber;
        }
        else
        {
            return "";
        }
    }
    catch(Exception)
    {
        return null;
    }
}


texts: ADT stack with a dynamic array (revision 1)

texts:
Here's the second draft of my ADT stack code which I posted here before after carrying out most of the improvements suggested there.

I decided to expose a function called resize_stack to adjust the size of the stack as desired by the user instead of doing it automatically.

stacklib.h

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#ifndef STACKLIB_H
#define STACKLIB_H

/* generic type pushed item_to the stack */
/* in this case it's just an int */
typedef int item_t;

/* our stack data type */
typedef struct {
    size_t size;
    size_t capacity;
    item_t *elements;
} stack;

/* interface to our new stack data type */
stack* create_stack(size_t capacity);
int push_stack(stack *mystack, item_t data);
item_t* pop_stack(stack *mystack);
void delete_stack(stack *mystack);
stack* resize_stack(stack *mystack, size_t capacity);

#endif

stacklib.c

#include "stacklib.h"

/* a helper function to handle exceptions */
void handle_error(const char* message)
{
    if(errno) {
        perror(message);
    } else {
        printf("Error: %s\n", message);
    }

    exit(1);
}

stack* create_stack(size_t capacity)
{
    stack *stack_ptr = malloc(sizeof(stack));

    if(stack_ptr == NULL)
        handle_error("Error while allocating memory.");

    item_t *elements_ptr = malloc(capacity*sizeof(item_t));

    if(elements_ptr == NULL) {
        free(stack_ptr);
        handle_error("Error while allocating memory.");
    }

    stack_ptr->size = 0;
    stack_ptr->capacity = capacity;
    stack_ptr->elements = elements_ptr;

    return stack_ptr;
}

void delete_stack(stack *mystack)
{
    free(mystack->elements);
    free(mystack);
}

/* Returns 0 on success, 1 on failure */
int push_stack(stack *mystack, item_t data)
{
    /* stack is full! */
    if(mystack->size == mystack->capacity)
        return 1;

    mystack->elements[mystack->size++] = data;
    return 0;
}

/* Returns a pointer to the popped data or NULL if the stack is empty */
item_t* pop_stack(stack *mystack)
{
    if(mystack->size == 0) {
        return NULL;
    } else {
        return &mystack->elements[--mystack->size];
    }
}

/* Returns a pointer to the adjusted stack or NULL on failure */
stack* resize_stack(stack *mystack, size_t capacity)
{

    item_t *tmp = realloc(mystack->elements, sizeof(item_t) * capacity);
    if(tmp == NULL)
        return NULL;
    mystack->elements = tmp;
    mystack->capacity = capacity;

    if(mystack->size > capacity)
        mystack->size = capacity;

    return mystack;

}

main.c

#include "stacklib.h"

int main(void){
    stack *my_stack = create_stack(20);
    item_t i;
    for(i = 0; i < 20; i++) {
        push_stack(my_stack, i);
    }

    resize_stack(my_stack, 10);

    item_t res, *item ;
    while((item = (item_t*)pop_stack(my_stack)) != NULL) {
        res = *item;
        printf("data: %d\n", res);
    }
    delete_stack(my_stack);
    printf("last item popped was  %d\n", res);
    return 0;
}


texts: Pairing Labels with Images when building a UI

texts:
In a prototype 4X space game that I am working on recently, I have two different scroll panes to show the ships and the stars of the player.  The ships are displayed in a vertical scroll pane on the right side of the screen, and the stars are displayed in a horizontal scroll pane running along the bottom. Here is a picture for the sake of clarity:

With the vertical scroll pane, displaying the labels along with the images is very straightforward. When iterating over the list of ships, a label is added for each ship, then a row, then the ship image.

The horizontal scroll pane presents a problem, however.  I want to have the label displayed above the corresponding image.  Accomplishing this is a bit more complicated than simply adding a row between each element in the table.

I thought about having two lists, iterating over the first list and getting the correct element from the second list based on the index.  Instead of doing this, I went with a Map<Label, Image>.  I'm not sure about this decision, and would love feedback on this approach.  It feels wrong to be using a Map here, because I will never be using it to look up the values based on the keys.

First, I have this method that creates the contents that will be used when building the scroll pane:

private void createContents() {
    this.contents = new HashMap<Label, Image>();

    for (Star star : this.game.getPlayerStars()) {

        Image starImage = new Image(this.libGDXGame.starTextures.get(star.type));
        starImage.addListener(new StarClickListener(star) {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                StarScrollPane.this.gameScreen.playerClickedStar(star);
            }
        });

        Label starLabel = new Label(star.type.name(), this.libGDXGame.skin);

        this.contents.put(starLabel, starImage);
    }
}

Then I have another method that actually creates the table and adds the contents to it like this:

    for (Label label : this.contents.keySet()) {
        this.starTable.add(label);
    }

    this.starTable.row();

    for (Image image : this.contents.values()) {
        this.starTable.add(image).width(width).height(height);
    }

By adding all of the labels to the table, then one row, then all of the images, they line up perfectly.


texts:
While implementing the Retry & Breaker patterns I decided that the Breaker does more then it should so I extracted two responsibilities into their own classes. Here they are.

I stripped out the Threshold to be only data:

public class Threshold
{
    public Threshold(int count, TimeSpan interval, TimeSpan timeout)
    {
        Count = count;
        Interval = interval;
        Timeout = timeout;
    }

    public int Count { get; }

    public TimeSpan Interval { get; }

    public TimeSpan Timeout { get; }

    public override string ToString()
    {
        return $"Count = {Count} Interval = {Interval} Timeout = {Timeout}";
    }
}

The second responsibility is the object counting the events and checking if the threshold is exceeded. I call it Fuse and implemented it this way:

public class Fuse
{
    public Fuse(Threshold threshold)
    {
        Threshold = threshold;
    }

    // todo: add null check
    public IClock Clock { get; set; } = new SystemClock();

    public Threshold Threshold { get; }

    public int Count { get; private set; }

    public DateTime? Point { get; private set; }

    public bool Blown
    {
        get
        {
            return
                Clock.GetUtcNow() - Point <= Threshold.Interval &&
                Count >= Threshold.Count;
        }
    }

    public bool TimedOut
    {
        get { return (Clock.GetUtcNow() - Point) > Threshold.Timeout; }
    }

    public Fuse Increase(int value)
    {
        if (TimedOut) { Reset(); }
        Count += value;
        Point = Clock.GetUtcNow();
        return this;
    }

    public Fuse Increase()
    {
        Increase(1);
        return this;
    }

    public Fuse Reset()
    {
        Count = 0;
        Point = null;
        return this;
    }

    public override string ToString()
    {
        return $"Count = {Count} Point = \"{Point?.ToString(CultureInfo.InvariantCulture)}\" Blown = {Blown} TimedOut = {TimedOut}";
    }
}

To be able to better test it I created an abstraction for the DateTime and called it IClock:

public interface IClock
{
    DateTime GetNow();
    DateTime GetUtcNow();
}

public class SystemClock : IClock
{
    public DateTime GetNow() => DateTime.Now;
    public DateTime GetUtcNow() => DateTime.UtcNow;
}

public class TestClock : IClock
{
    public DateTime Now { get; set; }
    public DateTime UtcNow { get; set; }
    public DateTime GetNow() => Now;
    public DateTime GetUtcNow() => UtcNow;
}

Without the breaker the two new modules are now easier to test:

var threshold = new Threshold(count: 3, interval: TimeSpan.FromSeconds(5), timeout: TimeSpan.FromSeconds(10));
var fuse = new Fuse(threshold) { Clock = new TestClock { UtcNow = new DateTime(2016, 11, 12, 9, 0, 0) } };
fuse.Increase(2).ToString().Dump();
fuse.Increase().ToString().Dump();
(fuse.Clock as TestClock).UtcNow = new DateTime(2016, 11, 12, 9, 0, 0).AddSeconds(20);
fuse.ToString().Dump();
fuse.Increase().ToString().Dump();

Output:

Count = 2 Point = "11/12/2016 09:00:00" Blown = False TimedOut = False
Count = 3 Point = "11/12/2016 09:00:00" Blown = True TimedOut = False
Count = 3 Point = "11/12/2016 09:00:00" Blown = False TimedOut = True
Count = 1 Point = "11/12/2016 09:00:20" Blown = False TimedOut = False


texts:
#include <vector>

std::vector<int> Range(int from, int to, int step = 1) {
    std::vector<int> range;

    if (step > 0) {
        for(int i = from; i < to; i += step) {
            range.push_back(i);
        }
    } else if (step < 0) {
        for(int i = from; i > to; i += step) {
            range.push_back(i);
        }
    }

    return range;
}

I don't like code duplication in my implementation, because I have two almost identical blocks.
Is it possible to avoid it?


texts: VBA save multiple records code, 2 for loops or change to 1 for loop with if statement inside

texts:
I am becoming more critical of the code I write. This is leading me to questions  like "Could I write my code to be more efficient?" Of course the answer to that is a resounding YES. So, I posit the question to those who know much more than I do. What could I do to make this more efficient?

The purpose of this code is to take data from an Access form and save it into two (or three if a condition is met) tables.

Note: I originally asked a form of this question on Stack Overflow.

Private Function SaveSerials()
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rs3 As DAO.Recordset
Dim qry As QueryDef
Dim i as Long
If Not BasicInclude.DebugMode Then On Error GoTo Error_Handler Else On Error GoTo 0
    Dim out As String: out = Validate(Me.Name, msclblstyle)
    If out = "" Then
        Set qry = dbLocal.QueryDefs("qryDeletefromLabelTemp")
        qry.Parameters(0) = "%1" & Me.txtOperator.Value & "%"
        qry.Execute
        Set rs = dbLocal.TableDefs("dbo_Part_Serial_Number").OpenRecordset(dbOpenDynaset, dbSeeChanges)
        Set rs2 = dbLocal.TableDefs("dbo_Label_Trace_Temp").OpenRecordset(dbOpenDynaset, dbSeeChanges)
        For i = 1 To Me.lstData.ListCount - 1
            rs.AddNew
            rs2.AddNew
            rs.Fields("Part_No").Value = Me.txtPart_No.Value
            rs2.Fields("PartNumber").Value = Me.txtPart_No.Value
            rs.Fields("Label_Date").Value = Me.txtLabel_Date.Value
            rs.Fields("Serial_No").Value = Me.lstData.Column(0,i)
            rs2.Fields("PartSerialNumber").Value = Me.lstData.Column(0,i)
            rs.Fields("Operator").Value = Me.txtOperator.Value
            rs2.Fields("Operator").Value = "%1" & Me.txtOperator.Value & "%"
            rs.Fields("Work_Order").Value = Me.cboWork_Order.Value
            rs2.Fields("WorkOrder").Value = Me.cboWork_Order.Value
            rs.Fields("Date_Code").Value = Me.txtDate_Code.Value
            rs2.Fields("Date_Code").Value = Me.txtDate_Code.Value
            rs.Fields("Notes").Value = Me.txtNotes.Value
            rs.Fields("Flex_Circuit_Date_Code").Value = Me.txtFC_Date_Code.Value
            rs.Fields("Flex_Circuit_Int_Date_Code").Value = Me.txtFCI_Date_Code.Value
            rs.Fields("Substrate_Date_Code").Value = Me.txtSubstrate_Date_Code.Value
            rs.Fields("SMF_Date_Code").Value = Me.txtSMF_Date_Code.Value
            rs.Fields("r").Value = Me.chkR.Value
            rs.Update
            rs2.Update
        Next
        If Me.txtPart_No Like "PS*" Then
            Set qry = dbLocal.QueryDefs("qryClear_tbl_BarcodeList")
            qry.Parameters(0) = Environ(GetEnvironString(esComputerName))
            qry.Execute
            Set rs3 = dbLocal.TableDefs("tbl_BarcodeList").OpenRecordset(dbOpenDynaset, dbSeeChanges)
            For i = 1 To Me.lstData.ListCount - 1
                rs3.AddNew
                rs3.Fields("Part_No").Value = Me.txtPart_No.Value
                rs3.Fields("Host").Value = Environ(GetEnvironString(esComputerName))
                rs3.Fields("Serial_No").Value = Me.lstData.Column(0,i)
                rs3.Update
            Next
            DoCmd.OpenReport "rpt_BarcodeList", acViewPreview
        End If
    SaveSerials = 0
    Else
        MsgBox "Please fill out the following fields: " & vbCrLf & out, vbCritical, "Error"
        SaveSerials = 1
    End If
Error_Exit:
set rs = Nothing
set rs2 = Nothing
set rs3 = Nothing
Exit Function
Error_Handler:
    MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: SaveSerials" & vbCrLf & _
           "Error Description: " & Err.Description _
           , vbOKOnly + vbCritical, "An Error has Occured!"
           SaveSerials = -1
Resume Error_Exit
End Function


texts:
Codepen Link

I've tried to Google, but there's no library that has an API to toggle table columns when clicked elsewhere on the page, so I've decided to do this:

function deleteColumnOnClick() {

    $('.hide div').click(function() {
        var index = $(this).index();
        $('table thead th').eq(index).toggleClass('hidden');
        var hidden = $('table thead th.hidden')
        $.each(hidden, function() {
            var idx = $(this).index();
            $.each($('table tbody tr'), function() {
                $(this).find('td').eq(idx).hide();
            });
        });

        var visible = $('table thead th:not(.hidden)');
        $.each(visible, function() {
            var idx = $(this).index();
            $.each($('table tbody tr'), function() {
                $(this).find('td').eq(idx).show();
            });
        });
    });
}

deleteColumnOnClick();

Is this an awful solution? If yes, how do I refactor it?


texts:
I have some function like:

void foo() { ... }

int main() {
  ...
  try {
    ...
    foo();
    ...
  } catch (const std::exception &e) {
    std::cout << "Fatal error: e.what() << std::endl();
    return;
  }
  ...
}

If an exception is thrown from foo, I'd like to know it. Also I want to know the reason of the original exception. I can split the code like this:

int main() {
  ...
  try {
    ...
  } catch (const std::exception &e) {
    std::cout << "Fatal error: " << e.what() << std::endl;
    return;
  }

  try {
    foo();
  } catch (const std::exception &e) {
    std::cout << "Fatal error (foo): " << e.what() << std::endl;
    return;
  }

  try {
    ...
  } catch (const std::exception &e) {
    std::cout << "Fatal error: " << e.what() << std::endl;
    return;
  }
  ...
}

It doesn't look good. Instead, I can update foo:

void foo()
{
  try {
    ..
  } catch (const std::exception &) {
    std::cout << "Foo failed. The reason is:" << std::endl;
    throw;
  }
}

However, I do not like solution, too (maybe, because error logging is split).  What is the right way to raise the exception upward?


texts: Generic test serie for various solutions to the same algorithmic problem

texts:
I am learning how to use the module unittest for test-driven development. Below is a simple yet practical example of an issue I will have many times: one single problem (e.g. an Abstract Data Type (ADT) describing a Data Type and an Operator on it), and various Data Structures (DS) implementing this ADT; in this case the problem of computing the number of elements smaller than an element x in a sorted array A (i.e. its "insertion rank"), and two solutions: binary search and Fibonacci search. This codes "does the job" in that I can define the tests in one single place for all solutions, and the list of solutions in another one, but it does not seem elegant?

import unittest

class InsertionRankTest(unittest.TestCase):
    def generic_test(self,algorithm):
        self.assertEqual(algorithm([1],0),0)
        self.assertEqual(algorithm([1],1),0)
        self.assertEqual(algorithm([1],2),1)
        self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],0),0)
        self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],40),4)
        self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],45),5)
        self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],100),10)

    def test_all_inertionRankAlgorithms(self):
        self.generic_test(binarySearchForInsertionRank)
        self.generic_test(fibonacciSearch)

def binarySearchForInsertionRank(A,x):
    """Computes the insertion rank r of x in A in time logarithmic in
    len(A).

    """
    assert(A!=None)
    if len(A)==0:
        return 0
    else:
        m = len(A)//2
        if x <= A[m]:
            return binarySearchForInsertionRank(A[:m],x)
        else:
            return m+1+binarySearchForInsertionRank(A[m+1:],x)

def fibonacciSearch(A,x):
    """Computes the insertion rank r of x in A in time logarithmic in
    r.

    """
    assert(A!=None)
    if len(A)==0:
        return 0
    l = 0
    r = 1
    while r < len(A) and A[r] < x:
        r += l
        l = r-l # i.e., former value of r
    return l + binarySearchForInsertionRank(A[l:min(r,len(A))],x)

def main():
    unittest.main(exit=False)
if __name__ == '__main__':
    main()

Does one define a class for the ADT, a class for the tests, derives the class for the ADT for each DS, and derives the test classes again? (As a bonus question: can the same tools be used to measure and compare the performance (as measured by either the number of comparisons or the running time)? What is the best way to measure the performance of each solution on each test case?)


texts: Binary heap (priority queue) implementation in JavaScript

texts:
I wrote this heap implementation because I need it to run Dijkstra's algorithm to find paths in a game (for which reason I'd like this implementation not to be unreasonably slow...)

Sadly I don't know JavaScript well, much worse than C or C++ for sure, so I might've made some silly mistakes, I'd love You to point them out for me :)

For example, I'm unsure if keeping heap nodes in an array is an OK approach here; sadly I can't find the relevant SO post now, but I remember reading on SO that using arrays as memory pools results in a gross performance degradation in JavaScript. Keeping nodes in an array is pretty convinient for implementing a heap, but should I have refrained from this anyway?

Also I am aware that people usually tell me my coding style is horrible and unreadable, so I suppose I'm going to get similar comments here, how exactly did I fail this time?

The code seems correct though, it passes this test: https://paste.ee/p/edrYt which was generated with this C++ code: https://ideone.com/zpCtIz

Ah and I tried to stick to JSv5, I tried to refreain from using ES6 features. I hope none slipped through.

var GZKM = GZKM || {}

;(function() {

GZKM.Heap = function() {
    this.arr = []
}

GZKM.Heap.prototype._parentIndex = function(i) {
    return Math.floor((i+1)/2)-1
}

GZKM.Heap.prototype._leftChildIndex = function(i) {
    return 2*(i+1)-1
}

GZKM.Heap.prototype._rightChildIndex = function(i) {
    return 2*(i+1)
}

GZKM.Heap.prototype._swapNodes = function(node1, node2) {
    // Idea taken from this SO answer: https://stackoverflow.com/a/22053474/4385532
    // Doing it this way b/c this SO answer scared me that the standard way may lead to a memory leak: https://stackoverflow.com/a/872433/4385532
    this.arr[node1._i] = [this.arr[node2._i], this.arr[node2._i]=this.arr[node1._i]][0]
    node1._i = [node2._i, node2._i=node1._i][0]
}

GZKM.Heap.prototype._moveUp = function(node) {
    var canMove = function() {
        return node._i > 0
    }
    var mustMove = function() {
        return this.arr[this._parentIndex(node._i)].priority > node.priority
    }.bind(this)
    while(canMove() && mustMove())
        this._swapNodes(node, this.arr[this._parentIndex(node._i)])
}

GZKM.Heap.prototype._moveDown = function(node) {
    var canMove = function() {
        return this._leftChildIndex(node._i) < this.arr.length
    }.bind(this)
    var nextNode = function() {
        if(this._rightChildIndex(node._i) >= this.arr.length ||
                this.arr[this._rightChildIndex(node._i)].priority > this.arr[this._leftChildIndex(node._i)].priority)
            return this.arr[this._leftChildIndex(node._i)]
        else return this.arr[this._rightChildIndex(node._i)]
    }.bind(this)
    var mustMove = function() {
        return nextNode().priority < node.priority
    }
    while(canMove() && mustMove())
        this._swapNodes(node, nextNode())
}

GZKM.Heap.prototype.push = function(priority, elt) {
    var eltIndex = this.arr.length;
    this.arr.push({elt: elt, priority: priority, _i: eltIndex})
    var ret = this.arr[eltIndex]
    this._moveUp(this.arr[eltIndex])
    return ret
}

GZKM.Heap.prototype.pop = function() {
    if(!this.arr.length) return undefined
    this._swapNodes(this.arr[0], this.arr[this.arr.length-1])
    var ret = this.arr.pop()
    this._moveDown(this.arr[0])
    return ret
}

GZKM.Heap.prototype.reprioritize = function(node, newPriority) {
    node.priority = newPriority
    this._moveUp(node)
    this._moveDown(node)
}

})()