texts: Count number of ways that sequences contain at least one of the given subsequences

texts:
Peter loves dices and some special numbers. Therefore he thrown dice n times and concatenate the numbers. Compute the probability that if he throws 6 to 27 seven times dice and concatenate the numbers, the sequence contains at least one subsequence of number sequence

1, 2, 3, 4, 5, 6
1, 1, 2, 2, 3, 3
4, 4, 5, 5, 6, 6
1, 1, 1, 2, 2, 2
3, 3, 3, 4, 4, 4
5, 5, 5, 6, 6, 6
1, 1, 1, 1, 1, 1
2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3
4, 4, 4, 4, 4, 4
5, 5, 5, 5, 5, 5
6, 6, 6, 6, 6, 6

I saw that there is a way to do it by Markov chains. Is there any way to write the code more elegantly, like using inclusion-exclusion principle?

My code that uses Markov chains:

from sets import Set

def matMul(a,b):
    zip_b = zip(*b)
    return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b))
             for col_b in zip_b] for row_a in a]

"""Matrix power for positive integer power"""
def matPow(a, n):
    if n<1: return None
    if n==1: return a

    if n%2==0:
        aToHalfN = matPow(a, n/2)
        return matMul(aToHalfN, aToHalfN)
    else:
        return matMul(matPow(a, n-1), a)

def getProbSomeSeqIsSub(symbols, seqs, n, exactRational=False):

    def cleanSeqs(arr):
        ret = list(arr)
        changed = True
        while changed:
            changed = False
            for x in ret:
                hadADelete = False
                for y in ret:
                    if x!=y and y in x:
                        ret.remove(x)
                        hadADelete = True
                        changed = True
                        break
                if hadADelete:
                    break
        return ret

    seqs = cleanSeqs(seqs)

    symbolsLen = len(symbols)
    prefixes = Set([""]) #first state is '' empty start state

    for seq in seqs:
        for i in xrange(1, len(seq)):
            prefixes.add(seq[0:i])

    prefixes = sorted(list(prefixes))
    M = len(prefixes)+1 #last state (index M-1) is the absorbing one

    def findFallsBackTo(appendedRun):
        for i in xrange(0,len(appendedRun)):
            if appendedRun[i:] in prefixes:
                return appendedRun[i:]
        return ""

    def incrState(stateDict, state):
        if state in stateDict:
            stateDict[state] += 1
        else:
            stateDict[state] = 1

    def someEndInSeqs(s):
        for i in xrange(len(s)):
            if s[i:] in seqs: return True
        return False

    def getToStateVals(stateStr):
        ret = {}
        for i in symbols:
            stPlusI = stateStr+str(i)
            if someEndInSeqs(stPlusI):
                incrState(ret, M-1)
            elif stPlusI in prefixes:
                incrState( ret, prefixes.index(stPlusI) )
            else:
                fallsToPrefix = findFallsBackTo(stPlusI)
                incrState(ret, prefixes.index(fallsToPrefix))
        return ret

    a = []
    aInts = []
    for i in xrange(M):
        a += [[]]
        aInts += [[]]
        for j in xrange(M):
            a[i] += [0]
            aInts[i] += [0]

    for i in xrange(M-1):
        ps = getToStateVals(prefixes[i])
        for toI in ps:
            a[toI][i] = float(ps[toI])/symbolsLen
            aInts[toI][i] = ps[toI]

    a[M-1][M-1] = 1.0
    aInts[M-1][M-1] = symbolsLen

    if exactRational: return str(matPow(aInts, n)[M-1][0])+" / "+str(symbolsLen**n)
    else: return matPow(a, n)[M-1][0]

for i in range(6,28):
 a = getProbSomeSeqIsSub([1,2,3,4,5,6], ["123456", "112233", "445566",  "111222", "333444", '555666', '111111', '222222', '333333', '444444',  '555555', '666666'], i, True)

 b = a.split("/")
 oso = int(b[0])
 nimi = int(b[1])
 print(str(i)+ " "+str(oso*6**i/nimi))


texts: Ruby if block refactor from new synthax needed

texts:
I have this, I guess, new Ruby syntax in my method but Rubocop are warning me that the second last line is too long. Could you please help me to refactor this method?

def show
  identification_document = IdentificationDocument.find(params[:id])
  authorize identification_document
  return unless identification_document

  #this line below is to too long
  document = params[:size] == 'resized' ? identification_document.id_document_resized : identification_document.id_document
  send_data(document.file.read, filename: identification_document.file_name)
end


texts:
The following was an exercise for me to try to understand how state can be passed down the stack without immutability.

I'm used to writing java code and this is just a way for me to understand.

I've made no attempt to make the computer play a clever game. It just selects a random move. Player is always X. Player always starts first. Moves are made by entering the 0 based index of the grid

 0 | 1 | 2
---+---+---
 3 | 4 | 5
-----------
 6 | 7 | 8

However I found it difficult to write and find the piece that calculates if there is any winning line very messy to read.

import scala.annotation.tailrec
import scala.io.StdIn
import scala.util.{Success, Failure, Random,Try}

/**
 * A simple expirement in tic tac toe the idea
 * is to try to have something that contains state
 * without having vars.
 */
object ttt extends App {

  object Player extends Enumeration {
    val X, O = Value
  }

  val grid: List[Option[Player.Value]] =
    None :: None :: None ::
      None :: None :: None ::
      None :: None :: None ::
      Nil

  val winningLines = List(0, 1, 2) ::
    List(3, 4, 5) ::
    List(6, 7, 8) ::
    List(0, 3, 6) ::
    List(1, 4, 7) ::
    List(2, 5, 8) ::
    List(1, 4, 8) ::
    List(2, 4, 6) :: Nil
  @tailrec
  def play(next: Player.Value, grid: List[Option[Player.Value]]): String = {
    val sliceHorizontal = (g:List[Option[Player.Value]]) =>
      g.slice(0, 3) ::
      g.slice(3, 6) ::
      g.slice(6, 9) :: Nil

    val toPrint = (p: Option[Player.Value]) => if (p.isEmpty) "   " else " " + p.get.toString() + " "
    val gridPrint = (g: List[List[Option[Player.Value]]]) => g.map(_.map(toPrint).mkString("|")).mkString("\n---+---+---\n")+"\n\n"
    println(gridPrint(sliceHorizontal(grid)))

    val emptyCells = (g: List[Option[Any]]) => g.zipWithIndex.
      filter(_._1.isEmpty).
      map(_._2)

    lazy val randomCell = Random.shuffle(emptyCells(grid)).head

    def playerChoice(g: List[Option[Player.Value]]): Int = {
      print("Please enter selection, ")
      val result = Try(StdIn.readInt());
      result match {
        case Success(v) => if (emptyCells(g).contains(v)) v else playerChoice(g)
        case Failure(_) => playerChoice(g)
      }
    }

    if (emptyCells(grid).isEmpty) {
      "Draw"
    } else {
      val newGrid = if (next == Player.O) {
        grid.updated(randomCell, Some(Player.O))
      } else {
        grid.updated(playerChoice(grid), Some(Player.X))
      }

      def listOfDuplicates[A](x: A, length: Int): List[A] = {
        if (length < 1) Nil
        else x :: listOfDuplicates(x, length - 1)
      }

      def allEqual[A](first: A, seq: List[A]):Boolean = {
        if (seq isEmpty) true
        else if (first != seq.head) false
        else allEqual(first, seq.tail)
      }

      //Okay this is very messy not used to this
      val hasWon= (p: Player.Value) => winningLines.
        foldLeft(false)((i, s) => i || allEqual(Some(p), s.map(newGrid(_))))
      if (hasWon(Player.X)) {
        println(gridPrint(sliceHorizontal(newGrid)))
        "X Wins"
      } else if (hasWon(Player.O)) {
        println(gridPrint(sliceHorizontal(newGrid)))
        "O Wins"
      } else play(if (next == Player.O) Player.X else Player.O, newGrid)
    }
  }

  println(play(Player.X, grid))
}

How can I clean this up and make it more idiomatic? easier to read? Also for tic-tac-toe it doesn't matter much but for a large game if it wasn't tail recursive I guess I couldn't use this strategy for holding state between moves.


texts: While loop uses extra variables - can this be cleaned up?

texts:
A piece of my program allows the looping and incrementing of a targeted entity to be used in a while loop somewhere else. Here is a sample of the while loop:

while (state.World.Looping(reqComponents))
{
    TimerComponent timer = state.World.GetComponent(TimerComponent.Type);

    if (timer.IsActive)
    {
        timer.TimeLeft -= gameTime.ElapsedGameTime.TotalSeconds;

        if (timer.IsFinished)
        {
            timer.IsActive = false;
        }
    }
}

Here is the actual loop function, which increments the current entity (which is grabbed by state.World.GetComponent():

public bool Looping(ComponentType reqComponents)
{
    if (!isLooping)
    {
        isLooping = true;
        CurrentEntity = 0;
    }
    else if (stopLooping)
    {
        isLooping = false;
        stopLooping = false;

        return false;
    }
    else if (++CurrentEntity == EntityCount - 1)
    {
        stopLooping = true;
    }

    if (!HasComponents(reqComponents))
    {
        return Looping(reqComponents);
    }

    return true;
}

The very top part of the Looping() feels really ugly to me. Is there a better way to do this?


texts:
The idea is this: To determine whether a string is funny, create a copy of the string in reverse e.g. . Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny.

This is my Python code for the same:

def funnyString(s):
    temp = s[::-1]
    arr1,arr2 = [],[]
    for i in range(len(s)-1):
        arr1.append(abs(ord(s[i+1])-ord(s[i])))
        arr2.append(abs(ord(temp[i+1])-ord(temp[i])))
    if arr1 == arr2: return "Funny"
    else: return "Not Funny"

It works but I want to get some feedback if this is too verbose and should/can be shortened. One solution example:

acxz
bcxz

Funny
Not Funny

The same implementation in C++

string funnyString(string s) {
    string temp;
    temp = s;
    vector<int> arr1, arr2;
    reverse(temp.begin(), temp.end());
    for (int i = 0; i < s.length()-1; i++) {
        arr1.push_back(fabs(int(s[i + 1]) - int(s[i])));
        arr2.push_back(fabs(int(temp[i + 1]) - int(temp[i])));
}
    if (arr1 == arr2) return "Funny";
    else return "Not Funny";

}


texts:
Suppose I need to process a list of list of list of many objects, where the data usually comes from third party APIs.

For the sake of an example, lets assume we have many users, and for each user we get many days of data, and for each day you get many events. We want to process all of these objects and store in our database

I thought about some differents design patterns I could use, but I'm not sure what is considered to be the best approach, if any.

These are my thoughts:

1) Nested iterations and do the side-effect (save to database) at the lowest-level loop.

for user in users:
    for day in user.days:
        for event in day.event:
            processed_object = process_event(event)
            save_to_db(processed_object)

2) Similar to one, except that each nested iteration is 'hidden' in another method.

for user in users:
    process_user(user)

def process_user(user):
   for day in user.days:
        process_day(day)

def process_day(day):
    for event in day.events:
        process_event(event)

def process_event(event):
    save_to_db(event)

3) Return everything from deep in the nest and then do the side-effects afterwards.

def process_users(users):
    processed = []
    for user in users:
        processed.append(process_user(user))
    return processed

def process_user(user):
    processed = []
    for day in user.days:
        processed.append(process_day(day))
    return processed

def process_day(day):
    processed = []
    for event in day.events:
        processed.append(process_event)
    return processed

processed_events = process_users(users)

for event in processed_events:
    save_to_db(event)

Is there a general, agreed on approach for these type of programs, where side-effects are involved?


texts:
I'm calling the below 2 function once per Cell in a table with over 135 columns and over 200 rows (that is 134*200 = 26800 times, I'm not running the functions on the first column).

I would like to optimize the functions as much as possible.  Do you have any suggestions on how to do that, if it even possible?

this.addBodyCellFunction = function(row, index, func, params) {
    var cell = $(document.getElementById("table_row_" + row +"_col_" +index));
    cell.click(function() {
        func.apply(this, params);
    });
    cell.css("cursor", "pointer");
};

this.addBodyCellTooltip = function(row, index, text) {
    var cell = $(document.getElementById("table_row_" + row +"_col_" +index));
    cell.attr("title", text);
};


texts:
I wrote a SEDE query to list all tag wikis with a body or an excerpt under a given number of characters. I've used this to find empty wikis or wikis with very little information. The tags can be sorted by post count to make choosing which to improve easier.

This is one of the first times I've written anything in SQL, I took ideas from other queries I found and threw them together. The conditional WHERE clause is my biggest concern. It looks really messy, but I'm not sure what the best way to achieve the same effect would be.

I'm aware that it doesn't actually get wikis with a length under the given number, but under or on. I wanted 0 to mean an empty wiki as that feel more intuitive than 1. I'm not sure about this design decision, what do you think?

-- MaxBodyLength: Max body length "Set to -1 to disable"
DECLARE @max_body_length INT = ##MaxBodyLength:INT?100##;
-- MaxExcerptLength: Max excerpt length "Set to -1 to disable"
DECLARE @max_excerpt_length INT = ##MaxExcerptLength:INT?-1##;

-- Max SE post length (see http://meta.stackexchange.com/a/176447/299387)
DECLARE @LEN_MAX INT = 30000;

BEGIN
  SELECT
    t.TagName,
    t.Count AS [Post count],
    LEN(pExcerpt.body) AS [Excerpt length],
    LEN(pWiki.Body) AS [Wiki length]
  FROM Tags t
    LEFT JOIN Posts pExcerpt ON t.ExcerptPostId = pExcerpt.Id
    LEFT JOIN Posts pWiki ON t.WikiPostId = pWiki.Id
  WHERE
    LEN(pWiki.body) <= CASE
      WHEN @max_body_length >= 0 THEN
        @max_body_length
      ELSE
        @LEN_MAX
      END
    AND LEN(pExcerpt.body) <= CASE
      WHEN @max_excerpt_length >= 0 THEN
        @max_excerpt_length
      ELSE
        @LEN_MAX
      END
END


texts: A simple SDL script that creates a window

texts:
Is there possibly a way to take out the nested if statements without losing the error reports? I am just learning SDL and would like to further simplify my code so that it is readable by me when I look at in a few days.

#include <SDL.h>
#include <iostream>

int main(int argc, char *argv[]) {
    SDL_Window *window = nullptr; //the window
    SDL_Surface *windowSurface = nullptr; //will store current window surface
    SDL_Surface *imageSurface = nullptr; //will store image to be applied to the window

    //inits video
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
        std::cout << "Video Init Error: " << SDL_GetError() << std::endl;
//if error
    else { //creates window
        window = SDL_CreateWindow("Slime Runner Prelim Tests",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
        if (window == NULL)
            std::cout << "Window creation error: " << SDL_GetError() <<
std::endl; //if error
        else { // if all is good with window creation.
            //WINDOW HAS BEEN CREATED

            windowSurface = SDL_GetWindowSurface(window);

            imageSurface = SDL_LoadBMP("Images/Background.bmp");
        if (imageSurface == NULL)
                std::cout << "Image load error: " << SDL_GetError() <<
std::endl;
            else {
                SDL_BlitSurface(imageSurface, NULL, windowSurface, NULL);
                SDL_UpdateWindowSurface(window);
            }
        }//end of window creation if
    }//end of SDL_INIT_VIDEOs
    SDL_Delay(4000);
    SDL_FreeSurface(imageSurface);
    imageSurface = nullptr;
    SDL_DestroyWindow(window);
    window = nullptr;
    SDL_Quit();

    return 0;
}


texts: Optionally disabling a call-tracing decorator in Typescript

texts:
I have a Typescript decorator that traces method calls. The decorator can be applied at both the class level and method level. I want to disable the decorator in production. Is this code the most correct way to bypass the decorator?

let enabled = process.env.NODE_ENV !== "production"

export function Trace() {

    var printIn = (className: string, methodName: string, args: any[]) => {
        console.debug("=> %s.%s(" + args.map(val => "%s").join(", ") + ")", className, methodName, JSON.stringify(args));
    };

    var printOut = (className: string, methodName: string, ret: any) => {
        console.debug("<= %s.%s: %s", className, methodName, ret);
    };

    return (target: any, name?: string, descriptor?: any) => {

// This line is here is how i'm trying to bypass the decorator.

        // Don't wrap if disabled
        if (!enabled) return target

        if (descriptor) {

            // decorating a method
            let original = descriptor.value;

            descriptor.value = function (...args: any[]) {

                printIn(target.constructor.name, name, args);
                let ret = original.apply(this, args);
                printOut(target.constructor.name, name, ret);

                return ret;
            }

            return descriptor;

        } else {

            // decorating a class
    Object.getOwnPropertyNames(target.prototype).forEach((methodName: string) => {

                if (methodName === "constructor") {
                    return;
                }

                let original = target.prototype[methodName];

                if (typeof original !== "function") {
                    return;
                }

                // an arrow function can't be used while we have to preserve right 'this'
                target.prototype[methodName] = function (...args: any[]) {

                    printIn(target.name, methodName, args);
                    let ret = original.apply(this, args);
                    printOut(target.name, methodName, ret);

                    return ret;
                };
            });

            return target;
        }
    };
}


texts: Stack with "getMiddle" and "deleteMiddle" operation

texts:
Looking for code review, optimizations and best practices.

public class FindMiddleStack<T> {

    private Node<T> top;
    private Node<T> middle;
    private int size = 0;

    private static class Node<T> {
        Node<T> left;
        T item;
        Node<T> right;

        Node(Node<T> left, T item, Node<T> next) {
            this.left =  left;
            this.item = item;
            this.right = next;
        }
    }

    public void push(T item) {
        final Node<T> node = new Node<T>(null, item, top);
        if (top == null) {
            top = node;
            middle = node;
        } else {
            top.left = node;
            top = node;
        }

        size++;
        if (size % 2 == 0) {
            middle = middle.left;
        }
    }

    public T pop() {
        if (top == null) {
            throw new EmptyStackException();
        }
        T item = top.item;
        top = top.right;
        // important, to not leak references.
        if (top != null) {
            top.left = null;
        }

        if (top == null) {
            middle = null;
        }

        if (size % 2 == 0) {
            middle = middle.right;
        }

        size--;
        return item;
    }

    public T peek() {
        if (top == null) {
            throw new EmptyStackException();
        }
        return top.item;
    }

    public T getMiddle() {
        if (top == null) {
            throw new EmptyStackException();
        }
        return middle.item;
    }

    public void deleteMiddle() {
        if (top == null) {
            throw new EmptyStackException();
        }

        if (middle.left != null) {
            middle.left.right = middle.right;
        }
        if (middle.right != null) {
            middle.right.left = middle.left;
        }

        if (size % 2 == 1) {
            // deleted middle.
            middle = middle.left;
        } else {
            middle = middle.right;
        }

        if (middle == null) {
            top = null;
        }
        size--;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }
}

public class FindMiddleStackTest {

    @Test
    public void testPushPop() {
        FindMiddleStack<Integer> fm = new FindMiddleStack<Integer>();
        fm.push(10);
        fm.push(20);
        fm.push(30);
        fm.push(40);
        fm.push(50);
        fm.push(60);
        fm.push(70);
        int[] expected1 = {70, 60, 50, 40, 30, 20, 10};
        int[] actual1 = new int[7];
        int i1 = 0;
        while (!fm.isEmpty()) {
            actual1[i1++] = fm.pop();
        }
        assertTrue(Arrays.equals(expected1, actual1));
    }

    @Test
    public void testPopAndMiddle( ) {
        FindMiddleStack<Integer> fm = new FindMiddleStack<Integer>();
        fm.push(10);
        fm.push(20);
        fm.push(30);
        fm.push(40);
        fm.push(50);
        fm.push(60);
        fm.push(70);
        int[] expected2 = {40, 40, 30, 30, 20, 20, 10};
        int[] actual2 = new int[7];
        int i2 = 0;
        while (!fm.isEmpty()) {
            actual2[i2++] = fm.getMiddle();
            fm.pop();
        }
        assertTrue(Arrays.equals(expected2, actual2));
    }

    @Test
    public void testDeleteMiddleAndMiddle() {
        FindMiddleStack<Integer> fm = new FindMiddleStack<Integer>();
        fm.push(10);
        fm.push(20);
        fm.push(30);
        fm.push(40);
        fm.push(50);
        fm.push(60);
        fm.push(70);
        int[] expected3 = {40, 50, 30, 60, 20, 70, 10};
        int[] actual3 = new int[7];
        int i3 = 0;
        while (!fm.isEmpty()) {
            actual3[i3++] =  fm.getMiddle();
            fm.deleteMiddle();
        }
        assertTrue(Arrays.equals(expected3, actual3));
    }
}


texts: Refactor two jQuery filter functions into one function

texts:
I have two separate lists both sitting side by side. How can I refactor the code below to only have one filter function for both lists?

$("input.filterInput").keyup(function() {
    filter(this);
});

function filter(element) {
    var value = $(element).val();
    $(".pdfList > li").each(function (){
        if ($(this).text().indexOf(value) > -1) {
                $(this).show();
        } else {
            $(this).hide();
        }
    });
}

$("input.filterInput2").keyup(function() {
    filter2(this);
});

function filter2(element) {
    var value = $(element).val();
    $(".pdfList2 > li").each(function (){
        if ($(this).text().indexOf(value) > -1) {
                $(this).show();
        } else {
            $(this).hide();
        }
    });
}


texts:
I have the following function to replace all the occurrence of a string that matches certain token.

public string ReplaceTokenBySample(string StingValue)
{
    List<Token> tokens = GetTokenList();
    foreach (var token in tokens)
    {
        StingValue = StingValue.Replace(token.Token, token.SampleValue);
    }
    return StingValue;
}

GetTokenList(); will return

Token                   SampleValue
##Username##            John Doe
##UserEmail##           john.doe@domain.com
##UserFirstName##       John
##UserLastName##        Doe

How can I optimize this code?

Full console app code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Token
    {
        public string TokenValue { get; set; }
        public string SampleValue { get; set; }
    }
    public class Program
    {
        public List<Token>GetTokenList()
        {
            List<Token> tokens = new List<Token>
            {
                new Token(){ TokenValue = "##Username##", SampleValue="John Doe" },
                new Token(){ TokenValue = "##UserEmail##", SampleValue="john.doe@domain.com " },
                new Token(){ TokenValue = "##UserFirstName##", SampleValue="John" },
                new Token(){ TokenValue = "##UserLastName##", SampleValue="Doe"}
            };
            return tokens;
        }

        public string ReplaceTokenBySample(string StringValue)
        {
            List<Token> tokens = GetTokenList();
            foreach (var token in tokens)
            {
                StringValue = StringValue.Replace(token.TokenValue, token.SampleValue);
            }
            return StringValue;
        }

        public static void Main(string[] args)
        {
            Program obj = new Program();
            string StringValue ="Hello ##Username##! I have emailed you at ##UserEmail##. ##UserFirstName## ##UserLastName## how is you days going on. Have a good day ##Username##. ";
            Console.WriteLine(obj.ReplaceTokenBySample(StringValue));
        }
    }
}


texts:
I'm trying to understand how to bridge receiver-based events to the Reactive world.  I asked a question on SO and was pointed to a different approach.  The author of that answer (David Karnok) is extremely knowledgeable about RxJava, so I trust that his approach is a good one.

My concern is about the order things are done in the last few lines of subscribeActual.  I think I've got it right.  Here's my reasoning:

If the Disposable is disposed (i.e., the Subscription is canceled) during the call to onSubscribe, it's okay to call onNext with the last known location and potentially receive another location update when the listener is briefly subscribed because of Reactive Streams spec rule 2.8:

  A Subscriber MUST be prepared to receive one or more onNext signals after having called Subscription.cancel() . . .

If the Disposable is disposed during the call to onSubscribe, the LocationListener will be unregistered in disposeActual before it is registered, then unregistered again in subscribeActual.  Many Android APIs senselessly throw exceptions instead of simply doing nothing if you try to unregister a listener that isn't registered, but LocationManager isn't one of those.  If it were, I could put a try/catch in disposeActual.

Have I omitted anything?

public class GpsLocationObservable extends Observable<Location> {
    private final LocationManager mLocationManager;
    private final long mMinTime;
    private final float mMinDistance;

    @RequiresPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    public GpsLocationObservable(final LocationManager locationManager, final long minTime, final float minDistance) {
        Params.requireNonNull(locationManager);
        Params.requireNonNegative(minTime);
        Params.requireNonNegative(minDistance);
        mLocationManager = locationManager;
        mMinTime = minTime;
        mMinDistance = minDistance;
    }

    @Override
    protected void subscribeActual(final Observer<? super Location> observer) {
        final LocationListener listener = new LocationAdapter() {
            @Override
            public void onLocationChanged(final Location location) {
                observer.onNext(location);
            }
        };

        final Disposable disposable = new AbstractDisposable() {
            @Override
            void disposeActual() {
                mLocationManager.removeUpdates(listener);
            }
        };

        observer.onSubscribe(disposable);
        final Location last = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(last != null) {
            observer.onNext(last);
        }
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, mMinTime, mMinDistance, listener);
        if(disposable.isDisposed()) {
            mLocationManager.removeUpdates(listener);
        }
    }
}

And my AbstractDisposable:

abstract public class AbstractDisposable implements Disposable {
    private final AtomicBoolean mDisposed = new AtomicBoolean();

    @Override
    public void dispose() {
        if(mDisposed.compareAndSet(false, true)) {
            disposeActual();
        }
    }

    @Override
    public boolean isDisposed() {
        return mDisposed.get();
    }

    abstract void disposeActual();
}


texts:
This code is used to toggle buttons within a div:

var chosen = {};
var form_name = 'the_div';
function(what) {
   if('number' != typeof what) { // toggle-one
        var el = $(what);
        var name = el.html();
        var ch = ['success','default'];
        if( !chosen[name] ) ch.unshift(ch.pop());
        el.removeClass('btn-' + ch[0]).addClass('btn-' + ch[1]);
        chosen[name] = !chosen[name];
        return;
    }
    var choices = $('#'+form_name).find('div');
    switch(what) { // when toolbar button clicked
        case 1: // select-all
            choices.each(function(idx,el){
                var el = $(el);
                var name = el.html();
                if(!chosen[name]) {
                    el.removeClass('btn-default').addClass('btn-success');
                    chosen[name] = true;
                }
            });
            break;
        case 0: // select-none
            choices.each(function(idx,el){
                var el = $(el);
                var name = el.html();
                if(chosen[name]) {
                    el.removeClass('btn-success').addClass('btn-default');
                    chosen[name] = false;
                }
            });
            break;
        case -1: // select-inverse / toggle-all
            choices.each(function(idx,el){
                var el = $(el);
                var name = el.html();
                var ch = ['success','default'];
                if(!chosen[name]) ch.unshift(ch.pop());
                el.removeClass('btn-'+ch[0]).addClass('btn-'+ch[1]);
                chosen[name] = !chosen[name];
            });
            break;
    }
}

Any suggestion on how to simplify this code?


texts:
I want to learn some C# syntax/paradigms (I'm more used to Java), and have been wanting to get a bit better at math as well, so I solved ProjectEuler3: Largest prime factor with the following small program in LINQPad. It gives the correct answer and completes in 0.05s-0.08s.

For reference, here is the problem statement:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143 ?

All feedback welcomed. In particular, are there some C# mistakes I am making or features I am missing on due to being very new at it?

I'm also not that great at math at the moment, if you know of edge cases that I may have missed with the calculations below, please let me know so I can improve my math knowledge a bit as well!

P.S.: Note the BigNumbersUtils.Sqrt extension method comes from this Stack Overflow answer. I am excluding it since it is not my code. it gives the same result as Math.Sqrt but for BigInteger type.

void Main()
{
    Console.WriteLine("ProjectEuler3: Largest prime factor");
    BigInteger testCase = 600851475143;
    ProjectEuler3 PE3 = new ProjectEuler3(testCase);
    Console.WriteLine("Prime factor of {0} is: {1}", testCase, PE3.GetAnswer());
}

class ProjectEuler3
{
    private BigInteger number;

    public ProjectEuler3(BigInteger number)
    {
        this.number = number;
    }

    public BigInteger GetAnswer()
    {
        // largest possible prime factor of a number is its square root [citation needed]
        BigInteger maxPrimeFactor = BigNumbersUtils.Sqrt(number);
        // make sure number we start from is odd, as even numbers are never going to be prime
        if (maxPrimeFactor % 2 == 0) { maxPrimeFactor += 1; }
        // iterating by 2s to skip even numbers
        for (BigInteger i = maxPrimeFactor; i >= 1; i = i - 2)
        {
            if (IsFactor(i, number) && IsPrime(i))
            {
                return i;
            }
        }
        return 1;
    }

    private bool IsFactor(BigInteger n, BigInteger factorOf)
    {
        return (factorOf % n == 0) ? true : false;
    }

    private bool IsPrime(BigInteger n)
    // Based on Wikipedia page for "Primality test"
    // https://en.wikipedia.org/wiki/Primality_test#Simple_methods
    {
        // short-circuit very common numbers
        if (n <= 1)
        {
            return false;
        }
        else if (n <= 3)
        {
            return true;
        }
        else if (n % 2 == 0 || n % 3 ==0)
        {
            return false;
        }
        else if (  (n != 5 && n % 5 == 0))
        {
            return false;
        }
        // iterate with trial division
        BigInteger i = 5;
        while (i * i <= n)
        {
            if (n % i == 0 || n % (i + 2) == 0)
            {
                return false;
            }
            i++;
        }
        return true;
    }

}


texts: Printing the power set of a given set of elements

texts:
Input: Set of elements (String)
Output: Printing the elements of the power set of the given set

public class PrintPowerSet {
public static List<String> permuteSet(String inputSet){

    List<String> powerSet = new ArrayList<String>();
    int n = inputSet.length(); //size for binary

    for(int i=0;i<Math.pow(2,n);i++){
        if(i==0){
            powerSet.add("Ø"); //empty set Case
            continue;
        }
        String binaryOfIndex = getBinaryString(i, n);
        StringBuffer subset = new StringBuffer();
        for(int j=0;j<binaryOfIndex.length();j++){
            if(binaryOfIndex.charAt(j)=='1'){
                subset.append(inputSet.charAt(j));
            }
        }
        powerSet.add(subset.toString());
    }
    return powerSet;
}

public static String getBinaryString(int i, int size) {
    String bin = Integer.toBinaryString(i);
    bin = String.format("%0" + size + "d", Integer.parseInt(bin));
    return bin;
}
public static void main(String args[]){
    String set = "gle";
    List<String> result;
    result = permuteSet(set);
    for(String word: result){
        System.out.print(word+" ");
    }
}
}


texts:
Forgive me if this is too simple, but I'm a beginner trying to learn and understand. I came across an exercise to create these three basic functions, and this is what I came up with.

Any glaring errors?

This program defines three functions:

sum(x,y)
range(x,y,step)
rangeSum (start, end)

sum will give you the sum of two numbers.

range will give you an array of numbers from x to y, with an optional step argument that dictates the increment to use when listing the range. If no step is given, the default value is 1.

rangeSum will give you the sum of a range of numbers from start to end.

// sum(x,y) takes the sum of two numbers
var sum = function(x,y){
  return x + y;
};
// range(x,y,step) gives an array of the range of x and y, with an optional step argument
var range = function(x, y, step){
    if (step == null) step = 1;
  var arr = [];

  if (step > 0) {
    for (var i = x; i <= y; i += step)
      arr.push(i);
  } else {
        for (var i = x; i >= y; i += step)
        arr.push(i);
  }
    return arr;
};
// rangeSum(start,end) gives the sum of the range from start to end.
var rangeSum = function(start,end){
  var arr = [];
  for (var i = start; i <= end; i++)
    arr.push(i);
  return arr.reduce(function(a,b){
    return a + b;
  });
};


texts: Simple ActiveRecord attributes encryption in Rails 5+

texts:
The task at hand was to ensure that certain columns in the database are encrypted in case the database data is stolen. I have a feeling that a lot can be improved here (naming, DSL, encapsulations) while keeping the functionality as simple as it is. Let me know what you think, I'd appreciate any suggestions and ideas!

application_record.rb

class ApplicationRecord < ActiveRecord::Base
  extend Encryptable
  #...
end

encryptable.rb

module Encryptable
  def encrypt_columns(*columns)
    columns.each do |column|
      if self.column_names.include?(column.to_s)
        define_method "#{column}=" do |value|
          self[column] = self.class.crypt.encrypt_and_sign(value)
        end

        define_method "#{column}" do
          self.class.crypt.decrypt_and_verify(self[column])
        end
      end
    end
  end

  def crypt
    salt = '"\xCA)P\x9Dbc\xF7\x85B\xF3v}*p\xA6~\xBAR\xC1K\xE3\x88\xB8\x18\xF7\xD1\xB6e0\x98\xEF \xB9%\xB3\x12\x9C\xFE,\x89\xF4\xDE\xED!:7\xAE<q\xB1.<~\xA3m\e\x8C\t\xCF&/3\xCE\xAE"'
    key = ActiveSupport::KeyGenerator.new('password').generate_key(salt)

    @crypt ||= ActiveSupport::MessageEncryptor.new(key)
  end
end

user.rb

class User < ApplicationRecord
  encrypt_columns :email, :social_security_number
end


texts: Counting the number of 1 bits in a sorted bit array

texts:
I wrote a function in python to count the number of 1-bits in a sorted bit array. I'm basically using binary search but the code seems unnecessarily long and awkward. I did test it for several different cases and got the correct output but am looking to write a cleaner code if possible.

Note: I want to use a binary-search inspired solution that theoretically takes O(lg n ) time.

def countOnes(arr):
    l, r = 0, len(arr)-1
    while l <= r:
        mid = l + (r-l)/2
        if mid == 0 and arr[mid] == 1:
            return len(arr)
        if mid == len(arr)-1 and arr[mid] == 0:
            return 0
        if arr[mid] == 1 and arr[mid-1] == 0:
            return len(arr) - mid
        elif arr[mid] == 1 and arr[mid-1] == 1:
            r = mid - 1
        elif arr[mid] == 0 and arr[mid+1] == 1:
            return len(arr) - (mid+1)
        else:
            l = mid + 1

print countOnes([0, 0, 0]) # got 0
print countOnes([0, 0, 1, 1]) # got 2
print countOnes([1, 1, 1, 1]) # got 4
print countOnes([0, 1, 1, 1]) # got 3
print countONes([1, 1, 1, 1, 1]) # got 5


texts: Create symmetrical matrix from list of values

texts:
I need to make a matrix (in the form of a numpy array) by taking a list of
parameters of length N and returning an array of dimensions N+1 x N+1 where the off-diagonals are symmetric and each triangle is made up of the values given. The diagonals are equal to 0 - the row sum of the off-diagonals.

I don't really like having to instantiate an empty array, fill the top triangle, then create a new matrix with the bottom triangle filled in. I'm wondering if I can do this in fewer lines (while still being readable) and also wondering if it can be made faster. vals is never going to be very large (between 2 and 100, most likely) but the operation is going to be repeated many times.

def make_sym_matrix(dim, vals):

    my_matrix = np.zeros([dim,dim], dtype=np.double)

    my_matrix[np.triu_indices(dim, k=1)] = vals
    my_matrix = my_matrix + my_matrix.T
    my_matrix[np.diag_indices(dim)] = 0-np.sum(my_matrix, 0)

    return my_matrix


texts: Find the most frequent character in a string

texts:
I'm trying to solve this problem https://community.topcoder.com/stat?c=problem_statement&pm=40

  Given a string made up of ONLY letters and
      digits, determine which character is repeated the most in the string ('A' is
      different than 'a'). If there is a tie, the character which appears first in
      the string (from left to right) should be returned.

Here is my approach is Scala. I feel it's not very functional, and slow(because of a new reversed String object).

def findMaxFunctional(word: String): Char = {
    var curMaxCount, maxCharId = 0
    word.reverse.foldLeft(new Array[Int](128))((acc, ch) => {
      acc(ch) = acc(ch) + 1
      if(acc(ch) >= curMaxCount) {
        curMaxCount = acc(ch)
        maxCharId = ch
      }
      acc
    })
    maxCharId.toChar
  }


texts: Find repeated substrings of length 3 in a string

texts:
The following method receives a string and finds all occurrences of repeated substrings with a length of three characters, including spaces. Is this a good approach?

public Map<String, Integer> findOccurences(String str) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        int counter = 0;
        String sub;
        int stringLen = str.length() - 2;
        for (int i = 0; i < stringLen ; i++) {
            sub = str.substring(i, i + 3);
            if (map.containsKey(sub)) {
                counter = map.get(sub);
                counter++;
                map.put(sub, counter);
                counter = 0;
            } else {
                map.put(sub, 1);
            }
        }
        return map;
    }

Input

This This

Output

 Th 1    <<< includes space
s T 1
his 2
Thi 2
is  1    <<< includes space


texts: Functional Merge Sort in Python with only boolean variables to control fall off logic

texts:
Merge Sort

I have just implemented this merge_sort, and this is also my first algorithm implemented in Python, I am totally open to feedback about how to better use python.

I am using Arrays instead of lists - I did this intentionally, to have a more a performant data structure.

My understanding is that a List in python is backed by an array, therefore, the performance should be the same as arrays, the difference is a single type for the collection elements.

A Functional Thinking

Since I am not sure(not a Python master), but I need to ask: Is this merge sort a functional one?

At least in terms of no side effects and referential transparency, can we say, it is a FP merge sort, since I do not change the input?

Code

from array import *

def split_arr(arr):
    length = len(arr) / 2
    return arr[:length], arr[length:]

def merge(arr_i, arr_j):
    k = len(arr_i) + len(arr_j)
    arr_out = array('i')
    i = 0
    j = 0
    i_end = False
    j_end = False
    while k > 0:
        if not i_end:
            if not j_end and arr_i[i] < arr_j[j]:
                arr_out.append(arr_i[i])
                i += 1
                if i == len(arr_i):
                    i_end = True
            elif not j_end and arr_i[i] > arr_j[j]:
                arr_out.append(arr_j[j])
                j += 1
                if j == len(arr_j):
                    j_end = True
            else:
                arr_out.append(arr_i[i])
                i += 1
                if i == len(arr_i):
                    i_end = True
        elif not j_end:
            arr_out.append(arr_j[j])
            j += 1
            if j == len(arr_j):
                j_end = True
        k -= 1
    return arr_out

def merge_sort(arr):
    length = len(arr)
    if length <= 1:
        return arr
    else:
        a1, a2 = split_arr(arr)
        return merge(merge_sort(a1), merge_sort(a2))


texts:
I've tried to implement the counting sort algorithm in C.

What efficiencies can you spot?
I squint at the end when running through the original array again to assign it the sorted array. Maybe there is a better way?

/**
* Sorts array of n values.
* Using counting sort O(n)
*/
void sort(int values[], int n)
{
  //set our known max length, initialize our placer array and then our sorted array
  int maxLength = 65536;
  int placer[maxLength];
  int sorted[n];

  //so we can know which indexes in our placer array are in values array
  for ( int i = 0; i < n; i++ ) {
    placer[ values[i] ] += 1;
  }

  //store the sum of previous elements in each element at each index because this will give us the sorted position
  for (int i = 0; i < maxLength; i++ ) {
    placer[ i + 1 ] += placer[i];
  }

  //fill the sorted array with the values elements using the corresponding placer index
  for ( int i = 0; i < n; i++ ) {
    sorted[ placer[ values[i] ] - 1 ] = values[i];
    placer [ values[i] ] -= 1;

  }

  //set the unsorted values array to the sorted array
  for (int i = 0; i < n; i++) {
    values[i] = sorted[i];
  }
}


texts: Checking whether various form fields are filled in

texts:
This is a customer information data entry form. First name and Last name are required. In addition phone number, e-mail and birth date are used to check the database for existing customers with the same information.

Either of these fields (phone, e-mail or birth date) can be empty or filled in. In order to validate against database I need to check if the user has filled each field in or not.

Is there a way to refactor the code and still set a different property for each scenario?

The code looks like this:

var sFirstName = Inputs.GetProperty("sFirstName");
var sLastName = Inputs.GetProperty("sLastName");
var sEmail = Inputs.GetProperty("sEmail");
var sPhone = Inputs.GetProperty("sPhone");
var sBirthDate = Inputs.GetProperty("sBirthDate");
var sCoAddress = Inputs.GetProperty("sCoAddress");
var sAddress = Inputs.GetProperty("sAddress");
var sZip = Inputs.GetProperty("sZip");
var sCity = Inputs.GetProperty("sCity");

if(!sFirstName || !sLastName){
    TheApplication().RaiseErrorText("First name and last name are required");
}

if(!sEmail && (!sCoAddress || !sAddress || !sZip || !sCity)){
    TheApplication().RaiseErrorText("Please enter either e-mail or postal address");
}
if(sEmail && sBirthDate && sPhone){
    Outputs.SetProperty("QueryAll","Y");
}
else if(sEmail && sBirthDate && !sPhone){
    Outputs.SetProperty("QueryEmailBday","Y");
}
else if(sEmail && !sBirthDate && sPhone){
    Outputs.SetProperty("QueryEmailPhone","Y");
}
else if(!sEmail && sBirthDate && sPhone){
    Outputs.SetProperty("QueryBdayPhone","Y");
}
else if(sEmail && !sBirthDate && !sPhone){
    Outputs.SetProperty("QueryEmail","Y");
}
else if(!sEmail && sBirthDate && !sPhone){
    Outputs.SetProperty("QueryBirthDate","Y");
}
else if(!sEmail && !sBirthDate && sPhone){
    Outputs.SetProperty("QueryPhone","Y");
}
else if(!sEmail && !sBirthDate && !sPhone){
    Outputs.SetProperty("QueryNameOnly","Y");
}


texts: Split function while reading multiple lines

texts:
The input begins with the number \$t\$ of test cases in a single line
  (\$t \le 10\$). In each of the next t lines there are two or more
  numbers \$m\$ and \$n\$ (\$1 \le m \le n \le 1000000000\$, \$n-m \le 100000\$) separated by a space.

  Print each number in a separate line which can be used further for
  summation.

  Input

2

50 100

100 50 105

  Output

50

100

100

50

105

This is the code that I've written that is giving me output:

import java.util.Scanner;
import java.util.StringTokenizer;

public class Generation {

    public static void main(String[] str) {

        Scanner keyboard = new Scanner(System.in);
        int inputSize;
        do {
            System.out.println("Enter the value of T Size");
            inputSize = keyboard.nextInt();
            keyboard.nextLine();
            if (inputSize < 2 || inputSize > 10) {
                System.out.println("Not a Valid Input Size");
            }
        } while (inputSize < 2 || inputSize > 10);

        String[] inputValue = new String[inputSize];
        int tokenCount = 0;
        for (int i = 0; i < inputSize; i++) {
            System.out.println("Enter the inputs");
            inputValue[i] = keyboard.nextLine();
            StringTokenizer strToken = new StringTokenizer(inputValue[i], " ");
            tokenCount += strToken.countTokens();
        }
        keyboard.close();

        //suppose this is 2nd part
        int[] splitedString = new int[tokenCount];
        int tempTokenCount = 0;
        for (int i = 0; i < inputSize; i++) {
            String[] tempSplitArray = inputValue[i].split(" ");
            for (int j = 0; j < tempSplitArray.length; j++) {
                splitedString[tempTokenCount] = Integer
                        .parseInt(tempSplitArray[j]);
                tempTokenCount++;
            }

        }
        /*for (String s : inputValue) {
            System.out.println(s);
        }*/
        for (Integer s : splitedString) {
            System.out.println(s);
        }

    }

}

How can I optimize the 2nd part where I have to use two for loop which result in \$O(n^2)\$ time complexity? What is the workaround for such situations?


texts:
As a first step into the world of Alloy, I've done my own version of the Fox/Chicken/Grain problem. I'd be grateful for any comments (also, is there a better place to do this?).
I thought it worth separating out the Farmer from the other items so I don't have to keep removing it from the set of items.
open util/ordering[Time]

sig Time {}

enum Place {Near, Far}

abstract sig Locatable { location: Place one -> Time }
abstract sig Edible extends Locatable {}
one sig Fox, Chicken, Grain extends Edible {}
one sig Farmer extends Locatable {}

pred init(t: Time) { Locatable.location.t = Near }

pred done(t: Time) { Locatable.location.t = Far }

pred stayPut(t, t': Time, edibles: set Edible) {
    all e : edibles | e.location.t = e.location.t'
}

pred carryAcross(t, t' : Time) {
    one e: Edible {
        e.location.t = Farmer.location.t
        e.location.t' = Farmer.location.t'
        stayPut[t, t', Edible - e]
    }
}

pred crossRiver(t, t' : Time) {
    stayPut[t, t', Edible]
}

pred nextCrossing(t, t' : Time) {
    Farmer.location.t' != Farmer.location.t
    carryAcross[t, t'] or crossRiver[t, t']
}

pred eats [a, b: Edible] { a->b in Fox->Chicken + Chicken->Grain }

fact ProtectFromEating {
    all p, q: Edible, t: Time |
    p.eats[q] and p.location.t = q.location.t => q.location.t = Farmer.location.t
}

fact Traces {
    first.init
    all t: Time - last | let t' = t.next |
        done[t] or nextCrossing [t, t']
}

fact Done {
    some t: Time | done[t]
}

run {} for 8 Time


texts: NodeJS authentication function rewrite with promises

texts:
I will post both of the modules, some of the code in them may be "irrelevant" for the main concern here, which is Security.prototype.authenticate(). Nevertheless, comments are welcome about all of the code.

Security.prototype.authenticate() is a controller for a /login API-endpoint.

security.js

'use strict';

var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var Promise = require('bluebird');

var config = require('./config');
var db = require('./db');

function Security() {}

function _verifyPassword(password, hash, salt) {
    var newHash = crypto.createHash('sha512').update(password).update(salt).digest("hex");
    return newHash === hash;
}

function _generateToken(username, secret, expiration) {
    var token = jwt.sign(username, secret, { expiresInMinutes: expiration });
    return { token: token };
}

Security.prototype = {

    tokenCheck: function(req, res) {

        jwt.verify(req.body.token, config.security.secret, function (err, decoded) {

            if (err) {
                return res.status(400).send("Token invalid or expired");
            }

            res.json({ username: decoded });

        });

    },

    authenticate: function(req, res) {

        if (!req.body.username || !req.body.password) {
            return res.status(400).send("Username and/or password field empty");
        }

        Promise.using(db.getConnection(), function(connection) {

            return connection.queryAsync("SELECT password_hash, password_salt FROM users WHERE email = ? AND admin = 1", req.body.username)
                .then(function(rows) {

                    connection.release();

                    if ( rows[0].length === 1 ) {
                        return rows[0][0];
                    } else {
                        throw new Error("Username not found");
                    }

            }).then(function(user) {

                    if ( !_verifyPassword(req.body.password, user.password_hash, user.password_salt) ) {
                        throw new Error("Incorrect password");
                    }

                    res.json({
                        token: _generateToken(req.body.username, config.security.secret, config.security.expiration),
                        username: req.body.username
                    });

            });

        }).error(function(e) {
            res.status(400).send("Database error");
        }).catch(Error, function(e) {
            res.status(400).send(e.message);
        });

    }

};

module.exports = new Security();

db.js

'use strict';

var config = require('./config');
var Promise = require("bluebird");
var mysql = require('mysql');
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);

function DB() {
    this._pool = _createPool();
}

function _createPool() {

    return mysql.createPool({
        connectionLimit: config.database.connectionLimit,
        host: config.database.host,
        user: config.database.username,
        password: config.database.password,
        database: config.database.database,
        debug: config.database.debug
    });

}

DB.prototype = {

    getConnection: function() {
        return this._pool.getConnectionAsync();
    }

};

module.exports = new DB();

My concerns are any possible anti-patterns that are visible here. I just got rid of one problem with this function, which was nested callbacks, by implementing promises. However, my knowledge of Bluebird is limited to the last ~12 hours. I have used promises before, but not a lot. Also, as I said, comments on the rest of the code are also welcome.


texts: Finding where column slices of elements in multi-dimensional array are equal

texts:
Skippable Intro:

I have a dataset that corresponds to an observed time-series. The dataset is organized into a dictionary - which contains an array of years, an array of months, an array of days, an array of hours, an array of observed speeds, etc., each obtainable via the appropriate key. My goal is to find all indices at which all input values match the dictionary values of all input keys. I did this by using numpy where on each sub-array from the dictionary (via input keys) to construct sub-array masks of zeros or ones (which alternate by index in range(len(keys))); values are filled in the sub-array masks at indices obtained from the numpy where routine. These filled sub-array masks are then used to construct a multi-dimensional array.

The part I'd like to improve:

The multi-dimensional array, consisting of sub-array masks of indices, is datain the code below. Consider this as a short sample problem.

import numpy as np

# assume a,b,c,d are array masks of indices obtained via numpy where
a = np.array([0, 9, 0]) # mask -- index of years
b = np.array([1, 9, 1]) # mask -- index of months
c = np.array([0, 9, 0]) # mask -- index of days
d = np.array([1, 9, 1]) # mask -- index of hours
data = np.array([a, b, c, d]) # multi-dimensional array of index masks

# routine to get indices where all indices are equal
condition = np.diff(data, axis=0) # get consecutive difference across rows at each column
rows, cols = np.where(condition == np.zeros(len(data)-1)) # get row and column where difference is zero
res = [datum[cols[0]] for datum in data] # check that values agree

# print(data)
[[0 9 0]
 [1 9 1]
 [0 9 0]
 [1 9 1]]

# print(condition)
[[ 1  0  1]
 [-1  0 -1]
 [ 1  0  1]]

# print(rows)
[0 1 2]

# print(cols)
[1 1 1]

# print(res)
[9, 9, 9, 9]

I was initially worried that this algorithm failed in edge-cases where the indices of a column would sum to zero without having all indices of the respective column being equal, but I see this is not the case via print(condition). Are there any bugs I missed? Is there a better implementation of this algorithm?

EDIT:

The algorithm actually fails when adding another sub-array to data. I'm not sure if it's ok to ask in this stack exchange, so I can delete it here and repost it in stackoverflow if necessary.

...
e = np.array([0, 9, 0]) # mask -- index of speeds
data = np.array([a, b, c, d, e]) # multi-dimensional array of index masks
...

# rows, cols = np.where(condition == np.zeros(len(data)-1)) # get row and column where difference is zero
## ^^ fails

Traceback (most recent call last):
   rows, cols = np.where(condition == np.zeros(len(data)-1)) # get row and column where difference is zero
ValueError: not enough values to unpack (expected 2, got 1)

rows, cols = np.where(condition == np.zeros(len(data)-2)) # get row and column where difference is zero
## ^^ works

...

# print(res)
[9, 9, 9, 9, 9]

Why does the original algorithm fail when modifying data?


texts: Better way for accumulating a value than using inject/reduce with conditional operator?

texts:
When there is a situation where I want to accumulate a value I see myself using inject/reduce with a conditional statement. E.g., when I want to add 1 to a value each time an element in a list has a certain value I do something like this:

puts names.reduce(0) {|acc, name| triangles.include?(name.points) ? acc+=1 : acc}

Here names is an array of names, triangles is a list of the first 30 triangle integers (1/2n(n+1)) and points is a method added to class String which calculates the integers value of each character in the name and adds them. So the point is to check how many names in the list are triangle values when you calculate the points in that way.

The issue I have is with the conditional area ([conditional] ? acc+=1 : acc). You can also rewrite the method as:

result = 0
names.each {|name| result +=1 if triangles.include?(name.points)}
puts result

But this method uses three lines and has to initialize the variable at first.

Is there a better way to keep track of the amount (e.g., result, or the acc in the inject/reduce) that does not use the conditional operator (?) or costs three lines of code?


texts: Grabbing information traversing multiple pages

texts:
I've written a script in python in combination with selenium to parse different information from a webpage and store the collected data in a csv file. The data are rightly coming through. The email portion looks weird cause I wrapped two conditions in a single line to grab all the leads (in case one missing, another will come into play) However, the way I've used csv writer doesn't look that good. I hope there is any better way of implementation of the logic I pursued below.

This is the script:

import csv
from selenium import webdriver
from bs4 import BeautifulSoup

urls = "https://www.krak.dk/byggefirmaer/p:{}/s%C3%B8g.cs?xcoord=90.3636094&ycoord=23.8150673"

def get_info(driver,urls):
    with open("output.csv","w",newline="") as infile:
        writer = csv.writer(infile)
        writer.writerow(["Name","Link","Email"])

        for url in [urls.format(page) for page in range(1,3)]:
            driver.get(url)
            soup = BeautifulSoup(driver.page_source,'html.parser')
            for links in soup.select("article.vcard"):
                name = links.select_one(".hit-company-name-ellipsis a").get_text(strip=True)
                link = links.select_one(".hit-homepage-link").get("href") if links.select_one(".hit-homepage-link") else  ""
                email = links.select_one(".hit-footer-wrapper span[data-mail]").get("data-mail") or links.select_one(".hit-footer-wrapper span[data-mail-e-contact-mail]").get("data-mail-e-contact-mail")
                print(f'{name}\n{link}\n{email}\n')
                writer.writerow([name,link,email])

if __name__ == '__main__':
    driver = webdriver.Chrome()
    try:
        get_info(driver,urls)
    finally:
        driver.quit()

Currently the above script traverses three pages and scrapes three fields name,link,email.


texts:
I wrote a quick and dirty program to perform binary search with an ordered array (list) of C style strings.  For example:

{"1", "12", "23", "124"} etc (though my input set is actually much different)

NOTE:

Apologies for the confusing names - string is not the string, string->ID is. (Like I said, I cobbled it together very quickly since I was writing into t a larger program). Assume all variables have been declared.
I only care about program (piece) correctness and efficiency of the algorithm (for example - ignore the multiple returns etc) at the moment.
Don't worry about function calls like Log() or macros that I've used.  Bottom and top are calculated off of stringEntries.
Think of ways this will break. Don't worry about the rest of the program - just focus on this piece!
pID is your input string. We're searching through "string"'s attribute "ID" (which is the string). Assume that "string" is actually something else, like a ptr to a struct or something, with a member "ID" which is a C-style string (null terminated and everything).
len is actually strlen(pID).

    while (TRUE)
            {

      *string = &stringEntries[mid = (bottom + top) / 2];

       if (*string == NULL) {
              Log(DEBUG, _ERROR,”*string is NULL\n”);
              return ERROR;
       }
       else if ((*string)->ID == NULL) {
              Log(DEBUG, _ERROR,”(*string)->ID is NULL\n”);
              return ERROR;
       }

       if (!(diff = strcmp(pID, (*string)->ID)))
               diff = len - strlen((*string)->ID);

       if (!diff) return PRESENT;

       if (bottom == top) {
              if (diff > 0)
                     (*string)++;  //ignore this bit - i need it later on
                     return NOT_PRESENT;
       }

       if (diff > 0){
              if (bottom == mid) bottom++;
              else  bottom = mid;
       }
       else        top = mid;
    }


texts:
I made the following regular expression for parsing ngnix log

log_1 = "1.169.137.128 -  - [29/jun/2017:07:10:50 +0300] "GET /api/v2/banner/1717161 http/1.1" 200 2116 "-" "Slotovod" "-" "1498709450-2118016444-4709-10027411" "712e90144abee9" 0.199"

My test cases (https://regex101.com/r/Eyhxod/1)

lineformat = re.compile(r"""(?P<ipaddress>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) -  - \[(?P<dateandtime>\d{2}\/[a-z]{3}\/\d{4}:\d{2}:\d{2}:\d{2} (\+|\-)\d{4})\] \"GET (?P<url>.+?(?=\ http\/1.1")) http\/1.1" \d{3} \d+ "-" (?P<http_user_agent>.+?(?=\ )) "-" "(?P<x_forwaded_for>(.+?))" "(?P<http_xb_user>(.+?))" (?P<request_time>[+-]?([0-9]*[.])?[0-9]+)""",re.IGNORECASE)

Output:

data = re.search(lineformat, log_1)
data.groupdict()

{'ipaddress': '1.169.137.128',
 'dateandtime': '29/jun/2017:07:10:50 +0300',
 'url': '/api/v2/banner/1717161',
 'http_user_agent': '"Slotovod"',
 'x_forwaded_for': '1498709450-2118016444-4709-10027411',
 'http_xb_user': '712e90144abee9',
 'request_time': '0.199'}

I believe I should make it more robust towards edge cases and broken logs. Also I consider splitting my long expression into a smaller one.
Any advices towards the best-practices are appreciated.


texts: Processing names and meanings from .txt files

texts:
I wrote this program to process the names and meanings from .txt files. From the while loops I wrote, I noticed they are very similar loops containing Scanners. I am wondering if there is any way to reduce the redundancy in the code.
Also, for this program my instructor only allows us to use Scanners, while and if/else loops, boolean and file input to solve this problem.
Here are samples for names.txt and meanings.txt:
names.txt

Jax    M  0  0 0 0  0  0 0  0  0 0 0  0  347
Randall   M 974 620  650 467  369  232  70 59 100 136 192  440  841
Minnie  F  8 22 50 87 122  168  258  516  995  0 0  0  0
Brianna F  0 0 0 0 0 0  0  0  0 340 61  15  30

meanings.txt

MUBINA f Arabic Feminine form of MUBIN
ANDRONIKOS m Ancient Greek Means "victory of a man" from Greek
(andros) "of a man" and (nike) "victory".
SALVATORE m Italian Italian cognate of SALVADOR

And here is my code:
import java.io.*;
import java.util.*;

public class BabyNames {
   public static void main(String[] args) throws FileNotFoundException {
      Scanner inputName = new Scanner(new File("names.txt"));
      Scanner inputMeanings = new Scanner(new File("meanings.txt"));
      Scanner console = new Scanner(System.in);

      intro();
      System.out.print("Name: ");
      String nameIn = console.next();
      System.out.print("Gender (M or F): ");
      String genderIn = console.next();

      nameAndMeaning(inputName, inputMeanings, nameIn, genderIn);
   }

   public static void intro() {
      System.out.println("This program allows you to search through the");
      System.out.println("data from the Social Security Administration");
      System.out.println("to see how popular a particular name has been");
      System.out.println("since 1890.");
      System.out.println();
   }

   public static void nameAndMeaning(Scanner inputName, Scanner inputMeanings, String nameIn, String genderIn) {
      boolean hasLine = false;
      while(inputName.hasNextLine()) {
         String line = inputName.nextLine();
         Scanner lineScan = new Scanner(line);
         if(lineScan.hasNext()) {
            String name = lineScan.next();
            String gender = lineScan.next();
            if(name.equalsIgnoreCase(nameIn) && gender.equalsIgnoreCase(genderIn)) {
               hasLine = true;
               System.out.println(line);
            }
         }
      }
      if(hasLine == false) {
         System.out.println("\""+ nameIn + "\" not found.");
      } else {
         while(inputMeanings.hasNextLine()) {
            String line = inputMeanings.nextLine();
            Scanner lineScan = new Scanner(line);
            if(lineScan.hasNext()) {
               String name = lineScan.next();
               String gender = lineScan.next();
               if(name.equalsIgnoreCase(nameIn) && gender.equalsIgnoreCase(genderIn)) {
                  String meaning = line;
                  System.out.println(line);
               }
            }
         }
      }
   }


texts: Generating Norwegian social security numbers

texts:
I have written some code in Node.js that takes a date as argument and return all the possible combination of social security numbers.

I'd really appreciate some advice when it comes to these areas:

Coding style
Code structure

In my code I have included a brief description on how these numbers are generated.

personnr.js

/*
Norwegian social security-number structure;

dd mm yy i1 i2 i3 k1 k2

i1, i2, i3 => 'Individ'-numbers

This structure is used pr. oct. 2013;

000–499 for people born some time in 1900–1999.
500–999 for people born some time in 2000–2039.

k1, k2 => calculated based on the numbers above (a checksum)

more info;

https://no.wikipedia.org/wiki/Fødselsnummer
*/

module.exports = init;

function Personnr(birthday) {
    if (typeof birthday !== 'string')   throw new Error('Argument must be a string');
    if (birthday.length !== 8)          throw new Error('Argument has to be on the format \'DDMMYYYY\'')

    var dd      = addZero(birthday, 0, 2),
        mm      = addZero(birthday, 2, 4),
        yy      = addZero(birthday, 6, 8),
        yyyy    = addZero(birthday, 4, 8)

    this.birthday   = [dd, mm, yy].join('');
    this.dd         = dd;
    this.mm         = mm;
    this.yy         = yy;
    this.yyyy       = yyyy;

    this.individ = {
        i1: 0,
        i2: 0,
        i3: 0
    };
}

Personnr.prototype.make = function() {
    var range       = getRange(this.yyyy),
        min         = range[0],
        max         = range[1],
        generate    = generateIndividSiffer(min, this.yy, this.individ),
        result      = [];

    for(var i = min; i < max; i++) {
        var individ = generate();
        var kontroll = generateKontrollSiffer(this.dd, this.mm, this.yy, this.individ);

        var personnr = [this.birthday, individ, kontroll].join('');
        result.push(personnr);
    }

    return result;
}

function init(birthday) {
    return new Personnr(birthday);
}

//Private functions

//If the number is < 10, an extra '0' is inserted before (e.g. 08, 09 etc..)

function addZero(number, min, max) {
    if (number.length === 2) {
        var number = parseInt(number.slice(min, max)),
            result = ('0' + number).slice(-2);
    }

    return result || number.slice(min, max);
}

function getRange(year) {
    var min = null,
        max = null;

    if (year >= 1900 && year <= 1999) {
        min = 0;
        max = 499;
    } else if (year >= 2000 && year <= 2039) {
        min = 500;
        max = 999;
    }

    return [min, max];
}

function generateIndividSiffer(start, year, individ) {
    var increment = start;

    return function() {
        increment++;

        individ.i3 = increment % 10;

        if (individ < 100){
            individ.i1 = 0;
            individ.i2 = parseInt(increment / 10) % 10;
        } else if (increment < 10) {
            individ.i1 = increment.i2 = 0;
        } else {
            individ.i1 = parseInt(increment / 100) % 10;
            individ.i2 = parseInt(increment / 10) % 10;
        }

        return [individ.i1, individ.i2, individ.i3].join('');
    }
}

function generateKontrollSiffer(day, month, year, individ) {

    var d1  = parseInt(day / 10),
        d2  = day % 10,

        m1  = parseInt(month / 10),
        m2  = month % 10,

        y1  = parseInt(year / 10),
        y2  = year % 10,

        i1  = individ.i1,
        i2  = individ.i2,
        i3  = individ.i3;

    var k1 = 11 - ((3*d1 + 7*d2 + 6*m1 + 1*m2 + 8*y1 + 9*y2 + 4*i1 + 5*i2 + 2*i3) % 11);
    if (k1 > 9) k1 = 0;

    var k2 = 11 - ((5*d1 + 4*d2 + 3*m1 + 2*m2 + 7*y1 + 6*y2 + 5*i1 + 4*i2 + 3*i3 + 2*k1) % 11);
    if (k2 > 9) k2 = 0;

    return [k1, k2].join('');

}

test.js

var personnr = require('./personnr');

var results = personnr('16111992').make();
console.log(results);


texts:
I'm just looking for constructive criticism of my Ruby implementation of a bubble sort algorithm.

class BubbleSorter < Object
  def bubble_sort(list)
    swaps = 0
    # parse the list until it is sorted
    until @sorted == true
      # run the comparison of adjacent elements
      for i in 0...(list.length - 1)
        # if the first is greater than the second, swap them with parallel assignment
        if list[i] > list[i+1]
          list[i], list[i+1] = list[i+1], list[i]
          # increase the number of swaps performed in this run by 1
          swaps += 1
        end
        # compare the next 2 elements
        i += 1
      end

      # uncomment the following line to see each iteration:
      # p list

    # If any swaps took place during the last run, the list is not yet sorted
    if swaps > 0
        @sorted = false
      # no swaps? Everything is in order
      else
        @sorted = true
      end
      # reset swap count for each run
      swaps = 0
    end
  end
end


texts:
I'm implementing a plus method that should work this way:

1 plus 2      // 3
"a" plus "b"  // "a and b = ab"

Here is my implementation:

object MyMath {
  implicit class MyMath(a: Any) {
    def plus(b: Any) = {
      (a, b) match {
        case (s: String, s2: String) => s"$s and $s2"
        case(i: Int, i2: Int) => i + i2
      }
    }
  }

  def main(args: Array[String]) {
    println(1 plus 2)
    println("a" plus "b")
  }
}

Should I avoid using type Any? Is this a sign of a code smell if I use Any too much?


texts: jQuery marquee, without flickering, less memory consumption, and no plugin

texts:
I have tried using jQuery to create an alternative of marquee, and got no success. It flickers and does not stop on hover. I edited and edited again and it finally came out with a jQuery + JavaScript mess.

JavaScript:

$(document).ready(function(){
        marquee();
        var timeout=1;
        function marquee(){
            var margin= -($('#mydiv > div:eq(0)').outerHeight()+ 20);
            $('#mydiv > div:eq(0)').animate({'margin-top': margin+'px'},4000,function(){
                $('#mydiv > div:eq(2)').html($(this).html());
                $(this).html('').css({'margin-top':'0px'}).appendTo($('#mydiv'));
                loop();
            });
        }
        function loop(){
            if(timeout)
            setTimeout(marquee,0);
        }
        $('#mydiv').hover(function(){
                timeout = 0;
                $('#mydiv > div:eq(0)').stop(true);
        },function(){
                timeout = 1;
                marquee();
        });
    });

Markup:

 Advantages:

blah 1

blah 2

blah 3

Applications:

blah 1

blah 2

blah 3


texts:
I am building a contact management system. Each contact can relate to the business in one of three ways: client, service provider, and third party.

I have a JSON file containing the relation types and their importance to the business (so I could priorities messages, for example):

{
    "Relations": [
        {
            "Name": "Client",
            "Importance": 1
        },
        {
            "Name": "Service Provider",
            "Importance": 2
        },
        {
            "Name": "ThirdParty",
            "Importance": 3
        }
    ]
}

I have a method that gets the name of the relation and retrieves a JObject containing the JSON representing this relation, using Json.NET:

private JObject GetRelationJSON(string relationName)
{
    string jString = File.ReadAllText("relations.json");
    JObject relationsJSON = JsonConvert.DeserializeObject<JObject>(jString);

    // I am specifically not sure about this line
    return (JObject)(relationsJSON["Relations"].Where(r => ((string)r["Name"]).Equals(relationName)).ToList()[0]);
}

Note that I am not allowed to deserialize the JSON into POCO classes.

How can I improve this code? Thanks!


texts: NASM tutorial (Linux syscalls, 64 bit) code with CI-build and test

texts:
According to this question,  I have made an agreement with Peter Cordes to create such a question here.

I think that I should prepare the tutorial using the modern technologies as the Continuous Integration (hereinafter referred to as "CI").

Here is the public repo (branch tests) and here is the successful CI-build with the tests.

The tests were written in C#/.NET Core, using the MSTest framework, on Ubuntu (CI also uses Ubuntu docker image).

The source code may be found here.

It was divided into 4 files:

functions.asm, the main source, which is working with the 64-bit
syscalls
sys_write.asm, the program, which using the SYS_WRITE
syscall
sys_write.loop.asm, the program, which using the SYS_WRITE
syscall repeatedly (10 times)
sys_read.asm, the program, which is using
the SYS_READ syscall

The corresponding tests (in C#) are located here.

Main source file (functions.asm):

SECTION .data
inputTemplate  db  "User input: ", 0h
maxBytesToRead equ 255

sprint:
    push rdx
    push rdi
    push rax
    push rsi

    mov  rax, rsi
    pop  rsi
    jmp  next_char
    ret

sprint_linefeed:
    call sprint

    push rsi
    mov  rsi, 0Ah
    push rsi
    mov  rsi, rsp

    call sprint
    pop  rsi
    pop  rsi
    ret

read_input:
    push rsi
    call kernel_fn_read_input
    mov  r8 , rsi
    mov  rsi, inputTemplate
    call sprint
    mov  rsi, r8
    call sprint
    pop rsi
    ret

quit:
    call kernel_fn_quit
    ret

next_char:
    cmp byte [rax], 0
    jz  count_length
    inc rax
    jmp next_char

count_length:
    sub rax, rsi
    mov rdx, rax
    jmp kernel_fn_print_string

kernel_fn_print_string:
    mov rax, 1
    mov rdi, 1
    syscall

    pop rax
    pop rdi
    pop rdx
    ret

kernel_fn_read_input:
    push rax
    push rdx
    push rdi

    mov rax, 0
    mov rdx, maxBytesToRead
    mov rdi, 0
    syscall

    pop rdi
    pop rdx
    pop rax
    ret

kernel_fn_quit:
    push rax
    push rdi

    mov rax, 60
    mov rdi, 0
    syscall

    pop rdi
    pop rax
    ret

Here, I'm providing the several functions for handling the SYS_WRITE and SYS_READ syscalls in 64-bit mode. The 1st remark, which I can make for myself, that I didn't use the namespaces, which act like the private methods in high-level languages, like:

subroutineA:
    mov     rcx, firstMsg
    call    sprint
    jmp     .finished

.finished:
    mov     rax, secondMsg
    ...

Peter has asked me:

  Why you designed it that way (with push / pop of all registers you use, instead of letting it clobber rax, rcx, rdx, rsi, rdi, and r8-r11 like the x86-64 SystemV ABI allows for the standard function calling convention?

My answer:

  I'm pushing it to the stack for safe keeping. When the function has finished it's logic, these registers should have their previous values, restored via the POP instruction. I'm achieving the result, that any values in the registers will be the same before and after. Also, I didn't read the SystemV ABI at that moment, but reading right now.

I'm new to x86/assembler/NASM world, so I want to hear your constructive critique, because later I shall post an answer to Peter Cordes' question in beginner-friendly manner.

Intended purpose of the future tutorial:

  The simple application with the CI service, which may help the newbie to learn the correct use of the int 0x80 (for 32-bit) & syscall (for 64-bit) Linux ABI, as I promise Peter. That's why CI-service IS IMPORTANT, because it will show the beginner the conflict/exception. I want to prepare the failure tests, which will show the beginner, what happens if to use the 32-bit int 0x80 Linux ABI in 64-bit code with the deep diagnostics. Repo is public, so the beginner may execute the job and view the results in live mode.


texts: Checking battery voltage with ADC and interrupts - which way is best?

texts:
Here are some stripped down versions of the two different programs I am deciding between.

In version one, my state machine is called within the interrupt:

void TimerInterrupt(void)
{
    int battery_voltage;

    StartADC();

    while(ADCrunning){}

    battery_voltage = ADC_value * scale_factor;

    BatteryStateMachine(battery_voltage);
}

void main (void)
{
    StartTimer();

    while(1){}
}

In version two, the interrupt populates a global variable, and my main program has a while loop wherein a function is called whenever that global variable changes:

int battery_voltage;

void TimerInterrupt(void)
{
    StartADC();

    while(ADCrunning){}

    battery_voltage = ADC_value * scale_factor;
}

void main (void)
{
    int old_battery_voltage;

    StartADC();

    while(ADCrunning){}

    old_battery_voltage = ADC_value * scale_factor;

    StartTimer();

    while(1){
        if (battery_voltage == old_battery_voltage){}
        else {
            BatteryStateMachine(battery_voltage);
        }
    }
}

What are the questions I need to ask in order to determine which of these is better for my requirements? Or is one of these methods already clearly superior to the other, and I just don't know it?


texts: Organising loops for parsing a text file

texts:
The following code is from a utility I've written for myself.

It takes a file in this format:

 [SOME_CODE]
 Some following text
 [SOME_OTHER_CODE]
 Some following multi-line
 text

And then outputs a C header file containing some #defines with the strings encoded.

The bottom function, convert, is the one I'm scratching my head about.  It works just fine, but I'm sure there's a better way of organising the loop. Performance isn't a great issue here, just maintainability.  It doesn't have to be super-resilient to unexpected input either. It uses JUCE - hence the non-std string class and file operations.

bool isShortCode(const String & stringToCheck)
{
    return (stringToCheck.length() > 1) && (stringToCheck[0] == '[');
}

String getEncodedDefineAndComment(const String & shortCode, const String & originalText)
{
    String t;
    t += "\n";
    t += "// " + originalText.replace("\n", "\\n") + "\n";
    t += "#define JCF_ENCODED_" + shortCode + " " + getDefineForString(originalText) + "\n";
    return t;
}

void convert(File inFile, File outFile)
{
    auto inString = inFile.loadFileAsString();

    if (inString.isEmpty())
    {
        cout << "error reading input" << endl;
        return;
    }

    auto inLines = StringArray::fromLines(inString);
    String shortCode;
    String text;
    String outputText;

    auto p = inLines.begin();

    while (p != inLines.end())
    {
        String s = *p;

        if (isShortCode(s))
        {
            shortCode = s.removeCharacters("[] ");
            text = String::empty;
            p++;
        }
        else
        {
            if (shortCode.isEmpty())
            {
                cout << "error: input must start with a shortcode" << endl;
                return;
            }

            bool firstTime = true;

            while ((p != inLines.end()) && (! isShortCode(*p)))
            {
                // I only want a new line where there are multiple lines.  I don't want one for the last line.
                if (! firstTime)
                {
                    text += "\n";
                    firstTime = false;
                }

                text += *p;
                p++;
            }
            outputText += getEncodedDefineAndComment(shortCode, text);
        }
    }

    // Happy to assume no errors here.
    outFile.replaceWithText(outputText);
}


texts:
This is a ( single file ) library I wrote as an helper to check arguments validity.Here below a sample usage:

public class Demo
    {
        /// <summary>
        /// Classical not null verification
        /// </summary>
        /// <param name="arg1"></param>
        public void DoSomething(string arg1)
        {
            Contract.Expect(() => arg1).IsNotNull();
        }
        /// <summary>
        /// Asserting an argument greather than another
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        public void DoSomething(int min,int max)
        {
            Contract.Expect(() => min)
                .IsLessThan(int.MaxValue)
                .Meet(a => a <= max);
        }
        /// <summary>
        /// Validate an integer argument in a certain range
        /// </summary>
        /// <param name="arg1"></param>
        public void DoSomething(int arg1)
        {
            Contract.Expect(() => arg1).IsGreatherThan(0)
                                       .IsLessThan(100);
                ;

        }
        /// <summary>
        /// Validate an array in length and asserts first element should be zero
        /// </summary>
        /// <param name="array"></param>
        public void DoSomething(int[] array)
        {
            Contract.Expect(() => array).Meet(a => a.Length > 0 && a.First() == 0);
        }

    }

Exception message are auto generated based on the argument names, so we don't need magic strings at all. What about it ? Improvement and suggestions? Entire code is hosted here.

EDIT
just to clarify the pourpose of the library: I'm trying to avoid code such as:

if (stringParameter == null)
    throw new ArgumentNullException("stringParameter");

in which we need to write a string to specify the parameter name. This is not refactory friendly, neither DRY since you write twice "stringParameter" instead of:

Contract.Expect(() => stringParameter).IsNotNull();

That is once, and refactor friendly ( at least in my opinion ;) ).


texts: Making Tic-Tac-Toe winning check more efficient

texts:
My code works perfectly fine and I would just like to clean it up a little. From the research I've done, I cannot find anyone that used a multidimensional list to a game of TTT. I'm just looking for a way to make this code prettier than it is right now.

grid = [['-','-','-'],
       ['-','-','-'],
       ['-','-','-']]
turn = 'x'
stl = True
print("Please use this format: row/col")
rounds = 0

def printGrid(grid):
    for i,j,k in grid:
        b = print(i,j,k)

def place(grid,turn,row,col):
    if grid[row][col] == '-':
        grid[row][col] = turn
        return True

    else:
        print("Please select an untaken postion\n")
        return False

while stl:
    rounds += 1
    print("Round %i!" % rounds)

    try:

        printGrid(grid)
        print("\nIt is %s's turn.\n" % turn)
        inp = input("What position do you want to place your symbol? (row/col 1-3/1-3) ")
        row,col = inp.split('/')
        row = int(row)-1
        col = int(col)-1
        print()

        a = place(grid,turn,row,col)

        if a == True:
            if turn == 'x':
                turn = 'o'
            else:turn = 'x'

    except(IndexError,ValueError):print("\nPlease select a viable position.\n")

    print('----------------------------------\n')

    if ['x','x','x'] in grid:
        print("X Victory! You won in %i rounds!\n" % rounds)
        printGrid(grid)
        stl = False
    elif ['o','o','o'] in grid:
        print("O Victory! You won in %i rounds!\n" % rounds)
        printGrid(grid)
        stl = False

    if grid[0][0] == 'x' and grid[1][0] == 'x' and grid[2][0] == 'x':
        print("X Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][1] == 'x' and grid[1][1] == 'x' and grid[2][1] == 'x':
        print("X Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][2] == 'x' and grid[1][2] == 'x' and grid[2][2] == 'x':
        print("X Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][0] == 'x' and grid[1][1] == 'x' and grid[2][2] == 'x':
        print("X Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][2] == 'x' and grid[1][1] == 'x' and grid[2][0] == 'x':
        print("X Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False

    elif grid[0][0] == 'o' and grid[1][0] == 'o' and grid[2][0] == 'o':
        print("O Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][1] == 'o' and grid[1][1] == 'o' and grid[2][1] == 'o':
        print("O Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][2] == 'o' and grid[1][2] == 'o' and grid[2][2] == 'o':
        print("O Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][0] == 'o' and grid[1][1] == 'o' and grid[2][2] == 'o':
        print("O Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False
    elif grid[0][2] == 'o' and grid[1][1] == 'o' and grid[2][0] == 'o':
        print("O Victory! You won in %i rounds!" % rounds)
        printGrid(grid)
        stl = False

As you can see, the last portion of the code is gross. I would just like to see if there is a better way of dealing with this.


texts: Script to hide Excel rows where certain columns contain 0

texts:
I have the following script which works, but takes a lot of time to run on a worksheet with 2000+ rows. Anyone know of a way to speed it up?

The code runs through the workbook and ignores the pages I do not want it to touch. Then, it runs through any pages that I want it to, looks for rows with a zero in column C and Column D and if found hides the row.

Sub HideDoubleZeors()

Dim LR As Long, i As Long
Dim c As Variant

For Each ws In Worksheets
Select Case ws.Name
    Case "Form1", _
            "Form 2", _
            "Form 3"
            'Do nothing on these tabs

    Case Else 'If not one of the above tab names then do this
    With ws.Activate
        LR = ws.Range("B" & Rows.Count).End(xlUp).Row
        For i = 1 To LR
        With ws.Range("B" & i)
        For Each c In Range("B" & i)
            If c.Value <> "All Forms" _
                And c.Value <> "Week One All Forms" _
                And c.Offset(0, 1).Value = 0 _
                And c.Offset(0, 1).Value <> vbNullString _
                And c.Offset(0, 2).Value = 0 _
                And c.Offset(0, 2).Value <> vbNullString _
            Then Rows(c.Row).Hidden = True
            Next c

       End With
      Next i
   End With
   End Select
Next ws
End Sub


texts: Calculating delta in SpriteKit using Swift

texts:
I am attempting to learn swift by refactoring one of my old games and I need to rewrite my update method which calculates a delta time. This code works but is ugly. How would I go about properly rewriting this?

import SpriteKit

class GameScene: SKScene {
    var lastUpdateTimeInterval: CFTimeInterval?

    override func update(currentTime: CFTimeInterval) {

        var delta: CFTimeInterval?
        if let luti = lastUpdateTimeInterval {
            delta = currentTime - luti
        } else {
            delta = currentTime
        }

        lastUpdateTimeInterval = currentTime;

        if (delta > 1.0) {
            delta = minTimeInterval;
            lastUpdateTimeInterval = currentTime;
        }

        updateWithTimeSinceLastUpdate(delta!)
    }
}


texts:
If I'm creating an immutable class from an existing class, should I override methods that mutate the property or have an instance of it and write my own methods to read from the property?

I have an existing class Set which is basically a fancy array. There's a few more methods in the class but for the purposes of this question they aren't relevant.

<?php

class Set implements \ArrayAccess, \Countable, \IteratorAggregate
{
    protected $items;

    public function __construct(array $items = array()) {
        $this->items = $items;
    }

    public function has($key) {
        return array_key_exists($key, $this->items);
    }

    public function get($key) {
        return $this->has($key) ? $this->items[$key] : null;
    }

    public function set($key, $value) {
        $this->items[$key] = $value;
    }

    public function remove($key) {
        unset($this->items[$key]);
    }

    public function count() {
        return sizeof($this->items);
    }

    public function offsetExists($offset) { return $this->has($offset); }
    public function offsetGet($offset) { return $this->get($offset); }
    public function offsetSet($offset, $value) { $this->set($offset, $value); }
    public function offsetUnset($offset) { $this->remove($offset); }

    public function getIterator() {
        return new \ArrayIterator($this->items);
    }
}

Now I want to create ImmutableSet and here are two options that I came up with:

class ImmutableSet extends Set
{
    public function set($key, $value) {
        throw new \Exception('Cannot set things');
    }

    public function remove($key) {
        throw new \Exception('Cannot remove things');
    }
}

The problem I see with this approach is the existence of set and remove for an immutable object doesn't seem right and supposing that the Set class implemented a method for example clear then I'd have to override that too.

Alternatively, I can do this:

class ImmutableSet implements \Countable, \IteratorAggregate
{
    private $items;

    public function __construct(array $items) {
        $this->items = new Set($items);
    }

    public function has($key) {
        return $items->has($key);
    }

    // Implement get, count, and getIterator to call $items->
}

My concern with this design is basically the opposite of the other one. Supposing that Set implemented a method getAllKeys, I'd have to implement it here too to benefit from the functionality.

What is the better approach here?


texts: Improve Parallel Cache with Reactive Extensions & Unity Interception

texts:
The requirement is to be able to cache method invocations made on a boundary layer (Services layer). I'm using Unity to inject the concrete implementation of the Service layer classes. The intercepting CacheCallHandler caches all the responses across this layer.

The twist is that this is a multi-threaded environment with multiple clients invoking the same boundary layer in the context of a single request. If a service layer call is already in "flight", it should wait for the original invokers return and use that.

I've used Reactive extensions to implement this.

/// <summary>
/// Intercepts the calls and tries to retrieve from the cache
/// </summary>
class CacheCallHandler : ICallHandler
{

    [Dependency]
    public ICache RequestCache { get; set; }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        IMethodReturn mesg = null;

        string cacheKey = CacheKeyGenerator.GetCacheKey(input);

        //create the task to retrieve the data
        var task = new Task<IMethodReturn>(() =>
        {
            return getNext()(input, getNext);
        });

        //make it observable
        var observableItem = task.ToObservable();

        //try to add it to the cache
        //we need to do this in the order of Add and then try to get, otherwise multiple thread might enter the same area
        if (RequestCache.TryAdd(cacheKey, observableItem))
        {
            //if the add succeeed, it means that we are responsible to starting this task
            task.Start();
        }
        else
        {
            if ( RequestCache.TryGetValue(cacheKey, out observableItem) )
            {
                //do nothing, the observable item is already updated with the requried reference
            }
            else
            {
                throw new CacheHandlerException("Could not add to cache AND could not retrieve from cache either. Something's wrong", input);
            }
        }

        //observe the return
        if ( observableItem != null )
            mesg = observableItem.FirstOrDefault();

        if (mesg == null)
            throw new CacheHandlerException("Not return value found. this should not happen", input);

        return mesg;
    }

    /// <summary>
    /// Should always be the first to execute on the boundary
    /// </summary>
    public int Order
    {
        get { return 1; }
        set { ; }
    }
}


texts: Custom bang! method and Rails validation

texts:
I have a model called booking.

class Booking < ActiveRecord::Base
  has_many :charges
  def charge!
    raise "Not active" if !active?

    c = charges.create()
    c.charge!
  end
end

However I feel this is not optimal. For example, it would be nice to integrate the activeness checking into Rails' own validation system.

Another example is that Rails build-in create or save are not used:

class Booking < ActiveRecord::Base
  has_many :charges
  def charge!
    raise "Not active" if !active?

    compute_charges!
  end
end

However I want the bang! method to imitate so that it feels like it went through validation and persistence. Is there a more elegant way to do this?


texts:
We have some BloomFilters (like a java.util.set without deletion) and we store them in ehcache (you can think it's as a java.util.Map):

For example, Constant.BLOOM_FILTER_CACHE ehcache contains:

key   value
aaa   bloomfilter (of name aaa)
bbb   bloomfilter (of name bbb)
ccc   bloomfilter (of name ccc)

If we call localCacheManager.get(Constant.BLOOM_FILTER_CACHE, aaa), it will return a bloomfilter (of name aaa) or Null (if not initialized).

If we call localCacheManager.put(Constant.BLOOM_FILTER_CACHE, aaa, new BloomFilter(100, 0.001)), it will put a bloomfilte to cache entry aaa.

If we want to add data1 into BloomFilter of name aaa, then we may call add(aaa, data1) and if we want to know if aaa BloomFilter contains data1, we should call contains(aaa, data1) (in that case, it will return true).

If we want to look up or add, we should check the bloomfilter is initialized or not.

package com.xxx.utils.bloomfilter;

import com.clearspring.analytics.stream.membership.BloomFilter;
import com.xxx.utils.cache.ehcache.LocalCacheManager;
import com.xxx.utils.common.Constant;

public class BloomFilterInCache {
  private int bloomFilterElementSize;
  private double bloomFilterErrorRate;
  private LocalCacheManager localCacheManager;

  public BloomFilterInCache(int bloomFilterElementSize,
      double bloomFilterErrorRate, LocalCacheManager localCacheManager) {
    this.bloomFilterElementSize = bloomFilterElementSize;
    this.bloomFilterErrorRate = bloomFilterErrorRate;
    this.localCacheManager = localCacheManager;
  }

  private boolean isBloomFilterExistsByName(String name)
  {
    BloomFilter bf = (BloomFilter) localCacheManager.get(Constant.BLOOM_FILTER_CACHE, name);
    if (bf == null)
      return false;
    return true;
  }

  private void newBloomFilter(String name)
  {
    BloomFilter bf = new BloomFilter(bloomFilterElementSize, bloomFilterErrorRate);
    localCacheManager.put(Constant.BLOOM_FILTER_CACHE, name, bf);
  }

  private void NotExistsThenPut(String name)
  {
    if (!isBloomFilterExistsByName(name))
    {
      newBloomFilter(name);
    }
  }

  public boolean contains(String name, String key)
  {
    NotExistsThenPut(name);
    BloomFilter bf = (BloomFilter) localCacheManager.get(Constant.BLOOM_FILTER_CACHE, name);
    return bf.isPresent(key);
  }

  public void add(String name, String key)
  {
    NotExistsThenPut(name);
    BloomFilter bf = (BloomFilter) localCacheManager.get(Constant.BLOOM_FILTER_CACHE, name);
    bf.add(key);
  }
}

Are there any flaws in this code?


texts: Upper section of a vertical single-page website

texts:
This is my very first attempt to write HTML and CSS. I designed this website for a friend. I'm not sure if I used the best practices or maybe I did something wrong but I just started my learning process so I would love a review to point bad practices and things I could have done better or I did wrong.

This is meant to be the first section (above the fold) of a vertical single-page website.

* {
  font-family: Open Sans;
  margin: 0px
}

#PageHeader {
  background-color: rgb(236, 100, 62);
  height: 615px;
}
/* logo and nav look aligned on the original file :c */
#logo {
  position: relative;
  margin-left: 40px;
  top: 30px;
}

a.nav:link {
  text-decoration: none;
  font-size: 12px;
  font-weight: bold;
  color: white;
  text-transform: uppercase;
  margin-right: 40px;
  float: right;
}

a.nav:hover{
  border-width: 0px 0px 3px 0px;
  border-style: solid;
}

#heading{
  color: white;
  text-align: center;
  line-height: 1.2;
  margin-top: 150px;
}

h1{
  font-size: 60px;
  margin-bottom: 30px;
}

    <title>Empreendi na Rede</title>
    <meta charset="utf-8">
    <meta name="author" content="Luciano Infanti">

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,800" rel="stylesheet">

        Solucoes
        Metodologia
        Sobre nos
        Depoimentos
        Clientes
        Contato

A consultoria empresarial
 acaba de ser redefinida

Aliquam et placerat lacus. Donec pharetra nibh a placerat tincidunt.

  Integer viverra nisl dolor, in viverra enim sollicitudin nec.