texts: Custom indexOf for strings javascript with regex

texts:
I was wondering how efficient my code is creating custom indexOf for strings in JavaScript using regex instead of looping with a for statement the whole way in most solution I find and I believe this got \$O(1)\$ since no loop is needed.

The idea is to use regex that put either the key or any list of word that is not key; this way I know that the value will be either in arr[0] or arr[1].  I also check using regex earlier whether the key exist in the value or not; this way I created non-looping indexOf with regex. This way I just return 0 if the key is in arr[0] or arr[0].length if it not in arr[0].

function findindex(value,key){
  let regex = RegExp( "((?!"+key+").)+|"+key , "ig" ); //regex for separating keys in the array
  let regex2 = RegExp(key,"ig");  // regex for checking if the key is exist in the value or not

  //first check before looping whether key is available in array or not
  if( !regex2.test(value) || value.length < key.length ){
    return -1;
  }

  let arr  = value.match(regex); //make an array

  //alternative with condition statement
  return ( arr[0] === key || regex2.test(arr[0]) ) ? 0 : arr[0].length;
}


texts: Enforcing correct input/output of integers

texts:
The problem:

Some types, like cstdint aliases or, at least purely theoretically, even std::size_t, may be (but don’t have to be) bound to char, signed char or unsigned char. In practice, std::int_least8_t seems to be often bound to signed char and std::uint_least8_t – to unsigned char. This seems odd, since semantically, all those types are supposed to represent integers rather than characters.
In case of variables of a character type, the >> operator writes the character code of the first non-whitespace character of the input stream into the variable, while the << operator outputs a character of the character code equal to the value of the variable.
Therefore it may happen that if we, for example, declare a variable as int_least8_t and use the input operator or the output operator on it, then the results will be far from expected. This seems to be even more awkward since whether such aliases are bound to character types or not depends only on the implementation and is a priori unknown.

An example of the above problems: http://ideone.com/JgyFhR A proof that purely theoretically, this can even be the case for std::size_t: https://stackoverflow.com/questions/32915434

I’ve attempted to write a generic solution to all those problems:

#ifndef INTIO_H
#define INTIO_H

#include <istream>
#include <ostream>
#include <type_traits>
#include <limits>

template
<class T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
class integer_IO
{
  T &val;

public:

  integer_IO(T &arg) : val(arg) {}
  integer_IO(T &&arg) : val(arg) {}

  friend std::istream &operator>> (std::istream &is, integer_IO<T> &&i)
  {
    using TT = decltype(+i.val);
    TT hlp;
    is >> hlp;
    TT constexpr minval = static_cast<TT>(std::numeric_limits<T>::min());
    TT constexpr maxval = static_cast<TT>(std::numeric_limits<T>::max());
    i.val = static_cast<T>(hlp > maxval ? maxval : hlp < minval ? minval : hlp);
    if(hlp > maxval || hlp < minval)
      is.setstate(std::ios::failbit);
    return is;
  }

  friend std::ostream &operator<< (std::ostream &os, integer_IO<T> const &&i)
  {
    os << +i.val;
    return os;
  }
};

template
<class T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
integer_IO<T> intIO(T &arg)
{
  return integer_IO<T>(arg);
}

template
<class T, typename = typename std::enable_if<std::is_integral<T>::value>::type>
integer_IO<T> intIO(T &&arg)
{
  return integer_IO<T>(arg);
}

#endif

The usage of this wrapper is simple:

#include <iostream>
#include <cstdint>
#include "intIO.hpp"
using namespace std;

int twoplustwo()
{
  return 2+2;
}

int main()
{
  int_least8_t i;
  cin >> intIO(i);
  cout << intIO(i) << '\n';
  cout << intIO(twoplustwo()) << '\n';
}

What is your opinion of my code?


texts: Should I create an abstract runnable? I've 4 sub-classes which perform similar work but only 3 of them have identical constructors

texts:
I've added the code for an abstract thread class and 2 sub-classes. The structure and job of the threads (sub-classes) is identical except one difference: ONE of the sub-classes, RefreshData does not need the client parameter. I've overloaded the constructor in the sub-class but I'm not sure if the abstraction makes sense anymore. Moreover, can I do something to ensure that RefreshData doesn't use the inherited client parameter accidentally and ends up getting an NPE.

    public abstract class BackgroundTask implements Runnable {

      protected final Manager manager;
      protected final Client client;
      private long msSyncInterval;
      private boolean shutdown; // has a setter

    public BackgroundTask(final Manager manager, final long msSyncInterval) {
        this.manager = manager;
        this.client = null;
        this.msSyncInterval = msSyncInterval;
        this.shutdown = shutdown;
    }

    public BackgroundTask(final Manager manager, final Client client, final long msSyncInterval) {
        this.manager = manager;
        this.client = client;
        this.msSyncInterval = msSyncInterval;
        this.shutdown = shutdown;
    }

    @Override
    public void run() {
        while (!shutdown) {
            executeTask();

            // sleep for msSyncInterval
        }
    }

    abstract void executeTask();
}

public class ExchangeData extends BackgroundTask {

    public ExchangeData(final Manager manager, final Client client, final long msSyncInterval) {
        super(manager, client, msSyncInterval);
    }

    @Override
    void executeTask() {
        // Some work here
    }
}

public class RefreshData extends BackgroundTask {

    public RefreshThrottleLimits(final Manager manager, final long msSyncInterval) {
        super(throttleManager, msSyncInterval);
    }

    @Override
    void executeTask() {
        // Doesn't use the client
    }
}


texts:
My problem statement is:

  Write a function to indicate if a given Sudoku board is legal. This function takes a Sudoku board (which you may assume is a N2xN2 2d list of integers, where N is an integer), and returns True if the board is legal, as described above.

And here's my solution:

import time, random

def solve_all(grids, name='', showif=0.0):
    """Attempt to solve a sequence of grids. Report results.
    When showif is a number of seconds, display puzzles that take longer.
    When showif is None, don't display any puzzles."""
    def time_solve(grid):
        start = time.clock()
        values = solve(grid)
        t = time.clock()-start
        ## Display puzzles that take long enough
        if showif is not None and t > showif:
            display(grid_values(grid))
            if values: display(values)
            print '(%.2f seconds)\n' % t
        return (t, solved(values))
    times, results = zip(*[time_solve(grid) for grid in grids])
    N = len(grids)
    if N > 1:
        print "Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max    %.2f secs)." % (
            sum(results), N, name, sum(times)/N, N/sum(times), max(times))

def solved(values):
    "A puzzle is solved if each unit is a permutation of the digits 1 to 9."
    def unitsolved(unit): return set(values[s] for s in unit) == set(digits)
    return values is not False and all(unitsolved(unit) for unit in unitlist)

def from_file(filename, sep='\n'):
    "Parse a file into a list of strings, separated by sep."
    return file(filename).read().strip().split(sep)

def random_puzzle(N=17):
    """Make a random puzzle with N or more assignments. Restart on contradictions.
    Note the resulting puzzle is not guaranteed to be solvable, but empirically
    about 99.8% of them are solvable. Some have multiple solutions."""
    values = dict((s, digits) for s in squares)
    for s in shuffled(squares):
        if not assign(values, s, random.choice(values[s])):
            break
        ds = [values[s] for s in squares if len(values[s]) == 1]
        if len(ds) >= N and len(set(ds)) >= 8:
            return ''.join(values[s] if len(values[s])==1 else '.' for s in squares)
    return random_puzzle(N) ## Give up and make a new puzzle

def shuffled(seq):
    "Return a randomly shuffled copy of the input sequence."
    seq = list(seq)
    random.shuffle(seq)
    return seq


texts: Revert knockout model original state back on update cancel?

texts:
I am using knockout in my project. I have some models like EmployeeModel, ServiceModel etc which user can update. On UI I give the user a Cancel control button by which he can revert the changes. On cancel I have to revert the model change back to its original state. For this I found these two good approaches by @rniemeyer:

Protected Observable

I can't use protected observables because I am using ko.mapping plugin which will create a knockout models base on server side viewmodels. Yes, I can use mapping option like Create, but I feel its not a good to keep separate observables state. I want solution which will be reusable and can apply to whole model.

And guess what I got, second good approach by same author @rniemeyer:

Simple editor pattern

I can't use this also because of the same reason I mentioned above. So I wrote 2 functions copy and reset which will do the job for me:

Copy

Here, source is the object whose current state we want to preserve, and dest keeps the current state.

function copy(source, dest) {

    for (var key in source) {

        if (source.hasOwnProperty(key)) {

            //no need to keep knockout added properties
            if (key === "__ko_mapping__")
                continue;

            //recursive call to copy if property is an object
            else if (typeof source[key] === "object") {
                dest[key] = {};
                copy(source[key], dest[key]);
            }

            else {
                //no need to copy the computed observable value
                if (!ko.isComputed(source[key])) {
                    var value = ko.utils.unwrapObservable(source[key]);
                    dest[key] = value;
                }
            }
        }
    }

    //remove all function
    for (var key in dest) {
        if (typeof dest[key] === "function")
            delete dest[key];
    }
}

Reset

Here, source is the previous dest and dest is the previous source.

function reset(source, dest) {

    for (var key in source) {

        if (source.hasOwnProperty(key)) {

            //recursive call to copy if it is an object
            if (source[key] !== null && typeof source[key] === "object") {
                reset(source[key], dest[key]);
            }

            else {
                if (ko.isObservable(dest[key]))
                    dest[key](source[key]);
                else
                    dest[key] = source[key];
            }
        }
    }
}

I want you to please review these function and let me know if these function require any improvement.


texts: Streaming modified lines of a file from a Controller

texts:
I am writing a piece of software that aims at streaming the modified lines of an external file located at given uri (and retrieved as a QueryString parameter).

I am trying to minimize the impact of big files so that I can maximize the use of asynchronous calls (i.e. async / await). I am using AsyncEnumerable (https://github.com/Dasync/AsyncEnumerable) to have at the same time the feature of enumerable and and async / await, in order to free up threads and memory (I am not going to keep the whole file in memory before sending the modified version back).

I created an extension method that can fetch the lines of a remote file.

public static class StringExtensions
{
    public static AsyncEnumerable<string> ReadLinesAsyncViaHttpClient(this string uri)
    {
        return new AsyncEnumerable<string>(async yield =>
        {
            using (var httpClient = new HttpClient())
            {
                using (var responseStream = await httpClient.GetStreamAsync(uri))
                {
                    using (var streamReader = new StreamReader(responseStream))
                    {
                        while(true)
                        {
                            var line = await streamReader.ReadLineAsync();

                            if (line != null)
                            {
                                await yield.ReturnAsync(line);
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                }
            }
        });
    }
}

And used that extension method in a Controller action:

using System;
using System.Collections.Async;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace WebApplicationTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LinesController : ControllerBase
    {
        private static readonly Random Random = new Random();

        // GET api/lines
        // POST api/lines
        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetAsync([FromQuery] string fileUri)
        {
            using (var streamWriter = new StreamWriter(HttpContext.Response.Body))
            {
                await fileUri.ReadLinesAsyncViaHttpClient().ForEachAsync(async line =>
                {
                    // Some dumb process on each (maybe big line)
                    line += Random.Next(0, 100 + 1);
                    await streamWriter.WriteLineAsync(line);
                });
            }

            return Ok();
        }
    }
}

I used the HttpContext.Response.Body stream instead of the PushStreamContent cause according to this answer: https://stackoverflow.com/a/48115434/4636721 (in .NET Core we don't need to use the PushStreamContent if no need of HttpMessage)

It seems to work I mean, I get a payload with the lines of the initial file passed in the query string and with some random numbers at the end of each line. It seems there is no increase in memory but I would like to have another pair of eyes to check what I have done.

[EDIT 2]
Turns out there is already an issue on the ASP.NET MVC Github about that: https://github.com/aspnet/Mvc/issues/6224


texts: Keyword classification in Scala... simple?

texts:
I am pretty newbie in Scala, my background expertise is basically Java and Python, and I'd like to know your thoughts about this code snippet written in Scala to know if this is a "regular piece of code written in Scala" or if this is something kind of "obfuscated" and overcomplicated.
The code just implements a simple decision flow to categorize keywords depending on a few rules.
Thanks!
def preprocess(kwd: Keyword): Option[PrepKeyword] = {

val isFoo = kwd.name.exists(_.toLowerCase(locale) == "foo")
    for {
      filterCategory <- (isFoo, kwd.type) match {
                case (true, _)  => Some(false)
                case (false, 1) => Some(true)
                case (false, 2) => Some(false)
                case _          => None
              }
      fooName <- kwd.name match {
                        case None | Some("name1")                           => None
                        case Some("myCategory") if filterCategory           => Some("GreatCategory")
                        case other                                          => other
                      }
    } yield PrepKeyword(
      keyword = kwd,
      name = fooName,
      path = if (isFoo) "Foo1" else "Foo2"
    )
  }


texts: wxpython program to clear the Desktop or restore files to the Desktop

texts:
This is a program that clears the desktop and also undoes the clear. How does the code look? Could I make it look better?

import wx
import os
import shutil
import time

class Window(wx.Frame):
    def __init__(self, parent, id):
        self.Desktop = "C:/Users/Name/Desktop/" and "C:/Users/Public/Desktop/"
        self.Dfiles = "C:/ Desktop_Files/"
        no_caption = wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP
        wx.Frame.__init__(self, parent, id, title="no_caption", size=(300,97), style=no_caption)
        self.panel=wx.Panel(self)
        self.Butt_Clear = wx.Button(self.panel, -1, label="Clear Desktop", pos=(0,0), size=(100,70))
        self.Butt_Clear.Bind(wx.EVT_BUTTON, self.ClearDesk, self.Butt_Clear)
        self.Butt_Undo = wx.Button(self.panel, -1, label="Undo Clear", pos=(185,0), size=(100,70))
        self.Butt_Undo.Bind(wx.EVT_BUTTON, self.UndoClear, self.Butt_Undo)
    def ClearDesk(self, e):
        MainDesktop = os.listdir(self.Desktop)
        MainDesktop.remove('desktop.ini')

        for Desktop_Path_Names in MainDesktop:
            Desktop_Path = os.path.join(self.Desktop, Desktop_Path_Names)
            shutil.move(Desktop_Path, self.Dfiles)

    def UndoClear(self, e):
        Dfolder = os.listdir(self.Dfiles)
        Dfolder.remove('desktop.ini')
        for Desktop_Folder_Path_Names in Dfolder:
            Dfolder_Path = os.path.join(self.Dfiles, Desktop_Folder_Path_Names)
            shutil.move(Dfolder_Path, self.Desktop)

if __name__=='__main__':
    app=wx.App(False)
    frame=Window(parent=None, id=-1)
    frame.Show()
    app.MainLoop()


texts: Checkered flag: a modular usage of Tkinter's geometry management

texts:
This is code that produces a checkered flag-like GUI. I wanted to demonstrate, also learn in detail, how tkinter's geometry managers can be used modularly, so I decided that I could write code for a checkered flag that has frames inside frames, that which have their geometries managed independent of each other.

The code produces the following:

The main window(root) has a frame that has 2 vertical frames as partitions (class TwoFrames).
Each one of those frames has 2 horizontal labels as partitions (class TwoLabels).

I wanted to show that you can manage a frame's geometry which manages its own widgets' geometry.

import tkinter as tk

#a class that has 2 columns of frames inside
class TwoFrames(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)

        #creates 2 frame objects and passes self as parent, which means object created using TwoFrames class is the parent
        self.frame1 = tk.Frame(self)
        self.frame2 = tk.Frame(self)

        #manages 2 frames geometry
        self.frame1.grid(row=0, column=0, sticky="nsew")
        self.frame2.grid(row=0, column=1, sticky="nsew")

        #enables resizing for 0th row, and 1st and 2nd columns of an object of this class
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)

class TwoLabels(tk.Frame):
    def __init__(self, master=None, color=True):
        super().__init__(master)

        #creates 2 Label objects with TwoLabels object as parent
        self.label1 = tk.Label(self)
        self.label2 = tk.Label(self)

        #configures the background color of labels for demonstrative purposes
        if color:
            #label1 will have black color
            self.label1.configure(bg="black")
            #label2 will have white color
            self.label2.configure(bg="white")
        else:
            #label1 will have white color
            self.label1.configure(bg="white")
            #label2 will have black color
            self.label2.configure(bg="black")

        #manages the geometry
        self.label1.grid(column=0, row=0, sticky="nsew")
        self.label2.grid(column=0, row=1, sticky="nsew")

        #enables resizing like above, but this time for 2 rows and 1 column
        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)

#creates the mainWindow
mainWindow = tk.Tk()

#creates a mainFrame that has 2 frames in it
mainFrame = TwoFrames(mainWindow)

#manages geometry of mainFrame and display it
mainFrame.pack(fill="both", expand=True)

#creates row_labels1 and row_labels2, both has 2 colored labels in them
row_labels1 = TwoLabels(mainFrame.frame1, True)
row_labels2 = TwoLabels(mainFrame.frame2, False)

#manages geometry of labels inside frames and displays them
row_labels1.pack(fill="both", expand=True)
row_labels2.pack(fill="both", expand=True)

#run the application
mainWindow.mainloop()

Review Concerns:

My main concern is to have this code well written in the structure of object oriented programming. Tiniest of issue is important to me.
I'd also like to know in what ways it can be more concise for better understanding tkinter's geometry managers.


texts: Search DataTable by column for a specific row

texts:
I would like to know if there are ways to make this run faster. Not a big concern right now, but I would like to think long term, it might be important.

This is C#, and I can not change the input parameters data types, but basically I have to make something like the SQL: SELECT returnCol FROM dt WHERE ColName = ColValue

As the datatable itself: it has more than 100 columns, but it should not too many rows, usually ~10 rows but it can spike up to 100 rows sometimes. This is part of a data parse that is happening once a minute, that is why I am trying to see if there are ways for enhancement.

private string FindInT(DataTable dt, string ColName, string ColValue, string returnCol)
        {
            foreach (DataRow row in dt.Rows)
            {
                if (row[ColName].ToString().ToLower().Trim() == ColValue.ToLower().Trim())
                {
                    return row[returnCol].ToString();
                }
            }
            return "";
        }


texts:
The idea is to write a function that reads string of unknown size from stdin, keep it in dynamically allocated array of unknown size and return a copy of that array.

Is this the right approach? Could I be more clear? Would reading the input char-by-char be better than getting bigger chunks at once?

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

char * read_string(void)
{
    int buff_size = 11; /* size of temporary buffer */
    char temp[11]; /* temporary input buffer */
    char *output; /* pointer to allocated memory */
    char *copy; /* copy of input string to be returned */
    char *iterator; /* pointer to beginning of an array, used when searching for \n in input string */

    output = malloc(10*sizeof(char)); /* allocates 10 bytes for first part of input */

    if(output == NULL)
        return NULL;

    size_t size = 10*sizeof(char); /* keeps track of actual size of output */
    //*output = '\0'; /* places NUL at the beginning of output, to make it empty string */
    while(fgets(temp, buff_size,stdin) != NULL) /* read  max 10 chars from input to temp */
    {
        strcat(output,temp); /* append read input to output, without \0 char */
        if(strlen(temp) != 10 || temp[9] == '\n') /* if buffer wasn't full or last char was \n-stop because it reached the end of input string */
            break;

        size += buff_size - 1; /* if didn' reach end of input increase size of output*/
        output = realloc(output,size);

        if(output == NULL)
        {
            return NULL;
        }
    }

    iterator = output; /* search for \n in output and replace it with \0 */

    while(*iterator != '\n')
        iterator++;

    *iterator='\0';

    copy=malloc(strlen(output) + 1); /* allocate memory for copy of output +1 for \0 char */
    if(copy == NULL)
        return NULL;

    strcpy(copy, output); /* strcpy output to copy */
    free(output);  /* free memory taken by output */

    return copy;
}


texts: Merging cells in multiple columns on multiple sheets

texts:
This code merges cells in multiple columns on multiple sheets, and it's too slow.

I'm hoping for any help at all to speed this up. Unfortunately, I'm not able to get around the fact that the cells must be merged.

I broke up the for statements - it helped a bit, but it's still very, very slow.

Also, I turned off screenupdating, events, calculation, displaypagesbreaks, etc.; it didn't seem to help.

Function MergeCells()

    Dim WS_Count As Integer
    Dim i As Integer
    Dim ShName As String

    WS_Count = ActiveWorkbook.Worksheets.Count

    PIS.Activate

    For i = 1 To WS_Count
        Select Case ActiveWorkbook.Worksheets(i).Name
            Case "Med Curr", "Med Ren", "Med RevRen", "Med Prop", "Med Renewal Alts A", "Med Renewal Alts B", _
                "Med Renewal Alts C", "Med Prop Other Markets 1A", "Med Prop Other Markets 1B", "Med Prop Other Markets 1C", _
                "Med Prop Other Markets 2A", "Med Prop Other Markets 2B", "Med Prop Other Markets 2C", _
                "Med Prop Other Markets 3A", "Med Prop Other Markets 3B", "Med Prop Other Markets 3C"
                    ActiveWorkbook.Worksheets(i).Activate
                    ShName = ActiveSheet.Name
                MergeCellsx (ShName)
        End Select
    Next i

End Function

Function MergeCellsx(ShName)

    Dim RngB As Range
    Dim row As Integer

    With Sheets(ShName)
        For row = 6 To 12
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 14 To 18
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 20 To 22
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 24 To 25
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 27 To 34
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
    End With
End Function


texts:
I used Nokogiri and a piece of ActiveSupport to parse an xml file from a given URL, format the data properly and return a JSON string. The script works as expected, so I'm only wondering if there are ways to make the code better from architecture/naming perspectives.

#!/usr/bin/env ruby

$:.unshift File.dirname(__FILE__)

require 'open-uri'
require 'nokogiri'
require 'active_support/core_ext'

class Scadenzario
  def initialize(url)
    @url = url
    @events = parse_events
  end

  def xml
    Nokogiri::XML::Document.parse(open(@url))
  end

  def to_json
    @events.to_json
  end

private

  def parse_events
    result = []
    xml.xpath('//item').each do |node|
      result << build_event(node)
    end

    result
  end

  def build_event(node)
    event = Hash.new
    event[:title] = node.at_xpath('title').content
    event[:url] = node.at_xpath('link').content
    event[:start] = format_event_time(node)
    event[:allDay] = false

    event
  end

  def format_event_time(node)
    Time.parse(node.at_xpath('pubDate').content).iso8601
  end
end

puts Scadenzario.new('servizi.seac.it/documenti/rss/rss_scadenzario_annuale.xml').to_json

The parse_events method can be written like this, but I think it would make the code rather unclear.

def parse_events
  xml.xpath('//item').inject([]) do |result, node|
    result << build_event(node)
  end
end


texts:
I have written a small Windows application that draws India's flag in the window. I am very new to using Visual C++ and I want to understand if my code can be improved further.

#include "afxwin.h"
#include <math.h>

class CMyApp : public CWinApp
{
public:
    virtual BOOL InitInstance ();
};

class CMainWindow : public CFrameWnd
{
public:
    CMainWindow();
protected:
    afx_msg void OnPaint();
    DECLARE_MESSAGE_MAP();
};

CMyApp myAPP;

BOOL CMyApp::InitInstance()
{
     m_pMainWnd = new CMainWindow;
     m_pMainWnd->ShowWindow(m_nCmdShow);
     m_pMainWnd->UpdateWindow();
     return TRUE;
}

BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
    ON_WM_PAINT()
    END_MESSAGE_MAP()

CMainWindow::CMainWindow ()
{
    Create(NULL,_T("India's Flag"), WS_OVERLAPPEDWINDOW );
}
void IndiaFlag(CDC &dc, int x, int y)
{
    dc.SetBkMode(TRANSPARENT);
    CRect rect;
    CPen pen(PS_SOLID, 1, RGB(0,0,0));
    CPen *oldPen = dc.SelectObject(&pen);
    {
        CBrush brush(RGB(255,130,0));
        CBrush *oldBrush = dc.SelectObject(&brush);
        dc.Rectangle(x,y,x+200,(y+50));
    }
    {
        CBrush brush(RGB(255,255,255));
        CBrush *oldBrush = dc.SelectObject(&brush);
        dc.Rectangle(x,(y+50),(x+200),(y+100));
        CPen pen2(PS_SOLID, 1,RGB(0,0,255));
        CPen *oldPen = dc.SelectObject(&pen2);
        dc.Ellipse((x+75),(y+50),(x+125),(y+100));
        double Nx,Ny;
        for (int angle=0;angle<360; angle+=15)
        {
            int angle2 = angle;
            double length = 25*(cos(double(angle2 *(3.14159265 / 180))));
            double len2 = 25*(sin(double(angle2 *(3.14159265 / 180))));
            int originX = (x+100);
            int originY = (y+75);
            Nx = originX + length;
            Ny = originY - len2;
            dc.MoveTo(originX,originY);
            dc.LineTo(Nx,Ny);
        }
    }
    {
        CBrush brush(RGB(34,139,34));
        CBrush *oldBrush = dc.SelectObject(&brush);
        dc.Rectangle(x,(y+100),(x+200),(y+150));
    }
}
void CMainWindow::OnPaint ()
{
    CPaintDC dc(this);
    IndiaFlag(dc, 150, 150);
}

In case you wondered, this is what the Indian flag looks like:


texts: Finding the number of ways to partition {1,2, ..., N} into p1 and p2 such that sum(p1) == sum(p2)

texts:
I am trying to write a space and time efficient algorithm to calculate the number of ways to partition a set of integers {1, 2, ..., N} into two partitions such that the sums of integers in the two partitions are equal. I have started with a brute force approach that seems to give me correct results:

from itertools import combinations
def f(n):
    s = set([i+1 for i in range(n)])
    valid_partitions = []
    for i in range(1,n):
        combos = combinations(s,i)
        for c in combos:
            p1 = frozenset(c)
            p2 = set(range(1,n+1)) - p1
            p2 = frozenset(p2)
            if sum(p1) == sum(p2):
                valid_partitions.append(frozenset((p1,p2)))

    return len(set(valid_partitions))

Also, since I am checking every way to partition {1,2,...,N} into two non-empty sets, is it correct to say that the Big O time complexity of this approach is S(N,2) (Stirling Number of the Second Kind)? Also, how would I evaluate the Big O space complexity of this approach? Is there a better approach I can take?


texts:
I've just started to teach myself Rust. I've written the following code to read a text file and store the contents in a String. Is this the typical way of doing this? Can anyone suggest any improvements to this?

use std::fs::File;
use std::io::Read;
use std::io;

fn main() {

    let file_name = "test.txt";

    let mut file_contents = String::new();

    match get_file_contents(file_name, &mut file_contents) {
        Ok(()) => (),
        Err(err) => panic!("{}", err)
    };

    println!("{}", file_contents);

}

fn get_file_contents(name: &str, mut contents: &mut String) -> Result<(), io::Error> {

    let mut f = try!(File::open(name));

    try!(f.read_to_string(&mut contents));

    Ok(())

}


texts: Print inverse right triangle using recursion

texts:
I wrote a program to print the following pattern using recursion to hands on recursion and my output is perfect but I want to know another and the most optimized approach for this.

This is the sample output of my program if we insert n = 5:

54321
4321
321
21
1

public class JavaApplication2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        printNumber(n,n);
        scan.close();
    }
    static int printNumber(int n,int a) {
            if(a == 0)
                return 0;
            else
            {
               System.out.print(n);

               if(n==1)
               {
                   System.out.println();
                   --a;
                   n = a +1;
               }
               n--;
            }
            return printNumber(n, a);
    }
}


texts:
A Brief Context

I recently gave an interview in a company where I was asked this particular question. After the interview was over, the HR gave the feedback that my solution (is correct programmatically) but is monolithic and not scalable. The interview was for frontend developer 2.

Question

Suppose there is a company which does some analytics work and returns data. The company (let's say X) gets a stream of numbers and it calculates average at that instant for all numbers received and returns the average. There could be other companies (let's say Y) which can ask for the average.

  Data:   1  3  5  7  9
  Avg:    1  2  3  4  5

So, in the above example, the average are calculated by company X.

After first no, average is 1,
After second no (i.e. 3), average is 2 ((3+1)/2) and so on

At any point in time, companies are only concerned about average at that time (basically, if average is asked after data value 5, you only need to return 3)

The geeksforgeeks link for problem is https://www.geeksforgeeks.org/average-of-a-stream-of-numbers/

Complexity

The solution needs to be O(1) time and O(1) space

My solution:

I wrote a closure in Javascript to save the current average and total number of values encountered so far. Then wrote another function to call it by passing some parameters. The parameters decide whether I should be updating the average or returning it.

function analytics() {
  const data = {
    avg: 0, //the average at that instant
    totalPoints: 0 //total number of values encountered till that point
  }
  return function(value) {
    //if value is not present, return the avg
    if (!value) {
      return data.avg
    }
    const newTotal = data.avg * data.totalPoints + value
    const newTotalP = data.totalPoints + 1
    //update the value for next usage
    data.avg = newTotal / newTotalP
    data.totalPoints = newTotalP
    return data.avg
  }
}

fn = analytics()

/*
 param = {
  type: //Company Names
  value: //Value to update
 }
*/

function y({
  type,
  value
}) {
  if (["Y"].indexOf(type) >= 0) {
    return fn()
  } else if (["X"].indexOf(type) >= 0) {
    return fn(value)
  }
}

console.log("get avg", y({
  type: "Y"
}))
console.log("update avg", y({
  type: "X",
  value: 1
}))
console.log("update avg", y({
  type: "X",
  value: 3
}))
console.log("update avg", y({
  type: "X",
  value: 5
}))
console.log("get avg", y({
  type: "Y"
}))
console.log("update avg", y({
  type: "X",
  value: 7
}))
console.log("update avg", y({
  type: "X",
  value: 9
}))
console.log("get avg", y({
  type: "Y"
}))

My concerns/doubts:

What did I miss here so that solution is not scalable
Any use cases when it might cause issues
How can it be re-written to make it scalable

Things the can be assumed won't cause any issues

Need not worry about precision issues while calculating the average
Need not worry about issues due to Number datatype not able to accomodate very large values
Data validation issues
Variable names etc (I re-wrote the solution again for codereview, so some names are not correct)

Hope, I am able to explain the situation properly and would like to get more insights here. Also, let me know if anyone needs any further explanation or something is missing


texts: Is there a better way of defining custom calendars?

texts:
I need to define custom calendars and, in particular, test a DateTime for being a holiday. My current code is shown below. Is there a more concise/better way of doing this, preferably without sacrificing performance?

let private isHoliday2011 (dt:DateTime) =
  match dt.DayOfWeek with
  | DayOfWeek.Saturday | DayOfWeek.Sunday ->
    match (dt.Month, dt.Day) with
    | (3,5) -> false
    | _ -> true
  | _ ->
    match dt.Month with
    | 1 ->
      match dt.Day with
      | 3 | 4 | 5 | 6 | 7 | 10 -> true
      | _ -> false
    | 2 ->
      match dt.Day with
      | 23 -> true
      | _ -> false
    | 3 ->
      match dt.Day with
      | 7 | 8 -> true
      | _ -> false
    | 5 ->
      match dt.Day with
      | 2 | 9 -> true
      | _ -> false
    | 6 ->
      match dt.Day with
      | 13 -> true
      | _ -> false
    | 11 ->
      match dt.Day with
      | 4 -> true
      | _ -> false
    | _ -> false


texts:
I am wondering how to optimize the following OCaml simple code.

#load "unix.cma";;
open Unix;;

let time f x =
    let start = Unix.gettimeofday ()
    in let res = f x
    in let stop = Unix.gettimeofday ()
    in let () = Printf.printf "Execution time: %fs\n%!" (stop -. start)
    in res ;;

let syracuse x =
    let rec aux x t =
        match x with
          1 -> t
          |x -> if x mod 2 = 0 then aux (x / 2) (t + 1) else aux (3 * x + 1) (t+1) in
     aux x 0 ;;

let syracuse2 x =
    let rec aux x t =
        if x = 1 then
            t
        else
            if x mod 2 = 0 then aux (x / 2) (t + 1) else aux (3 * x + 1) (t+1)
        in
     aux x 0 ;;

let rec iterate_over n f l  =
     if n = 0 then l else iterate_over (n-1) f ((f n)::l);;

let syracuses n = iterate_over n syracuse [];;
let syracuses2 n = iterate_over n syracuse2 [];;

(time syracuses 100000);;
(time syracuses2 100000);;

I made a first attempt replacing the match with with ifs but it slightly reduced the performance.

Execution time: 1.880309s
Execution time: 1.920133s

I tried to replace the t+1s by succ t but it did not bring anything. I think that there are some redundancies in the operations performed when calling mod 2 and dividing by 2 but I don't know how it can help.


texts:
I need to calculate the BLACKLOG_M value corresponding to the Snapdate of the first of the month. It becomes a constant value repeated for each line of the month

As it is explained in the picture:

SELECT     T1.SNAP, T1.PERI, T1.ANNEE, T1.MOIS, T1.[BCKL], T2.[BCKL] AS BCK2,[NBR1]
      ,[NBR2]
FROM         stg.FACTSALES AS T1 LEFT OUTER JOIN
                          (SELECT     YEAR(SNAP) AS ANNEE, MONTH(SNAP) AS MOIS, [BCKL]
                            FROM          stg.FACTSALES
                            WHERE      (DAY(SNAP) = 1)) AS T2 ON T2.ANNEE = T1.ANNEE AND T2.MOIS = T1.MOIS

The script returns the correct values, but is there any another best idea or improvement?


texts:
I've put together my first table using Qt's QTableView and a custom data model. Currently, some data is populated on initialisation, and the user has the option of adding and deleting entries.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
using namespace std;
QList<Contact> contacts;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QList<QString> contactNames;
    QList<QString> contactPhoneNums;

    contacts.append(Contact{4,"Adam"});
    contacts.append(Contact{5,"James"});
    contacts.append(Contact{2,"Emily"});
    contacts.append(Contact{1,"Mark"});

    // Create model:
    PhoneBookModel = new TestModel(this);

    // Connect model to table view:
    ui->tableView->setModel(PhoneBookModel);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionMode( QAbstractItemView::SingleSelection );

    // Make table header visible and display table:
    ui->tableView->horizontalHeader()->setVisible(true);
    ui->tableView->show();

    //slots to signals

    connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::foo);

}

void MainWindow::foo(){
    QItemSelectionModel *selected = ui->tableView->selectionModel();
    QModelIndexList rowList = selected->selectedRows();

    if (rowList.size() == 0){
        ui->label->setText("YAY");
        ui->tableView->selectRow(0);

    } else {
        ui->label->setText(contacts.at(rowList.at(0).row()).name);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

TestModel::TestModel(QObject *parent) : QAbstractTableModel(parent)
{
}

int TestModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return contacts.length();
}

int TestModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 2;
}

QVariant TestModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || role != Qt::DisplayRole) {
        return QVariant();
    }
    if (index.column() == 0) {
        return contacts[index.row()].id;
    } else if (index.column() == 1) {
        return contacts[index.row()].name;
    }
    return QVariant();
}

void TestModel::update(int row){

   QModelIndex i = this->index(row,0,QModelIndex());
   QModelIndex p = this->index(row,1,QModelIndex());

   emit dataChanged(i,p);
   emit layoutChanged();
}

QVariant TestModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
        if (section == 0) {
            return QString("Name");
        } else if (section == 1) {
            return QString("Phone");
        }
    }
    return QVariant();
}

void MainWindow::on_DeleteButton_clicked()
{
    QItemSelectionModel *selected = ui->tableView->selectionModel();
    QModelIndexList rowList = selected->selectedRows();

    for (int i = 0; i < rowList.count(); i++)
    {

        contacts.removeAt(rowList.at(i).row());
        if (rowList.at(i).row() == contacts.size()){ //last element
            ui->tableView->selectRow(rowList.at(i).row()-1);

        } else {

        }

        PhoneBookModel->update(rowList.at(i).row());
        foo();

    }

}

void MainWindow::on_AddButton_clicked()
{
    int id = ui->id->text().toInt();
    QString name = ui->name->text();

    contacts.append(Contact{id,name});

    PhoneBookModel->update(contacts.size()-1);

}

It all works fine, although I worry that I may be using QTableView incorrectly and/or inefficiently. Any suggestions on how to improve my code while maintaining the same functionality would be appreciated.


texts: Is my 4x4 matrix multiplication on a 1D float array correct?

texts:
I'm trying to develop my own math library to use on a Voxel engine, but I'm worried about Matrices multiplication. Everywhere I saw people using 4x4 Matrices on a 2D Float Array but I'm using a 1D Float Array because of performance needs.

    public float[] multiplicate(float[] factor){
        float[] result = new float[factor.length];
        for (int i = 0, a = 0, b = 0; i < factor.length; i++){
            a = (i/4)*4;
            b = (i%4);
            result[i] = (mat4f[a] * factor[b]) + (mat4f[a+1] * factor[b+4]) + (mat4f[a+2] * factor[b+8]) + (mat4f[a+3] * factor[b+12]);
        }
        return result;
    }

EDIT: I'm using a 1D array to store the 4x4 Vector. If I use 16 float variables instead, should I gain in performance or memory usage? The code should be like that:

    r00 = a00*b00+a01*b10+a02*b20+a03*b30;
    r01 = a00*b01+a01*b11+a02*b21+a03*b31;
    r02 = a00*b02+a01*b12+a02*b22+a03*b32;
    r03 = a00*b03+a01*b13+a02*b23+a03*b33;

    r10 = a10*b00+a11*b10+a12*b20+a13*b30;
    r11 = a10*b01+a11*b11+a12*b21+a13*b31;
    r12 = a10*b02+a11*b12+a12*b22+a13*b32;
    r13 = a10*b03+a11*b13+a12*b23+a13*b33;

    r20 = a20*b00+a21*b10+a22*b20+a23*b30;
    r21 = a20*b01+a21*b11+a22*b21+a23*b31;
    r22 = a20*b02+a21*b12+a22*b22+a23*b32;
    r23 = a20*b03+a21*b13+a22*b23+a23*b33;

    r30 = a30*b00+a31*b10+a32*b20+a33*b30;
    r31 = a30*b01+a31*b11+a32*b21+a33*b31;
    r32 = a30*b02+a31*b12+a32*b22+a33*b32;
    r33 = a30*b03+a31*b13+a32*b23+a33*b33;

Where r00~r33 are 16 float variables where I store the result and later set to my 16 float main fields...The variables a00~a33 and b00~b33 are the factors variables.

So if I use fixed fields instead of a float array, should I gain in performance or memory usage?


texts: Yet another BrainF*** Interpretter in Haskell

texts:
I wrote a BrainF*** interpretter in Haskell. A general review would be helpful and especially, a suggestion with a better way to deal with the IO (IO Memory, IO ()) would be helpful.

import Data.Either
import Data.List
import Data.Char
import System.Environment
import System.IO

type Program = [Instruction]

data Instruction = Lft
            | Rgt
            | Inc
            | Dec
            | Nop
            | Loop Program
            | Out
            | Inp
            deriving Eq

data Memory = Memory [Int] [Int]

emptyMem :: Memory
emptyMem = Memory [] [0]

parse :: String -> Program
parse xs = go xs []
   where
      go :: String -> [Either Char Instruction] -> Program
      go "" is      = reverse $ rights is
      go ('[':xs) is   = go xs ((Left '['):is)
      go (']':xs) is   = go xs ((Right l):l2)
         where
            (l1, (_:l2)) =  span (/= Left '[') is
            l = Loop $ (rights.reverse) l1
      go ('>':xs) is   = go xs (Right Rgt:is)
      go ('<':xs) is   = go xs (Right Lft:is)
      go ('+':xs) is   = go xs (Right Inc:is)
      go ('-':xs) is   = go xs (Right Dec:is)
      go ('.':xs) is   = go xs (Right Out:is)
      go (',':xs) is   = go xs (Right Inp:is)

runInstruction :: Memory -> Instruction -> IO (IO Memory, IO ())
runInstruction mem Nop = return (return mem, return ())
runInstruction (Memory xs (y:[])) Rgt = return (return (Memory (y:xs) [0]), return ())
runInstruction (Memory xs (y:ys)) Rgt = return (return (Memory (y:xs) ys), return ())
runInstruction (Memory (x:xs) ys) Lft = return (return (Memory xs (x:ys)), return ())
runInstruction (Memory [] ys) Lft = return (return (Memory [] (0:ys)), return ())
runInstruction (Memory xs (y:ys)) Inc = return (return (Memory xs ((y+1):ys)), return ())
runInstruction (Memory xs (y:ys)) Dec = return (return (Memory xs ((y-1):ys)), return ())
runInstruction mem@(Memory _ (x:xs)) Out = return (return mem, putChar (chr x))
runInstruction (Memory xs (y:ys)) Inp = return (mem', return ())
                                          where mem' = getChar >>= \z -> return (Memory xs ((ord z):ys))
runInstruction mem@(Memory xs (0:ys)) (Loop _) = return (return mem, return ())
runInstruction mem (Loop prog) = do
                                    (mem1, act') <- runProgram mem prog
                                    mem' <- mem1
                                    (mem'', act'') <- runInstruction mem' (Loop prog)
                                    return (mem'', act' >> act'')

runProgram :: Memory -> Program -> IO (IO Memory, IO ())
runProgram mem [] = return (return mem, return ())
runProgram mem (i:is) = do
                           (mem1, act1) <- runInstruction mem i
                           mem' <- mem1
                           (mem2, act2) <- runProgram mem' is
                           return (mem2, act1 >> act2)

main :: IO ()
main = do
   hSetBuffering stdin NoBuffering
   (fileName:_) <- getArgs
   prog <- readFile fileName
   (mem, act) <- runProgram emptyMem (parse (filter (`elem` "[]+-><.,") prog))
   act


texts:
I decided to train myself in OOP with a simple perfect precision Fraction class.

from __future__ import division
import doctest

class Fraction:
    """
    Implements a Fraction Class with perfect precision
    operations and utility methods. The built-in operators
    are overwritten to provide a more natural interface.
    """
    def __init__(self,num,den):
        if den == 0:
            raise ValueError("Denominator must not be zero.")

        self.num = num
        self.den = den

    @staticmethod
    def greatest_common_divisor(a,b):
        """
        Returns the greatest number 'n' existing such
        that a % n == 0 and b % n == 0.
        This number may be one if 'a' and 'b' are coprimes.

        >>> Fraction.greatest_common_divisor(20,15)
        5
        """
        def common(a,b):
            return [i for i in a if i in b]

        def div(n):
            return [i for i in range(1,n+1) if n % i == 0]

        return max(common(div(a),div(b)))

    @staticmethod
    def invert(fraction):
        """
        Returns a fraction where the numerator is the previous
        denominator and vice-versa.

        >>> Fraction.invert(Fraction(3,5))
        5/3
        """
        return Fraction(fraction.den,fraction.num)

    def from_string(text):
        """
        Generates a Fraction object from a string rapresentation
        of two integers seperated by '/'.

        >>> Fraction.from_string('4/9') + Fraction.from_string('2/18')
        5/9
        """
        return Fraction(*[int(i) for i in text.split('/')])

    def simplify(self):
        """
        Returns an eqivalent but simpler Fraction.

        >>> Fraction.simplify(Fraction(210,20))
        21/2
        """
        fact = self.greatest_common_divisor(self.num,
                                       self.den)
        return Fraction(self.num // fact, self.den // fact)

    def __mul__(self,fraction):
        """
        Fraction multiplication.

        >>> Fraction(4,3) * Fraction(1,20)
        1/15
        """
        return Fraction.simplify(
            Fraction(self.num*fraction.num,
                       self.den*fraction.den))

    def __add__(self,fraction):
        """
        Fraction addition.

        >>> Fraction(4,9) + Fraction(11,7)
        127/63
        """
        common_den = self.greatest_common_divisor(
            self.den,fraction.den)
        num1 = self.num * fraction.den
        num2 = fraction.num * self.den
        return Fraction.simplify(
            Fraction(num1+num2, fraction.den*self.den))

    def __sub__(self,fraction):
        """
        Fraction subtraction.

        >>> Fraction(1,2) - Fraction(1,3)
        1/6
        """
        return self + Fraction(-fraction.num,
                                fraction.den)

    def __truediv__(self,fraction):
        """
        Fraction division.

        >>> Fraction(4,8) / Fraction(9,2)
        1/9
        """
        return self * self.invert(fraction)

    def __repr__(self):
        """
        Returns a printable representation of the fraction
        that can also be fed back into the class via
        'Fraction.from_string'.
        This method is called automatically on printing.

        >>> Fraction(5,8)
        5/8
        >>> Fraction(2,9)
        2/9
        """
        return '{}/{}'.format(self.num, self.den)

def main():
    doctest.testmod()

if __name__ == "__main__":
    main()


texts:
I've written this small class in Python that wraps bound methods but does not prevent the deletion of self.

Do you have any thoughts on my code?
Do you think I handle errors appropriately?
Is it missing anything?
What should be done to make it more robust?
Is the documentation clear enough?

import weakref

class WeakBoundMethod:
    """
    Wrapper around a method bound to a class instance. As opposed to bare
    bound methods, it holds only a weak reference to the `self` object,
    allowing it to be deleted.

    This can be useful when implementing certain kinds of systems that
    manage callback functions, such as an event manager.

    """
    def __init__(self, meth):
        """
        Initializes the class instance. It should be ensured that methods
        passed through the `meth` parameter are always bound methods. Static
        methods and free functions will produce an `AssertionError`.

        """
        assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
               'Object is not a bound method.'

        self._self = weakref.ref(meth.__self__)
        self._func = meth.__func__

    def __call__(self, *args, **kw):
        """
        Calls the bound method and returns whatever object the method returns.
        Any arguments passed to this will also be forwarded to the method.

        In case an exception is raised by the bound method, it will be
        caught and thrown again to the caller of this `WeakBoundMethod` object.

        Calling this on objects that have been collected will result in
        an `AssertionError` being raised.

        """
        assert self.alive(), 'Bound method called on deleted object.'

        try:
            return self._func(self._self(), *args, **kw)
        except Exception, e:
            raise e

    def alive(self):
        """
        Checks whether the `self` object the method is bound to has
        been collected.

        """
        return self._self() is not None


texts: Rhino helper class to support ECMA-262 regular expressions

texts:
This is a sample class using Rhino (1.7R4). I need it because in the context of JSON Schema, regexes should be ECMA 262. One requirement is that it is thread safe, and it is.

But I'm not sure I actually use it correctly. Can you comment?

public final class RhinoHelper
{
    /**
     * JavaScript scriptlet defining functions {@link #regexIsValid}
     * and {@link #regMatch}
     */
    private static final String jsAsString
        = "function regexIsValid(re)"
        + '{'
        + "    try {"
        + "         new RegExp(re);"
        + "         return true;"
        + "    } catch (e) {"
        + "        return false;"
        + "    }"
        + '}'
        + ""
        + "function regMatch(re, input)"
        + '{'
        + "    return new RegExp(re).test(input);"
        + '}';

    /**
     * Script context to use
     */
    private static final Context ctx;

    /**
     * Script scope
     */
    private static final Scriptable sharedScope;

    /**
     * Reference to Javascript function for regex validation
     */
    private static final Function regexIsValid;

    /**
     * Reference to Javascript function for regex matching
     */
    private static final Function regMatch;

    private RhinoHelper()
    {
    }

    static {
        ctx = Context.enter();
        sharedScope = ctx.initStandardObjects();
        ctx.evaluateString(sharedScope, jsAsString, "re", 1, null);
        regexIsValid = (Function) sharedScope.get("regexIsValid", sharedScope);
        regMatch = (Function) sharedScope.get("regMatch", sharedScope);
        ctx.seal(null);
    }

    /**
     * Validate that a regex is correct
     *
     * @param regex the regex to validate
     * @return true if the regex is valid
     */
    public static boolean regexIsValid(final String regex)
    {
        final Context context = Context.enter();
        try {
            final Scriptable scope = context.newObject(sharedScope);
            scope.setPrototype(sharedScope);
            scope.setParentScope(null);
            return (Boolean) regexIsValid.call(context, scope, scope,
                new Object[]{ regex });
        } finally {
            Context.exit();
        }
    }

    /**
     *
Matches an input against a given regex, in the real sense
     * of matching, that is, the regex can match anywhere in the input. Java's
     * {@link java.util.regex} makes the unfortunate mistake to make people
     * believe that matching is done on the whole input... Which is not true.
     *

     *
     *
Also note that the regex MUST have been validated at this point
     * (using {@link #regexIsValid(String)}).

     *
     * @param regex the regex to use
     * @param input the input to match against (and again, see description)
     * @return true if the regex matches the input
     */
    public static boolean regMatch(final String regex, final String input)
    {
        final Context context = Context.enter();
        try {
            final Scriptable scope = context.newObject(sharedScope);
            scope.setPrototype(sharedScope);
            scope.setParentScope(null);
            return (Boolean) regMatch.call(context, scope, scope,
                new Object[]{ regex, input });
        } finally {
            Context.exit();
        }

    }
}


texts: Convert a custom object to a query string

texts:
I wrote an extension method that takes a custom object and converts its properties to a query string for use in a URL. You can specify what properties you want included by using a [QueryString] attribute. For example:

class Thing
{
    [QueryString]
    public int Id {get; set;}
    [QueryString]
    public string Name {get; set;}
    public object MetaData {get; set;}
}

var thing = new Thing { Id = 1, Name = "Test", MetaData = someObj };
thing.ToQueryString(); // outputs `?Id=1&Name=Test

Here's the code for the extension method:

public static string ToQueryString(this object obj)
{

    StringBuilder queryStringBuilder = new StringBuilder("?");

    Type objType = obj.GetType();
    // Get properties marked with `[QueryString]`
    List<PropertyInfo> props = objType.GetProperties()
        .Where(p => Attribute.IsDefined(p, typeof(QueryStringAttribute)))
        .ToList();

    foreach (var prop in props)
    {
        string name = prop.Name;
        var value = prop.GetValue(obj, null);

        if (value != null)
        {
            // Check's if this is the last property, if so, don't add an '&'
            if (props.IndexOf(prop) != (props.Count - 1))
            {
                queryStringBuilder.Append($"{Uri.EscapeDataString(name)}={Uri.EscapeDataString(value.ToString())}&");
            }
            else
            {
                queryStringBuilder.Append($"{Uri.EscapeDataString(name)}={Uri.EscapeDataString(value.ToString())}");
            }
        }
    }

    return queryStringBuilder.ToString();
}

The code works just fine, but it seems a bit messy to me. Specifically, checking if we are on the last property seems a bit messy, because we end up doing the same thing, just nixing one character. Is there a way to make that a little cleaner? Are there any other way's this method could be simplified?


texts: Updating MySQL with shuffled numbers between 1 and 50

texts:
I need to assign a number to each userId.  I think this is too much of a query for updating.  Is it possible to reduce the number of queries, or is it okay?

def newRanking(groupId: String) = {
    DB.withConnection { implicit con =>
      var rank: List[Int] = util.Random.shuffle(List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50))
      var i = 0
      val sql = SQL("SELECT userId FROM `groupInformation` WHERE groupId={groupId} limit 50").on("groupId" -> groupId)
      sql().map { row =>
        SQL("update groupInformation set rank={rank} where groupId={groupId} and userId={userId}").on("groupId" -> groupId, "rank" -> rank(i), "username" -> row[String]("userId")).executeUpdate()
        i += 1
      }.toList
    }
  }


texts:
To try and track down a troublesome AS400 bug, my company wants me to keep track of the order in which files are put into a folder. I spent an hour whipping something up in Go, but I'm still pretty new to Go so I'd like an opinion on a couple points:

Idiomatic Go: how do I make it more "Go"-like?
My method of freezing os.FileInfo objects

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "time"
)

var POLLTIME = 10 * time.Second

type watchinfo struct {
    head     string      // path/to/the/
    fileinfo os.FileInfo // file
    seen     time.Time
}

// freeze the os.FileInfo to be stored in a map[miniFileInfo]bool
type miniFileInfo struct {
    name string
    size int64
}

func watchFolder(dirname string, ch chan<- watchinfo) {
    set := make(map[miniFileInfo]bool)
    for {
        fis, err := ioutil.ReadDir(dirname)
        if err != nil {
            panic("I failed to read " + dirname)
        }
        for _, fi := range fis {
            minifi := miniFileInfo{name: fi.Name(), size: fi.Size()}
            if _, ok := set[minifi]; !ok {
                // fi doesn't exist in the set, add it
                set[minifi] = true
                now := time.Now()
                // and send its watchinfo to the channel
                ch <- watchinfo{head: dirname, fileinfo: fi, seen: now}
            }
        }
        time.Sleep(POLLTIME) // let's not spam the server
    }
}

// WatchFolders creates a goroutine for each folder to watch
func WatchFolders(dirnames []string, outch chan<- string) {
    inch := make(chan watchinfo)
    for _, dir := range dirnames {
        go watchFolder(dir, inch)
    }
    for watch := range inch {
        outch <- fmt.Sprintf("%s\\%s with modified time %s", watch.head, watch.fileinfo.Name(), watch.fileinfo.ModTime().Format("Jan 2 15:04:05"))
    }
}

func main() {
    flag.Parse()
    ch := make(chan string)
    go WatchFolders(flag.Args(), ch)
    for seenat := range ch {
        log.Println(seenat)
    }
}

My original problem seemed to stem from using os.FileInfo objects directly. Every polling period would show all the files as "new." I'm not sure how Go handles identity in maps (in Python I could implement __hash__ to tell it how to behave) but as long as the file has the same name and the same size in bytes, I don't mind assuming it's the same file.

I overengineered a bit to allow for future use, allowing for multiple directories (I only need one) and keeping the first seen time in the struct (I can just use the log time for now).


texts: A shorter way of Enablling/Disabling a text box from RadioButton selections

texts:
Three radio buttons and a text box, grouped in one group box... Just when I select one of those radio button the text box gets enabled, for the other two radio buttons it should be disabled. Here is the code that comes to mind at first, but it looks ugly to me becuase I have copy pasted the same AllowMissingData() method to Change evnt of each radio button. I was wondering if there is a better way of writing it:

private void RequiredRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void AllowBlankRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void SuppressRadioButton_CheckedChanged(object sender, EventArgs e)
{
        AllowMissingData();
}

private void AllowMissingData()
{
    if (AllowBlankRadioButton.Checked)
    {
        MissingDataValueTextBox.Enabled = true;
    }
    else
    {
        MissingDataValueTextBox.Text = System.String.Empty;
        MissingDataValueTextBox.Enabled = false;
    }
}


texts:
I built a class which uses an HttpClient instance for downloading the content of a page. This is working pretty well but I'm not really satisfied about my implementation of redirect.

In fact, I handle the redirect manually as you can see:

/// <summary>
/// Web request handler
/// </summary>
public class NetworkHelper
{
    /// <summary>
    /// Store the url.
    /// </summary>
    private static Uri _storedUrl = null;

    /// <summary>
    /// Store the html data.
    /// </summary>
    private static string _storedData = "";

    public static string GetHtml(Uri url)
    {
        if (url == _storedUrl)
            return _storedData;
        else
            _storedUrl = url;

        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

        try
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            HttpClient httpClient = new HttpClient(handler);

            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = url,
                Method = HttpMethod.Get
            };

            HttpResponseMessage response = httpClient.SendAsync(request).Result;

            int statusCode = (int)response.StatusCode;

            if (statusCode >= 300 && statusCode <= 399)
            {
                Uri redirectUri = response.Headers.Location;

                if (!redirectUri.IsAbsoluteUri)
                {
                    redirectUri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority) + redirectUri);
                }

                return GetHtml(redirectUri);
            }

            using (WebClient wClient = new WebClient())
            {
                wClient.Encoding = System.Text.Encoding.UTF8;
                _storedData = wClient.DownloadString(url);
            }

            return _storedData;
        }
        catch (WebException)
        {
            throw;
        }
    }
}

How can I improve my implementation for handling the redirect?


texts:
The following script reads a set of SIDs inside firewall rules and uses them to set ACL rules in a folder.

The question is: Is this syntax ok or is there better ways to write this script, considering powershell syntax features? (by the way, this code works)

param([Parameter(Mandatory)]$foldername)

$result=""

(Get-NetFirewallRule | Where-Object { ($_.Direction -eq "Outbound") -and ($_.DisplayName -like "*appcontainer*")}) |
         %{ ($_ | Get-NetFirewallApplicationFilter) |
        %{  $acl = Get-Acl $foldername
            $sec= New-Object System.Security.Principal.SecurityIdentifier($_.Package)
            $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($sec,"FullControl",(1 -bor 2),0, "Allow")
            $acl.SetAccessRule($AccessRule)
            $acl | Set-Acl $foldername
          } }


texts: Converting image size from Maybe (Int, Int) to (Float, Float)

texts:
I have a function that returns size of an image IO (Maybe (Int, Int))
It would be nice to convert it to float tuple beautifully.

I am sure there must be a better way than what I currently have:

data Vec2D = Vec2D Float Float

getImageSize :: FilePath -> IO (Maybe (Int, Int))
getImageSize path = do
    img <- readImage path
    case img of
        Left _ -> return Nothing
        Right img' -> return (go img')
    where
        go :: DynamicImage -> Maybe (Int, Int)
        go (ImageRGB8 (Image w h _)) = Just (w, h)
        go (ImageRGBA8 (Image w h _)) = Just (w, h)
        go _ = Nothing

getImageSizeVec :: FilePath -> IO Vec2D
getImageSizeVec path = do
    res <- getImageSize path
    let dims = fromMaybe (0, 0) res
    return $ Vec2D (fromIntegral (fst dims)) (fromIntegral (snd dims))


texts: Two permutation iterators for classes in Python with and without a generator

texts:
I am just testing out a couple of small classes for learning purposes. Here is my current working code:

class Permutation:
     '''An int list a permutation if starting at any index, one can reach every other index by
     repeated index accesses. The list [4, 0, 3, 1, 2] is a permutation: for example index 0
     stores a 4; index 4 stores a 2; index 2 stores a 3; index 3 stores a 1; index 1 stores a 0,
     bringing us back to that starting position after visiting every index.'''
     def __init__(self, p, start):
         self.p = p
         self.start = start

     def __iter__(self):
         class P_iter:
             def __init__(self, p, start):
                 self.p = p
                 self.start = start
                 self.curr = start
                 self.stahp = False

             def __next__(self):
                 if not self.stahp:
                     current = self.curr
                     self.curr = self.p[self.curr]
                     self.stahp = self.curr == self.start
                     return current
                  else:
                      raise StopIteration
         return P_iter(self.p, self.start)

class Permutation2:
     '''similar to the description above, but its __iter__ method should be implemented by a
     generator (not a P_iter nested class)'''
     def __init__(self,p,start):
         self.p = p
         self.start = start

     def __iter__(self):
         curr = self.start
         stahp = False
         while not stahp:
             yield curr
             curr = self.p[curr]
             stahp = curr == self.start
         else:
             raise StopIteration

I'm looking to clean the code a bit and maybe make it simpler. The code is fully working currently and generates the desired output.


texts:
This is a simple console menu that just holds a main menu and a few menu "buttons" (numbers and titles which the user has to enter for the button to do its action). It does not need submenus or more complicated input handling.

I went with an object-oriented approach and defined three classes: Menu, Button, and Controller. The Menu initialises with a name and a list of menu buttons.

class Menu(object):

    """Base class for the menu"""

    def __init__(self, name, buttons):
        # Initialize values
        self.name = name
        self.buttons = buttons

    def display(self):

        """Displaying the menu alongside the navigation elements"""

        # Display menu name
        print self.name

        # Display menu buttons
        for button in self.buttons:
            print "   ", button.nav, button.name

        # Wait for user input
        self.userInput()

    def userInput(self):

        """Method to check and act upon user's input"""

        # This holds the amount of errors for the
        # navigation element to input comparison.
        errSel = 0
        inputSel = raw_input("Enter selection> ")

        for button in self.buttons:
            # If input equals to button's navigation element
            if inputSel == str(button.nav):
                # Do the button's function
                button.do()
            # If input != navigation element
            else:
                # Increase "error on selection" by one, for
                # counting the errors and checking their
                # amount against the total number of
                # buttons. If greater to or equal that means
                # no elements were selected.
                # In that case show error and try again
                errSel += 1

        # No usable input, try again
        if errSel >= len(self.buttons):
            print "Error on selection; try again."

The Button class is accepting a name, a function and a navigation element (the number you have to press for it to do the button's action):

class Button(object):

    """Base class for menu buttons"""

    def __init__(self, name, func, nav):
        # Initialize values
        self.name = name
        # Function associated with button
        self.func = func
        # Navigation element; number which user has to enter to do button action
        self.nav = nav

    def do(self):
        # Do the button's function
        self.func()

Finally, the Controller. Did I do it the right way? I mean it works but having that while loop cycling with only the raw_input() function stopping it from spamming infinite messages - is that correct or should I write something that prevents the while loop while a menu was already displayed and is awaiting user input?

class Controller(object):
    def __init__(self, menu):
        # Initialize values
        self.menu = menu
        # Start menu displaying / cycling
        self.cycle()

    def cycle(self):

        """Method for displaying / cycling through the menus"""

        while True:
            # Display menu and redisplay after button's function completes
            # Is this right? Will this loop correctly and never interfere
            # with raw_input()?
            self.menu.display()

Finally, the code that puts it all together:

import sys

def main():
    mainMenuButtonName = Button("Show name", showName, 1)
    mainMenuButtonVersion = Button("Show version", showVersion, 2)
    mainMenuButtonAbout = Button("Show about", showAbout, 3)
    mainMenuButtonQuit = Button("Quit", quit, 0)

    mainMenuButtons = [mainMenuButtonName, mainMenuButtonVersion, mainMenuButtonAbout, mainMenuButtonQuit]

    mainMenu = Menu("Main menu", mainMenuButtons)
    controller = Controller(mainMenu)

    controller.cycle()

def showName():
    print "My name is..."

def showVersion():
    print "My version is 0.1"

def showAbout():
    print "I am a demo app for testing menus"

def quit():
    sys.exit(0)

if __name__ == "__main__":
    main()


texts: Python 3 function to rotate an image 90°

texts:
A coding challenge that rotates an image 90 degrees counterclockwise. The image is represented as an array matrix. I believe the time complexity is O(n2), but I'd like to know for sure, as well as any other feedback.

def rotate_image(img):
    rotated_image = [[] for x in range(len(img))]
    for i in range(len(img)):
        for j in range(len(img[i])):
          rotated_image[len(img) - j - 1].append(img[i][j])
    return rotated_image

Example usage:

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

rotated_img = rotate_image(image)
for i in rotated_img:
    print(i)

Outputs:

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


texts:
I would like to write a python or c++ function to print numbers like the following examples (with n as input parameter):

When n = 3, print:

1 2 3
8 0 4
7 6 5

When n = 4, print:

4  5  6  7
15 0  1  8
14 3  2  9
13 12 11 10

I have an answer in the following code block, but it is not quite elegant. Does anyone have a better solution?

def print_matrix(n):
  l = [i for i in range(0,n*n)]

  start = (n-1)/2
  end = n-1-start
  count = 0
  if start ==end:
    l [start+ n*end] = count
    start -= 1
    count +=1

  while start >=0:
        end = n - start
        for i in range(start, end-1):
                x= i
                y= start
                print y*n +x
                l[y*n +x] = count
                count +=1
        for i in range(start, end-1):
                x = end-1
                y = i
                print y*n +x
                l[y*n +x] = count
                count +=1
        for i in range(end-1,start,-1):
                x= i
                y= end-1
                print y*n +x
                l[y*n +x] = count
                count +=1
        for i in range(end-1, start,-1):
                x = start
                y = i
                print y*n +x
                l[y*n +x] = count
                count +=1
        start -=1

  print l


texts:
I'm looking for someone to tell me how I could refactor/change/improve my JS, I'm still learning and really want my code to be the best it can be for when it comes time for me getting a job in the industry. Would really appreciate a professional's help.

It's just a fairly simple todo list...

Here is the JS

let ul = document.getElementById('list');
let input = document.querySelector("input");
let toggle = document.querySelector('.fa-plus');

toggle.addEventListener('click', function() {
    toggle.classList.toggle('rotated');
    input.classList.toggle('hide');
});

input.addEventListener('keydown', function(e) {
    if (e.keyCode === 13 && input.value !== '') {
        addTodo();
    };
});

let deleted = () => {
    let spans = document.querySelectorAll('span');
    for (let span of spans) {
        span.addEventListener('click', function() {
            this.parentNode.parentNode.removeChild(this.parentNode);
        });
    };
};

let addTodo = () => {
    let listItem = document.createElement('li');
    listItem.innerHTML = ' ' + input.value;
    listItem.addEventListener("click", function() {
        this.classList.toggle("lineThrough");
    });
    ul.appendChild(listItem);
    deleted();
    input.value = '';
};

Here is the link to the project on codepen - https://codepen.io/ruaridouglas/pen/mdeaaKV


texts: A Processing sketch to generate and draw the Mandelbrot and Julia sets

texts:
I have used my limited knowledge of processing and made a sketch to generate the Mandelbrot set and various Julia sets. I've tried to make it efficient as possible. It's also interactive, and keyPressed() should explain that sufficiently.

Here is the code:

int mi = 255;
float r = 0.5, a = 0;
float[] bbox = new float[]{-0.5, 0, 2};
float[] c = new float[]{-0.8, 0.15};
boolean rot = false, mode = true;

void setup() {
  size(720, 720);
  display();
}

void draw() {
  if (rot) {c[0] = r*cos(a*PI); c[1] = r*sin(a*PI); a += 0.01; r += 0.001; display();}
}

void display() {
  loadPixels();
  float q, za, zb, zas, zbs, ta;
  int i = 0, x, y;
  for (x = 0; x < width; x++) {
    for (y = 0; y < width; y++) {
      za = map(x, 0, width, bbox[0]-bbox[2], bbox[0]+bbox[2]);
      zb = map(y, 0, width, bbox[1]-bbox[2], bbox[1]+bbox[2]);
      q = pow((za-0.25),2)+zb*zb;
      if (mode) {c[0] = za; c[1] = zb;}
      if (!mode || q*(q+(za-1/4)) >= zb*zb/4) {
        zas = za*za; zbs = zb*zb;
        for (i = 0; i < mi; i++) {
          ta = zas-zbs+c[0];
          zb = 2*za*zb+c[1];
          za = ta;
          zas = za*za; zbs = zb*zb;
          if (zas+zbs > 4) {
            break;
          }
        }
      }
      pixels[x+y*width] = color(map(sqrt(i%mi), 0, sqrt(mi), 0, 255));
    }
  }
  updatePixels();
}

void keyPressed() {
  //Zoom window
  if (key == 'e') {bbox[2] /= 2; display();} //Zoom in
  if (key == 'q') {bbox[2] *= 2; display();} //Zoom out

  //Pan window
  if (key == 'w') {bbox[1] -= bbox[2]/5; display();} //Pan up
  if (key == 'a') {bbox[0] -= bbox[2]/5; display();} //Pan left
  if (key == 's') {bbox[1] += bbox[2]/5; display();} //Pan down
  if (key == 'd') {bbox[0] += bbox[2]/5; display();} //Pan right

  //Resetting
  if (key == 'c') {c = new float[]{-0.8, 0.15}; display();} //Reset c value
  if (key == 'x') {if (mode) {bbox = new float[]{-0.5, 0, 2};} else {bbox = new float[]{0, 0, 2};}; display();} //Reset view

  //Changing mode
  if (key == 'z') {mode = !mode; if (mode) {bbox = new float[]{-0.5, 0, 2};} else {bbox = new float[]{0, 0, 2};}; display();} //Toggle mandelbrot/julia set mode

  //Animations
  if (key == 'r' && !mode) {rot = !rot; display();} //Toggle julia set rotating animation

  //Offset c value in f(z) = z^2 + c
  if (key == 't') {c[0] -= 0.01; display();} //Offset up
  if (key == 'f') {c[1] -= 0.01; display();} //Offset left
  if (key == 'g') {c[0] += 0.01; display();} //Offset down
  if (key == 'h') {c[1] += 0.01; display();} //Offset right

  // Change iteration number
  if (key == 'v') {mi = constrain(mi-8, 7, 1023); display();} //Decrease iteration number
  if (key == 'b') {mi = constrain(mi+8, 7, 1023); display();} //Increase iteration number
}

The reason that there is so much redundancy of display(); is that if I put it in the draw loop, it has a tendency to miss key presses. Also, i apologize for the cryptic variable names, however, most should be self explanatory.


texts: Reading source code and extracting json from a url

texts:
I made a program to read the source code from a url. To reach this url I need to specify a token. After read the source code, I extract a url in json format, andIi redirect my domain to this url. It's not relevant to what I'm asking, but I want explain what I'm doing.

As you can see, on my domain http://localhost/test, I have a query string called token that is used to read the source code of a different domain. After this I redirect to a page.

I defined the domain which I will read the source code but I don't know if someone could pass a value to the $_GET['token'] in a way that this will go to a different domain. I'm reading the source code from a url and using the result on my website, so I don't know if someone could do some kind of attack to my server. I'm not sure how these kind of attacks works, and I felt that I should ask someone that has more knowledge than I.

What do you think about my code?

php:

 //i use this condition to make sure that nobody can access the url directly,
 //and later make sure that the request is from my domain
    if(!empty($_SERVER['HTTP_REFERER'])){
        //if $_GET[] is empty then $.. is = NULL, else $.. is = $_GET[]
        $source = (empty($_GET['source']) ? NULL : $_GET['source']);
        $token = (empty($_GET['token']) ? NULL : $_GET['token']);

        if(!empty($source) && !empty($token)){
            if($source == 'player'){
                //check if the request is from the same domain
                if(preg_match('/^http:\/\/localhost\/test/', $_SERVER['HTTP_REFERER'])){
                    //inside this if() i read the source
                    //code from this url bellow
                    $urlPost = 'https://www.player.com/?token='.$token;
                    $url = file_get_contents($urlPost);
                    preg_match('/CONFIG = (.*)/', $url, $matches);

                    $jsn =  json_decode($matches[1]);
                    $streams = $jsn->streams;

                    foreach($streams as $i){
                        //this variable will be used to redirect the src
                        //iframe to a url that contains a video
                        $vdUrl = $i->url;
                    }
                    //redirect to the url that i got from the source code
                    die(header('location:'.$vdUrl));
                }else{
                    //if the request is not from the same domain then
                    //redirect to 404 Not Found
                    die(header('HTTP/1.1 404 Not Found'));
                }
            }else{
                die(header('HTTP/1.1 404 Not Found'));
            }
        }

    }

html:

<iframe src="http://localhost/test/?source=player&token=145215d1ww"></iframe>


texts: Convert Persian digits to English numbers

texts:
I use the following code to convert ۱۲۳۴۵ to 12345, effectively transliterating the persian numbers into latin numbers:

String.prototype.toEnglishDigits = function () {
        var num_dic = {
            '۰': '0',
            '۱': '1',
            '۲': '2',
            '۳': '3',
            '۴': '4',
            '۵': '5',
            '۶': '6',
            '۷': '7',
            '۸': '8',
            '۹': '9',
        }

        return parseInt(this.replace(/[۰-۹]/g, function (w) {
            return num_dic[w]
        }));
    }

console.log('۱۲۳۴۵'.toEnglishDigits());


texts: Showing or hiding groups of three text fields

texts:
        <input id="input0_0" class="input" type="text" />

        <input id="input0_1" class="input" type="text" />

        <input id="input0_2" class="input" type="text" />

        <input id="input1_0" class="input" type="text" />

        <input id="input1_1" class="input" type="text" />

        <input id="input1_2" class="input" type="text" />

        <input id="input2_0" class="input" type="text" />

        <input id="input2_1" class="input" type="text" />

        <input id="input2_2" class="input" type="text" />

add-more remove-last</>

js part that we need to deal with:

$("#inputRow1").hide();
$("#inputRow2").hide();
$("#remove-last").hide();

$("#add-more").click(function(){

    //count how many *direct children* elements are hidden.
    var hiddenElements = $('#members >:hidden').length;

    $("#remove-last").show();

    if (hiddenElements === 2) {
        $("#inputRow1").show();
    } else if(hiddenElements === 1) {
        $("#inputRow2").show();
        $(this).hide();
    }
});

$("#remove-last").click(function(){

    //count how many *direct children* elements are hidden.
    var hiddenElements = $('#members >:hidden').length;
    $("#add-more").show();

    if (hiddenElements === 0) {
        $("#inputRow"+2).hide();
    } else if (hiddenElements === 1) {
         $("#inputRow"+hiddenElements).hide();
        $(this).hide();
    }

});

Working example:
http://jsfiddle.net/URkuW/


texts: Hooking up active record model with external api in rails app

texts:
In my rails application, I have 2 different types of active record user, for e.g. User1 has first_name, email etc and User2 also has these attributes but for user 2 we get the data from an external API, so when creating the invoices I am passing the user model to the invoice, and I am thinking of doing something like this for User2
class User2
  def first_name
    if persisted?
      data['firstName']
    end
  end

  def email
    if persisted?
      data['email']
    end
  end

  private
  def data
    @__data ||= ExternalUserInfo.new(external_id).call
  end
end

The ExternalUserInfo client will make the call to the external API and return the response as such
{
  firstName: "John", email: "john@example.com"
}

The problem with this approach is that whenever I will need to write a spec which needs to create this user, then I will need to wrap that test around VCR cassette or stub the external request. So I wanted to review what could be a potential solution to avoid this or if this design even make sense at all


texts: Making equal-sized tabs to fill the full width of a box

texts:
How would you simplify the following block of jQuery code?

I use this in a tab-box to size the tabs to style the tabs to the full width of the box no matter if it's 2 or 10 tabs...

It works perfectly, just interested if there's a better/shorter way to achieve the goal.

$(document).ready(function() {
  $('ul.tabs-list').each(function () {
    if ($(this).children().length == 2)
  $(this).addClass("two");
    if ($(this).children().length == 3)
  $(this).addClass("three");
    if ($(this).children().length == 4)
  $(this).addClass("four");
    if ($(this).children().length == 5)
  $(this).addClass("five");
    if ($(this).children().length == 6)
  $(this).addClass("six");
    if ($(this).children().length == 7)
  $(this).addClass("seven");
    if ($(this).children().length == 8)
  $(this).addClass("eight");
    if ($(this).children().length == 9)
  $(this).addClass("nine");
    if ($(this).children().length == 10)
  $(this).addClass("ten");
  });
});


texts: Calculating shortest possible route between two given nodes

texts:
I recently came across this problem:

  Heroes in Indian movies are capable of superhuman feats. For example,
  they can jump between buildings, jump onto and from running trains,
  catch bullets with their hands and teeth and so on. A perceptive
  follower of such movies would have noticed that there are limits to
  what even the superheroes can do. For example, if the hero could
  directly jump to his ultimate destination, that would reduce the
  action sequence to nothing and thus make the movie quite boring. So he
  typically labours through a series of superhuman steps to reach his
  ultimate destination.

  In this problem, our hero has to save his wife/mother/child/dog/...
  held captive by the nasty villain on the top floor of a tall building
  in the centre of Bombay/Bangkok/Kuala Lumpur/.... Our hero is on top
  of a (different) building. In order to make the action "interesting"
  the director has decided that the hero can only jump between buildings
  that are "close" to each other. The director decides which pairs of
  buildings are close enough and which are not.

  Given the list of buildings, the identity of the building where the
  hero begins his search, the identity of the building where the captive
  (wife/mother/child/dog...) is held, and the set of pairs of buildings
  that the hero can jump across, your aim is determine whether it is
  possible for the hero to reach the captive. And, if he can reach the
  captive he would like to do so with minimum number of jumps.

  Here is an example. There are 5 buildings, numbered 1,2,...,5, the
  hero stands on building 1 and the captive is on building 4. The
  director has decided that buildings 1 and 3, 2 and 3, 1 and 2, 3 and 5
  and 4 and 5 are close enough for the hero to jump across. The hero can
  save the captive by jumping from 1 to 3 and then from 3 to 5 and
  finally from 5 to 4. (Note that if i and j are close then the hero can
  jump from i to j as well as from j to i.). In this example, the hero
  could have also reached 4 by jumping from 1 to 2, 2 to 3, 3 to 5 and
  finally from 5 to 4. The first route uses 3 jumps while the second one
  uses 4 jumps. You can verify that 3 jumps is the best possible.

  If the director decides that the only pairs of buildings that are
  close enough are 1 and 3, 1 and 2 and 4 and 5, then the hero would not
  be able to reach building 4 to save the captive.

That was breadth first search problem, which is easy to figure out.

#include <iostream>
#include <vector>
#include <queue>

int main (int argc, char const* argv[])
{
    int n, m;
    std::cin >> n >> m;
    std::vector<std::vector<int> >table(n,std::vector<int>(n));
    while(m--){
        int a ,b;
        std::cin >> a >> b;
        table[a-1][b-1] = 1;
        table[b-1][a-1] = 1;
    }
    int start , end;
    std::cin >> start >> end;
    start--;end--;
    std::vector<bool>visited(n);
    std::queue<int>queue_;
    visited[start] = true;
    queue_.push(start);
    std::vector<int>minDist(n);
    std::fill(minDist.begin(),minDist.end(),31000);
    minDist[start] = 0;
    while(!queue_.empty()){
        int s = queue_.front();
        queue_.pop();
        for(int i=0;i<n;i++){
            if(!visited[i] && table[s][i] == 1){
                visited[i] = true;
                minDist[i] = std::min(minDist[i],minDist[s]+1);
                queue_.push(i);
            }
        }
    }
    std::cout <<minDist[end]<< std::endl;
    return 0;
}

The code passed 9 test cases out of the 10 and got stuck at the 10th test case, which was really big. It didn't even run on my own machine.

Here is the test case of whooping 5 MBs: 10th test case in the archive

Can someone lend me some tips for optimizing the code for such a big input?


texts: Crawling pages to obtain .htm and .txt files from sec.gov

texts:
I am pretty much a python newbie and was looking at this question on StackOverflow.

Whereas the OP was interested in downloading the .htm |.txt files, I was simply interested in using Beautiful Soup and requests to gather all the links, to those files, into one structure. Ideally, it would have been a single list but I have a list of lists.

The process is:

Start with the landing page and grab all the links in the leftmost column which has the header CIK.

CIK column sample with single link selected on right

Navigate to each of those links and grab the document button links in the Format column:

Format column sample with single link selected on right

Navigate to each of those document button links and grab the document links in the Document Format Files section, if the file mask is .htm | .txt.

Document Format Files sample with single link selected on right

Print the list of links (which is a list of lists)

Other info:

I use CSS selectors throughout to target the links.

What particularly concerns me, given my limited Python experience, is the fact I have a list of lists rather than a single list, whether my re-use of variable names is confusing and potentially bug prone, and I guess whether what I am doing is particularly pythonic and efficient.

In languages I am more familiar with, I might attempt to create a class and provide the class with methods; which in effect are my current functions.

Set-up info:

The version of the jupyter notebook server is: 5.5.0

The server is running on this version of Python:

Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)]

Python code:

from bs4 import BeautifulSoup
import requests
from urllib.parse import urljoin

base = 'https://www.sec.gov'
start_urls = ["https://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK=&filenum=&State=&Country=&SIC=2834&owner=exclude&Find=Find+Companies&action=getcompany"]

def makeSoup(url):
    res = requests.get(url)
    soup = BeautifulSoup(res.content, "lxml")
    return soup

def getLinks(pattern):
    links = soup.select(pattern)
    return links

def getFullLink(links):
    outputLinks = []
    for link in links:
        outputLinks.append(urljoin(base, link.get("href")))
    return outputLinks

soup = makeSoup(start_urls[0])
links = getLinks("#seriesDiv [href*='&CIK']")
firstLinks = getFullLink(links)

penultimateLinks = []

for link in firstLinks:
    soup = makeSoup(link)
    links = getLinks('[id=documentsbutton]')
    nextLinks = getFullLink(links)
    penultimateLinks.append(nextLinks)

finalLinks = []

for link in penultimateLinks:
    for nextLink in link:
        soup = makeSoup(nextLink)
        links = getLinks("[summary='Document Format Files'] td:nth-of-type(3) [href$='.htm'],td:nth-of-type(3) [href$='.txt']")
        nextLinks = getFullLink(links)
        finalLinks.append(nextLinks)

print(finalLinks)


texts:
I am wondering what is the best way to map array values to properties in a class. Consider the following sample array describing information for an airport:

        [0] "6523"  string
        [1] "00A"   string
        [2] "heliport"  string
        [3] "Total Rf Heliport" string
        [4] "40.07080078125"    string
        [5] "-74.9336013793945" string
        [6] "11"    string
        [7] "NA"    string
        [8] "US"    string
        [9] "US-PA" string
        [10]    "Bensalem"  string
        [11]    "no"    string
        [12]    "00A"   string
        [13]    ""  string
        [14]    "00A"   string
        [15]    ""  string
        [16]    ""  string
        [17]    ""  string

I have the following class:

    public class Airport
    {
        public Airport(string[] data)
        {
            Action<string>[] PropertyMappings =
            {
                x=>this.Id=x,
                x=>this.Ident=x,
                x=>this.Type=x,
                x=>this.Name=x,
                x=>this.Latitude=x,
                x=>this.Longtitude=x,
                x=>this.Elevation=x,
                x=>this.Continent=x,
                x=>this.CountryIso=x,
                x=>this.RegionIso=x,
                x=>this.Municipality=x,
                x=>this.ScheduledService=x,
                x=>this.GPSCode=x,
                x=>this.DataCode=x,
                x=>this.LocalCode=x,
                x=>this.HomeLink=x,
                x=>this.WikipediaLink=x,
                x=>this.Keywords=x
            };
            for(int i=0;i<data.Count();i++)
            {
                PropertyMappings[i](data[i]);
            }
        }
        public string Id { get; set; }
        public string Ident { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
        public string Latitude { get; set; }
        public string Longtitude { get; set; }
        public string Elevation { get; set; }
        public string Continent { get; set; }
        public string CountryIso { get; set; }
        public string RegionIso { get; set; }
        public string Municipality { get; set; }
        public string ScheduledService { get; set; }
        public string GPSCode { get; set; }
        public string DataCode { get; set; }
        public string LocalCode { get; set; }
        public string HomeLink { get; set; }
        public string WikipediaLink { get; set; }
        public string Keywords { get; set; }
    }
}

And I call it like this:

Airport airport = new Airport(data);

Do you think this is a good way to do the mapping from the elements of the array to the properties of the class or is there a better way. I couldn't really find anything online.
Obviously I haven't done all of the safety checks etc. This is just a small experiment.


texts: Merging, sorting and limit Map streams using Java 8

texts:
I have two maps map1 and map2 . I want to merge both maps and then sort in desc order and get top 5. In case of duplicate keys in merge I need to sum the values. I have the following code that works:

Map<String, Long> topFive = (Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum)))
        .entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .limit(5).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (v1,v2) -> v1,
            LinkedHashMap::new));

But I would like to know if there is a better solution.