texts: Achieving thread safety in a payment service library

texts:
I wrote this code a while ago, which is an excerpt of a payment service library:

# recover a transaction details from the Wirecard API
module Wirecard
  module Elastic
    class Request
      class Transaction < Base

        attr_reader :merchant_id, :transaction_id, :payment_method

        def initialize(merchant_id, transaction_id, payment_method)
          @merchant_id    = merchant_id
          @transaction_id = transaction_id
          @payment_method = payment_method
        end

        # calling request
        def request
          @request ||= Request.new(query_uri: query, payment_method: payment_method).dispatch!
        end

        # processed response
        def response
          @response ||= Response.new(request: request, action: :transaction).dispatch!
        end

        # address we want to access on the API
        def query
          @query ||= "merchants/#{merchant_id}/payments/#{transaction_id}"
        end

      end
    end
  end
end

One of my methodologies to abstract methods into new subclasses and compose is to spot private methods which are achieving the same goal, and put them away into a new class. This is especially useful to respect the famous rules of Sandi Metz.

When it doesn't seem the class will ever need to be interchangeable, I don't use the dependency inversion principle. That would be the case with a XML scrapper because it sounds like we could extend it to an alternative JSON scrapper, for instance.

All that to say, in some cases I basically put the new subclass into a method and memoize it, then instantiate it only when needed, like in my example.

First, is this a fine way to code in your opinion? I've read so many different code styles, I'm not sure about anything at this point.

Now I'm wondering, is it thread-safe to go up and down like this? I'm quite new with this concept of thread safety and I've read a lot about atomization, making things stateless, which looks a lot like a functional way to code to me.

After all, I instantiate a new class, but what I pass to it in my example comes from a few instance variables I set at initialization of the parent class, the I/O should always be the same, right?

If it isn't good, what should I change in my example?


texts: Is the way I use my pattern good enough?

texts:
For quite a long, I have been using a pattern to make my life a bit easier. please help me evaluate how good or bad my approach is and how can I improve it.

I have a static class for just returning values:

    class ReturnValue {

            const STATUS_SUCCESS = "SUCCESS";
            const STATUS_FAIL = "FAILED";

            public static function doReturn($funtionName, $status = NULL, $value = NULL, $message = NULL) {
                if ($status == NULL) {
                    $status = self::STATUS_FAIL;
                }
                $return = array(
                action => $funtionName,
                status => $status,
                message => $message,
                returnValue => $value
            );
            return (object) $return;
        }

    }

usage example:

        function add($val, $val2) {
            if (empty($val)) {
                return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_FAIL, '', 'Val must be a number');
            }
            if (empty($val2)) {
                return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_FAIL, '', 'Val2 must be a number');
            }
            $sum = $val + $val2;
            return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_SUCCESS, $sum, "$val + $val2 = $sum");
    }

To get the returned value:

    $add = add(1, 2);
    print $add->returnValue; // Gives 1 + 2 = 3
    print $add->message; // Gives  "Val2 must be a number"
    print $add->status; // FAILED

    //OR to make an error
    $add = add(1, ''); // an empty param is passed
    print $add->returnValue;//Gives  3
    print $add->message; // Gives   "1 + 2 = 3"
    print $add->status; // SUCCESS


texts: Parsing indented text and inserting its data into a tree

texts:
My goal is to parse indented text in the style of python and YAML.

This only find the parent of each line.

This bit of code seems to do the trick, but I'm not really satisfied and I wanted to know if you would do this another way.

raw = """animal
    carnivorous
        tiger
        lion
    vegetarian
        cow
        sheep
plant
    algea
    tree
        leaf
        pine
    fungus
        good
        bad
            evil
            mean
    cactus
        big
        small"""

lines = raw.split('\n')
indents = [(0,0,'root')]
for a in raw.split('\n'):
    indent = 0
    while a[indent] == ' ': indent+=1
    if indent % 4:
        print("not multiple of 4")
        break
    indents.append((len(indents), int(indent/4)+1,a.replace('  ','')))
for a in indents: print(a)

stack=[indents[0]]
entries =[indents[0]]

prev_indent = 0
for item in indents[1:]:
    print("#########################")
    id, indent, name = item
    diff = indent - prev_indent
    print(item)
    print("diff",diff, [a[2] for a in stack])

    if diff>0:
        entries.append(item+(stack[-1][2],))
    elif diff<0:
        # entries.append(item+(stack[-diff][2],))
        count = -diff
        while count>-1: stack.pop();count-=1
        entries.append(item+(stack[-1][2],))
    elif diff==0:
        stack.pop()
        entries.append(item+(stack[-1][2],))
    stack.append(item)
    prev_indent = entries[-1][1]

    print("result", entries[-1])
print("########################")

for a in entries:
    if len (a) == 3: continue
    ident, level, name, parent = a
    print(level*' '*4, name, '(', parent, ')')

This results in this (the name in parenthesis is the parent):

animal ( root )
    carnivorous ( animal )
        tiger ( carnivorous )
        lion ( carnivorous )
    vegetarian ( animal )
        cow ( vegetarian )
        sheep ( vegetarian )
plant ( root )
    algea ( plant )
    tree ( plant )
        leaf ( tree )
        pine ( tree )
    fungus ( plant )
        good ( fungus )
        bad ( fungus )
            evil ( bad )
            mean ( bad )
    cactus ( plant )
        big ( cactus )
        small ( cactus )


texts:
This is my first code. I would really appreciate a critique for it, if anyone can spare the time.

def wedcost(hours):

    print " "

    try:
        hours = int(hours)
    except ValueError:
        print "Invalid input"
        new_hours = raw_input("Please use only numeric characters. ")
        hours = int(new_hours)
        print " "

    tcost = hours * 75 # $75/hr for two shooters
    if hours < 4:
        tcost = 250 # price starts at a fixed $250 from 1 to 3 hours
    if hours >= 6:
        tcost = hours * 100 # I don't like long shifts

    print "The total cost of our services will be $" + str(tcost) + "."

    print " "

    def recalc(answer): # this second function is where I had the most trouble

        outcome = 0 # only method I could get to work properly
        if answer.startswith('y' or 'Y'):
            print " "
            outcome += 1
            wedcost(raw_input("How long will we be on location? "))
        if answer.startswith('n' or 'N'):
            print " "
            print "Have a nice day :)"
            outcome += 1
        if outcome == 0:
            print "Invalid input"
            recalc(raw_input("Would you like to recalculate? ('Yes' or 'No') "))

        # I had previously tried checking 'answer' to items in lists

    recalc(raw_input("Would you like to recalculate? ('Yes' or 'No') "))

wedcost(raw_input("How long will we be on location? "))

I'm sure that there's a better way to go about this task. Any suggestions or hints?


texts:
I wanted to scrape all the wallpapers from the Bing wallpaper gallery.  This was for personal use and to learn about webscraping.  The gallery progressively gets images using javascript as the user scrolls down the page.  Then you can download the high-resolution image with a few clicks.  I actually succeeded in scraping all the wallpapers, but I sort of "cheated" and wanted to know if there's a better way.

Here's what I did:

First, I went to the site in the browser, started capturing network traffic with developer tools, and scrolled all the way down the page as far as possible.  Then I exported the log to a .csv file.  This produced a bunch of URLs like:

  http://az619519.vo.msecnd.net/files/PolandFarm_EN-US8019728095_320x180.jpg

Luckily, the full resolution version (for almost every image) is located in the same place, except with "1920x1200" substituted at the end:

  http://az619519.vo.msecnd.net/files/PolandFarm_EN-US8019728095_1920x1200.jpg

I ran the following script to retrieve the full resolution images:

import csv
import os
import re
import urllib.request

target_dir = 'C:/Users/[Username]/Desktop/Bing'

def main():
    os.chdir(target_dir)
    with open('NetworkData.csv', 'r', encoding='utf-8') as csvfile:
        for line in csv.reader(csvfile):
            url_request = repr(line[0])
            if r'vo.msecnd.net/files' in url_request:
                pic_url = re.sub('_\d+x\d+\.jpg', '_1920x1200.jpg', url_request)
                pic_url = pic_url.strip('\'"')
                try:
                    urllib.request.urlretrieve(pic_url, pic_url.split('/')[-1])
                except:
                    print("Image not found.")

if __name__ == '__main__':
    main()

I thought this solution was actually okay, but I was wondering if there was a way to automate or avoid the manual step of capturing the network traffic.  I was hoping to avoid selenium if possible, because it looks kind of slow and cumbersome.  Also, if you have any advice on improving the script, that would be good.  I had some issues with string encoding, and I feel like in the end the script isn't very readable.


texts:
I have been trying to create a class that would list prime numbers forever. I know it has already been done but I think I learned some valuable principles during my trials.

This project helped me understand (to a better extent) return values, arguments for methods, simple math arithmetic and what I personally enjoyed working with was the power of the for and if/else statements.

I would appreciate any insight into improvements that would increase this code performance and/or any obvious flaws with my code structure.

//first the class is declared
public class startListingPrimeNumbers {

    // method is created to start the prime number listing from 1 to infinity
    // and beyond
    public void startFromOneListingPrimeNumbers() {

        // Create the primary for loop using doubles so the program will
        // continue on infinitely
        for (double x = 1; x > 0.000; x = x + 1.000) {

            // The double c is for determining numbers that only have 2 factors
            // are prime
            double c = 2.000;

            // I use the primeLogger to keep track of each numbers amount of
            // factors it contains, to later compare this value to c to know if
            // it's prime or not
            double primeLogger = 0.000;

            // the multiplier is used to iterate through the for loop below
            double multiplier;

            // this is the bread and butter, I take multiplier and iterate it
            // until it is greater than x, if a remainder exists from x divided
            // by multiplier then my primeLogger adds nothing to itself
            // if there is no remainder then primeLogger adds one, meaning
            // multiplier is a factor of x.

            for (multiplier = 1.000; multiplier <= (x); multiplier = multiplier + 1.000) {
                if (x % multiplier == 0) {
                    primeLogger = primeLogger + 1.000;
                } else {
                    primeLogger = primeLogger + 0.000;
                }
            }

            // here we see if there are only 2 factors for x, and the console
            // prints the number
            if (c == primeLogger) {
                System.out.println(x + " is a prime number");
            }

            // primeLogger is set back to zero to go on to the next x value
            // based on the primary for loop description
            primeLogger = 0.000;
        }
    }
}


texts:
I have the following lines to parse from a log file with 8000 lines which takes about 5 minutes to parse:

text="2017-01-12 15:16:42,404 - RestLogger[10c059f7] - INFO - rest_server::log_request:102 - REST call: <POST /multi/ HTTP/1.1> with args {} and content {u'inv_initiators': {u'path': u'/v2/types/initiators/', u'args': }} from user admin @ 10.106.97.145\n"
text+="2016-10-06 20:58:04,025 - RestLogger - INFO - rest_server::log_request:98 - REST call: <GET /types/volumes/59 HTTP/1.1> with args {}\n"

re.findall('([12]\d{3}-[0-3]\d-[01]\d \d{2}:\d{2}:\d{2},\d{3}) .*rest_server::log_request:\d+ - REST call: <(\w+) (.*) .+?> with args ({.*?})(?: and content ({.*}))?.*?\n', text)

Since I would like to grab lines with optional text "and content" I am adding ?: and ? to grab the lines in one regex and the results are really slow.

Any advice how to make it faster?


texts: Checking proper English sentences of user's input with grammar using C++

texts:
Write a program that checks if a sentence is correct according to the
  “English” grammar in §6.4.1. Assume that every sentence is terminated
  by a full stop (.) surrounded by whitespace. For example, birds fly
  but the fish swim . is a sentence, but birds fly but the fish swim
  (terminating dot missing) and birds fly but the fish swim. (no space
  before dot) are not. For each sentence entered, the program should
  simply respond “OK” or “not OK.” Hint: Don’t bother with tokens; just
  read into a string using >>.

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

string str;

void putback(string s) {
    str = s;
}

string verb() {
    if (str == "rules" || str == "fly" || str == "swim") {
        return str + ' ';
    }
    else
        return "";
}

string noun() {
    if (str == "birds" || str == "fish" || str == "C++") {
        return str + ' ';
    }
    else
        return "";
}

string article() {
    if (str == "the") {
        string temp = str;
        cin >> str;
        return temp + ' ';
    }
    else
        return "";
}

string conjunction() {
    if (str == "and" || str == "or" || str == "but") {
        return str + ' ';
    }
    else
        return "";
}

string l;
string sentence() {
    l += article();
    if (noun() == "") {
        cerr << "NOT OK";
        return "";
    }
    else {
        l += noun();
        cin >> str;
        string temp = verb();
        if (temp == "") {
            cerr << "NOT OK";
            return "";
        }
        else {
            l += temp;
            cin >> str;
            if (str == "") {
                cerr << "NOT OK";
                return " ";
            }
            else if (str == ".") {
                l += ".";
                return l;
            }
            else {
                if(conjunction() == "") {
                    cerr << "NOT OK";
                }
                else {
                    l += str + ' ';
                    cin >> str;
                }
                return sentence();
            }
        }
    }
}

int main()
try
{
    string sen = " ";
    while (cin) {
        cin >> str;
        sen = sentence();
        if (str == ".") {
            cout << sen << '\n';
        }
    }
    //keep_window_open();
}
catch (exception& e)
{
    cerr << "error: " << e.what() << '\n';
    //keep_window_open();
    return 1;
}
catch (...)
{
    cerr << "Oops: unknown exception!\n";
    //keep_window_open();
    return 2;
}

The Grammar:
Sentence:
          Noun Verb                                   // e.g., C++ rules
          Article Noun Verb
          Sentence Conjunction Sentence   // e.g., Birds fly but fish swim
Conjunction:
          "and"
          "or"
          "but"
Article:
          "the"
Noun:
          "birds"
          "fish"
          "C++"
Verb:
          "rules"
          "fly"
          "swim"

This is perfectly working code. Is there anything I can improve on for my code? Do you think using global variables in this case is okay? Even for whether I have proper variable names is worth commenting. This question is from this webpage, exercise 6 at the very bottom.


texts: Backbone.js App approach not very scalable - nested views

texts:
I'm creating a Backbone App, and although everything seems to work i'm afraid i might need to refactor very soon if I keep adding functionalities and views with this approach. I'm using Parse in the backend, meaning that the object Parse is equivalent to the Backbone.Model. I can't control my models since they've been optimized for mobile and here i need to display only certain key values of 3 different models.

Although there's nothing "wrong" (it works) it's only a matter of time until i start doing 'bigger' mistakes.

Here's my Router:

App.Controllers.Documents = Backbone.Router.extend({
 routes:{
    "story/:id" : "fullStory",
    "" : "index"
 },
// ...
 fullStory: function(id){
  var self = this;
  var query = new Parse.Query(Steps);
  query.equalTo("story", id)
  var steps = query.collection();

  steps.fetch({
   success: function() {

     new App.Views.Steps({ collection: steps });

     var title = new Story({ objectId: id });
     title.fetch({
          success: function(model, resp) {
          new App.Views.Title({ model: title});
          var idUser = title.toJSON().idUser;
          var user = new Parse.User({ objectId: idUser });
          user.fetch({
              success: function(){
                     // I just need the username key here...
                 new App.Views.Username({model:user,el:$("#user")});
              },
              error: function(){
                 new Error({ message: 'Could not find the user you requested.' });
              }
           })
         },
          error: function() {
            new Error({ message: 'Could not find that story.' });

           }
      })
    },
    error: function() {
      new Error({ message: "Error loading story." });
    }
  });
}

Given the way objects have been created in Parse I need to access 3 different objects, that's why i'm rendering the View in "parts". I'd like this function to render just a FullStory View with these 'sub views' inside of it but i'm unsure on how to do it 'cause the Parse.Objects need a reference to the other object -> var user = new Parse.User({ objectId: idUser }); where idUser is a key from another object.

Finally my Views:

App.Views.Steps = Backbone.View.extend({
 tagName : "ul",
 className: "steps",
 initialize: function() {
 this.render();
},
 render: function() {
   this.$el.html(_.template($("#story_steps").html())({ collection: this.collection }));
   $('#steps_wrapper').html(this.el);
 },
});

App.Views.Title = Backbone.View.extend({
 initialize: function() {
 this.render();
},
 render: function() {
  this.$el.html(_.template($("#story_title").html())({ model: this.model }));
  $('#title').html(this.el);
 }
});
App.Views.Username = Backbone.View.extend({
 initialize: function() {
 this.render();
},
 template: _.template('<%= name %>'),

  render: function() {
   this.$el.html(this.template(this.model.toJSON()));
  }
});


texts:
I'm adding an onclick listener to the whole document then checking the source of the click. If the source of the click contains the attribute data-widget I want to go to the appropriate action. I did it but I'm hoping for a more efficient way of doing things and if I can do without the self invoking function.

<div data-widget="myaction"> Click here </div>

document.addEventListener("click", function(e) {
    var widgets = new Widgets();
    var w = e.target.getAttribute("data-widget");
    if(w){
        e.preventDefault();
        widgets[w];
    }
});

function Widgets(){
    var myaction = (function myaction(){
        console.log('indeed');
    })();
}


texts: Configuring DI when using four-layer architecture

texts:
In my presentation layer I use an MVC pattern with DI to achieve thin controllers like so:

public class HomeController : Controller
{
    private IHomeService _service;

    public HomeController(IHomeService service)
        : base()
    {
        _service = service;
    }

    public override ActionResult Index()
    {
        HomeIndexViewModel viewModel = new HomeIndexViewModel();
        viewModel.NewsArticles = _service.GetLatestNewsArticles();
        return View(viewModel);
    }
}

I'm using Ninject thus I've configured Ninject within the presentation layer like so:

public class NinjectConfig
{
    public static IKernel CreateKernel()
    {
        StandardKernel kernel = new StandardKernel();

        kernel.Bind<IHomeService>().To<HomeService>();
        kernel.Bind<ISearchService>().To<SearchService>();

        return kernel;
    }
}

I'm a bit confused as to whether I should be configuring Ninject in the presentation layer, or whether this should be done in the application layer.

I'm also wondering whether it is acceptable to have multiple Ninject configurations in multiple layers, such as a configuration in the application layer and another in the business layer.


texts:
Ok, it's not completely like Simon Says, since it's text-based. There is nothing about memorizing based on visual cues and/or sound here, just memorizing long sequences of numbers. I wanted to do it in the language I write the least code in, Scheme (w/ Chicken), and see what happens.

(use posix)
(use (srfi 1))

(define button-count 4)

(define (clear-screen)
  (system "cls"))

(define (make-delay)
  (sleep 2))

(define (show-sequence sequence)
  (if (not (null? sequence))
    (begin
      (clear-screen)
      (make-delay)
      (write (car sequence))
      (make-delay)
      (show-sequence (cdr sequence)))
    (begin
      (clear-screen)
      (write-line "GO!"))))

(define (show-score score)
  (format #t "Your score: ~A~%" score))

(define (get-player-input)
  (read-line))

(define (make-sequence length)
  (map random (make-list length button-count)))

(define (player-sequence-matches? target-sequence)
  (cond
    [(null? target-sequence) #t]
    [(string=? (get-player-input) (number->string (car target-sequence)))
     (player-sequence-matches? (cdr target-sequence))]
    [else #f]))

(define (simon-says difficulty)
  (let [(current-sequence (make-sequence difficulty))]
    (show-sequence current-sequence)
    (if (player-sequence-matches? current-sequence)
      (+ 1 (simon-says (+ difficulty 1)))
      0)))

(define (play-simon-says)
  (show-score (simon-says 1)))

If you want to run it on something Unix, you'll need to change (system "cls") to (system "clear").


texts: Fields are required, except if all fields are empty

texts:
I have a group of four inputs, the first three are required, the fourth is optional.

$fieldA
$fieldB
$fieldC
$fieldD #Optional

So to validate the inputs, I just use this:

if($fieldA === '' || $fieldB === '' || $fieldC === '') {
    #error
}

That works pretty well, except there is a special case: If all four inputs are empty, the input is still valid.

That special case complicates the if condition quite a bit:

if(($fieldA !== '' || $fieldB !== '' || $fieldC !== '' || $fieldD !== '')
    && ($fieldA === '' || $fieldB === '' || $fieldC === '')) {
    #error
}

The condition in the first pair of parenthesis makes sure that at least one field is not empty, while the rest of the condition makes sure that none of the required fields is empty.

Is there some sneaky way to simplify that if statement that I did not think of?


texts:
I'm somewhat new to writing real-world projects in C, so I'm not familiar with best practices and standards. I'm writing code dealing with EGL and OpenGL, and some setup calls might fail for reasons outside my control. I want to write an initialization function that performs all necessary setup for my application, but exits early and returns false if any call fails (essentially replicating simple exception handling behavior).

Given various philosophies regarding multiple returns, GOTOs, and so forth, I've  written my function as follows:

int init_gl(EGLDisplay* outDisplay, EGLContext* outContext, EGLSurface* outSurface) {
    int success = 1;

    EGLConfig config;
    EGLint num_config;

    EGLDisplay display;
    EGLContext context;
    EGLSurface surface;

    static const EGLint attribute_list[] =
    {
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_NONE
    };

    static const EGLint context_attributes[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    bcm_host_init();

    success = success && (display = eglGetDisplay(EGL_DEFAULT_DISPLAY)) != EGL_NO_DISPLAY;
    check();

    success = success && eglInitialize(display, NULL, NULL) != EGL_FALSE;
    check();

    success = success && eglChooseConfig(display, attribute_list, &config, 1, &num_config) != EGL_FALSE;
    check();

    success = success && eglBindAPI(EGL_OPENGL_ES_API) != EGL_FALSE;
    check();

    success = success && (context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attributes)) != EGL_NO_CONTEXT;
    check();

    success = success && (surface = eglCreateWindowSurface(display, config, NULL, NULL)) != EGL_NO_SURFACE;
    check();

    success = success && eglMakeCurrent(display, surface, surface, context) != EGL_FALSE;
    check();

    if(success) {
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        check();

        *outDisplay = display;
        *outContext = context;
        *outSurface = surface;
    }

    return success;
}

Is this awful? As I understand it, this is not an appropriate place to use assert() for postconditions as the success of these functions is outside of my control. Would it be better to write this as a series of if(!function()) { return 0; } or leave it as is?
Don't worry about the check(); statements, this is just a debug macro for assert(glGetError() == 0).


texts: Merging the frequency rankings of boys' names and girls' names

texts:
Problem statement:

The html pages for each year which represents the top 1000 most common Girl and Boy names in the order of their frequency are ranked and provided. And they are ranked based on the frequency of their naming. To elaborate if John is named 101 times and Johan is named 130 times they both are ranked serially as

Johan   1
John    2

To get an idea of this you can refer to this website:
https://www.ssa.gov/oact/babynames/decades/names2010s.html.

In some years, a name appears more than once in the html, but we'll just have to use one number per name. We have to make the algorithm smart about this case and choose whichever number is smaller. After retrieving the names along with their ranks we have to write that data into text file in the following format:

2006
Aaliyah 91
Aaron 57
Abagail 895
Abbey 695
Abbie 650

Implementation: I have retrieved the Girl names and Boy names along with their rankings using regular expressions. Later on I have created two dictionaries boyNames_Rank_Dict, girlNames_Rank_Dict. These dictionaries have basically names of Girls and Boys that are named in that particular year along with their ranks.

Now the challenge is to look for common girls names, boys names and their corresponding ranks. Now if there is a girl and a boy name that are same then the ranks are to be compared and the lowest rank in them has to be selected.

I have written a script for this, below is the code which is an implementation of the requirement:

from time import time
import re

def extract_names(filename):

    boyNames_rank_Dict = {}
    girlNames_rank_Dict = {}
    filestream = open(filename, "r")
    filebuffer = filestream.read()
    filematch_year = re.search(r"Popularity\s([\w.-]+)\s([\d.-]+)", filebuffer)
    year1 = filematch_year.group(2)

    filematch_rank_names = re.findall(r'td>([\d.-]+)	([\w.-]+)	([\w.-]+)', filebuffer)

    for filematch_rank_name in filematch_rank_names:
        x = int(filematch_rank_name[0])
        boyNames_rank_Dict[x] = filematch_rank_name[1]
        girlNames_rank_Dict[x] = filematch_rank_name[2]

    for boy_Rank, boy_Name in boyNames_rank_Dict.items():
        for girl_Rank, girl_Name in girlNames_rank_Dict.items():
            if boy_Name == girl_Name and boy_Rank < girl_Rank:
                 del girlNames_rank_Dict[girl_Rank]
            elif boy_Name == girl_Name and girl_Rank < boy_Rank:
                 del boyNames_rank_Dict[boy_Rank]

    names_Rank_Dict = girlNames_rank_Dict.items() + boyNames_rank_Dict.items()

    file = open("output.txt", 'w')
    file.write(year1)

    for rank, name in names_Rank_Dict:
        strx = name+' '+str(rank)
        file.write('\n')
        file.write(strx)

    file.close()

def timex():
    return round(time()*1000)

def main():
    start_time = timex()
    extract_names("/home/sreedhar/Desktop/google-python-exercises/babynames/baby1998.html")
    end_time = timex()
    print "time taken:%d seconds", (end_time-start_time)

if __name__ == "__main__":
    main()

How can I search for the rank in these Dictionaries when a matching name is found in a more efficient manner. Since when I tried to Profile the time it has taken to execute this program it took 263 milliseconds on a mere 1000 records.

  1017 function calls in 0.263 seconds

When I extrapolate this function to work on a million records the time complexity seems to be out of bounds.

Could some body kindly guide towards a more efficient implementation of this. Also make note that I'm an amateur to Python.


texts:
I'm preparing for an interview so I'm trying to solve some problems to stretch my mind. Here is one:

  Describe how you could use a single array to implement three stacks.

And here is my implementation:

class StackUnderflowError extends RuntimeException {
    public StackUnderflowError(String msg) {
        super(msg);
    }
}

class ThreeStacks<T>{

private T[] array;
private int firstIndex = 0;
private int secondIndex = 1;
private int thirdIndex = 2;

public ThreeStacks(Class<T> classT, int capacity) {
    array = (T[])Array.newInstance(classT, capacity);
}

void push(T data, int stack){ //enum to select the stack
    switch(stack)
    {
        case 1: pushOne(data);
            break;
        case 2: pushTwo(data);
            break;
        case 3: pushThree(data);
            break;
        default: throw new IllegalArgumentException("stack");
    }
}

T pop(int stack){
    switch(stack){
        case 1: return popOne();
        case 2: return popTwo();
        case 3: return popThree();
        default: throw new IllegalArgumentException("stack");
    }
}

private void pushOne(T data) {
    if (firstIndex > array.length - 1) {
        throw new StackOverflowError("firstStack");
    } else{
        array[firstIndex] = data;
        firstIndex += 3;
    }
}

private void pushTwo(T data) {
    if (secondIndex > array.length - 1) {
        throw new StackOverflowError("secondStack");
    } else{
        array[secondIndex] = data;
        secondIndex += 3;
    }
}

private void pushThree(T data) {
    if (thirdIndex > array.length - 1) {
        throw new StackOverflowError("thirdStack");
    } else{
        array[thirdIndex] = data;
        thirdIndex += 3;
    }
}

private T popOne() {
    firstIndex -= 3;
    if(firstIndex < 0){
        throw new StackUnderflowError("fristStack");
    }
    return array[firstIndex];
}

private T popTwo() {
    secondIndex -= 3;
    if(secondIndex < 0){
        throw new StackUnderflowError("fristStack");
    }
    return array[secondIndex];
}

private T popThree() {
    thirdIndex -= 3;
    if(thirdIndex < 0){
        throw new StackUnderflowError("fristStack");
    }
    return array[thirdIndex];
}

}

And test:

    ThreeStacks<String> threeStacks = new ThreeStacks<>(String.class, 1024);
    threeStacks.push("1", 1);
    threeStacks.push("2", 2);
    threeStacks.push("3", 3);
    threeStacks.push("4", 1);
    threeStacks.push("5", 2);
    threeStacks.push("6", 3);

    System.out.println( threeStacks.pop(1) );
    System.out.println( threeStacks.pop(2) );
    System.out.println( threeStacks.pop(2) );
    System.out.println( threeStacks.pop(1) );
    //System.out.println( threeStacks.pop(1) );

How can I improve this? A few thoughts:

use array instead of switch (stacks' indexes)
use enum to choose stack
use ArrayList (if interviewer agrees)


texts: Make querySelector in kotlin-js more convenient and type-safe

texts:
I'd like you to take a look at those extension functions I made in kotlinjs (version 1.3.61):

inline fun <reified E : Element> Element.queryHtmlSelectorOrNull(selectors: String): E? {
    return this.querySelector(selectors = selectors) as E?
}

inline fun <reified E : Element> Element.queryHtmlSelector(selectors: String): E {
    return this.queryHtmlSelectorOrNull(selectors = selectors)
        ?: error("couldn't find element by selectors '$selectors'")
}

Now let me elaborate. I was using classic javascript querySelector. This signature:

fun querySelector(selectors: String): Element?

Has some downsides/qualities:

It is optional.
When I force cast to for example HTMLDivElement and result is actually null, I get NullPointerException with no additional information/error message. Example:

document.querySelector(".something-non-existent") as HTMLDivElement //throws

I have to explicitly cast my query to specific element I want (example HTMLDivElement? or HTMLDivElement).

My functions fix some of the issues, but create new issues:

You can explicitly select what type you need or compiler can guess it based on variable type.

Example:

document.queryHtmlSelector<HTMLDivElement>(".something")

or

val element: HTMLDivElement = document.queryHtmlSelector(".something")

The downside is that this doesn't work (need to set type explicitly):

val element = document.queryHtmlSelector(".something")

I would be cool somehow to "default" base type to Element if none is specified, but can't think of way to do that.

I'd like something that can pretty much replace original function and just add benefits of stronger typing and nicer error message. Any hints on how to improve this are greatly appreciated.


texts: Checking for differences between two (large) files

texts:
I want to write a relatively simple program, that can backup files from my computer to a remote location and encrypt them in the process, while also computing a diff (well not really...I'm content with seeing if anything changed at all, not so much what has changed) between the local and the remote files to see which ones have changed and are necessary to update.

I am aware that there are perfectly good programs out there to do this (rsync, or others based on duplicity). I'm not trying to reinvent the wheel, it's just supposed to be a learning experience for myself

My question is regarding to the diff part of the project. I have made some assumptions and wrote some sample code to test them out, but I would like to know if you see anything I might have missed, if the assumptions are just plain wrong, or if there's something that could go wrong in a particular constelation.

Assumption 1: If files are not of equal length, they can not be the same (ie. some modification must have taken place)
Assumption 2: If two files are the same (ie. no modification has taken place) any byte sub-set of these two files will have the same hash
Assumption 3: If a byte sub-set of two files is found which does not result in the same hash, the two files are not the same (ie. have been modified)

The code is written in Java and the hashing algorithm used is BLAKE-512 using the java implementation from Marc Greim.
_File1 and _File2 are 2 files > 1.5GB of type java.io.File

public boolean compareStream() throws IOException {
    int i = 0;
    int step = 4096;
    boolean equal = false;

    FileInputStream fi1 = new FileInputStream(_File1);
    FileInputStream fi2 = new FileInputStream(_File2);

    byte[] fi1Content = new byte[step];
    byte[] fi2Content = new byte[step];

    if(_File1.length() == _File2.length()) { //Assumption 1
        while(i*step < _File1.length()) {

            fi1.read(fi1Content, 0, step); //Assumption 2
            fi2.read(fi2Content, 0, step); //Assumption 2

            equal = BLAKE512.isEqual(fi1Content, fi2Content); //Assumption 2

            if(!equal) { //Assumption 3
                break;
            }

            ++i;
        }
    }

    fi1.close();
    fi2.close();
    return equal;
}

The calculation for two equal 1.5 GB files takes around 4.2 seconds. Times are of course much shorter when the files differ, especially when they are of different length since it returns immediately.

Thank you for your suggestions :)


texts: Scraping Clinical Studies database (via ClinicalTrials.Gov)

texts:
I have written the following script to scrape data from the U.S. National Library of Medicine website ClinicalTrials.Gov based on an NCTID.

def clinicalTrialsGov (nctid):
    data = BeautifulSoup(requests.get("https://clinicaltrials.gov/ct2/show/" + nctid + "?displayxml=true").text, "xml")
    subset = ['study_type', 'allocation', 'intervention_model', 'primary_purpose', 'masking', 'enrollment', 'official_title', 'condition', 'minimum_age', 'maximum_age', 'gender', 'healthy_volunteers', 'phase', 'primary_outcome', 'secondary_outcome', 'number_of_arms']
    tag_matches = data.find_all(subset)
    tag_dict = dict((str('ct' + tag_matches[i].name.capitalize()), tag_matches[i].text) for i in range(0, len(tag_matches)))
    tag_dict = multipleFields(data, ['intervention_name'], tag_dict)
    tag_dict = multipleFields(data, ['intervention_type'], tag_dict)
    tag_dict = multipleFields(data, ['arm_group_type'], tag_dict)
    tag_dict['ctID'] = nctid
    #for key in tag_dict:
        #print(key + ': ' + tag_dict[key])
    return removeEmptyKeys(tag_dict)

def multipleFields (data, subset, tagDict):
    fields = data.find_all(subset)
    field = []
    try:
        for each in fields:
            field.append(each.text)
        tagDict[str('ct' + subset[0].capitalize())] = ", ".join(field)
        return tagDict
    except:
        return tagDict

def removeEmptyKeys (dict1):
    newDict = {}
    for key in dict1:
        if str(dict1[key]) is not '':
            newDict[key] = dict1[key]
    return newDict

What can I do to make this process more efficent?


texts: Solution to Dummy Packet Assembler (Task from r/dailyprogrammer)

texts:
I tried to solve the Packet Assembler task posted at r/dailyprogrammer.
The Question is this:

When a message is transmitted over the internet, it is split into multiple packets, each packet is transferred individually, and the packets are reassembled into the original message by the receiver. Because the internet exists in the real world, and because the real world can be messy, packets do not always arrive in the order in which they are sent. For today's challenge, your program must collect packets from stdin, assemble them in the correct order, and print the completed messages to stdout.
The point of reading from stdin is to simulate incoming packets. For the purposes of this challenge, assume there is a potentially unlimited number of packets. Your program should not depend on knowing how many packets there are in total. Simply sorting the input in its entirety would technically work, but defeats the purpose of this exercise.

Input Format is this:

Each line of input represents a single packet. Each line will be formatted as X Y Z some_text, where X Y and Z are positive integer and some_text is an arbitrary string. X represents the message ID (ie which message this packet is a part of). Y represents the packet ID (ie the index of this packet in the message) (packets are zero-indexed, so the first packet in a message will have Y=0, the last packet in a message will have Y=Z-1). Z represents the total number of packets in the message.

Here is the Python3 solution I did
from re import split

def add_id(packets, p_id, len):
    packets[p_id] = {}
    packets[p_id]["len"] = len
    packets[p_id]["packets"] = {}

    return packets

def add_packet(packets, p_id, p_num, p_len, msg):
    if p_id not in packets.keys():
        packets = add_id(packets, p_id, p_len)

    if p_num > packets[p_id]["len"]:
        return packets

    packets[p_id]["packets"][p_num] = msg

    return packets

def main():
    packets = {}
    while True:
        try:
            recv = split(r'\s+', input())

            packets = add_packet(packets, int(recv[0]), int(recv[1]),
                                int(recv[2]), " ".join(recv[3:]))
        except EOFError:
            break

    for p_id in sorted(packets):
        for packet in range(packets[p_id]["len"]):
            print("%d %d %d %s" %(p_id, packet, packets[p_id]["len"], packets[p_id]["packets"][packet]))

if __name__ == '__main__':
    main()

Please rate this solution and suggest some improvements that can be made?


texts: FASM assembly: Write a program which checks if a number is a prime number

texts:
Coming from high-level languages like PHP and JavaScript, I'm doing an Assembly course on Udemy.

Yesterday I tried to implement the following task:

  Write a program that takes a number m as input, and prints back 1 to the
  console if m is a prime number. Otherwise, it prints 0.

Original text can be found here (Exercise 3.0).

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:
    call read_hex
    mov esi, eax ; Store the provided number in esi.
    mov edi, 1

    cmp eax, 2
    je finish

    mov ebx, 2 ; ebx stores the divisor.
    mov edx, 0 ; Will contain the remainder. Therefore: Make sure it's empty.
go_forward:
    ; Divisor has reached the size of the number and it was still
    ; not possible to divide the number without a rest : Got a prim number.
    cmp ebx, esi
    je finish ; Jump out of the loop.

    div ebx

    cmp edx, 0
    je no_prim

    ; Preparations for the next iteration.
    inc ebx ; Increase the divisor.
    mov edx, 0
    mov eax, esi ; Restore the user entered value.

    jmp go_forward ; Restart the loop.
no_prim:
    mov edi, 0 ; No prim : Then set the result to 0 !
finish:
    mov eax, edi
    call print_eax ; Provided by teacher: Print content eax to stdout.

    push    0
    call    [ExitProcess]

include 'training.inc'

I have tried to comment a lot. I hope that makes my thoughts understandable. I'm still very much a beginner and the program could (without doubt) be improved.


texts:
What is an island?
A group of connected 1s forms an island. For example, the below matrix contains 5 islands:

{{1, 1, 0, 0, 0},
 {0, 1, 0, 0, 1},
 {1, 0, 0, 1, 1},
 {0, 0, 0, 0, 0},
 {1, 0, 1, 0, 1}}

I'm looking for code review, best practices, optimizations etc.

public final class CountIslands {

    private CountIslands() {}

    private static enum Direction {
        NW(-1, -1), N(0, -1), NE(-1, 1), E(0, 1), SE(1, 1), S(1, 0), SW(1, -1), W(-1, 0);

        int rowDelta;
        int colDelta;

        Direction(int rowDelta, int colDelta) {
            this.rowDelta = rowDelta;
            this.colDelta = colDelta;
        }

        public int getRowDelta() {
            return rowDelta;
        }

        public int getColDelta() {
            return colDelta;
        }
    }

    private static boolean isValid(int newRow, int newCol, Direction direction, int[][] m, boolean[][] visited) {
        // visited was constructed from matrix so we are sure that checking visitor for row lengh would do no harm.
        if (newRow < 0 || newRow >= visited.length) return false;
        if (newCol < 0 || newCol >= visited[0].length) return false;
        if (visited[newRow][newCol]) return false;
        return m[newRow][newCol] == 1;
    }

    private static void dfs(int row, int col, int[][] m, boolean[][] visited) {
        visited[row][col] = true;
        for (Direction direction : Direction.values()) {
            int newRow = row + direction.getRowDelta();
            int newCol = col + direction.getColDelta();
            if (isValid(newRow, newCol, direction, m, visited)) {
                dfs(newRow, newCol, m, visited);
            }
        }
    }

    /**
     * Returns the number of 1 islands.
     *
     * @param m     the input matrix
     * @return      the number of 1 islands.
     */
    public static int count(int[][] m) {
        final boolean[][] visited = new boolean[m.length][m[0].length];
        int count = 0;

        for (int row = 0; row < m.length; row++) {
            for (int col = 0; col < m[0].length; col++) {
                if (m[row][col] == 1 && !visited[row][col]) {
                    dfs(row, col, m, visited);
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[][] m = { { 1, 1, 0, 0 }, { 0, 0, 0, 1 }, { 0, 0, 1, 1 } };

        System.out.println("Expected 2, Actual " + count(m));

        int[][] m1 = { { 1, 1, 0, 0 }, { 0, 0, 1, 1 }, { 0, 0, 1, 1 } };

        System.out.println("Expected 1, Actual " + count(m1));

    }
}


texts: Binary search implementations comparison

texts:
I implemented a binary search algorithm. And did it using recursive and non-recurcive approaches. Then I compared the performance of both implementations with java out-of-the-box solution. And what I got is my implementations execute for pretty the same time as Arrays.binarySearch(), which seems to be perfectly valid result as far as the execution lasts only for log(n) time. Despite the theoretical conclusions, I am still in doubts. Are the implementations good enough and how can I heavy load the test case to notice any, let it be tiny, distinction?

Any feedback and suggestions are highly appreciated.

import java.time.*;
import java.time.temporal.*;
import java.util.*;
import java.util.stream.*;

//The program has two modes: recursive and ordinary.
//One can choose recursive mode using command line argument R.
//Or, skipping an argument, run the program in ordinary mode.
public class BinarySearch{
    private int[] array;
    private BinarySearch(int[] array){
        //We have to use sorted array to perform binary search
        Arrays.sort(array);
        this.array = array;
    }
    //Recursive search
    private int searchUtilRecursive(int[] array, int start, int finish, int item){
        if((finish - start) == 1 && array[start] == item) return start;
        else if((finish - start) == 1 && array[start] != item) return -1;
        int middle = (finish - start)/2;
        if(array[start + middle] <= item) return searchUtilRecursive(array, start + middle, finish, item);
        else return searchUtilRecursive(array, start, start + middle, item);
    }
    //Ordinary search
    private int searchUtil(int[] array, int start, int finish, int item){
        start = (finish - start)/2;
        while((finish - start) >= 1){
            if(array[start] < item) start += (finish - start)/2;
            else finish = start;
            if((finish - start) == 1 && array[start] == item) return start;
            else if((finish - start) == 1 && array[start] == item) return -1;
        }
        return -1;
    }
    private int search(String mode, int item){
        switch(mode){
        case "R": System.out.println("Start test in Recursive mode");
            return searchUtilRecursive(array, 0, array.length, item);
        default: System.out.println("Start test in Ordinary mode");
            return searchUtil(array, 0, array.length, item);
        }
    }
    public static void main(String[] args){
        //The idea of the test is to examine log n time complexity.
        //We need to use large enough array to perform a search.
        //It helps us detect tiny distinctions between Java SE
        //implementation and the custom search implementation.
        int numberOfRandoms = 10000000;
        int randomNumberToPick = new Random().nextInt(numberOfRandoms);
        IntStream intStream = new Random().ints();
        int[] intArray = intStream.limit(numberOfRandoms).toArray();
        BinarySearch binarySearch = new BinarySearch(intArray);

        Instant beforeInstantMyImpl = Instant.now();
        int resultMyImpl = binarySearch.search(args.length > 0 ? args[0] : "", intArray[randomNumberToPick]);
        Instant afterInstantMyImpl = Instant.now();

        Instant beforeInstantJavaImpl = Instant.now();
        int resultJavaImpl = Arrays.binarySearch(intArray, intArray[randomNumberToPick]);
        Instant afterInstantJavaImpl = Instant.now();

        assert resultMyImpl == resultJavaImpl: "Search result doesn't equal to Java SE implementation of search";
        assert beforeInstantMyImpl.until(afterInstantMyImpl, ChronoUnit.NANOS) == beforeInstantJavaImpl.until(afterInstantJavaImpl, ChronoUnit.NANOS): "Search is not as efficient as Java SE implementation";
        System.out.println("Test is passed");
    }
}


texts:
This is a problem from Automate the Boring Stuff from "Pattern Matching with Regular Expression". I am a beginner in Python and the purpose of this program is to match urls which start with http:// or https://, with some urls having an optional www. after https://

How can this code be improved?

#! /usr/bin/python3
#websiteURL.py - Find website URLs that begin with http:// or https://

import pyperclip, re

#protocol Regex - checks for http:// or https://
protocolRegex = re.compile(r'''
    https?://           #match http:// or https://
    (?:w{3}\.)?         #www-dot
    [a-zA-Z0-9_-]+      #domin name
    \.                  #dot
    [a-zA-Z]{2,3}       #extension
    ''', re.VERBOSE)

text = str(pyperclip.paste()) #copying data from document to clipboard and converting it into a string
matches = [] #stores all matches in this list

for website in protocolRegex.findall(text): #finding website from the string text
    matches.append(website)

if len(matches) > 0:
    pyperclip.copy('\n'.join(map(str, matches))) #copying result to clipboard after adding newline after each match
    print('Copied to clipboard:')
    print('\n'.join(matches))
else:
    print('No website found')

Running code:

chmod +x websiteURL.py
./websiteURL.py


texts: Efficiently determining maximum allowed euclidean distance between lists of colors

texts:
I was recently tasked with determining which hex RGB colors in list  color_list are nearest to each hex RGB color in list target_colors, using euclidean distance as the measuring stick, and only returning items that are within 10 distance from each target color.  My first pass at this was for each item in target_colors, check the distance between it and everything in color_list, and return the colors at or below the target distance. This works well enough when color_list is small. But when color_list is large, looping over the entire list for each item in target_colors is slow. I am wondering if there is a better way to go about doing this, so that I don't have to loop over the entire list every time.

My first thought was to cache the results, but given that there are 16 million potential colors, that is potentially 2*16m^2 combinations, it would not be very space efficient.

My next thought was that perhaps the source color list can be sorted in a way that would make searching it faster, but I have to loop over all of the colors to get the distance as the thing to sort on, and I would not be in any better of shape.

My last thought was that given an r, g, or b color, perhaps I could eliminate colors that are obviously going to be out of range. If I have a color like #AABBAA, I instinctively know that #001100 is going to be way too far away, so I could sort the source list of colors l, then eliminate anything that smells like its out of range. But, I get back to the "well I would calculate the distance to figure out if it smells out of range", and I'm back to square one.

distance.rb:

TARGET_DISTANCE = 10.0

# calculate the euclidiean distance between two hex colors
def color_distance(c1, c2)
  c1_parts = c1.split('').each_slice(2).map{|c| c.join}.to_a
  c2_parts = c2.split('').each_slice(2).map{|c| c.join}.to_a
  r_diff = c1_parts[0].to_i(16) - c2_parts[0].to_i(16)
  g_diff = c1_parts[1].to_i(16) - c2_parts[1].to_i(16)
  b_diff = c1_parts[2].to_i(16) - c2_parts[2].to_i(16)
  Math.sqrt(r_diff**2 + g_diff**2 + b_diff**2)
end

def random_color
  3.times.map{rand(254).to_s(16).rjust(2, '0')}.join()
end

color_list = []
1.upto(10000) { color_list << random_color }

target_colors  = []
1.upto(100) { target_colors << random_color }

results = {}
target_colors.each do |t|
  results[t] ||= []
  color_list.each do |c|
   distance = color_distance(c, t)
   if distance <= TARGET_DISTANCE
     results[t] << [c, distance]
   end
  end
end


texts:
I've written the following function in C which shall take as input a character array (decayed to a char * of course), and mutate the string into a title-cased string in the form "this is a string" -> "This Is A String".

void title_case(char str[])
{
    assert(str);
    size_t i;
    str[0] = toupper((int) str[0]);
    if(strlen(str) == 1) return;
    for(i = 1; i < strlen(str); ++i)
    {
        str[i] = tolower((int)str[i]);
        if(str[i -1] == ' ')
        {
            str[i] = toupper((int)str[i]);
        }
    }
    return;
}

Please provide any feedback you see fit. Is there a more concise way to do this? Is array bracket notation the most clear way?

Driver:

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

void title_case(char str[]);
int main(void)
{
    char sentence[] = "this is a SeNTeNce.";
    title_case(sentence);
    printf("%s\n", sentence);
    return 0;
}


texts:
I need to show article's content based on this logic:

if article's content has to be truncated (e.g for preview)

if there's [read more] substring in the content

replace first [read more] with link to the article
truncate content to the first occurence of [read more]

else

truncate content to the first 500 characters

remove all [read more] from content.

I've written a presenter for this, how can it be refactored?
(_h gives access to the helpers)
This is just one of the responsibilities that this presenter has, there are already a few methods (public & private), so... should I extract it into a helper?

class ArticlePresenter
  # ... omitted
  DEFAULT_LENGTH  = 500
  READ_MORE_REGEX = /\[read more\]/i

  def content(truncate)
    content = article.content
    if truncate
     index = content.index(READ_MORE_REGEX)
     if index
       url = _h.article_url(article)
       content = _h.truncate(content, length: index, omission: " [Show more](#{url})")
     else
       content = _h.truncate(content, length: DEFAULT_LENGTH)
     end
   end

   content.gsub!(READ_MORE_REGEX, '')

   html = MarkdownService.instance.render content
   content_tag :div, html
 end


texts: A graph representation of Adjacent Matrix in Python

texts:
I'm trying to create a graph representation in Adj Matrix in Python. I'm not sure if this is the best pythonic way.

class Graph(object):
    def __init__(self, edge_list):
        self.edge_list = edge_list

    def add_edge(self, edge_list):
        self.edge_list.append(edge_list)

    def adj_mtx(self):
        v = 0
        counter = set()
        for src, dest in self.edge_list:
            counter.add(src)
            counter.add(dest)

        v = len(counter)

        mtx = [[0 for y in range(v)]for x in range(v)]
        for e in self.edge_list:
            src, dest = e
            src = src - 1
            dest = dest - 1
            mtx[src][dest] = 1

        return mtx

edge_list = [(1,2), (2,3), (1,3)]
graph = Graph(edge_list)
mtx = graph.adj_mtx()

assert mtx == [[0, 1, 1], [0, 0, 1], [0, 0, 0]]

graph.add_edge((3,3))
mtx = graph.adj_mtx()
assert graph.adj_mtx() == [[0, 1, 1], [0, 0, 1], [0, 0, 1]]


texts:
I have a ASP.NET Web Forms project, and I want to build calls to .aspx pages in a strongly-typed fashion. I ended up rolling my own serializer that takes simple structs and saves them to/loads them from the query string. What do you think? Is my approach sane? Is there an accepted alternative I don't know about? Any feedback on the code?

Here's what building a call to a particular page looks like:

var fooParams= new FooPage.Parameters
{
    NodeID = nodeId,
    FooString = "the foo string"
};
string url = MyHelper.BuildCall(FooPage.URL, fooParams);
//url: ~/dir/FooPage.aspx?NodeID=5&FooString=the%20foo%20string

FooPage:

public partial class FooPage : System.Web.UI.Page
{
    public const string URL = "~/Dir/FooPage.aspx";
    public struct Parameters
    {
        public long? NodeID;
        public string FooString;
        public int? OtherParam;
    }

    protected Parameters Params;

    protected void Page_Load(object sender, EventArgs e)
    {
        Params = MyHelper.DeserializeFromNameValueCollection<Parameters>(Request.Params);

        //...
        //use Params.NodeID, Params.FooString, etc..
    }
}

Serialize/Deserialize to/from NameValueCollection:

public static void SerializeToNameValueCollection<T>(NameValueCollection nameValueCollection, T @object) where T : struct
{
    Type type = typeof(T);

    var fields = type.GetFields();
    foreach (var field in fields)
    {
        string key = field.Name;
        var value = field.GetValue(@object);

        if (value != null)
            nameValueCollection.Add(key, value.ToString());
    }
}

public static T DeserializeFromNameValueCollection<T>(NameValueCollection nameValueCollection) where T : struct
{
    T result = new T();

    Type type = typeof(T);

    var fields = type.GetFields();

    foreach (var field in fields)
    {
        string key = field.Name;

        string stringValue = nameValueCollection[key];
        if (stringValue != null)
        {
            object value;

            var baseType = Nullable.GetUnderlyingType(field.FieldType);
            if (baseType != null)
            {
                value = Convert.ChangeType(stringValue, baseType);
            }
            else
            {
                value = Convert.ChangeType(stringValue, field.FieldType);
            }

            field.SetValueDirect(__makeref(result), value);
        }
    }

    return result;
}

Format NameValueCollection into query string:

public static string BuildCall<T>(string url, T queryStringParams) where T : struct
{
    var queryStringBuilder = HttpUtility.ParseQueryString("");

    UrlHelper.SerializeToNameValueCollection(queryStringBuilder, queryStringParams);

    string queryString = queryStringBuilder.ToString();

    return url + "?" + queryString;
}


texts:
This is my Clojure code for finding prime numbers.

Note: this is an advanced version which starts eliminating from i*i with step i, instead of filtering all list against mod i == 0 (Sieve of Eratosthenes).

It has better asymptotic runtime: O(n log log n) instead of O(n log n) in typical examples of finding primes in Clojure.

What can be done better? Do I use some slow constructions? Can I make it more concise? Gain more performance? Format it better?

(defn primes [n]
  (let [mark (fn [i di v]
               (if (<= i (count v))
                 (recur (+ i di) di (assoc v (dec i) di))
                 v))
        step (fn [i ps v]
               (if (<= i (count v))
                 (if (= (v (dec i)) 1)
                   (recur (inc i) (conj ps i) (mark (* i i) i v))
                   (recur (inc i) ps v))
                 ps))]
(->> (repeat 1) (take n) vec (step 2 []))))

(defn -main
  [& args]
  (println (primes 50)))


texts:
I have the following function:

from collections import Counter

import itertools

def combinationsWithMaximumCombinedIntervals(data, windowWidth, maximumCombinedIntervals):

    for indices in itertools.combinations(range(len(data)),windowWidth):
        previous = indices[0]
        combinedIntervals = 0
        for i in indices[1:]:
            combinedIntervals = combinedIntervals + i-previous-1
            if combinedIntervals > maximumCombinedIntervals:
                break
            previous = i
        else:
            yield(tuple(data[i] for i in indices))

test = ["a","b","c","d","e","f","g","h","i","j","k","l"]
combinations = combinationsWithMaximumCombinedIntervals(test, 5, 2)

for i in combinations:
    pass

The function is associated with a set of combinations for the data supplied to it. Each element in the list represents a combination with the length of each of these combinations equal to windowLength.

If we take the flowing combination ("a","b","c","d","f"), then the combined interval is 1 since "d" to "f" is a hop of 1. If we take the flowing combination ("a","b","c","e","g"), then the combined interval is 2 since "c" to "e" and "e" to "g" are hops of 1 each. Finally, combination ("a","b","c","d","g") has a combined interval of 2 since "d" to "g" is a hop of 2. The maximumCombinedIntervals argument limits the number of combinations based on the combined interval. In other words, this combination is not available when maximumCombinedIntervals is 2: ("a","c","e","f","h") since the combination of hops is now greater than 2.

I wish to run this function on data with a length of many thousands, a windowWidth in the order of 10 and a maximumCombinedIntervals under 10. However this takes forever to execute.

Can anyone suggest how I might refactor this function so that it will run much more quickly in Python. itertools.combinations is implemented in C.

Here is a similar function which I'm also interested in using:

def combinationsWithMaximumIntervalSize(data, windowWidth, maximumIntervalSize):
    maximumIntervalSizePlusOne = maximumIntervalSize+1

    for indices in itertools.combinations(range(len(data)),windowWidth):
        previous = indices[0]
        for i in indices[1:]:
            if i-previous>maximumIntervalSizePlusOne:
                break
            previous = i
        else:
            yield(tuple(data[i] for i in indices))

I'm working in python 3.

Edit: Here's my latest attempt. Any comments?

def combinationsWithMaximumCombinedIntervals2(data, combinationWidth, maximumCombinedIntervals):

    windowWidth = combinationWidth + maximumCombinedIntervals

    combinations = []

    for startingIndex in range(len(data)-windowWidth+1):
        for indices in itertools.combinations(range(startingIndex, startingIndex+windowWidth), combinationWidth):
            if not indices in combinations:
                yield(tuple(data[j] for j in indices))
                combinations.append(indices)


texts:
I have implemented a solution to this Cracking the Coding Interview question:

Write a method to replace all spaces in a string with %20.
You may assume that the string has sufficient space at the end of the string to hold the additional characters,
and that you are given the true length of the string.
USE character array to perform this operation in place.

public static String conversion(String str, int length){

    char[] strChars = str.toCharArray();
    int numSpaces = 0;

    for(int i = 0; i < length; i++){
        if(strChars[i] == ' ')
            numSpaces++;
    }

    int newLength = length + 2 * numSpaces;
    char[] newChars = new char[newLength];

    for(int i = length - 1; i >= 0; i--){
        char c = strChars[i];
        if(c != ' '){
            newChars[i + 2 * numSpaces] = c;
        }
        else{
            newChars[i + 2 * numSpaces] = '0';
            newChars[i + 2 * numSpaces - 1] = '2';
            newChars[i + 2 * numSpaces - 2] = '%';
            numSpaces--;
        }
    }
    String newString = String.valueOf(newChars);
    return newString;
}

Can anyone give me any feedback on my implementation in regards of efficiency or improvements?


texts: Can I further optimize this solution for HackerRank's “Making Candies”?

texts:
My C++ solution for HackerRank's "Making Candies" problem, reproduced below, is as optimized as I can make it and appears similar to what others say are optimal solutions. However, six of the test cases still fail due to timing out. I would be interested to know if there are any significant opportunities to optimize my code that I missed.
I'm guessing that I'm either missing some way to simplify the computation (perhaps part of it can be precomputed and stored in a lookup table?), or there's some way to compute the answer without using a loop.
std::ios::sync_with_stdio(false);

long m, w, p, n;

std::cin >> m >> w >> p >> n;

for (long candies = 0, passes = 0, total = LONG_MAX; ; ++passes) {
    const auto production = __int128{m} * w;

    const long goal = n - candies;

    const long passes_needed = goal/production + !!(goal%production);

    const long subtotal = passes + passes_needed;

    if (passes_needed <= 2) {
        std::cout << subtotal;
        return 0;
    }

    if (total < subtotal) {
        std::cout << total;
        return 0;
    }

    total = subtotal;

    candies += production;

    if (candies >= p) {
        const auto d = std::div(candies, p);

        long budget = d.quot; candies = d.rem;

        const long diff = w - m;

        if (diff < 0) {
            const long w_hired = std::min(budget, -diff);

            budget -= w_hired;
            w += w_hired;
        } else if (diff > 0) {
            const long m_purchased = std::min(budget, diff);

            budget -= m_purchased;
            m += m_purchased;
        }

        const long half = budget >> 1;

        m += half + (budget & 1);
        w += half;
    }
}


texts:
Given a sorted array consisting 0’s and 1’s. The task is to find the index of first ‘1’ in the given array. I submitted the below code in geeks for geeks and the execution time is 5.77. Need help in optimizing the below code.
class FindIndex {
    public static void main (String[] args) {
        Scanner scanner = new Scanner(System.in);
        int noOfTestCase = scanner.nextInt();

        while (noOfTestCase-- > 0) {
            int n = scanner.nextInt();
            int[] array = new int[n];
            int index = -1;
            for (int i = 0 ; i < n ; i++) {
                array[i] = scanner.nextInt();
                if (array[i] == 1 && index == -1) {
                    index = i;
                }
            }
            System.out.println(index);
        }
    }
}

Source


texts: Sum(), ForEach() with Lambda in a hierarchical List Collection

texts:
I have to list the number of documents related to items in a hierarchical tree.

The specification states:
The tree will only ever be 2 levels deep.
The higher level items will list not only the number of documents in it's folder, but also the total count of documents in the child folders.   They want this total to include the documents in the current folder.

I've developed the solution below, it works, however it just seems complicated, hard to maintain and probably not the most efficient way to do this.  Also, if the tree is ever more than 2 levels deep, this will fail.

class Item
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public int DocumentCount { get; set; }
    public int ChildItemCount { get; set; }
    public int ChildCount { get; set; }
}

static class Program
{
    static void Main()
    {
        var items = new List<Item>
        {
            new Item {Id = 1, ParentId = 0},
            new Item {Id = 2, ParentId = 1},
            new Item {Id = 3, ParentId = 1},
            new Item {Id = 4, ParentId = 2},
            new Item {Id = 5, ParentId = 2},
            new Item {Id = 6, ParentId = 3},
            new Item {Id = 7, ParentId = 3},
            new Item {Id = 8, ParentId = 3}
        };
        // setup
        var rnd = new Random();
        items.ForEach(c => c.DocumentCount = rnd.Next(1, 10));

        // act
        items.ForEach(z => z.ChildCount = items.Count(x => x.ParentId == z.Id));
        items.ForEach(z => z.ChildItemCount = items.Where(x => x.ParentId == z.Id).Sum(y => y.DocumentCount) + z.DocumentCount);
        items.Where(k => k.ParentId == 0).ToList().ForEach(z => z.ChildItemCount = items.Where(x => x.ParentId == z.Id).Sum(y => y.ChildItemCount) + z.DocumentCount);

        // output
        items.ForEach(i => Console.WriteLine("Id: {0}, ParentId: {1}, DocumentCount: {2}, ChildCount: {3}, ChildItemCount: {4}", i.Id, i.ParentId, i.DocumentCount,i.ChildCount, i.ChildItemCount));
        Console.ReadKey();
    }
}

This gives the output below which is technically correct and meets the spec, but I just feel the solution is not the best solution.  Can anyone think of a better way to do this?

Id: 1, ParentId: 0, DocumentCount: 8, ChildCount: 2, ChildItemCount: 46
Id: 2, ParentId: 1, DocumentCount: 7, ChildCount: 2, ChildItemCount: 16
Id: 3, ParentId: 1, DocumentCount: 8, ChildCount: 3, ChildItemCount: 22
Id: 4, ParentId: 2, DocumentCount: 2, ChildCount: 0, ChildItemCount: 2
Id: 5, ParentId: 2, DocumentCount: 7, ChildCount: 0, ChildItemCount: 7
Id: 6, ParentId: 3, DocumentCount: 9, ChildCount: 0, ChildItemCount: 9
Id: 7, ParentId: 3, DocumentCount: 1, ChildCount: 0, ChildItemCount: 1
Id: 8, ParentId: 3, DocumentCount: 4, ChildCount: 0, ChildItemCount: 4


texts: Rewriting this function to use `promises` instead of `async: false`

texts:
Using parse.com's javascript API, I would like to get a variable number or images from img tags on a page and save those images in the currently logged in user's user object.

To my knowledge, parse cannot store image files directly from a url so I am using ajax to send each url to a php page that converts it and returns a base64 encoded string

Of course, left unchecked, the code would continue to run and save the user object before the php page returns the encoded images.

As a quick and dirty solution I set async: false which does work but of course give the warning: synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

How can I re-write the below to use promises instead of async: false?

Or, should I gather up all of the image urls, send them in one ajax call, encode each, send them all back, and move the save user code into the success function of the ajax call?

function accountCreation(){

        var user = Parse.User.current(); // get the currently logged in user object

        // loop through each image element
        $('.images').each(function(index, element) {
              // first we'll need to get the image source
              var src = $(element).attr('src');
              // alone, the source is just a url and not of much use to us
              // we'll need to take the source and create a base64 encoded string from it
              // we'll use an ajax call to a small php script (shown below) to do this
              // it might be better to gather up each src url and send them all in one ajax call??
              var encodedImg;
              try {
                $.ajax({
                   type: "POST",
                   url: "encodeImgToBase64.php", // you may need to adjust this path depending on where you store the file in relation to this file
                   data: 'url='+src,
                   success: function(data){
                     encodedImg = data; // encodedImg is now a base64 encoded string
                     // if I did send all the image urls at once and return all the encoded strings in one response, I guess I could just move the rest of the below code into this success function and be done with it
                   },
                   async: false
                   // note the use of `async: false` here
                   // this works but gives the warning:
                   // synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
                   // I know I should be using a promise here but Im not sure how to incorporate it
                 });
                var file = new Parse.File("photo.jpg", { base64: encodedImg }); // this part actually saves the image file to parse
                user.set("image"+index,file); // set this image to the corosponding column on our object
              } catch (e) {
                console.log('failed to create file, src= '+src+', encoded img='+encodedImg)
              }
        });
        // save the user object
        user.save(null,{
          success: function(user) {
              // do success stuff...
          },
          error: function(user, error) {
              // do fail stuff...
          }
        });
 }

Here is the php code from encodeImgToBase64.php

<?php
if (isset($_POST['url']) ){
    echo base64_encode(file_get_contents($_POST['url']));
}else{
    echo 'Error: No image to encode';
}
?>


texts:
Delete all matching ID
Insert new data

function add_date($id,$date) {

mysql_query("DELETE FROM wp_opening_date WHERE Id='$id'");
$dates = explode(",",$date);
foreach ($dates as $date) {
    $date = explode("/",$date);
    $d    = $date[0];
    $m    = $date[1];
    $y    = $date[2];
    mysql_query("INSERT INTO wp_opening_date (Id, D, M, Y) VALUES ('$id','$d', '$m', '$y')");
}
mysql_close();

}

And i using function like this

$id = '277';
$dates = '01/10/2012,28/11/2012,27/11/2012,29/11/2012';
add_date($id,$dates);

Review my code + idea pls

The idea i will searching Ids by month or year or date


texts: Recursive function refactoring help: occurrences of char in string starting at ith char

texts:
Just getting into functional programming and F# with the most appropriately titled Functional Programming Using F#. I wrote the following function definition for problem 2.4 but I'm thinking there's most likely a more elegant and/or idiomatic solution:

let rec occurrencesFromIth =
    let bool2int x = if x then 1 else 0
    function
    | str:string, i, _ when i >= str.Length -> 0
    | str, i, ch ->
        isIthChar (str,i,ch ) |> bool2int |> (+) (occurrencesFromIth (str,i+1,ch ))

isIthChar is defined as:

let isIthChar ( str:string, i, ch ) = str.[i] = ch

The actual problem description is:

  Declare the F# function occFromIth:

  string * int * char -> int where
  occFromIth(str,i,ch) = the number of occurrences of character ch in positions j in the string str with j >= i.

  Hint: the value should be 0 for i >= size str.


texts:
I am trying to write a method that takes in a String and returns an Object. The catch is I want to parse it to one of a few different data-types, and if that fails, return the original String. I currently have the code below. Is this the best way to handle what I want or is there something obvious that I'm missing?

private static Object tryParse(String str) {
    try {
        return Long.parseLong(str);
    } catch (NumberFormatException ex1) {
        try {
            return Double.parseDouble(str);
        } catch (NumberFormatException ex2) {
            return str;
        }
    }
}

EDIT: I made a tweak that I think should improve performance a bit since I only need to check for longs, doubles, and Strings.

private static Object tryParse(String str) {
    try {
        Double d = Double.parseDouble(str);
        if (d % 1 == 0) {
            return d.longValue();
        }
        return d;
    } catch (NumberFormatException ex1) {
        return str;
    }
}


texts: Represent json file with a set of different data members to a C++ class

texts:
I want to parse a json file, where some elements are common each time while others are different based on a type.
For example a message json:

{
    "title": string,
    "body": string,
    "type": int (0 for email, 1 for sms, 2 for terminal)
    "typeProperties": {
        // Different based on type value
    }
}

I ended up to the following code to represent the json object:

#include <string>
#include <vector>
#include <iostream>

class Message {
    public:
        int id;
        std::string title;
        std::string body;
        int type; // 0 - Email, 1 - SMS, 2 - Terminal
};

class Email : public Message {
    public:
        std::string emailRecipients;
        std::string emailCC;
};
class Sms : public Message {
    public:
        std::string  phoneNumber;
};
class Terminal : public Message {
    public:
        int terminalId;
};

std::vector<Message*> list_msg;

int main(int argc, char** argv) {
    Email mail;
    mail.id = 1;
    mail.title = "title1";
    mail.body = "body1";
    mail.type = 0;
    mail.emailRecipients = "text1";
    mail.emailCC = "text2";

    list_msg.push_back(&mail);

    Terminal tms;
    tms.id = 2;
    tms.title = "title2";
    tms.body = "body2";
    tms.type = 1;
    tms.terminalId = 123;

    list_msg.push_back(&tms);

    for (auto m : list_msg) {
        std::cout << "id: " << m->id << ", type: " << m->type << std::endl;

        if (m->type == 0) {
            Email *tmp = static_cast<Email*>(m);
            std::cout << ">>>> recipient: "  << tmp->emailRecipients << ", cc: " << tmp->emailCC << std::endl;
        } else if (m->type == 1) {
            Terminal *tmp = static_cast<Terminal*>(m);
            std::cout << ">>>> terminalId: "  << tmp->terminalId << std::endl;
        }
    }
}

Questions:

Is the above code correct?
From performance perspective, can this be optimized?
If I don't use inheritance and have one class Message with a boost::variant member - what are the pros and cons of this approach?


texts: Using a MutationObserver to reformat numbers in the user's locale

texts:
I mostly just want to make sure I've understood the specs correctly with this code, but here goes:

var nums = document.getElementsByTagName('x-number');
var observer = new MutationObserver(replaceNumerics);
var config = { childList: true, subtree: true };
observer.observe(document.body, config);
replaceNumerics(); // initial load

function replaceNumerics() {
    var l = nums.length, i, span;
    for( i=l-1; i>=0; i--) { // node list is live so iterate backwards
        span = document.createElement('span');
        span.classList.add("x-number");
        span.textContent = parseFloat(nums[i].textContent).toLocaleString();
        nums[i].parentNode.replaceChild(span,nums[i]);
    }
}

The idea is to have a custom <x-number> tag that contains... a number, obviously. JavaScript will detect these tags, parse out the number, then render it according to the user's locale. I'm planning to do a similar thing for dates, which will be especially useful since <input type="date" /> already uses the user's locale.

My biggest concern is I think this will result in an infinite loop, as the replaceChild call will fire the MutationObserver again... but if I understand the spec correctly, this second firing will only happen if and when all <x-number> elements have been replaced (as opposed to the earlier DOMSubtreeModified event which would fire immediately), at which point there would be no more <x-number> elements to replace and the loop would end.

Honestly this is all very unfamiliar territory to me, but I believe this should work fine... But I figured I'd subject it to public opinion before going any further with it.


texts:
I want to build a grid and I have 2 concepts: Grid which is consist of Cell.

Grid class is:

var Grid = function (rows, columns, cellInit) {
    var canvas = create_canvas();
    this.context = canvas.getContext('2d');

    this.matrix = new Array(rows);
    for (var x = 0; x < rows; x+=1) {
        this.matrix[x] = new Array(columns);
        for (var y = 0; y < columns; y+=1) {
            this.matrix[x][y] = new Cell(x, y, cellInit(), this.context);
        }
    }
};

Cell class is:

var Cell = function (x, y, value, context) {
    this.x = x;
    this.y = y;
    this.rectX = s.cell_width * this.x + s.pad;
    this.rectY = s.cell_height * this.y + s.pad;
    this.value = value;
    this.context = context;
};

Also I have fill method for Cell:

Cell.prototype.fill = function(type) {
    this.context.fillStyle = s.colors[type];
    this.context.fillRect(this.rectX, this.rectY, s.rect_width, s.rect_height);
    return this;
}

And actually I have 2 questions about this code:

Looks like that Grid and Cell should have parent-child relationship. Is it normal that I'm creating child objects at parent class?
I need somehow to give access to context var from Cell class without passing it via constructor. I had tried to play with prototypes but can't figure out how to do that.


texts:
I was attempting to solve this problem

  Given a char array representing tasks CPU need to do. It contains
  capital letters A to Z where different letters represent different
  tasks.Tasks could be done without original order. Each task could be
  done in one interval. For each interval, CPU could finish one task or
  just be idle.

  However, there is a non-negative cooling interval n that means between
  two same tasks, there must be at least n intervals that CPU are doing
  different tasks or just be idle.

  You need to return the least number of intervals the CPU will take to
  finish all the given tasks.

  Example 1: Input: tasks = ["A","A","A","B","B","B"], n = 2

  Output: 8

  Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

The greedy criteria I came up with is, for scheduling a particular task optimally with minimum empty slots we pick the highest occurring task and maintain maximum number of distinct tasks at each stage.

Algoritm :

Load the task by it's occurrence in a queue
While the number of distinct tasks is greater than the cool period we pick the cool number of tasks with highest occurrence and decrease it by 1.
If the number of distinct tasks is less that the cool period then we multiply cool period with the highest occurrence of the task.

The code is below.

template<typename T> int CountLastTask(T& queue, int n)
{
    int count = 0;
    while(!queue.empty() && queue.top().first == n) {
        ++count;
        queue.pop();
    }
    return count;
}

struct compare
{
    bool operator()(const pair<int, char> left, const pair<int, char> right)
    {
        return left.first < right.first;
    }
};
int leastInterval(vector<char>& input, int cool)
{
    map<char, int> values;
    for(auto c : input)
    {
        values[c] += 1;
    }
    int answer = 0;
    priority_queue<pair<int, char>, vector<pair<int, char>>, compare> queue;
    for(auto c: values)
    {
        queue.push({c.second, c.first});
    }
    while(queue.size() > 0)
    {
        auto top = queue.top();

        if(queue.size() < cool + 1)
        {
            int last_task = CountLastTask(queue, top.first);
            answer += ((top.first - 1) * (cool + 1)) + last_task;
            return answer;
        }
        int index = 0;
        vector<pair<int, int>> history;
        while(index < cool + 1)
        {
            top = queue.top();
            if(top.first > 1)
            {
                history.push_back({top.first -1, top.second});
            }
            queue.pop();
            ++index;
        }
        for(auto it : history)
        {
            queue.push(it);
        }
        answer += cool + 1;
    }
    return answer;
}

I am not sure if my solution uses the right data structure in the correct way. As inserting back into the queue requires me to store the pop-ed values in an temporary array and then insert it back.

Could you review this code for the right usage of data structures.


texts:
I am implementing a generic repository pattern. I have done this quite a few times now but every time I do it there is something bugging me.

If I have a database design like below. (All the tables relate to one another.)
And I make a call like the following:

public IEnumerable<Domain> GetRealEstate()
{
     return _repository.GetAll();
}

I can get all the models from just that one call (The wonders of EF). The thing that bugs me is the fact that I have to say Domain in the method call, from the domain entity I will get all the relevant entity (Lazy loading) Companies etc. etc. It just feels wrong to use domain entity to get all the companies etc. etc. The repo pattern that I am using is a straight forward one.

Is there a better way of writing the methods so that it does not look so weird?

Controller
RealEstateController

[RoutePrefix("api/realestate")]
    public class RealEstateController : ApiController
    {
        private readonly IRealEstateService _service;

        public RealEstateController(IRealEstateService service)
        {
            _service = service;
        }

        [Route("")]
        public Task<Domain> GetRealEstates()
        {
            var collection =  _service.GetRealEstate();
            return null;
        }

        [Route("{domainName}")]
        public Task<Domain> GetRealEstate(string domainName)
        {

        }
    }

Service

public class RealEstateService : IRealEstateService
    {
        private readonly IRealEstateRepository _repository;
        public RealEstateService(IRealEstateRepository repository)
        {
            _repository = repository;
        }
        public IEnumerable<Domain> GetRealEstate()
        {
            return _repository.GetAll();
        }
    }


texts:
I have a JavaScript function that takes in a user number (total amount placed on a betting table in denominations of 50) and returns an Array of the optimum chips (lowest # required) to form each stack.

My function works, the correct array for each value tested is output - but since this should be running on the client browser with a fast response time for smooth UI I feel like the code is not optimised.

Is there a better, more efficient (+ mathematically solid) way of computing the same output?

Any suggestions would be appreciated.

//number will be validated before running through function to make sure it has a factor of 50.

function chipStack(number) {
    var k = 0; //1k chip
    var f = 0; //500 chip
    var t = 0; //300 chip
    var o = 0; //100 chip
    var fi = 0; // 50 chip

    k = Math.floor(number / 1000);
    var number2 = number % 1000

    if (number2 === 0) {
        return [k, f, t, o, fi];
    } else {
        f = Math.floor(number2 / 500)
        var number3 = number2 % 500
    }

    if (number3 === 0) {
        return [k, f, t, o, fi];
    } else {
        t = Math.floor(number3 / 300)
        var number4 = number3 % 300
    }

    if (number4 === 0) {
        return [k, f, t, o, fi];
    } else {
        o = Math.floor(number4 / 100)
        var number5 = number4 % 100
    }

    if (number5 === 0) {
        return [k, f, t, o, fi];
    } else {
        fi = Math.floor(number5 / 50)
        var number6 = number5 % 50
    }

    if (number6 === 0) {
        return [k, f, t, o, fi];
    } else {
        return "Something isn't right " + number6;
    }
}


texts:
This is an exercise to use C++, Cevelop IDE & libtidy rather than the HTML Tidy command line tool. The program just reads from standarg input, processes the contents with HTML Tidy then puts the cleaned up version to standard out. Errors and diagnostics go to standard error. Function tidyit takes a std::string and returns one with error messages going to stderr while main handles the standard I/O.

I am using the most current C++17 with no concerns for older versions. The version of Cevelop IDE is 1.7.1. HTML Tidy provides both a command line tool and a C library, libtidy. The code is based upon the C code in the Sample Program.

I am looking for improvements given it is in C++ rather than the original in C.

// tidyit.cpp
#include <sstream>
#include <iostream>
#include <string>

const std::string tidyit(const std::string a_input);           // Change to auto in cevelop 1.8.

int main(int argc, char **argv) {
   std::stringstream input;
   input << std::cin.rdbuf();
   std::cout << tidyit(input.str());
   }

#include <tidy/tidy.h>
#include <tidy/buffio.h>

bool is_severe_error(int a_code){return (a_code<0);}           // Change to auto in cevelop 1.8.

const std::string tidyit(const std::string a_input) {          // Change to auto in cevelop 1.8.
   TidyBuffer errbuf = {0}, outbuf = {0};
   TidyDoc tdoc = tidyCreate();
   tidyOptSetInt(tdoc, TidyIndentContent, yes);
   tidyOptSetBool(tdoc, TidyXhtmlOut, yes);
   tidyOptSetBool(tdoc, TidyForceOutput,yes);
   int rc{-1};                                                 // Change to auto in cevelop 1.8.
   if (is_severe_error(rc=tidySetErrorBuffer(tdoc, &errbuf))
         || is_severe_error(rc=tidyParseString(tdoc, a_input.c_str()))
         || is_severe_error(rc=tidyCleanAndRepair(tdoc))
         || is_severe_error(rc=tidyRunDiagnostics(tdoc))
         || is_severe_error(rc=tidySaveBuffer(tdoc,&outbuf))){
      std::cerr << "tidyit-A severe error (" << rc << ") occurred.\n";
      }
   else {
      if(errbuf.bp)
         std::cerr << "tidyit-Diagnostics:\n\n" << errbuf.bp << "\n";
      }
   const std::string outstr{(char*)(outbuf.bp)};
   tidyBufFree(&outbuf);
   tidyBufFree(&errbuf);
   tidyRelease(tdoc);
   return outstr;
   }

Cevelop C++ IDE

  Version: 1.7.1-201704211123

Compiler info

  Command: clang++-4.0

  All options: -std=c++1z -O0 -g3 -Wall -c -fmessage-length=0
  -Wno-attributes

Library info

  Libraries: tidy

Updated code available at: CodeReview - HTML Tidy Sample Program in C++17 (pastebin)


texts: Read CSV files and find the same values on the specific columns

texts:
I created a simple command line application to read CSV files in a specific folder and find the same values on the specify column which exists on all files. (Here's the complete source code.)

Here's the core of the logic:

func csvReader(inputColumn, fileLocation string) {
    startTime := time.Now()

    // get all the files from the specific folder
    files, err := ioutil.ReadDir(fileLocation)
    if err != nil {
        log.Fatal(err)
    }

    noColumn := make(chan struct{}, len(files))
    results := make(chan map[string]bool, len(files))

    // reading all the files from dir concurrently
    for _, file := range files {
        wg.Add(1)
        // and read it concurrently to get the data from specific column
        go func(file os.FileInfo) {
            defer wg.Done()
            f, err := os.Open(dir + file.Name())
            if err != nil {
                log.Fatal(err)
            }
            datas, ok := readFile(inputColumn, f)

            if !ok {
                noColumn <- struct{}{}
                return
            }

            results <- datas

        }(file)

    }

    wg.Wait()

    // check if we got the column or not
    select {
    case <-noColumn:
        fmt.Printf("The column name = %v doesnt exist\n", inputColumn)
        return

    default: // do nothing and continue
    }

    close(results)
    close(noColumn)

    //receive results and determine which size datas is the smallest
    theSameValue := getSameValues(&results)

    fmt.Printf("final result = %+v\n", theSameValue)
    fmt.Printf("final result size = %+v\n", len(theSameValue))
    fmt.Printf("time consume = %+v\n", time.Since(startTime).Seconds())

}

The function is finding the files on specified fileLocation and then concurrently reading the file to get the values from the given column inputColumn, and passing the values to channel to save the results from reading the CSV files.

The channel results := make(chan []map[string]bool) is passed to a function the begin searching the values that exist on all files.

theSameValue := getSameValues(&results)

Notice that the function getSameValues() receives the pointer of results. I did this because I don't' want the results channel to be copied to the functions argument which takes resource of memory.

And here is the getSameValues() function:

// getting the same value from all the datas
func getSameValues(results *chan map[string]bool) []string {
    var datas = make([]map[string]bool, len(*results))
    minIndex := -1
    minSize := int(MaxUint >> 1)
    i := 0
    for values := range *results {
        sizeValues := len(values)
        if sizeValues < minSize && sizeValues > 0 {
            minSize = sizeValues
            minIndex = i
        }
        datas[i] = values
        i++
    }

    // getting the same value from all the datas
    var theSameValue []string
    for value, _ := range datas[minIndex] {
        isExistAll := false
        for _, data := range datas {
            if data[value] {
                isExistAll = true
            } else {
                isExistAll = false
            }
        }

        if isExistAll {
            theSameValue = append(theSameValue, value)
        }
    }

    return theSameValue
}

Hopefully this would help others and if you find something that can be improved please give some suggestion.


texts:
Inspired by this article about natural numbers from first principles in swift I implemented integers from scratch in Haskell.

Besides obviously being extremely inefficient, is this code idiomatic Haskell?

import Data.List
import GHC.Real

data ℤ = Pred ℤ | Zero | Succ ℤ

toNat = toEnum :: Int -> ℤ
fromNat = fromEnum :: ℤ -> Int

toInteger' :: ℤ -> Integer
toInteger' Zero = 0
toInteger' (Succ n) = toInteger' n + 1
toInteger' (Pred n) = toInteger' n - 1

instance Show ℤ where

  show = ((++) "Nat: ") . show . toInteger'

data SimpleNat = MinusOne | One deriving (Eq, Ord, Show)

toList :: ℤ -> [SimpleNat]
toList Zero = []
toList (Succ n) = One : toList n
toList (Pred n) = MinusOne : toList n

fromList :: [SimpleNat] -> ℤ
fromList [] = Zero
fromList (One:xs) = Succ (fromList xs)
fromList (MinusOne:xs) = Pred (fromList xs)

normaliseList :: [SimpleNat] -> [SimpleNat]
normaliseList xs = normaliseSorted $ sort xs
                   where normaliseSorted xs = map fst filtered
                         filtered = filter (uncurry (==)) $ zip xs (reverse xs)

normalise :: ℤ -> ℤ
normalise = fromList . normaliseList . toList

instance Enum ℤ where

  succ (Pred n) = n
  succ n = Succ n

  pred (Succ n) = n
  pred n = Pred n

  toEnum n | n < 0 = Pred $ toEnum (n+1)
           | n > 0 = Succ $ toEnum (n-1)
           | otherwise = Zero

  fromEnum Zero = 0
  fromEnum (Succ n) = fromEnum n + 1
  fromEnum (Pred n) = fromEnum n - 1

instance Num ℤ where

  Zero + n = n
  n + Zero = n
  (Succ n) + m = Succ (n + m)
  (Pred n) + m = Pred (n + m)

  abs n = abs' $ normalise n
          where abs' (Pred n) = Succ (abs' n)
                abs' n = n

  signum n = signum' $ normalise n
             where signum' Zero = Zero
                   signum' (Succ n) = Succ Zero
                   signum' (Pred n) = Pred Zero

  negate n = negate' $ normalise n
             where negate' Zero = Zero
                   negate' (Succ n) = Pred (negate' n)
                   negate' (Pred n) = Succ (negate' n)

  fromInteger n | n < 0 = Pred $ fromInteger (n+1)
                | n > 0 = Succ $ fromInteger (n-1)
                | otherwise = Zero

  Zero * _ = Zero
  _ * Zero = Zero
  (Succ n) * m = n*m + m
  (Pred n) * m = n*m - m

instance Eq ℤ where

  n == m = normalise n `eq` normalise m
           where Zero `eq` Zero = True
                 (Succ n) `eq` (Succ m) = n `eq` m
                 (Pred n) `eq` (Pred m) = n `eq` m
                 _ `eq` _ = False

instance Ord ℤ where

  a `compare` b = normalise a `comp` normalise b
                  where Zero `comp` Zero = EQ
                        Zero `comp` (Succ _) = LT
                        Zero `comp` (Pred _) = GT
                        (Succ _) `comp` Zero = GT
                        (Succ _) `comp` (Pred _) = GT
                        (Pred _) `comp` Zero = LT
                        (Pred _) `comp` (Succ _) = LT
                        (Succ n) `comp` (Succ m) = n `comp` m
                        (Pred n) `comp` (Pred m) = n `comp` m

instance Real ℤ where

  toRational n = toInteger' n % 1

instance Integral ℤ where

  toInteger = toInteger'

  quotRem _ Zero = error "divide by zero"
  quotRem Zero _ = (Zero, Zero)
  quotRem n d | n == d = (Succ Zero,0)
              | n < d = (Zero, n)
              | otherwise = (Succ (fst foo), snd foo)
                          where foo = (n-d) `quotRem` d


texts:
I am relatively new to LINQ queries as I normally just use plain SQL to get my data back but i am changing for the good - Anyway obviously with SQL you pass in parameters so you do not get any SQL injections etc. Now the LINQ query I have written I think is safe but I am thinking it may be able to done a little easier and more efficient.

So I am passing in my data in the query from the model which is being sent from the view and my tables columns are being called from the ProjectLinqDataContext class. Is this safe? is there anything which I am doing which is not best practice.

 var context = new ProjectLinqDataContext();
 var user = from y in context.Customers
               where y.CustomerUsername == model.Email && y.CustomerPassword == model.Password
               select y;