texts: Keeping data processing out of controllers

texts:
I would like to start by mentioning that I am LAMP stack guy who happens to be making my first ever .NET C# web app and I'm seeking general advises for best practices and to see how more experienced people would have done it.

I am using code first development pattern with latest Entity Framework . I have a AppUser model. The user could be on of few types, one of them is employee.

public class AppUser{
  public int Id { get; set; }
  public UserType Type { get; set; }
  public Title Title { get; set; }
  public string FirstName { get; set; }
  public string MiddleName { get; set; }
  public string LastName { get; set; }
  public virtual AddressDetails AddressDetails { get; set; }
  public virtual Company Company { get; set; }
  ..................................................
}

public class AddressDetails
{
  public int Id { get; set; }
  public string AddressLine { get; set; }
  public string City { get; set; }
  public string County { get; set; }
  public string PostCode { get; set; }
  public float Latitude { get; set; }
  public float Longtitude { get; set; }
  [JsonIgnore]
  public virtual AppUser User { get; set; }
}

I believe that smaller methods are the better. So, I am trying to keep controllers as small as possible. I made classes which handles all interactions with database and keeps business logic out of Models and Controllers. First class is abstract MasterRepository ,which has  logic for Database Update/Add/SaveChanges. All other "repositories" inherit it.
( "AppDB" is inheriting from DbContext and holds all DbSets)

public abstract class MasterRep
{
  protected AppDB _db { get; set; }
  protected AppUser _currentUser { get; set; }

  protected int _companyId { get; set; }
  protected string _applicationUserId { get; set; }
  public MasterRep(string applicationUserId, AppDB db = null)
  {
    _db = db ?? new AppDB ();
    _currentUser = GetUserByApplicationId(applicationUserId);
    _companyId = _currentUser.Company.Id;
    _applicationUserId = applicationUserId;
   }
  }
  .........................................

Each model has it own "repository". So, User of type "employee" has:

 public class EmployeeRep : UserRep
{
    public EmployeeRep(string applicationUserId, AppDB db = null) :      base(applicationUserId, db) { }

    private IEnumerable<AppUser> Employees
    {
        get
        {
            IEnumerable<AppUser> employees = _db.AppUsers.Where(
               r =>
               r.Company.Id == _companyId &&
               r.Type == UserType.Employee &&
               r.IsDeleted == false
            );
            return employees;
        }
    }
   public User GetById(int Id)
    {
        User employee = Employees.FirstOrDefault(r =>
            r.Id == Id
        );
        return employee;
    }
    .......................

The EmployeeRep holds all logic for getting/updating all employees.

And here is example of retrieving a single employee in controller

 public class HomeController : Controller
  {
    private EmployeeRep _employeeRep { get; set; }
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

            _employeeRep = (User.Identity.GetUserId() != null) ? new EmployeeRep(User.Identity.GetUserId()) : null;

    }
    public ActionResult Index(int id)
    {
        NHUser currentUser = _employeeRep.CurrentUser;

        NHUser employee = _employeeRep.GetById(id);
        ViewBag.CurrentUser = currentUser;

        return View(employee );
    .............................................

So, controllers are in charge of what get displayed and "Repositories" in charge of all business logic/database interactions. All methods are small and doing only one task. However, I am confused by open source projects which I found on github. It looks like everyone doing their own thing.

Am I on a right track here? What is more common way of achieving same goal? i.e having a separate class which handles data processing.


texts: Accept a boolean or a list of acceptable values

texts:
I want to be able to accept True/False or a list of acceptable exit statuses for a command. This way I can choose whether to check and default to checking exit status 0 unless a list of exit statuses is provided to check against. My first instinct is to do a double reassignment.

def raw(self, ssh_command, check=False):
    # removed ssh calls and processing
    check = [] if not check else check
    check = [0] if check is True else check
    # c.call_result.status -> <encapsulation object>.<named tuple>.<exit status>
    if c.call_result.status not in check:
        raise RuntimeError("Exit status of command {} was {}.".format(ssh_command, c.call_result.status))
    return c.call_result

Is this design simply non-pythonic. Should I refactor to not accept booleans and change check=None to the function with check = [] if check is None?

def raw(self, ssh_command, statuses=None):
    # removed ssh calls and processing
    # This won't work because we'll check against an empty list always even when None is passed.
    statuses = [] if statuses is None else statuses
    if c.call_result.status not in statuses:
        raise RuntimeError("Exit status of command {} was {}.".format(ssh_command, c.call_result.status))
    return c.call_result

EDIT:
Here are what I intended the above to be in order

Accepting booleans or list of exit statuses to accept:

def raw(self, ssh_command, check=False):
    # removed ssh calls and processing which instantiate object c
    check = [0] if check is True else check
    if check and c.call_result.status not in check:
        raise RuntimeError("Exit status of command {} was {}.".format(ssh_command, c.call_result.status))

Not accepting booleans only list of statuses to accept (changed param as this is backwards incompatible):

def raw(self, ssh_command, statuses=None):
    # removed ssh calls and processing which instantiate object c
    if statuses and c.call_result.status not in check:
        raise RuntimeError("Exit status of command {} was {}.".format(ssh_command, c.call_result.status))
    return c.call_result


texts: Query to find instances of two types of events occurring more than one second apart

texts:
I have 3 tables on my database: BusinessObject and CustomEvent, and EventType. BusinessObject having a lot of columns, CustomEvent having the following:

Id
EventTypeId
DateEvent
CommentEvent
UserId
BusinessObjectId

I want to get all the BusinessObject having two CustomEvent with EventTypeId in (10, 11) such has the difference between the two DateEvent are more than 1 second. From the 6 first month of this year.

I came up with the following query but it's quite slow (~40 seconds). I assume there's a (lot of) ways to speed this up, but my SQL level is not good enough.

Here's the query:

select bo.Id
from BusinessObject bo
where
(
    select top 1 DATEDIFF(second,
                (select top 1 DateEvent from CustomEvent where EventTypeId = 11 and BusinessObjectid = bo.BusinessObjectId),
                (select top 1 DateEvent from CustomEvent where EventTypeId = 10 and BusinessObjectid = bo.BusinessObjectId))
    from CustomEvent ce inner join BusinessObject innerBO on ce.BusinessObjectId = bo.BusinessObjectId
    where EventTypeId = 11
        and innerBO.CreationDate < '20180701'
        and innerBO.CreationDate > '20180101'
        and innerBO.BusinessObjectId = bo.BusinessObjectId
) > 1

FYI, the query returns 4.138 rows. Here's the tables volumes:

BusinessObject  => 302k lines

CustomEvent => 4.326k lines

How could I speed this up?


texts: Cucumber scenario to test REST interface to scuba diving logbooks

texts:
I am looking for ideas how to improve this cucumber scenario (testing a REST interface) and make it more concise.

Feature: Get list of Logbooks
    As a client, I want to get a list of a certain users logbooks so that i can present
    the logbooks name and the number of scuba dives to the user.

Scenario: Get a list of logbooks
    Given the system knows about the user "tom"
    And the user has the email "tom@tom.com"
    And he owns the logbooks
      | pacific  |
      | atlantic |
      | gulf     |
    When the client asks the system for a list of logbooks owned by user
    Then the client gets a list with 3 logbooks
    And all logbooks of the list have the users name
    And all logbooks of the list have the users email
    And one logbook has the name
      | pacific  |
      | atlantic |
      | gulf     |
    But if the user has no logbook
    And the client requests a logbook from the system
    Then the client gets an error message

Details:
A client (browser/other service) is accessing a logbook service via REST. The client can ask with a user name and an email address the system about a list of logbooks (named pacific, atlanic and gulf) the user might have stored at the system. In case the user has no logbooks stored, a error message is returned.


texts: Nested values copies from one object to another

texts:
Here is a nodejs code that copies values from one object (submitted from a firm) to a model object.

Model:

var directory_model = {

    "link_title": {
        "value": 1, // This needs to be filled with object data
        "validation": null
    },

    "link_desc": {
        "value": 2, // This needs to be filled with object data
        "validation": null
    },
};

Object values that must get into the model:

   { link_title: 'test1', link_desc: 'test2' }

Here is the code that does, it with lodash. This code does the job:

_.forOwn(directory_model, function(directory_model_value, directory_model_key) {
    _.forOwn(fields, function(fields_value, fields_key) {
        "use strict";
        if (directory_model_key === fields_key)  {
            directory_model[directory_model_key].value = fields_value;
        }
    });

});

I don't like the nested loop, and would like to know if you know another way to do this.
I found several ways, but none of them works, because of the nested properties.


texts: Python program to transform an Excel document, with some parsing

texts:
I wrote this to parse through an Excel doc, extract desired columns, parse certain cells and output another formatted Excel doc.

This is the original Excel doc I have condensed most of the columns for space

Here are the the results of the program that I am mostly happy with, it parses the name column and writes a unit identifier(i.e 83) along with a  tower identifier(i.e 5) on a new line along with a completed date if the completed column is TRUE.  I think the only thing I would change would be getting rid of the blank line under the row that has H 7

And here is the code

import xlrd
import xlwt
import re

# open and create workbook
workbookread = xlrd.open_workbook('seedtestexcelbytask.xls')
workbookwrite = xlwt.Workbook('output.xlsx')

# open and create sheets
worksheetread = workbookread.sheet_by_index(0)
worksheetwrite = workbookwrite.add_sheet('Sheet1')

timelist = []
towerlist = []

i = 0
l = 0
t = 0

# iterate through rows in worksheet, get columns completed, completed_at and name.
# add to timelist[] and towerlist[] if completed == true
for rows in range(worksheetread.nrows):
    cell0 = worksheetread.cell(rows, 2).value
    cell1 = worksheetread.cell(rows, 3).value
    cell2 = worksheetread.cell(rows, 15).value

    if cell0 == 1:
        parsedvalue = re.split(', |/', cell2)
        timelist.append(cell1)
        towerlist.append(parsedvalue)

b = 2
g = 1
for rows in range(len(timelist)):
    row = worksheetwrite.row(i)

# get current index from timelist and towerlist and assign to currenttime  and currentvalue

    currenttime = timelist[t]
    currentname = towerlist[t]

# get the length of the current index this will help us decide how to parse
    length = len(towerlist[t])

# if length <= 2 the index is not formatted properly so we only need index 1 which is the cafe and towers together
    if length <= 2:
        row.write(0, currenttime)
        row.write(1, currentname[1])
        i += 1
        l += 1

# if length = 4 index is formatted properly and we just grab the columns we need
    elif length == 4:
        a = 2

        for values in range(0, 2):
            row = worksheetwrite.row(l)
            row.write(0, currenttime)
            row.write(1, currentname[1])
            row.write(2, currentname[a])
            a += 1
            i += 1
            l += 1

# if length > 4 we need to iterate through each index and write them
    else:

        # define the length of the current cell of the excel sheet we have
        lengthd = (len(currentname)+1)/2
        length = int(lengthd)

        for values in range(length):
            # set variables that we will need to hold on to
            currentcafe = currentname[g]
            currenttower = currentname[b]

            # if the value of the current tower is 2,4,5,6,7 we need to write the current cafe and current tower
            # then move on to the next value and set that as the current cafe, we also need to jump to the
            # value after the current cafe and set that as the current tower
            if currenttower == "2" or currenttower == "4" or currenttower == "5" or currenttower == "6" or currenttower == "7":
                row = worksheetwrite.row(l)
                row.write(0, currenttime)
                row.write(1, currentcafe)
                row.write(2, currenttower)

                b += 1
                i += 1
                g = b
                b = g + 1
            # otherwise we can just write the value fo the current cafe and current tower, advance to the next value
            # which is another tower and set current tower to that
            else:
                row = worksheetwrite.row(l)
                row.write(0, currenttime)
                row.write(1, currentcafe)
                row.write(2, currenttower)
                b += 1
                i += 1

            l += 1
        i += 1
    t += 1
workbookwrite.save('output.xls')

This is the first time I have written anything with Python and I am fairly new to programming, any comments would be greatly appreciated.


texts:
This code is intended to function exactly like functools.lru_cache. Is there anything I could improve in design, implementation, style, or any other area? (Python version = 3.6.*).

from collections import OrderedDict
from functools import wraps

def lru_cache(maxsize=None):
    def decorator(func):

        cache = OrderedDict()
        @wraps(func)
        def decorated(*arg, **kwargs):
            key = (*arg, None, *kwargs)
            try:
                val = cache[key]
                del cache[key]
            except KeyError:
                val = func(*arg, **kwargs)

            cache[key] = val
            if maxsize and len(cache) > maxsize:
                cache.popitem(last=False)

            return val

        return decorated
    return decorator


texts: Checking whether relations are equal to foreign fields using LINQ Any()

texts:
Can you find a more understandable way to write the following one-liner?

Enumerable.Range(0, relation.Fields.Count).
           Any(i => relation.Fields[i] != relation.ForeignFields[i])

but still preserving its brevity?

Simply put, I wanna cycle on relation.Fields collection to see if their string elements are one-by-one equal to relation.ForeignFields ones.

The reason I had to use Enumerable.Range is that I need an index, in order to cycle the two collections.

Note: they have for sure the same count.

I wrote an extension method based on @t3chb0t's answer


texts:
I am developing data-interfacing that converts between two different data models.
However, I must be sure that all required fields exist. Therefore I have written this utility class that I can easily use to verify required fields.

However I am unsure whether this is the best way because of the expression that needs to be compiled and the usage of reflection. Any feedback is welcome!

Usage

    public OutputDataElement DetermineRetailTransactionShopperType(IHeaderEntity headerEntity)
    {
        Ensure.IsNotNull(() => headerEntity);
        Ensure.IsNotNull(() => headerEntity.ShopId, "headerEntity");

        // Some mapping logic removed from the example
    }

Utility

/// <summary>
/// Helper class able to ensure expectations
/// </summary>
public static class Ensure
{
    public static void IsNotNull<T>(Expression<Func<T>> property) where T : class
    {
        IsNotNullImpl(property, null);
    }

    public static void IsNotNull<T>(Expression<Func<T>> property, string paramName) where T : class
    {
        IsNotNullImpl(property, paramName);
    }

    private static void IsNotNullImpl<T>(Expression<Func<T>> property, string paramName) where T : class
    {
        // Compile the linq expression
        Func<T> compiledFunc = property.Compile();

        // Invoke the linq expression to get the value
        T fieldValue = compiledFunc.Invoke();

        // Check whether we have a value
        if ((fieldValue is string && fieldValue.ToString() == string.Empty) || (fieldValue == null))
        {
            // We have no value. Get the initial expression
            var expression = (MemberExpression)property.Body;

            // log information about the expression that failed
            throw new ArgumentException(string.Format("Missing required field '{0}'", expression.Member.Name), string.IsNullOrEmpty(paramName) ? null : paramName);
        }
    }
}


texts: Is this the right way to work with callbacks and the EventEmitter?

texts:
I'm creating a small online multiplayer game in NodeJS and I'm wondering if I'm "doing it right".
Here is a bit of my code:

// app.js
// if I give an id as argument we assume it's an existing player.
var Player = new player();

Player.on('playerLoaded', function (err, result) {

    if (result) {

        Player.setName('somename');

        Player.on('setName', function (err, result) {

            console.log('Name changed');

        });

    } else {

        // couldn't load the player

    }

});

This is my player object:

function Player(id) {

    // if we don't have a id, this player needs to be created
    this.id = (typeof id !== 'number') ? this.createPlayer() : this.setPlayer(id);
    this.name = "";
    EventEmitter.call(this);

}

This is the createPlayer method:

Player.prototype.createPlayer = function () {

    var self = this;

    // we only need a datetime to insert
    connection.query("INSERT INTO players SET `created_at` = now()", function (err, result) {

        if (result) {

            process.nextTick(function () {

                if (result.insertId) {

                    console.log("Successfully found player no. " + result.insertId);

                    self.id = result.insertId;

                    // everything was successful
                    self.emit('playerLoaded', false, true);

                } else {

                    console.log("Trouble inserting a new player");

                    self.emit('playerLoaded', true, false);

                }

            });

        } else {

            process.nextTick(function () {

                console.log("Trouble with the mysql while inserting player: " + err);

                self.emit('playerLoaded', err, null);

            });

        }

    });

};

And this is the setName method:

Player.prototype.setName = function (name) {

    var self = this;

    connection.query("UPDATE players SET ? WHERE ?", [
        { name: name },
        { id: self.id }
    ], function (err, result) {

        if (result) {

            process.nextTick(function () {

                self.name = name;

                console.log("Successfully updated name of player no. " + self.id);

                self.emit('setName', false, true);

            });

        } else {

            process.nextTicket(function () {

                console.log("Trouble with the mysql while changing player name: " + err);

                self.emit('setName', err, false);

            });

        }

    });

};

Basically my question is if this is the right way to deal with callbacks?


texts: OOP Web scraper using regex to grab tag contents

texts:
I'm about learning about implementing the solid principle in PHP.

I want to create simple content crawler/grabber from some websites. This crawler will grab the content from the website url. Since we know that every website has different html tag structure, so I created an interface.

<?php

interface BotInterface
{

    public function tembakURL();

    public function parseBody();
}

Then implemented the interface into child class. My plan is to create a class for every website. Here's an example.

<?php

class BotYogyes implements BotInterface
{

    protected $rest;
    protected $url;
    protected $body;

    public function __construct($url, \GuzzleHttp\Client $rest) {
        $this->rest = $rest;
        $this->url = $url;
    }

    public function tembakURL() {
        $response = $this->rest->get($this->url);
        $code = $response->getStatusCode();
        $body = $response->getBody();
        if ($code == 200) {
            $this->body = $body;
        } else {
            throw new Exception("Gagal menembak url [$code]");
        }
    }

    public function parseBody() {
        $html = implode('', $this->unfoldLines($this->body));
        #judul
        preg_match_all('/\<h1\>(.*)\<div\sclass="social\-share"\>/', $html, $header, PREG_PATTERN_ORDER);
        preg_match_all('/\<h1\>(.*)\<\/h1\>/', $header[0][0], $judul, PREG_PATTERN_ORDER);
        preg_match_all('/\<p\sclass="address"\>(.*?)\s\(\<a/', $header[0][0], $alamat, PREG_PATTERN_ORDER);
        preg_match_all('/\<p\sclass="meta\-description"\>(.*?)\<\/p>/', $header[0][0], $deskripsi, PREG_PATTERN_ORDER);
        #konten
        preg_match_all('/\<div\sid="photo\-gallery\-mini"\>(.*)\<\!\-\-\sinsertRelatedArticle\(\)\s\-\-\>/', $html, $match, PREG_PATTERN_ORDER);
        preg_match_all('/\<p\>(.*?)\<\/p\>/', $match[0][0], $paragraf, PREG_PATTERN_ORDER);
        #peta
        preg_match_all('/\<p\sclass="address"\>GPS\sCoordinate:\s\<a[^\>]*\>(.*?)\<\/a\>\<\/p\>/', $html, $peta, PREG_PATTERN_ORDER);
        file_put_contents('/vagrant/tmp/anarky.txt', var_export(array($judul, $alamat, $deskripsi, $paragraf, $peta), true));
    }

    private function unfoldLines($content) {
        $data = array();
        $content = explode("\n", $content);
        for ($i = 0; $i < count($content); $i++) {
            $line = rtrim($content[$i]);
            while (isset($content[$i + 1]) && strlen($content[$i + 1]) > 0 && ($content[$i + 1]{0} == ' ' || $content[$i + 1]{0} == "\t" )) {
                $line .= rtrim(substr($content[++$i], 1));
            }
            $data[] = $line;
        }
        return $data;
    }

}

This how the classes will be used:

<?php
try {
            $rest = new \GuzzleHttp\Client();
            $sync = new BotYogyes('http://website.to/grab/content', $rest);
            $sync->tembakURL();
            $sync->parseBody();
        } catch (Exception $e) {
            watchdog('bot_yogyes', $e->getMessage(), null, WATCHDOG_ERROR, null);
        }

These code blocks work properly, but, am I it doing right?


texts: Most efficient way in C++ to strip strings

texts:
If I want to strip a string completely of its whitespaces, punctuation and numbers (i.e. anything that is not A-Z, a-z), what is the most efficient way of doing it in C++?

I tried this:

string strip(string in) {
    string final;
    for(int i = 0; i < in.length(); i++) {
        if(isalpha(in[i])) final += in[i];
    }
    return final;
}

It works as expected, but is too slow on strings with ~2000 characters. I figured out that the code causing this slowness is the isalpha() call.

So does anyone know of a better, more efficient way of stripping a string of everything except [A-Z][a-z] in C++?

At most, the string will be 20000 characters long and I need to strip it in <1 second.

Thanks in advance.

EDIT:

If I remove the if condition, the output will display instantly. But with the if condition, it will take about 1.6 seconds to display the output.

For trying out the code, use this: http://pastebin.com/g3NtBFaD and a normal 20k char string. Then try comparing.


texts:
I have two classes with similar first checking codes, but different behaviors. I suppose there is a way to refactor the code, so I don't need to retype it every time.  Is it possible to refactor this, or I must retype this code every time?

# Get actual logged user
user, msg = checkLoggedUser()
if user:
    self.renderPage("customMessage.htm", custom_msg=msg)
else:

The code is simple. Forget about my way to render the page, is a method over my own PageHandler class that works.

# Check for actual logged user
def checkLoggedUser():
    # Get actual logged user
    user = users.get_current_user()

    # Don't allow to register for a logged user
    if user:
        return True, "You are already logged in."
    else:
        return False, None

# Get and post for the login page
class Login(custom.PageHandler):
    def get(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            self.renderPage('login.htm')

    def post(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            # Make the login
            # bla, bla bla... code for login the user.

# Get and post for the register page
class Register(custom.PageHandler):
    def get(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            self.renderPage("registerUser.htm")

    def post(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            # Store in vars the form values
            # bla, bla bla... code for register the user.


texts: Super Resolution in the Wolfram Language, Attempt 2

texts:
This is a wolfram language program I wrote for super-resolution, in this case meaning to guess at how to increase the the resolution, and so detail shown in a raster image such as a photograph.

It uses a different but related approach to its predecessor, that I created some time ago:
Super Resolution in the Wolfram Language

I think that I have had more success this time.

The program upscales an image with simple interpolation, before choosing random regions from the original image to transparently replace areas of the new image if they are similar enough.

Run the program by calculating all three input blocks provided below in order, note that this seems to use up most of the available recourses on a free account for a calculation.

attempts decides how long the search takes.

Increasing required results in better candidates but each takes longer to find.

And alpha is the transparecy to use for each successful candidate.

originalSizeX = 100;
original = ImageResize[ExampleData[{"TestImage", "U2"}], originalSizeX];
resultSizeX = 300;
attempts = 20000;
required = 0.2;
alpha = 0.5;

originalSizeY = ImageDimensions[original][[2]];
result = ImageResize[original, resultSizeX];
resultSizeY = ImageDimensions[result][[2]];

original
result
Map[
  {
    candidateSize = RandomInteger@{1, originalSizeX},
    candidateSourcePos = {
      RandomInteger@{1, originalSizeX - candidateSize + 1},
      RandomInteger[{1, originalSizeY - candidateSize + 1}]},
    candidateSource = ImageTake[
      original,
      {candidateSourcePos[[2]], candidateSourcePos[[2]] + candidateSize - 1},
      {candidateSourcePos[[1]], candidateSourcePos[[1]] + candidateSize - 1}],
    candidateTargetPos = {
      RandomInteger@{1, resultSizeX - candidateSize + 1},
      RandomInteger@{1, resultSizeY - candidateSize + 1}},
    candidateTarget = ImageTake[
      result,
      {candidateTargetPos[[2]], candidateTargetPos[[2]] + candidateSize - 1},
      {candidateTargetPos[[1]], candidateTargetPos[[1]] + candidateSize - 1}],
    dist = ImageDistance[
      candidateSource, candidateTarget,
      DistanceFunction -> NormalizedSquaredEuclideanDistance],
    result = If[
      dist < required,
      ImageCompose[
        result, {candidateSource, alpha},
        {candidateTargetPos[[1]] - 1, resultSizeY - candidateTargetPos[[2]] + 1},
        {Left, Top}
      ],
      result
    ]
  }&,
  Range@attempts
];
result
result // ImageAdjust


texts: Breadth First Search Python Implementation

texts:
I have the below implementation of the BFS algorithm, in which I've used OrderedDict instead of a list or set. ( I've used OrderedDict in DFS to preserve the order of visited vertices ). Is this an efficient implementation of BFS and any other suggestions for improvements?

(Note: My use case is a sparse graph, i.e., the input will always be an adjacency list)

import collections

def bfs_iterative(graph, vertex):
    visited = collections.OrderedDict()
    queue = collections.deque([vertex])
    while queue:
        vertex = queue.popleft()
        if vertex not in visited:
            visited[vertex] = True
            queue.extend(graph[vertex])
    return list(visited.keys())

def main():
    test_graph1 = {
        'A': ['B', 'C'],
        'B': ['A', 'D', 'E'],
        'C': ['A', 'F'],
        'D': ['B'],
        'E': ['B', 'F'],
        'F': ['C', 'E']
    }

    test_graph2 = {
        1: [2, 4, 5],
        2: [3, 6, 7],
        3: [],
        4: [],
        5: [],
        6: [],
        7: []
    }

    print(bfs_iterative(test_graph1, 'A'))    # output: ['A', 'B', 'C', 'D', 'E', 'F']
    print(bfs_iterative(test_graph2, 1))      # output: [1, 2, 4, 5, 3, 6, 7]

if __name__ == '__main__':
    main()


texts:
this is the first time I' implementing a Trie. My goal was to make it as simple as possible. So here is the result:
Can I simplify anything else? Are there some things I can change to increase performance ? Also any feedback on code quality/design is welcome :)
Node.java

package trie;

public class Node {
    final Node[] children = new Node[26];
    boolean isEnd = false;
}

Trie.java

package trie;

import java.util.ArrayList;
import java.util.List;

public class Trie {
    static final int ALPHABET_SIZE = 26;
    final Node root = new Node();

    void add(String str) {
        Node curr = root;
        for (int i = 0; i < str.length(); i++) {
            int idx = str.charAt(i) - 'a';
            if (curr.children[idx] == null) {
                curr.children[idx] = new Node();
            }
            curr = curr.children[idx];
        }
        curr.isEnd = true;
    }

    Node getNode(String str) {
        Node node = root;
        for (int i = 0; i < str.length(); i++) {
            Node child = node.children[str.charAt(i) - 'a'];
            if (child == null) {
                return null;
            }
            node = child;
        }
        return node;
    }

    boolean contains(String str) {
        Node node = getNode(str);
        return node != null && node.isEnd;
    }

    List<String> prefixedWords(String str) {
        Node curr = getNode(str);
        List<String> prefixedWords = new ArrayList<>();
        DFS(curr, str, prefixedWords);
        return prefixedWords;
    }

    void DFS(Node root, String prefix, List<String> list) {
        if (root != null) {
            if (root.isEnd) {
                list.add(prefix);
            }
            for (int i = 0; i < ALPHABET_SIZE; i++) {
                if (root.children[i] != null) {
                    DFS(root.children[i], prefix + (char) (i + 'a'), list);
                }
            }
        }
    }
}


texts:
I have the following MySQL query which selects product details and whether the viewing user likes them. I feel like it could be more efficient and that there is a more practical approach than using a sub-query here.

Any suggestions?

SELECT p.*,
         pm.filename AS thumbnail,
         (SELECT COUNT(id) FROM likes WHERE productId = p.id AND
                userId = '$viewingUserId' AND isActive = '1' LIMIT 1)
            as liked
            FROM products p, productmedia pm
        WHERE p.userId = '$userId'
        AND p.id = pm.productId
        AND pm.sortOrder = '0'
        ORDER BY p.timestamp DESC


texts: Singleton class and correct way to access it in C++

texts:
I'm currently trying to implement the singleton pattern in C++. After reading about it for a while now, it seems like there are a really large amount of different ways to do this.

Is the way I ended up doing it correct or did I miss out on something important here? Is this implementation thread safe in modern C++ (I read there were some changes to that in particular with C++11)? In addition I am not sure at all about the way I am accessing the class within MyFunction().

Is it really necessary to use a raw pointer there? Does this code contain any memory leaks?

#include <iostream>

class Singleton
{
private:

    Singleton();
    ~Singleton();

public:

    static Singleton& instance()
    {
        static Singleton INSTANCE;
        return INSTANCE;
    }

    void Test();
};

void Singleton::Test()
{
    std::cout << "Test() called" << std::endl;
}

Singleton::Singleton()
{
    std::cout << "CONSTRUCTOR CALLED" << std::endl;
}

Singleton::~Singleton()
{
    std::cout << "DESTRUCTOR CALLED" << std::endl;
}

void MyFunction()
{
    // use the singleton class
    Singleton * MySingleton = &Singleton::instance();
    MySingleton->Test();
}

int main()
{
    MyFunction();
    return 0;
}


texts: ASP.net Identity admin reset user password

texts:
I have an application which uses ASP.net Identity as for its user authentication.

I do not wish for users to reset their own password (for reasons which are not relevant here), so I have developed the following back end system to allow system administrators to reset the users password.

I have the following implementation:

Password Reset View:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

ResetPasswordViewModel

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

            @Html.LabelFor(model => model.NewPassword, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.NewPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NewPassword, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })

                <input type="submit" value="Reset Password" class="btn btn-default" />

}

AccountAdmin Controller

    // GET: /AccountAdmin/ResetPassword
    public ActionResult ResetPassword(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ResetPasswordViewModel model = new ResetPasswordViewModel() { Id = id };
        return View(model);
    }

    //
    // POST: /AccountAdmin/ResetPassword
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ResetPassword(ResetPasswordViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var removePassword = UserManager.RemovePassword(model.Id);
        if (removePassword.Succeeded)
        {
            //Removed Password Success
            var AddPassword = UserManager.AddPassword(model.Id, model.NewPassword);
            if (AddPassword.Succeeded)
            {
                return View("PasswordResetConfirm");
            }
        }

        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

ResetPassword View Model

public class ResetPasswordViewModel
{
    public string Id { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}


texts:
I've got a view which has a corresponding template. The template looks something like like:

        <button id="saveStream" class="button-icon button-small save <%= userLoaded ? '' : 'disabled' %>" title="<%= userLoaded ? saveStreamMessage : cantSaveNotSignedInMessage %>">

        </button>

        <button id="clearStream" class="button-icon button-small clear" title="<%= chrome.i18n.getMessage('clearStream') %>" >

        </button>

I've passed into the template some variables such as userLoaded. This allows me to render the initial state of the saveStream button.

Now, the state of userLoaded has changed and I would like to update the button. I don't want to render my entire template again because streamItems is an expensive list to render.

So, I wrote the following:

initialize: function() {
    this.listenTo(User, 'change:loaded', this.toggleSaveStream);
},

toggleSaveStream: function () {
    var userLoaded = User.get('loaded');
    var templateHelpers = this.templateHelpers();

    this.ui.saveStreamButton.toggleClass('disabled', userLoaded);
    this.ui.saveStreamButton.attr('title', userLoaded ? templateHelpers.saveStreamMessage : templateHelpers.cantSaveNotSignedInMessage);
}

Which serves to keep my button up to date.

I'm unhappy with this solution because the logic for the disabled state of the button is duplicated into two spots. Is this a valid concern? How to handle?

Button is rendered disabled in template and I don't want to re-render whole template to change button state. How to stay DRY?


texts: Optimize way of reading and writing file in node.js

texts:
I want to read the content of file then want to make few updates to content and then write that content to another file. I have created the code with node.js as follows.

var filePath = path.join('public/index.html'),
    exactFileName = path.basename(filePath),
    outputDir = "output/";
function readContent(callback) {
    //start reading file
    fs.readFile(filePath, {encoding: 'utf-8'}, function (err, content) {
        if (err) return callback(err)
        callback(null, content);

        //Check if directory available or not, if no then create new directory
        if(!fs.existsSync(outputDir)){
            fs.mkdirSync(outputDir, 0766, function(err){
                if(err){
                    console.log(err);
                    response.send("ERROR! Can't make the directory! \n");
                }
            });
        }

        /*
            will process content here and then write to output file
        */

        //write the data in another file
        fs.writeFile(outputDir+''+exactFileName, content, function (err) {
            if (err) return console.log(err);
            console.log('Content written to '+ exactFileName);
        });
    })
}

readContent(function (err, content) {
    console.log(content);
});

I need inputs on:

optimizing this code
direction on how we can apply it for multiple files


texts:
The problem is to find LCM of two numbers. I have tried to solve the problem in two ways. First by using the LCM formula :

LCM (a,b)= a*b/GCD(a,b).

Second, by finding out the multiples of each number and then finding the first common multiple.
 Below are the codes that I have written:

Code 1:

#Using the LCM formula LCM = a*b / gcd(a,b)
def LCM(x , y):
    """ define a function LCM which takes two integer inputs and return their LCM using the formula LCM(a,b) = a*b / gcd(a,b) """
    if x==0 or y == 0:
        return "0"

    return (x * y)/GCD(x,y)

def GCD(a , b):
    """ define a function GCD which takes two integer inputs and return their common divisor"""
    com_div =[1]
    i =2
    while i<= min(a,b):
        if a % i == 0 and  b % i ==0:
            com_div.append(i)
        i = i+1
    return com_div[-1]

print LCM(350,1)
print LCM(920,350)

Code 2:

#Finding the multiples of each number and then finding out the least common multiple
def LCM(x , y):
    """ define a function LCM which take two  integerinputs and return their LCM"""
    if x==0 or y == 0:
        return "0"
    multiple_set_1  = []
    multiple_set_2  = []
    for i in range(1,y+1):
        multiple_set_1.append(x*i)
    for j in range(1,x+1):
        multiple_set_2.append(y*j)
    for z in range (1,x*y+1):
        if z in multiple_set_1:
            if z in multiple_set_2:
                return z
                break

print LCM(350,450)

I want to know which one of them is a better way of solving the problem and why that is the case. Also suggest what other border cases should be covered.


texts:
Please let me know your thoughts on the code below, please be brutal. Here is the question I solved:

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]

   public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root==null){
            return res;
        }
        ArrayList<Integer> level = new ArrayList<Integer>();
        level.add(root.val);
        res.add(level);
        int depth=1;
        queue.add(root);
        TreeNode empty = new TreeNode(2);
        queue.add(null);
        level = new ArrayList<Integer>();
        while(!queue.isEmpty()){
            TreeNode curr = queue.poll();
            if(curr==null){
                if(!queue.isEmpty()){
                    queue.add(null);
                }
                else{
                    break;
                }
                res.add(level);
                level = new ArrayList<Integer>();

                depth++;
            }
            else{
                if(depth%2==0){
                    if(curr.left!=null){
                        level.add(curr.left.val);
                        queue.add(curr.left);
                    }
                    if(curr.right!=null){
                        level.add(curr.right.val);
                        queue.add(curr.right);

                    }
                }
                else{
                    if(curr.right!=null){
                        level.add(curr.right.val);
                        queue.add(curr.right);
                    }
                    if(curr.left!=null){
                        level.add(curr.left.val);
                        queue.add(curr.left);
                    }
                }
            }
        }
        return res;
    }


texts:
From SICP

  Exercise 1.11: A function \$f\$ is defined by the rule that:

  \$f(n) = n\$ if \$n < 3\$, and

  \$f(n) = f(n-1)+2f(n-2)+3f(n-3)\$ if \$n >= 3\$.

  Write a procedure that computes f by means of a recursive process.
  Write a procedure that computes f by means of an iterative process.

Please review my code.

I think the recursive process is obvious enough but I put it here just in case it could be improved.

(define (f n)
  (if (< n 3) n
        (+ (f (- n 1))
                 (* 2 (f (- n 2)))
                 (* 3 (f (- n 3))))))

Now, here's the iterative process. I followed the relationship created by the fibonacci example. The idea is:

\$a = f(n+2)\$
\$b = f(n+1)\$
\$c = f(n)\$

(define (f n)
  (f-iter 2 1 0 n))

(define (f-iter a b c count)
  (if (= count 0)
      c
      (f-iter (+ a (* 2 b) (* 3 c)) a b (- count 1))))

How to make this code better and faster? Are there more efficient ways?


texts: String puzzle - operations with numbers inside of strings

texts:
Puzzle description: input is dimensions (length, width, heigth) of various presents.

Example:

2x3x1
5x9x10
1x40x2

Part 1: determine the area of paper needed to wrap the gifts, wich is equal to 2*(l*w + w*h + l*h) + the smallest between l*w, w*h and l*h for each gift.

Part 2: determine the length of ribbon needed to wrap the gift, wich is equal to l*w*h + smallest perimeter for each gift.

I learned about aoc recently and decided to start from 2015. Below is my code from the day 2 (problem link). How can I improve it? Is it too long?

import java.io.*;
import java.util.*;

public class adventofcode2 {
    public static void main(String[] args){
        System.out.println("input: ");
        Scanner input = new Scanner(System.in);
        String line;
        String text = "";
        while (!(line = input.nextLine()).isEmpty()){
            text += line + "\n";
        }
        calcTotal(text);
        System.out.println("Paper area used -  " + TotalPaper);
        System.out.println("Ribbon length used -  " + TotalRibbon);
    }
    /**
     * 1 -  Calculates the area of paper necessary to make the presents wrapping
     * 2 -  Calculates the length of ribbon necessary to the wrapping
     * @param presentsText list of strings in the style numberxnumberxnumber
     */
    private static void calcTotal(String presentsText){
        String[] presents = presentsText.split("\n");
        for (String present : presents){
            calcEachPresent(present.split("x"));
        }
    }
    /**
     * Iteration inside the calcTotal method
     * @param presentText array of each present string written in
     * the style numberxnumberxnumber
     */
    private static void calcEachPresent(String[] presentText){
        //Definition of the three dimensions of the present.
        int l = Integer.parseInt(presentText[0]), w = Integer.parseInt(presentText[1]), h = Integer.parseInt(presentText[2]);

        //Definition of the area of the sides in the present.
        int[] d = {l*w,w*h,h*l};

        int min = getMin(d);

        int area = 2*(d[0] + d[1] + d[2]) + min;

        int ribbon = (l*w*h) + smallestPerimeter(l,w,h);
        TotalPaper += area;
        TotalRibbon += ribbon;
    }
    /**Get the smallest area to use in the area calculation
     *
     * @param num array of numbers
     * @return smallest number in an array
     */
    private static int getMin(int[] num){
        int min = num[0];
        for (int n : num){
            if(n < min) min = n;
        }
        return min;
    }
    /**Get smallest perimeter to use in ribbon length calculation
     *
     * @param l length of present
     * @param w width of present
     * @param h heigth of present
     * @return smallest perimeter
     */
    private static int smallestPerimeter(int l,int w,int h){

        int[] num = {l,w,h};
        Arrays.sort(num);

        return 2*(num[0] + num[1]);
    }

    /**
    *   VARIABLES TO RETURN IN THE MAIN METHOD
    */
    private static int TotalPaper = 0;
    private static int TotalRibbon = 0;
}


texts:
I'm writing a simple database class so I could use it in my future projects. It is based on some Codeigniter database methods, but my implementation, so if you could review this, that would be cool. It is not finished yet, but I want to remove all bad code early on.

<?php

class Database {

    private static $instance = null;
    private $pdo;
    private $query;
    private $results;
    private $count = 0;
    private $error = false;

    private $query_string = "";
    private $bindValues = array();
    private $lastId;

    private function __construct() {

        try {
            // Put your database information
            $this->pdo = new PDO("mysql:host=127.0.0.1;dbname=login","root","");
        } catch (PDOException $e) {
            die($e->getMessage());
        }

    }

    public static function getInstance() {
        if (is_null(self::$instance)) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function query($sql, $parameters = array()) {
        $this->error = false;

        if ($this->query = $this->pdo->prepare($sql)) {
            $i = 1;
            foreach ($parameters as $param) {
                $this->query->bindValue($i, $param);
                $i++;
            }
            if ($this->query->execute()) {
                // You can PDO::FETCH_OBJ instad of assoc, or whatever you like
                $this->results = $this->query->fetchAll(PDO::FETCH_ASSOC);
                $this->count = $this->query->rowCount();
                $this->lastId = $this->query->lastInsertId();
            } else {
                $this->error = true;
            }
        }
        return $this;
    }

    public function select($fields = "*") {
        $action = "";
    $this->query_string = "";
        if (is_array($fields)) {
            $action = "SELECT ";
            for ($i = 0; $i < count($fields); $i++) {
                $action .= $fields[$i];
                if ($i != count($fields) - 1)
                    $action .= ', ';
            }
        } else {
            $action = "SELECT * ";
        }
        $this->query_string .= $action;
        return $this;
    }

    public function from($table) {
        $this->query_string .= " FROM {$table} ";
        return $this;
    }

    public function where($where = array()) {
        $keys = array_keys($where);
        $action = " WHERE ";
        for ($i = 0; $i < count($keys); $i++) {
            $action .= $keys[$i] . ' = ?';
            if ($i < count($keys) - 1)
                $action .= ' AND ';
            $this->bindValues[] = $where[$keys[$i]];
        }
        $this->query_string .= $action;
        return $this;
    }

    public function execute() {
        if (!empty($this->query_string))
            $this->query($this->query_string, $this->bindValues);
        $this->bindValues = array();
    }

    public function getQueryString() {
        return $this->query_string;
    }

    public function results() {
        return $this->results;
    }
    public function first() {
        return $this->results[0];
    }
    public function last() {
        return $this->results[$this->count-1];
    }
    public function row($id) {
        return $this->results[$id];
    }
    public function error() {
        return $this->error();
    }
    public function count() {
        return $this->count;
    }
    public function lastId() {
        return $this->lastId;
    }
}


texts: Subdividing a 4×4 array into four 2×2 arrays

texts:
I want to subdivide a 4×4 2d array into 4 2×2 arrays and I have figured out how to do this in a very crude way, but am having a tougher time with a more elegant general solution.

    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            for (int k = 0; k < 2; k++)
            {
                int j2 = j;
                int k2 = k;
                if (i == 1) { k2 += 2; }
                if (i == 2) { j2 += 2; }
                if (i == 3) { j2 += 2; k2 += 2; }
                twoByTwo[i][j, k] = fourByFour[j2, k2];
            }
        }
    }


texts: Finding an exact "phrase" with a given string (as typed/in order)

texts:
<?php
    function filterExactPhrase($input, $phrase)
    {
        $phrase = explode("\t", $phrase);
        $phrases = count($phrase);

        for($i = 0; $i < $phrases;)
        {
            if(preg_match("/(" . $phrase[$i] . ")\b/", $input))
            {
                $out[] = ['INPUT' => $input, 'FOUND' => 1,
                'VALUEofFOUND' => $phrase[$i]];
            } else {
                $out[] = 'Not found';
            }
            $i++;
        }
        print_r($out);
    } //end function

    $this->filterExactPhrase("this is a test, foobar", "foobar");

Calling the function like this yields

Array ( [0] => Array ( [INPUT] => this is a test, foobar [FOUND] => 1 [VALUEofFOUND] => foobar ) )

Giving the function foo as $input instead of foobar yields

$this->filterExactPhrase("this is a test, foo", "foobar");

Array ( [0] => Not found )

I thought this was quite interesting to find as I was looking for a solution to find a very specific phrase with spaces, in a extensively long, log file to remove from it.


texts:
I made this Pig Latin translator in C++ and I was wondering what I could improve and what is good about it.

I used the stringstream class to get the individual words.

#include <iostream>
#include <vector>
#include <sstream>
std::string translate(std::string word){
   if(word.length() > 1){
       word += word[0];
       word[0] -= word[0];
       word += "ay";
   }
   return word;
}
int main(){
    std::vector<std::string> v;
    std::string str = "Hello the world has ended";
    std::stringstream stringStream(str);
    for(int i = 0; i < str.length(); i++){
        std::string currentWord;
        stringStream >> currentWord;
        v.push_back(currentWord);
    }

for(int i = 0; i < v.size(); i++){
    std::cout << translate(v[i]) + " ";
}

std::cout << std::endl;

}


texts:
I have a game in which the player has to do something within a defined time.

E.g.: the player has 10 seconds to complete a level.

My current code animates an imageview (it's only a horizontal line) when the game starts:

progressAnimation = new TranslateAnimation(0, -Settings.screenWidth, 0, 0);
progressAnimation.setDuration(level * 10000);
progressAnimation.setFillAfter(true);
progressAnimation.setInterpolator(new LinearInterpolator());

progressView = new ProgressView(context);
progressView.startAnimation(progressAnimation);

Simultaneously I start a handler:

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        fireResultActivity(-1); // -1 means, time's up.
    }
}, level * 10000);

If the user can finish the game within 10 seconds an activity comes up and congratulates, if they can't another, "fail" activity comes up.

Is it a good practice to use animation to indicate the progress and start a handler simultaneously?

Could you recommend other (better) solution?


texts:
I would like to improve this function to reduce the run time and optimize it.

function [Pl,Plm] = funlegendre(gamma)

    Plm = zeros(70,71);
    Pl = zeros(70,1);
    P0 = 1;
    Pl(1) = gamma;
    Plm(1,1) = sqrt(1-gamma^2);

    for L=2:70
        for M=0:L

                if(M==0)
                    if (L==2)
                    Pl(L) = ((2*L-1)*gamma*Pl(L-1)-(L-1)*P0)/L;
                    else
                    Pl(l) = ((2*l-1)*gamma*Pl(l-1)-(l-1)*Pl(l-2))/l;
                    end
                elseif(M<L)
                    if(L==2)
                        if(M==1)
                        Plm(L,M) = (2*L-1)*Plm(1,1)*Pl(L-1);
                        else
                        Plm(L,M) = (2*M-1)*Plm(1,1)*Plm(L-1,m-1);
                        end
                    else
                        if(M==1)
                        Plm(L,M) = Plm(L-2,m) + (2*L-1)*Plm(1,1)*Pl(L-1);
                        else
                        Plm(L,m) = Plm(L-2,m) + (2*L-1)*Plm(1,1)*Plm(L-1,M-1);
                        end
                    end

                elseif(M==L)
                    Plm(L,M) = (2*L-1)*Plm(1,1)*Plm(L-1,L-1);
                else
                    Plm(L,M) = 0;
                end
        end
    end
    Pl = sparse(Pl);
    Plm = sparse(Plm);
    end


texts:
The following code generates all \$k\$-subsets of a given array. A \$k\$-subset of set \$X\$ is a partition of all the elements in \$X\$ into \$k\$ non-empty subsets.

Thus, for {1,2,3,4} a 3-subset is {{1,2},{3},{4}}.

I'm looking for improvements to the algorithm or code. Specifically, is there a better way than using copy.deepcopy? Is there some itertools magic that does this already?

import copy
arr = [1,2,3,4]

def t(k,accum,index):
    print accum,k
    if index == len(arr):
        if(k==0):
            return accum;
        else:
            return [];

    element = arr[index];
    result = []

    for set_i in range(len(accum)):
        if k>0:
            clone_new = copy.deepcopy(accum);
            clone_new[set_i].append([element]);
            result.extend( t(k-1,clone_new,index+1) );

        for elem_i in range(len(accum[set_i])):
            clone_new = copy.deepcopy(accum);
            clone_new[set_i][elem_i].append(element)
            result.extend( t(k,clone_new,index+1) );

    return result

print t(3,[[]],0);


texts:
I am trying to wrap my arms around all the digital files we have, so I thought I would organize all of our pictures and videos into folders named after dates.  I'm learning F#, and this felt like a good chance for me to exercise that muscle.

Please review the code.  I'm open to any criticisms, but I also have some specific areas of interest:

I feel like the filtering out of the thumbs.db file should be inside the sequence expression.  What's a good way to do that?
In getNewFilename, that function and its internal incrementFilename function each have an expression checking for the existence of the file.  I think that check could be cleanly put into a single check, but I can't think quite how.
It took 1 hour and 10 minutes to copy 120GB in over 28,000 files.  This is on a quad-core laptop with a 7,200 RPM drive.  Realizing that the drive is the limiting factor for this work, and there could be clashes in filenames, what might be some good concurrent processing techniques to possibly have this code finish sooner?

open System
open System.Drawing
open System.IO
open System.Text
open System.Text.RegularExpressions

let rec getAllFiles baseDir =
    seq {
        yield! Directory.EnumerateFiles(baseDir)

        for dir in Directory.EnumerateDirectories(baseDir) do
            yield! getAllFiles dir
    }

let dateTakenFromExif file =
    let r = new Regex(":")
    use fs = new FileStream(file, FileMode.Open, FileAccess.Read)
    use myImage = Image.FromStream(fs, false, false)
    let propItem = myImage.GetPropertyItem(36867)
    let dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2)
    DateTime.Parse(dateTaken)

let getDateTaken file =
    try
        dateTakenFromExif file
    with
    | :? Exception ->
        File.GetLastWriteTime(file)   //Use the last write time in the event that the file was moved/copied

let addToFile file n =
  match n with
  | 2 ->
    let fileDir = Path.GetDirectoryName(file)
    let nextFile = Path.GetFileNameWithoutExtension(file) + "-" + n.ToString() + Path.GetExtension(file)
    Path.Combine(fileDir, nextFile)
  | _ ->
    let prev = n-1
    file.Replace("-" + prev.ToString(), "-" + n.ToString())

let getNewFilename newFilePath =
    let rec incrementFilename file n =
        let filenameIncremented = addToFile file n
        match File.Exists(filenameIncremented) with
        | false -> filenameIncremented
        | true -> incrementFilename filenameIncremented (n+1)

    match File.Exists(newFilePath) with
    | false -> newFilePath
    | true  -> incrementFilename newFilePath 2

let move destinationRoot files =
    let moveHelper file =
        let dateTaken = getDateTaken file
        let finalPath = Path.Combine(destinationRoot, dateTaken.Year.ToString(), dateTaken.ToString("yyyy-MM-dd"))
        if not(Directory.Exists(finalPath)) then Directory.CreateDirectory(finalPath) |> ignore

        let newFile = getNewFilename (Path.Combine(finalPath, Path.GetFileName(file)))

        try
          File.Copy(file, newFile)
        with
        | :? Exception as e ->
          failwith (sprintf "error renaming %s to %s\n%s" file newFile e.Message)

    files |> Seq.iter moveHelper

let moveFrom source =
  getAllFiles source
    |> Seq.filter (fun f -> Path.GetExtension(f).ToLower() <> ".db")  //exlcude the thumbs.db files
    |> move """C:\_EXTERNAL_DRIVE\_Camera"""
  printfn "Done"

#time
moveFrom """C:\Users\Mike\Pictures\To Network"""
moveFrom """C:\_EXTERNAL_DRIVE\Camera"""


texts:
I'm using a DataContext to insert an object. Currently it's working, but I'm feeling things could be done better. Method is called from UI (Using Caliburn Micro Binding). IsBusy is a property used by the UI (Xceed Extended WPF Toolkit) to display a wait message.

Repository inherits from DataContext (using Entity Code First).

public async void AddTemplate()
{
    IsBusy = true;

    await Task.Run(() => {
        using (var repo = new Repository())
        {
            var template = new Template() { ... };
            try
            {
                repo.Templates.Add(template);
                repo.SaveChanges();
                this.TryClose(true);
            }
            catch (SqlException ex)
            {
                _util.Log.AddException(Exceptions.DB_EXC, ex.Message);
            }
            catch (EntityException ex)
            {
                _util.Log.AddException(Exceptions.EF_EXC, ex.Message);
            }
            catch (Exception ex)
            {
                _util.Log.AddException(Exceptions.US_EXC, ex.Message);
            }
            finally
            {
                IsBusy = false;
            }
        }
        this.TryClose(false);
    });
}

I'm feeling odd about covering using with the await Task.Run since I can also await for repo.SaveChangesAsync(), but then IsBusy will not change (and the Wait message will not be made visible).


texts: Print combinations of balanced parentheses

texts:
Solved the below problem. Would love to hear your feedback, especially on performance improvements (granted, the solution should remain recursive).

Especially concerned about the obj.include? elem check I had to add to prevent duplicates. Don't know a better way to do without it.

# Implement an algorithm to print all valid (e.g., properly
# opened and closed) combinations of n-pairs of parentheses.
# EXAMPLE
# Input: 3
# Output: ((())), (()()), (())(), ()(()), ()()()

def brackets(n)
  return ["()"] if n == 1

  brackets(n-1).each_with_object([]) do |p, obj|
    for i in 0..p.length
      # stuff the "()" in every possible position within 'p'
      elem = p.dup.insert(i, "()")
      obj << elem unless obj.include? elem
    end
  end
end


texts:
I am trying to learn the clean architecture by Uncle Bob. I wanted some basics and following this good post I tried to implement it in python with some minor differences.

class ValidationError(Exception):
    pass

class Repository(object):

    repositories = {}

    @classmethod
    def register(cls, type_, repo):
        cls.repositories[type_] = repo

    @classmethod
    def get(cls, type_):
        return cls.repositories[type_]

    @classmethod
    def all(cls):
        return cls.repositories

class UserValidator(object):

    def validate(self, user):
        if not (user.name and user.email):
            raise ValidationError

class UserRepo(object):

    def __init__(self, validator=None):
        self.users = {}
        self.next_id = 1
        self.validator = validator

    def save(self, user):
        self.validator.validate(user)
        user.id = self.next_id
        self.users[self.next_id] = user
        self.next_id += 1
        return user

    def all(self):
        return self.users

    def get(self, id):
        return self.users[id]

    def delete(self, id):
        return self.users.pop(id)

class CompanyRepo(object):

    def __init__(self):
        self.companies = {}
        self.next_id = 1

    def save(self, company):
        company.id = self.next_id
        self.companies[self.next_id] = company
        self.next_id += 1
        return company

    def all(self):
        return self.companies

    def get(self, id):
        return self.companies[id]

    def delete(self, id):
        return self.companies.pop(id)

class BaseEntity(object):

    def __init__(self):
        self.id = None
        self.created_at = None
        self.updated_at = None

class Company(BaseEntity):

    def __init__(self, name, address):
        self.name = name
        self.address = address
        super(Company, self).__init__()

class User(BaseEntity):

    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.company_id = None
        super(User, self).__init__()

    def serialize(self):
        return {'id': self.id, 'name': self.name, 'email': self.email, 'company_id': self.company_id}

    def value(self):
        return self.serialize()

class WorkerAdder(object):

    def __init__(self, name, email):
        self.user_repo = Repository.get('user')
        self.company_repo = Repository.get('company')

        self.company = self.company_repo.save(Company('FooBar', 'Dummy street'))
        self.user = User(name, email)

    def add(self):
        try:
            self.user.company_id = self.company.id
            print self.user_repo.save(self.user).value()
            print self.user_repo.all()
            print self.user_repo.get(1)
            print self.company_repo.all()
        except ValidationError as ve:
            print "Validation error!"

if __name__ == '__main__':

    Repository.register('user', UserRepo(validator=UserValidator()))
    Repository.register('company', CompanyRepo())

    adder = WorkerAdder('Foo', 'foo@example.com')
    adder.add()

O/P from above code:

{'company_id': 1, 'email': 'foo@example.com', 'id': 1, 'name': 'Foo'}
{1: <__main__.User object at 0x7f4b34139d50>}
<__main__.User object at 0x7f4b34139d50>
{1: <__main__.Company object at 0x7f4b34139d10>}

I have basically tried to implement the in memory repository pattern. I would like to hear from others what they think, and why there is so scarcity in the python community regarding the design patterns and different architectures as compared to ruby?

PS: The code above is just for learning purpose hence error handling and error cases are not handled properly.


texts:
This is my first time using semaphores and I was wondering if I implemented them to the best of their abilities in my code....

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include<semaphore.h>
#include <math.h>

#define NR_THREAD 2

int sum=0;
unsigned int seed;
sem_t sem0;

void* func0(void *param) {
    int tmp;
    int i;
    for(i=0; i<10; i++) {
        sem_wait (&sem0);
        tmp=sum;
        tmp++;
        if(rand_r(&seed)%2) {
            printf("sleeping for 1 sec\n");
            sleep(1);
        } else {
            printf("sleeping for 2 sec\n");
            sleep(2);
        }
        sem_post (&sem0);
        sem_wait (&sem0);
        sum=tmp;
        if(rand_r(&seed)%2) {
            printf("sleeping for 1 sec\n");
            sleep(1);
        } else {
            printf("sleeping for 2 sec\n");
            sleep(2);
        }
        sem_post (&sem0);
    }

    return (void*)0;
}

int main() {
    int i;
    int error;
    pthread_t *tid;
    pthread_attr_t attr;

    seed=(unsigned int)time(NULL);

    if((tid=(pthread_t*)calloc(NR_THREAD, sizeof(pthread_t)))==NULL) {
        fprintf(stderr, "calloc() failed\n");
        exit(1);
    }
    sem_init(&sem0, 0, 1);
    if(sem_init(&sem0, 0, 1)==-1) {
        perror("Failed to sem_init() sem0");
        exit(1);
    }

    pthread_attr_init(&attr);
    for(i=0; i<NR_THREAD; i++) {
        if((error=pthread_create(&tid[i], &attr, func0,
            (void*)0))) {
            fprintf(stderr, "pthread_create() failed: %d %d\n",
                i, error);
            tid[i]=pthread_self();
        }
    }

    for(i=0; i<NR_THREAD; i++) {
        if(pthread_equal(pthread_self(), tid[i]))
            continue;

        if((error = pthread_join(tid[i], NULL))) {
            fprintf(stderr, "pthread_join() failed: %d %d\n",
                i, error);
        }
    }

    printf("Final sum= %d\n", sum);

    free(tid);

    if(sem_destroy(&sem0)==-1) {
        perror("Failed to sem_destroy() sem0");
        exit(2);
    }

    return 0;
}

It runs and gets the correct answer, but I was wondering if there were better places to put them or not. Also, I'm getting a warning, I'm receiving an implicit declaration warning on if(rand_r(&seed)%2) { and I'm not sure how to go about fixing this problem.

This is a demo in which two threads each sleep 10 times.


texts: Custom Knight dialer solution's time and space complexity

texts:
I recently solved the Knight Dialer problem but I'm not quite sure if I got the time complexity right; hence I'm requesting the following:

1) Time and space complexity review and explanation on why so.

The question says:

  Imagine you place a knight chess piece on a phone dial pad. This chess piece moves in an uppercase “L” shape: two steps horizontally
  followed by one vertically, or one step horizontally then two
  vertically: Pay no attention to the poorly-redacted star and pound
  keys Suppose you dial keys on the keypad using only hops a knight can
  make. Every time the knight lands on a key, we dial that key and make
  another hop. The starting position counts as being dialed.
  How many distinct numbers can you dial in N hops from a particular starting position?

Knight dialer: (movs map has all the possible movements for every number)

private static int knightDialer(int start, int nth, Map<Integer, Integer[]> movs, Set<Integer> res) {

    if (nth == 0) {

        return 0;
    }

    Integer[] validMoves = movs.get(start);

    for (Integer mov : validMoves) {

        if (!res.contains(mov)) {

            res.add(mov);
            knightDialer(mov, nth - 1, movs, res);
        }

    }

    return res.size();

}

If I'm missing something important for the review, please let me know.

Thanks.

Test Case:

public static void main(String[] args) {

    int start = 0;

    int nth = 3;

    System.out.println(knightDialer(start, nth));
    System.out.println();
}

private static int knightDialer(int start, int nth) {

    Map<Integer, Integer[]> movs = getAllMoves();

    Set<Integer> res = new HashSet<>();
    res.add(start);

    return knightDialer(start, nth, movs, res);

}

private static Map<Integer, Integer[]> getAllMoves() {

    Map<Integer, Integer[]> movs = new HashMap<>();

    movs.put(1, new Integer[]{ 6, 8 });
    movs.put(2, new Integer[]{ 7, 9 });
    movs.put(3, new Integer[]{ 4, 8 });
    movs.put(4, new Integer[]{ 3, 9, 0 });
    movs.put(6, new Integer[]{ 1, 7, 0 });
    movs.put(7, new Integer[]{ 2, 6 });
    movs.put(8, new Integer[]{ 1, 3 });
    movs.put(9, new Integer[]{ 2, 4 });
    movs.put(0, new Integer[]{ 4, 6 });

    return movs;
}


texts: Java - Functional interface for merging two lists

texts:
Hello dear colleagues.
As an exercise for Java streams, I've written simple program, which scrapes links to references from a news portal. Basically, I wanted to find out, which portals are the most referenced.
Right now, I ended up with the following piece of code:
final Map<String, List<URL>> hostToURLs = Analyzer.mapByHost(ReferencesStore.read());
// E.g. bbc.com -> [ https://www.bbc.com/article1, https://www.bbc.com/article2, etc ]

// The following creates LinkedHashMap sorted by the number of URLs
final LinkedHashMap<String, List<URL>> sortedHostToURLs = hostToURLs
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(List::size)))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m, n) -> { m.addAll(n); return m; }, LinkedHashMap::new));

I'm interested, if the the ugly merge lambda
(m,n)-> {m.addAll(n); return m;}
in the collect method can be replaced with some method reference from  standard library. I wasn't able to find anything useful in the  documentation, nor was I able to ask google the right question to find out if such merge function exists. Thank you in advance.


texts: C++ wrapper class for array of OpenGL buffer objects -- just the constructors

texts:
A similar question was asked here, and I'm trying to do the same thing. But

I'm trying a different approach by deriving from std::array, and
This is a very focused question about constructors only.

Here is my gl_wrap.h:
// header guards snipped

#include <array>
#include <algorithm>
#include <cstring>
#include <GL/gl.h>

namespace gl_wrap {

// aliases for style consistency and to mark as parts of gl_wrap
using gl_name = GLuint;
using gl_enum = GLenum;

template<size_t N>
class buffer_objects : public std::array<gl_name, N> {
public:
    buffer_objects() noexcept;
    ~buffer_objects();
    buffer_objects(const buffer_objects&) = delete;
    buffer_objects operator=(const buffer_objects&) = delete;
    buffer_objects(buffer_objects&& from) noexcept;
    buffer_objects& operator=(buffer_objects&& from) noexcept;
};

template<size_t N>
buffer_objects<N>::buffer_objects() noexcept
{
    glGenBuffers(N, this->data());
}

template<size_t N>
buffer_objects<N>::~buffer_objects()
{
    glDeleteBuffers(N, this->data());
}

template<size_t N>
buffer_objects<N>::buffer_objects(buffer_objects<N>&& from) noexcept
    : std::array<gl_name, N>(std::move(from))
{
    memset(from.data(), 0, N * sizeof(gl_name));
}

template<size_t N>
buffer_objects<N>& buffer_objects<N>::operator=(buffer_objects<N>&& from)
    noexcept
{
    std::array<gl_name, N>::operator=(std::move(from));
    memset(from.data(), 0, N * sizeof(gl_name));
    return *this;
}

}
// namespace gl_wrap

Some specific questions I have about this code/approach are, if applicable,

Error handling design decision: should the constructors throw, or should I leave error checking, if desired, to the caller?
Design decision: is it a good idea to use templates here? Will this lead to problematic code bloat if I'm using a lot of different-sized buffer_objects, or is it efficient? Can I evaluate this through profiling?
Are the memcpys worth it to put the rvalues in a valid non-owning state, or can I treat the rvalues as non-owning leftovers?
Am I properly using the base class's move constructor?


texts: jquery checking nested input with repetitive code

texts:
I have a table with 'nested' inputs that need to be checked or unchecked when a button 'select all' is pressed.  There are several levels that can be toggled with their respective 'select all' button.  In my code I have a repetitive .each() statement where the second one tests if there are differing numbers of checked/unchecked inputs and if there are it overwrites what the first .each() statement did.  How can I write the following code better?

$(document).ready(function(){
    $(".checkAll").click(function(e){
        e.preventDefault();
        var thisRow = $(this).parents("tr");
        var thisRowNumber = parseInt(thisRow.attr("id").replace("row",""));
        var thisLevel = parseInt(thisRow.children().first().attr("class").replace("textlevel",""));
        var checked = 0;
        var unchecked = 0;
        $(".tablefull tr").each(function(){
            if($(this).attr("class") !== "heading"){
                r = parseInt($(this).attr("id").replace("row",""));
                if(r > thisRowNumber){
                    n = parseInt($(this).children().first().attr("class").replace("textlevel",""));
                    if(n === thisLevel){
                        return false;
                    }
                    if(n > thisLevel){
                        $(this).find("input[name='ci_id']").prop("checked",function(index, oldAttr){
                            if(oldAttr){
                                checked++;
                            }
                            else {
                                unchecked++;
                            }
                            return !oldAttr;
                        });
                    }
                }
            }
        });
        if(checked > 0 && unchecked > 0){
            $(".tablefull tr").each(function(){
                if($(this).attr("class") !== "heading"){
                    r = parseInt($(this).attr("id").replace("row",""));
                    if(r > thisRowNumber){
                        n = parseInt($(this).children().first().attr("class").replace("textlevel",""));
                        if(n === thisLevel){
                            return false;
                        }
                        if(n > thisLevel){
                            $(this).find("input[name='ci_id']").prop("checked",true);
                        }
                    }
                }
            });
        }
    });
});

here's the working code in a fiddle: http://jsfiddle.net/KnU4X/1/

here's the code without my lengthy fix in a fiddle: http://jsfiddle.net/KnU4X/2/

To see the problem, click 'select all' with level 1, then 'select all' with level 2, then 'select all' with level 1 again. You will notice it unchecks everything except the level 2 which becomes checked.

Is there a way to remove all that seemingly redundant code and keep that functionality?


texts: Code to make elements fit within their container while keeping their aspect ratio

texts:
This function receives the id of an element (frame) and calculates the correct height and width so it fits inside its parent element, while keeping its aspect ratio. Before I had a way to calculate the frame ratio dynamically, but I decided it was easier to simply hard code it, it calculates it through naturalHeight and naturalWidth if it's an image, and use 0.5625 for the rest which are iframes, and that ratio makes sense for all of those. It works, tried it in different sizing scenarios, what I'm not 100% sure is if the math involved to calculate the correct width and height in all cases is correct.

In all cases the element should fill as much as possible.

function fix_frame(frame_id)
{
    var id = `#${frame_id}`

    var frame = $(id)

    if(frame_id === "media_image_frame")
    {
        var frame_ratio = frame[0].naturalHeight / frame[0].naturalWidth
    }

    else
    {
        var frame_ratio = 0.5625
    }

    var parent = frame.parent()
    var parent_width = parent.width()
    var parent_height = parent.height()
    var parent_ratio = parent_height / parent_width

    var frame_width = frame.width()
    var frame_height = frame.height()

    if(parent_ratio === frame_ratio)
    {
        frame.width(parent_width)
        frame.height(parent_height)
    }

    else if(parent_ratio < frame_ratio)
    {
        frame.width(parent_height / frame_ratio)
        frame.height(parent_height)
    }

    else if(parent_ratio > frame_ratio)
    {
        frame.width(parent_width)
        frame.height(parent_width * frame_ratio)
    }
}


texts:
This is actually an old 'problem' that I never really knew how to improve, but I'm wondering now if there is a better approach for this problem.

I'm creating MineSweeper with Java and struggling with an OOP aspect of the game. Basically I have a class Square.java, SquareBoms(extends Square) and Field.java. My approach on the Square is that it should only be aware of itself and should not communicate in any way or form with the Field.

However, the Field should check the surrounding SquaresBombs for bombs once a Square has been clicked. So the Square SHOULD message the Field that it has been clicked, but I don't think this is the right way of using OOP.

import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;

public class Square extends JButton {
    Field owner; //This is not OOP as the Square should only be aware of itself and what is in it.
    int coords;
    boolean isChecked = false;
    boolean isMarked = false;
    int bombsAround;

    public Square(Field owner, int coords) {
        this.owner = owner;
        this.coords = coords;
        this.setSize(400, 400);
        this.setMargin(new Insets(0, 0, 0, 0));
        this.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
                if (e.getButton() == MouseEvent.BUTTON1) {
                    Clicked();
                }
                else if(e.getButton() == MouseEvent.BUTTON3) {
                    Mark();
                }
            }
        });
    }

    public void Clicked() {
        if(!isChecked) {
            this.setBackground(new Color(238, 238, 238)); // Reset when it had been marked
            isChecked = true;
            this.setEnabled(false);

            owner.checkSquare(this); //This is not OOP as the Square should only be aware of itself and what is in it.
        }
    }

    public void Mark() {
        if(!isChecked) {
            if(!isMarked)
                this.setBackground(Color.GREEN);
            else
                this.setBackground(null);

            isMarked = !isMarked; // toggle on every click
        }
    }

}

UPDATE

My original question was if it was 'allowed' to let a child object know about its parent. After doing some research i've come to the conclusion that this is not wrong in pure OOP-terms.


texts:
Very new to JS (wrote my "Hello World" around 3 days ago), but not to programming in general. My documentation is inspired by the approach I followed for Python (since I haven't learned JS documentation conventions yet).

My Code

"use strict";

/*
   Inserts elements from a given source array in a specified target array in sorted order. Modifies the target array in place.

   Args:
      * `source` (Array): Source array. The array is assumed to be already sorted.
      Sorting is not done, as a custom sort function may be desired, and checking for sorting is not done as doing so would
      greatly diminish the performance benefits of working with already sorted data.
      * `target` (Array): Target array. The array is assumed to be already sorted (for similar reasons as above).
      * `cmp` (function): Comparison function (predicate).
         - Defaults to `<` operator.
         - Args:
            `a`.
            `b`.
         - Returns (boolean): Indicates if `a < b`.
            It is important that the predicate indiates `a < b` and not `a <= b` so that the sort is stable.
*/
const sortedInsert = function(source, target, cmp = (a, b) => a < b)
{
   let insertPosition = 0;
   source.forEach(itm => {
      let insertAtEnd = true;
      for(let i = insertPosition; i < target.length; i++)
      {
         if(cmp(itm, target[i]))
         {
            target.splice(i, 0, itm);
            insertPosition = i;
            insertAtEnd = false;
            break;
         }
      }
      if (insertAtEnd)
      {
         target.splice(target.length, 0, itm);
         insertPosition = target.length;
      }
   })
}


texts:
I am solving the following HackerRank problem:

Consider a list (list = []). You can perform the following commands:

insert i e: Insert integer e at position i.
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.

Initialize your list and read in the value of followed by lines of
commands where each command will be of the types listed above. Iterate
through each command in order and perform the corresponding operation
on your list.

My solution was:
if __name__ == '__main__':
    N = int(input())

    my_list = []

    commands = dict(
            insert=lambda i,v: my_list.insert(i,v),
            print=lambda: print(my_list),
            remove=lambda e: my_list.remove(e),
            append=lambda v: my_list.append(v),
            sort=lambda: my_list.sort(),
            pop=lambda: my_list.pop(),
            reverse=lambda: my_list.reverse()
        )

    for _ in range(N):
        command, *args = input().split()
        commands[command](*list(map(int, args)))

I did find another solution (I didn't write it) that seems cleaner than mine:
n = input()
l = []
for _ in range(n):
    s = raw_input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        cmd += "("+ ",".join(args) +")"
        eval("l."+cmd)
    else:
        print l


texts:
Here's my second try at pairwise summation in Haskell:
pairwiseSum :: (Num a) => [a] -> a
pairwiseSum [] = 0
pairwiseSum [x] = x
pairwiseSum x = pairwiseSum (sumPairs x)

sumPairs :: (Num a) => [a] -> [a]
sumPairs [] = []
sumPairs [x] = [x]
sumPairs (x:y:xs) = ((x + y) : sumPairs xs)

I ran both versions on pairwiseSum (map exp [1,0.9999..(-56.0)]), and this one's noticeably faster. Is it well written?
ETA: here are some runs comparing pairwiseSum with sum :
*Main> pairwiseSum (map exp [1,0.9999..(-56.0)])
27184.177448160026
*Main> sum (map exp [1,0.9999..(-56.0)])
27184.177448147617
*Main> pairwiseSum (map exp [1,0.99999..(-56.0)])
271829.5419903211
*Main> sum (map exp [1,0.99999..(-56.0)])
271829.54198831413

The previous version of pairwiseSum gave 27184.177448160022 as the sum of the first list. On the second, I counted to 13 while pairwiseSum ran and to 11 while sum ran.


texts: Implement operation and simulation mode in an interface

texts:
Context:

I have to create an interface between devices and a client.
My package is composed of:

Device.py
Error.py
DeviceA.py (for example)
DeviceB.py
...

Basically each DeviceA, DeviceB, ... inherit Device class. Device is composed of one FSM (state machine: module Fysom) and does several thing about communication, parsing, ... The purpose is to have one common FSM (same rules) for all devices but each device follow his own FSM. That's why there is one thread per device (Device inherit a Threading module).
A code simplified:

# One common state rule
TableFSM = {
'initial' : 'none',
'events': [
    {'name': 'do_start', 'src': ['OFF', 'none'], 'dst': 'LOADED'},
    {'name': 'do_stop', 'src': ['LOADED'], 'dst': 'OFF'},
    # same for resume, pause, ...
]

class Device(MyThread):
    def __init__(self):
        # FSM is instantiate here so ONE FSM per device with same rule
        self.fsm = Fysom(TableFSM)
        self.mode = "operation" #or simulation
    def start(self):
        self.fsm.do_start()
        # Real common Device parsing stuff
    def stop(self):
        self.fsm.do_stop()
        # Real common Device parsing stuff
    def pause(self):
        self.fsm.do_pause()
        # Real common Device parsing stuff
    def resume(self):
        self.fsm.do_resume()
        # Real common Device parsing stuff

class DeviceA(Device):
    def __init__(self):
        Device.__init__(self)
    def start(self):
        #Specific Real Device stuff
        super(DeviceA, self).start()
    def stop(self):
        #Specific Real Device stuff
        super(DeviceA, self).start()
    #def ...

class DeviceB(Device):
    def __init__(self):
        Device.__init__(self)
    def start(self):
        #Specific Real Device stuff
        super(DeviceB, self).start()
    def stop(self):
        #Specific Real Device stuff
        super(DeviceB, self).start()
    #def ...

Here methods called will be DeviceA().start() or DeviceB().stop() (bad represention) for example.

Issue:

I have to implement for each device an operation and simulation mode
For example  I could add in each method of each device class the following statement:

if self.mode == "operation":
    #some stuff
elif self.mode == "simulated":
    #almost nothing

I want to write it as generic as possible.
From a previous post I could derivate SimuDevice from Device with the same methods. Basically SimuDevice will only trigger the FSM :

class DeviceSimu(Device):
    def __init__(self):
        Device.__init__(self)
    def start(self):
        self.fsm.do_start()
    def stop(self):
        self.fsm.do_stop()
    def pause(self):
        self.fsm.do_pause()
    def resume(self):
        self.fsm.do_resume()

Question:

My issue is about instanciation and object. I want to be able to switch between operation and simulation mode without deleting and reinstantiate an object.

I can't understand how DeviceA could access to DeviceSimu method?
Is it a good way (conceptually) to do simulation and operation mode? Maybe I have to change the link between class.
Any other advice ?


texts: Polishing partitions - Reimplementing a partitionOn

texts:
So I've read an F# question on partitioning a list in F# and wondered whether I could cleanly write the concept down in haskell and if that would help me review the code ...

Now I have a haskell implementation of this "not-quite partition, not-quite group" and noticed it seems somewhat clumsy

partitionOn :: ([a] -> Bool) -> [a] -> [[a]]
partitionOn pred list = go pred [] list
    where
        go :: ([a] -> Bool) -> [a] -> [a] -> [[a]]
        go _ working [] = [working]
        go pred working l@(x:xs) = if pred working
                then (working:(go pred [] l))
                else go pred (working++[x]) xs

A few questions:

The compiler gets very annoyed with me when I try to express the else-branch as a concatenation with : instead of ++. Would it be cleaner to use the following go?

go _ working [] = [reverse working]
go pred working l@(x:xs) = if pred working
    then ((reverse working):(go pred [] l))
    else go pred (x:working) xs

Am I missing a special case of groupBy here? It feels like there should be a simple standard function to do this


texts:
I recently came across a coding challenge on some sort of technological basket weaving forum, where you had to pick 2 cards from a shuffled deck. I believe the challenge can be interpreted 2 ways:

Generate random deck, pick first 2
Generate sequential (or any) deck, pick 2 random cards

I went for option one. I believe I have used a good shuffling algorithm and accounted for modulo bias.
My main priorities:

correctness
code easy to handle and read

cards.c
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define SWAP_INT(a,b) {int tmp=a; a=b; b=tmp;}

const char const* suits[4] = {"Diamonds","Clubs","Hearts","Spades"};
const char const* ranks[13] = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};

// from min inclusive to max inclusive
int rand_ranged_inclusive(int min, int max)
{
    if (min > max)
        SWAP_INT(min, max);

    if (min == max)
        return min;

    int range = max-min+1;
    int biased_interval = RAND_MAX%(range-1);
    int x;

    // prevent modulo bias by choosing a number outside biased interval
    do {
        x = rand();
    } while (x < biased_interval);

    return x%range + min;
}

// Fisher-Yates (Durstenfield)
int shuffle(int arr[], int len)
{
    for (int i = 0; i < len; ++i) {
        int j = rand_ranged_inclusive(i, len-1);
        SWAP_INT(arr[i], arr[j]);
    }
}

void print_card(int c)
{
    if (c < 0 || c > 52)
        printf("Joker\n");

    const char const* suit = suits[c/13];
    const char const* rank = ranks[c%13];

    printf("%s of %s\n", rank, suit);
}

int main(int argc, char const *argv[])
{
    srand(time(NULL));

    int cards[52] = {0};

    for (int i = 0; i < 52; ++i)
        cards[i] = i;

    shuffle(cards, 52);

    print_card(cards[0]);
    print_card(cards[1]);

    return 0;
}

I feel like it can be optimized some more, especially picking random numbers, but reading from dev/urandom seems overall slower, when the modulo bias is so small and easily overcome.


texts: Python tool to assemble CodeReview posts from source files

texts:
I hate having to format questions around here. Adding four spaces to each source file and the correct name at the top of each source file becomes a headache when I have to post longer questions.

This is a simple python question parser that takes in arguments from the console and prints out correct format for a CodeReview question. Any suggestions on how to make this code more readable, concise and pythonic would be appreciated.

Question Parser.py

import os
import sys
import argparse

def format_string(PATH,EXTENSION):
    source_files=[f for f in os.listdir(PATH) if os.path.isfile(os.path.join(PATH,f))]
    source_files=[f for f in source_files if f.endswith(EXTENSION)]

    indentation=4
    formatted_string=""
    for source_file in source_files:
        formatted_string+= ("**%s**\n\n" % source_file)
        with open(os.path.join(PATH,source_file)) as source:
            for line in source.readlines():
                formatted_string+=(" "*indentation+"".join(line))

    return formatted_string

if __name__=="__main__":
    parser=argparse.ArgumentParser(description="Automatic formatter for CodeReview Stackexchange Questions")
    parser.add_argument("-p","--path",help="Path for the source files. Default is the current directory",nargs="?",default=os.getcwd(),const=os.getcwd())
    parser.add_argument("header",help="The file that is added to the top of the question")
    parser.add_argument("-e","--extension",help="Filter by the type of source files that is present in the directory",nargs="+",default="")
    parser.add_argument("-o","--out",help="Output the result to a file. By default outputs to the console.",nargs="?")
    args=parser.parse_args()

    if not os.path.isfile(args.header):
        raise parser.error("Header file doesnot exist.\nPlease specify a correct header file path")

    if os.path.exists(args.path):
        question="".join(open(args.header).readlines())
        question+="\n"+format_string(args.path,tuple(args.extension,))
        if not (args.out==None):
            with open(args.out,"w") as outfile:
                outfile.write(question)
        else:
            print(question)

    else:
        raise parser.error("Path doesnot exist.")


texts:
I am trying to improve my C skills, and I hope someone might be able to provide me with some feedback on the following code.

It is just basic string splitting, it should behave the similar to Ruby's String#split or Clojure's clojure.string.split. I couldn't think of a simple/efficient way to create an array of variable-size strings so I went the callback route.

Anyway, any and all feedback is greatly appreciated, thank you! Check out the code:

void strsplit(char *str, char *delim, int limit, void (*cb)(char *s, int idx))
{
  char *search = strdup(str);

  if (limit == 1) {
    cb(search, 0);
  }
  else {
    int i = 0, count = 0, len = strlen(str), len_delim = strlen(delim);
    char *segment = NULL, *leftover = NULL;
    limit = limit > 0 ? limit - 1 : len;

    segment = strtok(search, delim);
    for (i = 0; segment != NULL && i < limit; i++) {
      count += strlen(segment) + len_delim;
      cb(segment, i);
      segment = strtok(NULL, delim);
    }

    if (len != limit && count < len) {
      leftover = (char*) malloc(len - count + 1);
      memcpy(leftover, str + count, len - count);
      leftover[len - count] = '\0';
      cb(leftover, i);
      free(leftover);
    }
  }
}

Also see the code with a test framework.


texts:
In one finance application I'm working on, the requirements call that I truncate a decimal value at certain number of places and not round.

Example: 11.685 truncated to 2 decimal places should be 11.68

I wrote this extension method, but was wondering if someone knew of an easier way.

public static class DecimalExtentsions
{
    public static decimal TruncateDecimalPlaces(this decimal val, int places)
    {
        if (places <= 0)
            return Math.Truncate(val);

        var dv = Math.Pow(10, places);
        decimal part = (val % 1) * Convert.ToDecimal(dv);
        val -= (part % 1) / Convert.ToDecimal(dv);
        return val;
    }
}


texts:
I'm studying C on K&R and now I'm facing a recursion exercise that states:

  Write a recursive version of the function reverse(s), which reverses the string s in place.

I've written the code below and I'm pretty sure that it works.  I'll be glad to receive some critiques about it.

Reverse function:

/* reverse: reverse string s in place */
void reverse(char s[])
{
    static int i, j = 0;
    int c;

    if (i == 0) {
        i = 0;
        j = strlen(s)-1;
    }
    c = s[i];
    s[i] = s[j];
    s[j] = c;
    i++;
    j--;
    while(i < j)
        reverse(s);
}

Main:

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

#define MAXLINE 100

void reverse(char s[]);

int main(void)
{
    char s[MAXLINE] = "foo bar baz";

    reverse(s);
    printf("%s\n", s);
    return 0;
}


texts: Should a User class only contain attributes and no methods apart from getters/setters?

texts:
I'm trying to improve my OOP code and I think my User class is becoming way too fat.

In my program a user has rights over "lists". Read, Write, Update, Delete.
So I made a User class

class User
{
protected $_id;
protected $_email;
protected $_username;
protected $_hashedPassword;

//...Various setters/getters

public function canRead(List $list){
    //Database query verifies if user has READ rights
}

public function canUpdate(List $list){
    //Database query verifies if user has UPDATE rights
}
//etc...
}

Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?
If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?


texts:
I'm new to Haskell, and this is one of the more interesting programs I've made with it so far. I understand there are already solutions to this problem that use much less code, but to me this one seems fairly intuitive. Are there any ways I can improve this code to be more readable or efficient?
fib :: Int -> [Integer]
fib n = (n-1) `replicate` 0 !: 1 ++ (+) `zipPoly` repFor tail (fib n) n
(!:) :: [x] -> x -> [x]
[] !: a = [a]
(l:ls) !: a = l : ls !: a
zipPoly :: (x -> x -> x) -> [[x]] -> [x]
zipPoly _ [] = []
zipPoly _ [a] = a
zipPoly f (a:b:c) = zipPoly f $ zipWith f a b : c
repFor :: (x -> x) -> x -> Int -> [x]
repFor _ _ 0 = []
repFor f a n = a : repFor f (f a) (n-1)
main = do
    s <- getLine
    putStrLn "Starting..."
    putStr $ unlines $ map show $ fib (read s :: Int)

Explanations of functions:

fib n is a list containing the n-bonacci numbers, starting with n-1 zeros and then a one.
list !: elem concatenates elem to the end of list.
zipPoly func lists is equivalent to zipWith but with more than two lists.
repFor func start amount is a list of length amount where the first element is start and every element after it is func applied to the element before it  ([x, f x, f (f x), f (f (f x))...]).