texts: "How can I make this SEDE query better?" (bad title finder)

texts:
It was suggested on Meta for July 2015 Community Challenge to make a bot that can find questions with bad titles. I wrote this query to help others find examples to help them make write their code.

I made it a point to document as I wrote it so that someone who is a beginner with SQL could still make changes to it easily. Is there room for improvements?

Here is the query on SEDE

DECLARE @Question INT = (SELECT Id FROM PostTypes WHERE Name = 'Question');
DECLARE @Answer INT = (SELECT Id FROM PostTypes WHERE Name = 'Answer');

SELECT
/* Uncomment below if you want to limit the results */
/* TOP 100 */
    Posts.Id AS [Post Link]
  /* only for sanity check in case the filter is removed from WHERE clause */
  , CASE
      WHEN Posts.PostTypeId = @Question THEN 'Question'
      WHEN Posts.PostTypeId = @Answer THEN 'Answer'
      ELSE 'Other' END
      AS [Post Type]
  , Posts.Score
  , Posts.CreationDate
  , Users.Id AS [User Link]
  , Users.Reputation
FROM Posts
INNER JOIN Users
  ON Posts.OwnerUserId = Users.Id
WHERE
  /* Filter out non-question posts */
  Posts.PostTypeId = @Question

  /* Generic title */
  AND (
    Posts.Title LIKE '%please%' OR
    Posts.Title LIKE '%review%' OR
    Posts.Title LIKE '%improve%' OR
    Posts.Title LIKE '%better%' OR
    Posts.Title LIKE '%how to%'OR
    Posts.Title LIKE '%how can i%' OR
    Posts.Title LIKE '%how do i%'
  )

  /* Post not closed yet */
  AND Posts.ClosedDate IS NULL

  /* Question doesn't have positive score */
  /* AND Posts.Score <= 0 */

  /* User has low reputation */
  AND Users.Reputation <= 500

ORDER BY

  /* Lowest scores first - Change to DESC if you want Highest first */
  Posts.Score ASC

  /* Newest first - Change to ASC if you want oldest first */
  , Posts.CreationDate DESC


texts: Prime factorization for integers with up to 9-digit long prime factors

texts:
I've become interested prime factorization since solving Project Euler problem 3 (finding the largest prime factor of 600851475143). Learning here that initializing lists with many elements to later prune them is the computational equivalent of swimming with bricks, I challenged myself to code a function that returns all prime factors as efficiently as possible, without the need for initializing a big list beforehand.

The routine takes the input n and divides it by 2 as many times as possible before leaving a remainder, redefining n to be the result of the division each time. When 2 no longer cleanly divides n, it moves to 3, but it is after 3 that the crux of the inefficiency arises.

After 3, if n does not equal 1 and there are still factors to be found, the next factor tried is the next consecutive odd integer after 3. For example, take the number \$129373200 = (2^4) × (3^5) × (5^2) × (11^3)\$. After the algorithm divides all 2's, 3's and 5's away, the next test-number is 7, which I view as efficient because 7 is prime. However, as the routine iterates, 9 is tested before 11, and I see this as inefficient because 9 is composite.

If I edit the code such that it stores all tested numbers in a list, and checks if the next test-number is a multiple of a previously tested one or not before iterating, the runtime slows down considerably. Is there an efficient way to do this sort of check via elementary functions without storing tested numbers in a list (or set, dictionary, etc.)?

TLDR: I want to understand why factoring numbers with 8-digit-long prime factors takes the code 7 seconds versus numbers with 9-digit-long prime factors that take nearly 2.5 minutes to solve. I want to reduce this large jump in runtime.

def pf(n):
    startTime=datetime.now()
    factors = [] #Initialize a list to store prime factors.
    while n % 2 == 0:  #While n/2 continues to yield no remainder:
        factors += [2] #Append 2 to the factor list.
        n /= 2         #Redefine n as n/2.
    if n == 1:         #If n is 1, all of its prime factors have been found,
        print datetime.now() - startTime
        return factors #so return the factor list to the user.
    p = 3 #Initialize a count at 3, the next prime after 2
    while p*p <= n:        #While n is greater than or equal to p*p:
        if n%p == 0:       #If p divides n:
            factors += [p] #Append p to the factor list.
            n /= p         #Redefine n as n/p.
        else:       #If p doesn't divide n:
            p += 2  #See if the next consecutive odd number up divides n.
                    #Once all smaller factors are found, and n is smaller than p*p,
    factors += [n]  #append n to the factor list,
    print datetime.now() - startTime,
    return factors  #and then return it to the user.

print pf(121)
print pf(42768)
print pf(19440)
print pf(97200)
print pf(129373200) #inefficiency example
print pf(600851475143)
print pf(31610054640417607788145206291543662493274686990) #consecutive primes
print pf(4383898882371133212190175441147530134182228613257) #5-6 digit primes
print pf(815145012617325671714771027149) #8-digit primes
print pf(9657874875862260078751562987967607300225789) #9-digit primes

Output:

0:00:00 [11, 11]
0:00:00 [2, 2, 2, 2, 3, 3, 3, 3, 3, 11]
0:00:00 [2, 2, 2, 2, 3, 3, 3, 3, 3, 5]
0:00:00 [2, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5]
0:00:00 [2, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 11, 11, 11]
0:00:00 [71, 839, 1471, 6857L]
0:00:00 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113L]
0:00:00.023000 [37489, 59617, 63577, 63841, 74771, 75521, 82217, 97283, 102181, 104717L]
0:00:06.935000 [15485867, 32452843, 32452867, 49979687L]
0:02:24.362000 [122949829, 314606891, 393342743, 674506111, 941083987L]


texts:
I'm a business student who just started to learn VBA. I am trying to write a macro for a project but only have minimal experience actually stepping into the code.

The macro I have written is to delete all row entries which do not meet my criteria if they contain certain words, including removing those with future month's dates in them, and I'd like for this to update based on the current month.  I have found that normally the code runs very quickly, but when I add the last part, which removes those with future dates, the code becomes extremely slow.

Is there a way to speed it up or rewrite it so that it is faster?

Sub Remove_excess_entries()
    Dim lRow As Long
    Dim iCntr As Long
    lRow = 10000
    For iCntr = lRow To 1 Step -1
        If Cells(iCntr, 12).Value = "Mule" Or Cells(iCntr, 11).Value = "*R1*" Or Cells(iCntr, 11).Value = "*R2*" Or Cells(iCntr, 7).Value = "*Mule*" Or Cells(iCntr, 6).Value = "*Unassigned*" Or Cells(iCntr, 12).Value = "PS" Or Cells(iCntr, 7).Value = "Marketing" Or Cells(iCntr, 12).Value = "V1" Or DatePart("m", Cells(iCntr, 16).Value) > DatePart("m", Date) Then
            Rows(iCntr).Delete
        End If
    Next
End Sub


texts:
def gcd(a,b):
    if (a>b):
        r1=a
        r2=b
    else:
        r1=b
        r2=a
    if(r1%r2==0):
        print (r2)
    else:
        gcd(r2, r1%r2)
a= int(input("Enter a number"))
b= int(input("Enter a number"))
gcd(a,b)

This code is about finding the greatest common divisor of two numbers.
Are there any better methods?
How can I improve this code?


texts: Validating the difference in days between two dates

texts:
I have some code that is used for validating a condition based on dates, which is always a bit tricky. Here is the code:

package rules

type valueInterval struct {
    min int
    max int
}

func (v valueInterval) containsClosed(x int) bool {
    return x >= v.min && x <= v.max
}

func permanentExpiryLimit(entityToCheck bla.Entity, intervalInDays valueInterval, compare time.Time) (RuleStatus, string) {
    if entityToCheck.PermanentExpiry == nil {
        return RULE_NOT_APPLICABLE, "... TODO ..."
    }

    diff := beginningOfDay(*entityToCheck.PermanentExpiry).Sub(beginningOfDay(compare))
    diffInDays := int(diff.Hours()) / 24

    if diffInDays < 0 {
        return RULE_NOT_APPLICABLE, "... TODO ..."
    }

    if !intervalInDays.containsClosed(diffInDays) {
        return RULE_FAILED, "... TODO ..."
    }

    return RULE_PASSED, "... TODO ..."
}

func beginningOfDay(datetime time.Time) time.Time {
    oneDay := 24 * time.Hour
    return datetime.Truncate(oneDay)
}

Client code:

   status, msg := permanentExpiry(entity, valueInterval{0, 100}, time.Now())

The idea is that this code check if the PermanentExpiry is at most 100 days in the future from a given compare date.

It can be assumed that both dates are in the same timezone. The dates should be compared only on day basis, that's why the time objects are reset to 00:00:00 time.

Still feels a bit clunky and not sure if it's clear that the comparision is done based on full days only. Any comments appreciated.


texts: matplotlib fixing axis scale and alignment

texts:
There is few points In the script I don't like I think it can be improved, but I need a second opinion, here is the interactive plot I'm trying to build.

here is the code with thought in comments.

#!/usr/bin/python3

from functools import lru_cache

import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

@lru_cache # beacuse it redraws each time
def get_pdf(mu, sigma=1, offset=4):
    o = sigma * offset
    x = np.linspace(mu - o, mu + o, 100)
    rv = ss.norm(mu, sigma)
    return x, rv.pdf(x)

fig, ax = plt.subplots()
# added the subplot for bottom margin and the slider, since its also the ax
plt.subplots_adjust(bottom=0.25)

ax.fill_between(*get_pdf(0), label='A', alpha=0.7)
ax.set_xlim(-10, 10)
ax.set_ylim(0, 1)

# my guess is this has to be integrated with the update rather than outside
# and using t variable as global which I don't like, and guess it can be improved
t = ax.fill_between(*get_pdf(2), label='B', color='crimson', alpha=0.7)

slider = widgets.Slider(
    # ax position are absolute, should be easy without subplot may be
    ax      = plt.axes([0.25, 0.1, 0.5, 0.03]),
    label   = "shift",
    valmin  = -5,
    valmax  = 5,
    valinit = 2,
    valstep = 0.5
)

def update(val):
    x, y = get_pdf(val)
    global t # really hate to do this
    t.remove()
    t = ax.fill_between(*get_pdf(val), color='crimson', alpha=0.7)
    fig.canvas.draw_idle()

slider.on_changed(update)
ax.legend()
plt.show()


texts: Code efficiency check for hangman in Delphi

texts:
I recently coded a game of hangman and wanted to know,

A: Are there any places it could be more efficient?

B: Are there any things that are distinctly wrong with it, since I know people seem to say to avoid using GOTO and SLEEP?

C: Is there a way to have it generate words randomly or a database the code could access?

If you don't get any of the variables please let me know, although I have made an effort to match the name to the purpose. (Also if anyone has a better way to print the man, that would be appreciated too).

Since this still hasn't been answered i'm going to try direct responses to only shortening the Gameplay. Many thanks!

Code:

program Hangman;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  Classes,
  Math;

var
  WordPlaceHolder: array [1 .. 10] of string;
  BoardStore, BoardPieces: array [1 .. 6] of string;
  Wordlist: TStringList;
  Check, Lives, Points, Counter, RandomNum: integer;
  GuessedWord, SelectedWord: string;

procedure PrintGameBoard;
begin
  Writeln('  |//======|');
  Writeln('  |/      \| ');
  Writeln('  |        ', BoardPieces[1]);
  Writeln('  |      ', BoardPieces[2], BoardPieces[3], BoardPieces[4]);
  Writeln('  |       ', BoardPieces[5], ' ', BoardPieces[6]);
  Writeln('  |');
  Writeln(' /|\');
  Writeln('/|||\');
  for Counter := 1 to length(SelectedWord) do
    write(WordPlaceHolder[Counter]);
  Writeln('');
end;

Procedure GamePlay;
Begin

  Writeln('Please guess a letter');
  GuessedWord := 'a';
  Writeln(SelectedWord);
  repeat
    readln(GuessedWord);
    GuessedWord := lowercase(GuessedWord);
  until ((GuessedWord[1] in ['a' .. 'z']) and (length(GuessedWord) = 1)) or
    (lowercase(GuessedWord) = SelectedWord);
  if GuessedWord = SelectedWord then
  begin
    Points := 100;
    exit;
  end;
  for Counter := 1 to length(SelectedWord) do
  begin
    if SelectedWord[Counter] = GuessedWord[1] then
    begin
      WordPlaceHolder[Counter] := ' ' + GuessedWord[1];
      Points := 1;
      Check := Check + 1;
    end;
  end;
  if Points = 0 then
  begin
    BoardPieces[Lives] := BoardStore[Lives];
    Lives := Lives + 1;
  end;
  Points := 0;
  if Check = length(SelectedWord) then
    Points := 100;
  if Lives = 7 then
    Points := 100;
  PrintGameBoard;
End;

begin
  RANDOMIZE;
  Wordlist := TStringList.Create;
  Wordlist.CommaText :=
    'amazing,supreme,ironic,whatever,guesses,obscene,quintuple,eliminate,random,headway,existing,interest,leaves,seasons,swell,hyper';
  Writeln('Hangman');
  Writeln('Gameboard');
  BoardStore[1] := 'O';
  BoardStore[2] := '/';
  BoardStore[3] := '( )';
  BoardStore[4] := '\';
  BoardStore[5] := '/';
  BoardStore[6] := '\';
  Lives := 1;
  PrintGameBoard;
  RandomNum := randomrange(0, 16);
  SelectedWord := Wordlist[RandomNum];
  Writeln('');
  for Counter := 1 to 10 do
    WordPlaceHolder[Counter] := ' _ ';
  for Counter := 1 to length(SelectedWord) do
    write(WordPlaceHolder[Counter]);
  Writeln('');
  repeat
    GamePlay;
  until Points = 100;
  if Lives = 7 then
  begin
    Writeln('');
    Writeln('The word was: ', SelectedWord);
    Writeln('You lose, R.I.P.');
  end;
  if (Points = 100) and (Lives <> 7) then
  begin
    Writeln('');
    Writeln('Well done you win!');
  end;
  readln;

end.


texts: Algorithm that receives a dictionary, converts it to a GET string, and is optimized for big data

texts:
I found this question online as an example from a technical interview and it seems to be a flawed question in many ways. It made me curious how I would answer it.  So, If you were on a technical Python interview and asked to do the following:

  Write an algorithm that receives a dictionary, converts it to a GET string, and is optimized for big data.

Which option would you consider the best answer? Any other code related comments are welcome.

Common:

import requests
base_url = "https://api.github.com"
data = {'per_page': 10}
node = 'users/arctelix/repos'

Option 1:

My first thought was just answer the question in the simplest form and use pagination to control the size of the data returned.

def get_query_str(node, data=None):
    # base query
    query_str = "%s/%s" % (base_url, node)
    # build query params dict
    query_params = "&".join(["%s=%s" % (k,str(v))
                             for k, v in data.items()])
    if query_params:
        query_str += "?%s" % query_params
    return query_str

print("\n--Option 1--\n")
url = get_query_str(node, data)
print("url = %s" % url)

Option 2:

Well, that's not really optimized for big data and the requests library will convert a dict to params for me. Secondly, a generator would be a great way to keep memory in check with very large data sets.

def get_resource(node, data=None):
    url = "%s/%s" % (base_url, node)
    print("geting resource : %s %s" % (url, data))
    resp = requests.get(url, params=data)
    json = resp.json()
    yield json

print("\n--Option 2--\n")
results = get_resource(node, data)
for r in results:
    print(r)

Option 3:

Just in case the interviewer was really looking to see if I knew how join() and a list comprehension could be used to convert a dictionary to a string of query parameters. Let's put it all together and use a generator for not only the pages, but the objects as well. get_query_str is totally unnecessary, but again the task was to write something that returned a "GET string"..

class Github:
    base_url = "https://api.github.com"

    def get_query_str(self, node, data=None):
        # base query
        query_str = "%s/%s" % (self.base_url, node)
        # build query params dict
        query_params = "&".join(["%s=%s" % (k,str(v))
                                 for k, v in data.items()])
        if query_params:
            query_str += "?%s" % query_params
        return query_str

    def get(self, node, data=None):
        data = data or {}
        data['per_page'] = data.get('per_page', 50)
        page = range(0,data['per_page'])
        p=0
        while len(page) == data['per_page']:
            data['page'] = p
            query = self.get_query_str(node, data)
            page = list(self.req_resource(query))
            p += 1
            yield page

    def req_resource(self, query):
        print("geting resource : %s" % query)
        r = requests.get(query)
        j = r.json()
        yield j

gh = Github()
pages = gh.get(node, data)
print("\n--Option 3--\n")
for page in pages:
    for repo in page:
        print("repo=%s" % repo)


texts:
I have a small library for utility functions for ES5 mainly aimed at OO code organization.

Are there any recommendations for the API or for the code quality / organization?

github page
styleGuide it complies to

Note the library has a few tricks in it for aggressive minification.

Code inlined

/*
    pd(obj) -> propertyDescriptorsOfObject {
        bindAll: function that binds all the methods of an object to the object,
        extend: function that extends the first argument with the rest
        Name: returns a namespace(anyKey) -> uniqueObject function
    }

    pd requires ES5. Uses the shimmable subset of ES5.
*/
(function (Object, slice) {
    "use strict";

    extend(pd, {
        bindAll: bindAll,
        extend: extend,
        Name: Name
    });

    typeof window !== "undefined" ? window.pd = pd : module.exports = pd;

    /*
        pd will return all the own propertydescriptors of the object

        @param Object object - object to get pds from.

        @return Object - A hash of key/propertyDescriptors
    */
    function pd(obj, retObj) {
        retObj = {};
        Object.getOwnPropertyNames(obj).forEach(function(key) {
            var pd = Object.getOwnPropertyDescriptor(obj, key);
            retObj[key] = pd;
        });
        return retObj;
    }

    /*
        Extend will extend the firat parameter with any other parameters
        passed in. Only the own property names will be extended into
        the object

        @param Object target - target to be extended
        @arguments Array [target, ...] - the rest of the objects passed
            in will extended into the target

        @return Object - the target
    */
    function extend(target) {
        slice.call(arguments, 1).forEach(function(source) {
            Object.defineProperties(target, pd(source));
        });
        return target;
    }

    /*
        defines a namespace object. This hides a "privates" object on object
        under the "key" namespace

        @param Object object - object to hide a privates object on
        @param Object key - key to hide it under

        @author Gozala : https://gist.github.com/1269991

        @return Object privates
    */
    function namespace(object, key) {
        var privates = Object.create(object),
            valueOf = object.valueOf;

        Object.defineProperty(object, "valueOf", {
            value: function(value) {
                return value !== key ? valueOf.apply(this, arguments) : privates;
            },
            writable: true
        });

        return privates;
    }

    /*
        Constructs a Name function, when given an object it will return a
        privates object.

        @author Gozala : https://gist.github.com/1269991

        @return Function name
    */
    function Name(key) {
        key = {};
        return name;

        function name(object) {
            var privates = object.valueOf(key);
            return privates !== object ? privates : namespace(object, key)
        }
    }

    /*
        bindAll binds all methods to have their context set to the object

        @param Object obj - the object to bind methods on
        @param Array whitelist - optional whitelist of methods to bind

        @return Object - the bound object
    */
    function bindAll(obj, whitelist) {
        (whitelist || Object.keys(obj).filter(getMethods)).forEach(bindMethods);

        return obj;

        function getMethods(key) {
            return obj[key].call;
        }

        function bindMethods(name) {
            obj[name] = obj[name].bind(obj)
        }
    }
})(Object, [].slice);


texts: Getting functional Common Lisp code for handling state in a SDL animation

texts:
The following code draws a red rectangle bouncing between the borders of a white display. I'm not particularly happy with the update function:

(require 'lispbuilder-sdl)

(defun update-h-speed (state h-border top-left-border)
  (if (or (< (cdr (assoc 'h-coord state)) top-left-border) ;;if too left
      (> (cdr (assoc 'h-coord state)) h-border))       ;;if too right
      ;; negate the horizontal speed
      (acons 'h-speed (- (cdr (assoc 'h-speed state))) state)
      state))

(defun update-v-speed (state v-border top-left-border)
  (if (or (< (cdr (assoc 'v-coord state)) top-left-border) ;;if too high
      (> (cdr (assoc 'v-coord state)) v-border))       ;;if too low
      ;; negate the vertical speed
      (acons 'v-speed (- (cdr (assoc 'v-speed state))) state)
      state))

(defun update-coords (state)
  (acons 'h-coord (+ (cdr (assoc 'h-coord state))
               (cdr (assoc 'h-speed state)))
       (acons 'v-coord (+ (cdr (assoc 'v-coord state))
                  (cdr (assoc 'v-speed state))) state)))

(defun update (state width height size)
  (let ((h-border (- width (/ size 2)))
    (v-border (- height (/ size 2)))
    (top-left-border (/ size 2)))
    (update-coords
     (update-h-speed
      (update-v-speed state v-border top-left-border) h-border top-left-border))))

(defun game (&optional (width 320) (height 240) (speed 2) (size 20))
  (let ((decoy (pairlis (list 'h-coord 'v-coord 'h-speed 'v-speed)
            (list (/ width 2) (/ height 2) speed speed))))
    (sdl:with-init ()
      (sdl:window width height :title-caption "My game")
      (setf (sdl:frame-rate) 60)
      (sdl:with-events ()
    (:quit-event () t)
    (:key-down-event (:key key)
             (when (sdl:key= key :sdl-key-escape) (sdl:push-quit-event)))
    (:idle ()
           ;; update state
           (setq decoy (update decoy width height size))
           (sdl:clear-display sdl:*white*)
           ;; draw the rectangle according to the updated state
           (sdl:draw-box (sdl:rectangle-from-midpoint-*
                  (cdr (assoc 'h-coord decoy)) (cdr (assoc 'v-coord decoy)) size size)
                 :color sdl:*red*)
           (sdl:update-display))))))

In fact, the big-bang function in Racket made such things quite easy. With big-bang, I usually created a structure to hold every object (just coordinates and speeds of the rectangles) and modified each part of the structure with separate functions.

Please note that this is not a question about making this animation work.

1) I would like to get advice about, how to refactor such programs to make the update function more functional, so that it is easier to expand (add new features) and debug.

2) I'm particularly confused about whether I should prefer special variables to hold the structures, or prefer to create them locally as is the case. Do you prefer one over the other during different cycles of programming (like development and distribution)?

Note: I preferred an assoc list in place of a hash table, because of the few number of pairs, and the acons enables a sort of history feature, if this thing will ever going to work.


texts:
I wrote this little hook so I could fetch some remote resources:
import {DependencyList, useEffect, useRef, useState} from "react";

export default function useAsyncValue<T>(cb: () => Promise<T>, deps?: DependencyList): T | undefined {
    const [value, setValue] = useState<T | undefined>(undefined)
    const nonce = useRef(Symbol())

    useEffect(() => {
        const current = nonce.current = Symbol()
        Promise.resolve(cb()).then(result => {
            if (nonce.current === current) {
                setValue(result)
            }
        })

        return () => {
            nonce.current = Symbol()
        }
    }, deps)

    return value
}

Use is like:
const value = useAsyncValue(() => fetch("..."))

I added a nonce and some deps too so if you do:
const value = useAsyncValue(() => fetch(`/get?foo=${foo}`), [foo])

Then you value will always be the latest result, and you won't have any results out-of-order bugs from older fetch returning after a later fetch.
Are there any problems with this? I don't need to pass the counter into the useEffects deps list do I?


texts: Find maximum gap between elements of an array

texts:
I am solving interview questions from here.

Problem : Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
Example : A =  [3 5 4 2]  Output : 2 for the pair (3, 4)

Here is my solution:
def maximum_gap( A):
    """find maximum gap between index(j -i ) with  A[i] <= A[j]"""
    gap = 0
    A = list(map( list,enumerate(A))) # get list of [index,value]
    for item in A:
        item[0],item[1] = item[1], item[0] # swap index with value
    a = sorted(A)  # sort list A as per values

    max_index = a[0][1] # initialise max_index to first index in sorted list
    min_index = a[0][1] # initialise min_index to first index in sorted list

    for v,i in a:
        if i > max_index:  # if current > max_index, set max to current
            max_index = i
        if i < min_index:  # if current < min_index, set min to current
            min_index = i
            max_index = i  # reset max to current

        gap_new = max_index - min_index  # find the maximum gap
        if gap < gap_new:
            gap = gap_new

    return gap

Test cases:
print maximum_gap([-1,-1,2])  == 2
print maximum_gap([1,3,5,7,2,4,10])  ==  6
print maximum_gap([3,2,1]) == 0
print maximum_gap([3,2,1,4]) == 3
print maximum_gap([2,2,1,4,3])  == 4
print maximum_gap([ 0,1,2,3])  == 3
print maximum_gap([ 100,100,100,100,100])  == 4

How can I make this code better?


texts: OpenCL approximation of Pi using vectorized implementation

texts:
Yesterday I started following the hands-on OpenCL course. I now got to the point where we are requested to reimplement an approximation algorithm for Pi in OpenCL (in steps, up to a vectorized implementation). I have done so and wanted to get a review for it coupled with some questions I had.
My kernel:
__kernel void pi(const long steps_total, const long steps_per_kernel,
const double step, __global double *global_sums)
{
    const int global_id  = get_global_id(0);
    const int local_id   = get_local_id(0);
    const int local_size = get_local_size(0);

    const long vector_size = 16;
    const double16 deltas  = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

    const long work_dx_start     = global_id * steps_per_kernel;
    const long work_dx_end       = min(work_dx_start + steps_per_kernel, steps_total);
    const long vectorized_dx_end = work_dx_end / vector_size * vector_size;

    double work_sum = 0.0;
    for (long dx = work_dx_start; dx < vectorized_dx_end; dx += vector_size)
    {
        const double16 mid_points   = (dx - 0.5 + deltas) * step;
        const double16 partial_sums = (4.0 / (1.0 + mid_points * mid_points));

        work_sum += partial_sums.s0 + partial_sums.s1 + partial_sums.s2 + partial_sums.s3 +
                    partial_sums.s4 + partial_sums.s5 + partial_sums.s6 + partial_sums.s7 +
                    partial_sums.s8 + partial_sums.s9 + partial_sums.sa + partial_sums.sb +
                    partial_sums.sc + partial_sums.sd + partial_sums.se + partial_sums.sf;
    }
    for (long dx = vectorized_dx_end; dx < work_dx_end; dx++)
    {
        const double mid_point = (dx - 0.5) * step;
        work_sum += 4.0 / (1.0 + mid_point * mid_point);
    }

    const double group_sum = work_group_reduce_add(work_sum);
    if (local_id == 0)
    {
        global_sums[global_id / local_size] = group_sum;
    }
}

I create max_compute_units * preferred_work_group_size work-items, with preferred_work_group_size as the number of items in a group (and so each kernel executes around steps/global_work_size iterations). On the host side the global sums array is finally added again.
Any comments are greatly appreciated (style, optimizations,...), I also have some questions:

It there a nicer way to remove the extra loop at the end in case the iterations are not a multiple of the vector size?
Is there a way to sum all elements of an OpenCL vector faster than this (the elements of partial_sums)? The best I could find was IIRC calculating the dot product (which only seems to exist for vectors up to size 4, and even then, it was slower on my GPU). Also stepwise reducing to vectors of half the size by using addition between lower and upper has no apparent effect. I guess it may not even be possible to optimize further?
On my GPU, using vectors of size 16 performs the best. I take it this can change depending on the device? Is there some way to try to detect/heuristically calculate this up front (statically) and dynamically load a specific kernel? (or other techniques?)


texts:
I have created an employee object to be immutable.

package com.immutable.ex01;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public final class Employee implements Cloneable, Externalizable{
    private final Integer age;
    private final String name;
    private final List<String> companies;
    private final Date dob;

    public Employee(Integer age, String name,List<String> companies, Date dob) {
        this.age = age;
        this.name = name;
        this.companies = companies;
        this.dob = dob;
    }

    public Integer getAge() {
        return this.age;
    }

    public String getName() {
        return this.name;
    }

    public Date getDob() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(this.dob);
        return cal.getTime();
    }

    public List<String> getCompanies() {
        List<String> clone = new ArrayList<String>(this.companies.size());
        for(String companyName : this.companies) {
            clone.add(companyName);
        }
        return clone;
    }

    @Override
    public String toString() {
        StringBuffer strb = new StringBuffer();
        strb.append("AGE").append(" ").append(this.age)
            .append(", NAME ").append(this.name)
            .append(", DOB ").append(this.getDateString())
            .append(", COMPANIES WORKED IN ");
        for(String companyName : this.companies) {
            strb.append(companyName).append(",");
        }

        strb.deleteCharAt(strb.length() - 1);
        return strb.toString();
    }

    @Override
    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot be cloned");
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        throw new IOException("This operation is not supported");
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException {
        throw new IOException("This operation is not supported");
    }

    private String getDateString() {
        String date = null;
        DateFormat df = null;
        try {
            df = new SimpleDateFormat("dd MMM yyyy");
            date = df.format(this.dob);
        }catch(Exception e) {
            e.printStackTrace();
        }
        return date;
    }
}

My main method class

package com.immutable.ex01;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainTest01 {
    public static void main(String [] args) {
        Employee emp = null;
        List<String> companyList = null;
        Date date = null;
        try {
            companyList = new ArrayList<String>();
            companyList.add("IBM");
            companyList.add("Google");
            companyList.add("Norton");
            companyList.add("Seable");
            companyList.add("Nekki");
            date = toDate("28 Oct 1981");
            emp = new Employee(23, "John Molkovich", companyList, date);

            date = emp.getDob();

            date = new Date();

            companyList = emp.getCompanies();
            companyList.add("Toyo Corp");
            System.out.println(emp);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    private static Date toDate(String dateString) throws Exception{
        Date d = null;
        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        d = df.parse(dateString);
        return d;
    }
}

Please review my code and check if I have achieved immutability for my employee class.


texts: MVC OnActionExecuted - session cookie - expire after x minutes of inactivity

texts:
first time poster here.

I'm creating a session cookie which should expire after 30 minutes of user inactivity. I've added the following code to the base controllers OnActionExecuted method.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var sessionCookie = Request.Cookies[COOKIE_VALUE];

        if (sessionCookie == null)
        {
            sessionCookie = new HttpCookie(COOKIE_VALUE)
            {
                Expires = DateTime.Now.AddMinutes(30)
            };

            sessionCookie.Value = Guid.NewGuid().ToString();
        }
        else
        {
            sessionCookie.Expires = DateTime.Now.AddMinutes(30);
        }

        Response.Cookies.Add(sessionCookie);

        base.OnActionExecuted(filterContext);
    }

As this is happening every time a request is made, would this cookie update be noticeable in regards to speed? Any help or suggestions would be greatly appreciated.


texts: Is this attempt at a merge sort correct?

texts:
I am trying to write a merge sort algorithm. I can't tell if this is actually a canonical merge sort. If I knew how to calculate the runtime I would give that a go. Does anyone have any pointers?

public static void main(String[] argsv) {

    int[] A = {2, 4, 5, 7, 1, 2, 3, 6};
    int[] L, R;

    L = new int[A.length/2];
    R = new int[A.length/2];

    int i = 0, j = 0, k;

    PrintArray(A);
    // Make left and right arrays
    for (k = 0; k < A.length; k++) {
        if (k < A.length/2) {
            L[i] = A[k];
            i++;
        }
        else {
            R[j] = A[k];
            j++;
        }
    }

    PrintArray(L);
    PrintArray(R);

    i = 0;
    j = 0;
    // Merge the left and right arrays
    for (k = 0; k < A.length; k++) {
        System.out.println(i + " " + j + " " + k);
        if (i < L.length && j < R.length) {
            if (L[i] < R[j]) {
                PrintArray(A);
                A[k] = L[i];
                i++;
            }
            else {
                PrintArray(A);
                A[k] = R[j];
                j++;
            }
        }
    }

    PrintArray(L);
    PrintArray(R);
    PrintArray(A);
}

public static void PrintArray(int[] arrayToPrint) {
    for (int i = 0; i < arrayToPrint.length; i++) {
        System.out.print(arrayToPrint[i] + " ");
    }
    System.out.print("\n");
}


texts:
I've got a working program that turns XML into a XmlObject. The object can then be accessed using getName(), getValue(), and getChild(). The code works but I'm looking for recommendations. I couldn't find anything built into c# that creates an object from XML. I'm currently learning by doing games in Unity so hopefully the code isn't too awful.

The static class for creating an XmlObject

namespace XmlToObject
{
    using System.Collections.Generic;
    using System.Xml;
    using System.IO;
    using UnityEngine;

    /// XmlObjectCreator turns xml into an XmlObject
    public static class XmlObjectCreator
    {

        /// Generates the xml object.
        public static XmlObject generateXmlObject (TextAsset xmlTextFile, string nameOfFirstTag)
        {
            //load the xml document
            XmlDocument xmlDoc = new XmlDocument ();
            xmlDoc.Load (new StringReader (xmlTextFile.text));

            //Navigate to the first tag
            XmlNode firstNode = xmlDoc.SelectSingleNode ("//" + nameOfFirstTag);

            //Return the built object
            return recursiveBuildXmlObject (firstNode);
        }

        /// Recursivly builds an xml object.
        private static XmlObject recursiveBuildXmlObject (XmlNode startNode)
        {
            //Create the buildObject
            XmlObject buildObject = new XmlObject ();

            //Set the name and value
            buildObject.setName (startNode.Name);
            buildObject.setValue (startNode.InnerText);

            //Add child nodes to subList if they exist
            foreach (XmlNode child in startNode.ChildNodes) {
                buildObject.add (recursiveBuildXmlObject (child));
            }

            //Once children are done
            return buildObject;
        }
    }
}

The XmlObject is what is actually used for accessing the data taken from the XML document.

namespace XmlToObject
{
    using System.Collections.Generic;

    /// Xml object is the actual object used for navigating the data.
    public sealed class XmlObject
    {
        private string name;
        private string value;
        private List<XmlObject> subList;

        /// Initializes a new instance of the XmlObject class.
        public XmlObject ()
        {
            subList = new List<XmlObject> ();
            value = null;
        }

        /// Add the specified inputXmlObject.
        public void add (XmlObject inputXmlObject)
        {
            subList.Add (inputXmlObject);
        }

        /// Gets a xml child by name.
        public XmlObject getChild (string name)
        {
            foreach (XmlObject child in subList) {
                if (name.Equals (child.getName ())) {
                    return child;
                }
            }

            throw new System.ArgumentException ("Child with name: " + name + " does not exist.");
        }

        //Setters and getters for fields: name, value

        public string getName ()
        {
            return name;
        }

        public void setName (string newName)
        {
            name = newName;
        }

        public string getValue ()
        {
            return value;
        }

        public void setValue (string newValue)
        {
            value = newValue;
        }
    }
}

I've seen lots of code that deals with known XML structures, but few examples where the XML structure is not predefined/known. I'm sure that there is a better way to do what this code does, I'm just not sure what it is.


texts: Simple REST Base Web Server with Unit Tests

texts:
I am building out a simple web server in Go. My goal is to expand on this framework in a different application I am building.

Here is my github repo
https://github.com/jmacnc/gowebserver

Is what I have here using best practices?

I am specifically looking for feedback on the tests, and how I am connecting to different databases (testing and main application). As seen below...

//Handler for posting a new user
func (d *MongoDB) PostUser(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    //Retrieving request body
    var user User
    _ = json.NewDecoder(r.Body).Decode(&user)
    //Posting Company
    err := d.PostUserToDB(user)
    //Error Handling
    if err != nil {
        fmt.Println(err)
        w.WriteHeader(500)
    }
}

//Populating a new user in the database
func (d *MongoDB) PostUserToDB(user User) error {
    _, err := d.db.Collection("users").InsertOne(context.Background(), user)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    //Connects to the database
    d , _ := ConnectToDB()
    //Creates mux router/multiplexer
    r := mux.NewRouter()
    //Handle Functions
    r.HandleFunc("/user", d.PostUser).Methods("POST")
    //Starts web server
    //Prints a string saying that the app is running...
    fmt.Println("Application Running...")
    log.Fatal(http.ListenAndServe(LOCALHOST, r))
}


texts:
The facade pattern is used to abstract adding events.  Should support IE5+ as stands.

Looking for minor improvements.  Don't need to support prior to IE5.

I choose not to use a library.

/*addEL
**  dependencies - none
**  browser - IE5+
**  notes - improved per answer
*/
NS.addEL = (function binding() {
    if (window.addEventListener) {
        return function addEventListener(element, type, callNow) {
            element.addEventListener(type, callNow);
        };
    }
    if (window.attachEvent) {
        return function attachEvent(element, type, callNow) {
            element.attachEvent('on' + type, callNow);
        };
    }
}());


texts: Validating a string under few conditions

texts:
Following code validates NIC number of a person (National Identity Card, no like SSN)
Requirements are...

Length should be 10 digits or characters
All should be digits except the last one
Last one would be x or v in simple letters

Currently I'm using following method and its working. I just want to know that could this be make better or simplified?

    private bool ValidateNIC(string nic)
    {
        if (!string.IsNullOrEmpty(nic))
        {
            char[] letter = nic.ToCharArray();
            if (letter.Length == 10)
            {
                if (letter[9] == 'v' | letter[9] == 'x')
                {
                    for (int i = 0; i <= (letter.Length - 2); i++)
                    {
                        if (char.IsNumber(letter[i]) == false)
                        {
                            MessageBox.Show(string.Format("letter {0 } is not allowed, all Should be numbers except the last one.", letter[i]));
                            return false;
                        }
                    }
                    return true;
                }
                else
                {
                    MessageBox.Show("Last letter should be x or v in simple letters");
                    return false;
                }
            }
            else
            {
                MessageBox.Show("Length should be 10 ");
                return false;
            }
        }
        else
        {
            MessageBox.Show("NIC is null");
            return false;
        }
    }


texts:
I was looking for a way of doing simple message passing in Guile and found some references to the module (ice-9 occam-channel) which is a pretty nifty, but undocumented, module for occam-like channels. Since I decided I wanted to use buffered channels I decided to try and write my own implementation of it based on the occam-channel module.

My first attempt looks like this:

(define-module (gbot buffered-channel)
               #:use-module (oop goops)
               #:use-module (ice-9 threads)
               #:export (make-buffered-channel
                          ? ??
                          !))

(define-class <channel> ())

(define-class <buffered-channel> (<channel>)
              (buffer #:accessor buffer #:init-value '())
              (cv #:accessor cv #:init-form (make-condition-variable))
              (mutex #:accessor mutex #:init-form (make-mutex)))

(define-method (make-buffered-channel)
               (make <buffered-channel>))

; Hold until there is something in the channel and then
; pop the first item in the buffer.
(define-method (? (ch <buffered-channel>))
               (lock-mutex (mutex ch))
               (if (eq? (buffer ch) '())
                 (wait-condition-variable (cv ch) (mutex ch)))
               (let ((res (car (buffer ch))))
                 (set! (buffer ch) (cdr (buffer ch)))
                 (unlock-mutex (mutex ch))
                 res))

; Return #f if there is nothing in the buffer, otherwise
; pop the first element of the buffer.
(define-method (?? (ch <buffered-channel>))
               (lock-mutex (mutex ch))
               (let ((res (if (eq? (buffer ch) '())
                            #f
                            (let ((res (car (buffer ch))))
                              (set! (buffer ch) (cdr (buffer ch)))
                              res))))
                 (unlock-mutex (mutex ch))
                 res))

(define-method (! (ch <buffered-channel>))
              (! ch *unspecified*))

; Push x onto the buffer FILO-style.
(define-method (! (ch <buffered-channel>) x)
               (lock-mutex (mutex ch))
               (set! (buffer ch) (cons x (buffer ch)))
               (signal-condition-variable (cv ch))
               (unlock-mutex (mutex ch)))

Being rather new at scheme programming and the pitfalls of concurrent programming I'm quite suspicious of the correctness of this code since it's significantly shorter than the code in occam-channel while still being more capable. I've done some simple testing but still haven't found any problems with it, any suggestions for improvement?


texts:
Looking at back at the C++ projects I've developed, the Makefiles are a mess.  To tell you the truth, I copied one a long time ago and basically have been cutting and pasting it haphazardly ever since.  I've decided to change that so I've been reading more about how Make actually works and some best practices for using it going forth.  As most of the programs I write are not that complicated I've come up with a generic Makefile I can cut and paste ^W^W^W deploy going forth.  I'd like some feedback on it.

Any input (except "you should be using cmake or $(OTHER_TRENDY_NEW_TOOL) instead") is welcome but some specific questions that come to mind are:

Have I forgotten to add something?
Conversely, have I added too much?
Is it worth making this a POSIX makefile.  Currently I've only tried
it with GNU make on Linux but portability is good.  What about BSD or
Windows make? Or should I just rely on gmake being available pretty
much everywhere?
Do I have all the recommended compiler/linker flags for C++?  I would
like to be able to choose between g++ and clang atleast so options
should be portable between both though if there is something good
that only one supports I can special case it.  (Can I?)
I'm assuming Visual Studio/Windows in general is a whole separate can
of worms so I've ignored it for now but if you know how this Makefile
could be adapted for Windows development I'd be happy to know.

Thanks in advance.

    PROGRAM=someprogram
    SRCDIR:=src
    INCDIR:=include
    DEPDIR:=deps
    BUILDDIR:=build
    DESTDIR?=
    PREFIX?=/usr/local
    BINDIR?=bin

    SRC:=$(wildcard $(SRCDIR)/*.cc)
    OBJECTS:=$(patsubst $(SRCDIR)/%.cc,$(BUILDDIR)/%.o,$(SRC))
    DEPFILES:=$(patsubst $(SRCDIR)/%.cc,$(DEPDIR)/%.d,$(SRC))

    CXX?=/usr/bin/g++
    STRIP?=/usr/bin/strip
    INSTALL?=/usr/bin/install
    VALGRIND?=/usr/bin/valgrind

    CPPFLAGS:=-I$(INCDIR)
    CXXFLAGS:=-std=c++17 -Wall -Wextra -Wpedantic -flto ${CXXFLAGS}
    LDFLAGS:=-ffunction-sections -fdata-sections -Wl,-gc-sections $(LDFLAGS)
    DEPFLAGS=-MT $@ -MMD -MP -MF $(DEPDIR)/$*.Td

    COMPILE.cc=$(CXX) $(DEPFLAGS) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
    LINK.cc=$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)
    POSTCOMPILE=mv -f $(DEPDIR)/$*.Td $(DEPDIR)/$*.d && touch $@

    all: debug

    $(BUILDDIR)/%.o: $(SRCDIR)/%.cc $(DEPDIR)/%.d | $(DEPDIR) $(BUILDDIR)
        $(COMPILE.cc) $(OUTPUT_OPTION) $<
        $(POSTCOMPILE)

    $(BUILDDIR)/%.o: $(SRCDIR)/%.s | $(BUILDDIR)
        $(COMPILE.s) $(OUTPUT_OPTION) $<

    $(BUILDDIR): ; @mkdir -p $@

    $(DEPDIR): ; @mkdir -p $@

    $(DEPFILES):

    $(PROGRAM): $(OBJECTS)
        $(LINK.cc) $(OUTPUT_OPTION) $^

    debug: CPPFLAGS += -DDEBUG
    debug: CXXFLAGS += -g3
    debug: $(PROGRAM)

    release: CXXFLAGS += -O2
    release: distclean $(PROGRAM)
        $(STRIP) --strip-all  -R .comment -R .note $(PROGRAM)

    memcheck: debug
        $(VALGRIND) --suppressions=valgrind.suppressions --quiet --verbose --leak-check=full --show-leak-kinds=all --track-origins=yes --log-file=valgrind.log ./$(PROGRAM)

    install: release
        $(INSTALL) -m755 -D -d $(DESTDIR)$(PREFIX)/$(BINDIR)
        $(INSTALL) -m755 $< $(DESTDIR)$(PREFIX)/$(BINDIR/$(PROGRAM)

    clean:
        -rm -rf $(BUILDDIR)
        -rm -rf $(DEPDIR)
        -rm valgrind.log

    distclean: clean
        -rm $(PROGRAM)

    .PHONY: all debug release memcheck install clean distclean

    .DELETE_ON_ERROR:

    -include $(wildcard $(DEPFILES))

```


texts: Better method structure for insertion in doubly linked list

texts:
Here is my insertion method for a doubly linked list. It works, but passing two parameters for the method seems cumbersome. Can anyone suggest a cleaner approach than this?

   LinkedList list = new LinkedList();
    Link link1 = new Link("A");
    list.insert(list.head,link1);
    Link link2 = new Link("B");
    list.insert(link1, link2);
    Link link3 = new Link("C");
    list.insert(link2, link3);
    list.display_List_Start_From_Head();

public void insert(Link currentNode, Link newNode)
    {
        if(head == null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            currentNode.next = newNode;
            newNode.prev = currentNode;
            tail = newNode;
        }

    }


texts:
I need to redo a migration occasionally. The workflow is usually something like this:

find or ls | grep the migration using some keyword
copy the timestamp
paste the timestamp in bundle exec rake db:migrate:redo VERSION=123

As I hate repetitive work, I wrote a small bash script that allows running a migration using only a partial name. If there are many matches, it lists them all.

#!/usr/bin/env bash

err() {
  echo "redo: error: $1"
  echo "redo: usage: redo <migration_name>"
  exit 1
}

[[ -d ./db/migrate ]] || err "dir db/migrate not found"

migrations=$(find './db/migrate' -name '*.rb' | grep "$1" | sed 's#^\./db/migrate/##')
declare -A times
for m in $migrations; do
  time=$(echo "$m" | sed 's#\([0-9]*\)_.*.rb#\1#')
  name=$(echo "$m" | sed 's#[0-9]*_\(.*\)\.rb#\1#')
  times["$name"]="$time"
done

if [[ ${#times[@]} == 1 ]]; then
  name="${!times[@]}"
  ver="${times[$name]}"
  echo "redo: executing \`bundle exec rake db:migrate:redo VERSION=$ver\`"
  bundle exec rake db:migrate:redo VERSION="$ver"
  exit 0
fi

echo -e "redo: be more specific, candidates are:\n"
for k in "${!times[@]}"; do
  echo "$k : ${times[$k]}"
done
exit 1

I'd love to get feedback.


texts: Building a report of DNA sites and chunks

texts:
Here is the slow part of my code:

def Prepare_WCfst_file():
    content_WCfst = "iteration\tlocus\tFromSite\tToSite\tWCFst\n"
    nbchunks = nbsites/nbsitesPerChunk
    if nbchunks%1 != 0:
        print("\n\nThe number of sites per chunk for WCFst is not a divisor of the number of sites per locus.\nProcess is aborted!\n\n")
        sys.exit(1)
    nbchunks = int(nbchunks)
    nbsitesPerChunk_minus1 = nbsitesPerChunk - 1
    for iteration in xrange(nbiterations):
        for locus in xrange(nbloci):
            FromSite = 0
            ToSite = nbsitesPerChunk_minus1
            for chunk in xrange(nbchunks):
                content_WCfst += str(iteration) + "\t" + str(locus) + "\t" + str(FromSite) + "\t" + str(ToSite) + "\n"
                FromSite = ToSite + 1
                ToSite = FromSite + nbsitesPerChunk_minus1
    return content_WCfst

Typically, nbiterations and nbloci take values between 1 and 100. nbchunks however can take values of the order of 10^6 to 10^9. This function will be called about 100 to 10,000 times in total.

Suggested data to benchmark

nbloci = 10^6
nbiterations = 20
nbloci = 2
nbsitesPerChunk = 10

What the function does

Basically, what this piece of code does is to create a long string content_WCfst (which will afterward be written on a file). The file needs to contain 4 columns: iteration, locus, FromSite and ToSite. The difference between the columns FromSite and ToSite is always nbsitesPerChunk_minus1. By the end the number of lines is nbiterations * nbloci * nbchunks.

My thoughts about what to improve

I think the part that can be improved is the three loops or eventually only the most internal loop (for chunk in xrange(nbchunks):)

Note that I've tried to replace

str(iteration) + "\t" + str(locus) + "\t" + str(FromSite) + "\t" + str(ToSite) + "\n"

by

"\t".join(str(iteration), str(locus), str(FromSite), str(ToSite), "\n")

but it was even slower.

Note also that the function doesn't receive any arguments and therefore, all parameters are defined globally outside this function. I don't expect it to be an issue as they are not called over and over again.

I am hoping that a solution can exist so that the looping occurs in C, using NumPy eventually.


texts:
Originally, I was going to post a question about how to condense four repetitive functions into a single function, but I wound up figuring it out myself before I could even post it.

However, the original idea that I had was to break down some of the repetitive sections into their own function and use those new sub-functions as part of the main one. I'm still not sure how I would have been able to make that work if I hadn't figured out the bigger picture.

function GetClock(){
    var d=new Date().addHours(1);
    var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getYear();
    if(nyear<1000) nyear+=1900;
    var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;

    if(nhour===0){ap=" ";nhour=12;}
    else if(nhour<12){ap=" ";}
    else if(nhour===12){ap=" •";}
    else if(nhour>12){ap=" •";nhour-=12;}

    if(nhour<=9) nhour="0"+nhour;
    if(nmin<=9) nmin="0"+nmin;
    if(nsec<=9) nsec="0"+nsec;

    document.getElementById('clockbox').innerHTML=""+tday[nday]+", "+tmonth[nmonth]+" "+ndate+", "+nyear+" "+nhour+":"+nmin+":"+nsec+""+ap+"";
}

This is one of the sections that I was originally thinking about splitting off into its own function:

if(nhour===0){ap=" ";nhour=12;}
else if(nhour<12){ap=" ";}
else if(nhour===12){ap=" •";}
else if(nhour>12){ap=" •";nhour-=12;}

These were my two feeble attempts to make it work:

function ampm() {
    if(nhour===0){ap=" ";nhour=12;}
    else if(nhour<12){ap=" ";}
    else if(nhour===12){ap=" •";}
    else if(nhour>12){ap=" •";nhour-=12;}
}

And then this:

function ampm(nhr,ampm) {
    if(nhr===0){ampm=" ";nhr=12;}
    else if(nhr<12){ampm=" ";}
    else if(nhr===12){ampm=" •";}
    else if(nhr>12){ampm=" •";nhr-=12;}
}

But they both failed due to (what I'm assuming are) issues with scope that I'm not sure how to solve.


texts: Efficiently matching pairs of elements and applying specific hover trigger/animation to each pair

texts:
After scouring the interweb, I am having trouble finding an efficient solution to the following issue (the biggest problem was knowing what to ask):

I'm trying to find a way to write a more efficient version of the jQuery script found on the example site (also listed below). The biggest hurdle I'm facing is figuring out a way to dynamically match a trigger element (for example, .logo_wrap div.logo.img1) with its respective animating element (.sliding_titles .img1).

I've added numbers to the end of the divs that need to be matched, I just can't seem to find a way to properly match them, then apply a hover trigger to one and a slide-out animation to the other.

The example site I've created for this post only lists six objects, however there's another site that needs this to be done to 29 separate pairs of objects - which ends up being a ton of code.

Please see example site - which works fine. I just need to find a way to more efficiently write the script associated with it: http://redesign.mproven.com/sliding_example.html

Any and all help in this matter is greatly appreciated, thank you.

Here's a simple example:

Javascript (jQuery):

$(document).ready(function(){

$('.logo.img1, .logo.img2, ...etc,').fadeTo("fast", 0);

    $(".logo.img1").hover(function() {
    $(this).stop().animate({"opacity": "1"}, "500");
    $('.sliding_titles div.img1').stop().animate({opacity: 1, width: "500px", overflow: "visible" }, 400);
},
function() {
    $(this).stop().animate({"opacity": "0"}, "500");
    $('.sliding_titles div.img1').stop().animate({opacity: 0, width: "0px", overflow: "hidden" }, 1);
});

$(".logo.img2").hover(function() {

    ... etc.

});

HTML (in the order they appear in the body tag):

First are the content modules that slide out when its matched logo is hovered over:

YouTube slideout placeholder content

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 ... etc ...

Then come the logo divs, which - when hovered - will trigger its respective content div to slide out (listed above):

    ... etc ...


texts:
This JavaScript converts degrees to a compass point, e.g. convert.toCompass(140) gets 140° -> SE.

I can't help but think: is there a more concise way to do this?

var convert = {
    toCompass: function(degrees)
    {
        if(degrees >= 0 && degrees <= 11.25)
        {
            return 'N';
        }

        else if(degrees > 11.25 && degrees <= 33.75)
        {
            return 'NNE';
        }

        else if(degrees > 33.75 && degrees <= 56.25)
        {
            return 'NE';
        }

        else if(degrees > 56.25 && degrees <= 78.75)
        {
            return 'ENE';
        }

        else if(degrees > 78.75 && degrees <= 101.25)
        {
            return 'E';
        }

        else if(degrees > 101.25 && degrees <= 123.75)
        {
            return 'ESE';
        }

        else if(degrees > 123.75 && degrees <= 146.25)
        {
            return 'SE';
        }

        else if(degrees > 146.25 && degrees <= 168.75)
        {
            return 'SSE';
        }

        else if(degrees > 168.75 && degrees <= 191.25)
        {
            return 'S';
        }

        else if(degrees > 191.25 && degrees <= 213.75)
        {
            return 'SSW';
        }

        else if(degrees > 213.75 && degrees <= 236.25)
        {
            return 'SW';
        }

        else if(degrees > 236.25 && degrees <= 258.75)
        {
            return 'WSW';
        }

        else if(degrees > 258.75 && degrees <= 281.25)
        {
            return 'W';
        }

        else if(degrees > 281.25 && degrees <= 303.75)
        {
            return 'WNW';
        }

        else if(degrees > 303.75 && degrees <= 326.25)
        {
            return 'NW';
        }

        else if(degrees > 326.25 && degrees <= 348.75)
        {
            return 'NNW';
        }

        else if(degrees > 348.75 && degrees <= 360)
        {
            return 'N';
        }
    }
}


texts: DRY for rendering same header table for different content

texts:
I'm trying to make the following code DRY. The code outputs a table that shows violations. If there is any violation.status = resolved they go in separate table for resolved items. Since the header and columns of the table are the same, I believe I should be able to make this DRY using a For loop. However, I'm not sure that's possible in Django templates.

There's three relevant context variables:

violation_list which is a query set of all violations
not_resolved_violations which is (1) excluding status = resolved
resolved_violations which is (1) filtered on status = resolved

{% if violation_list %}

{% if not_resolved_violations %}

Open Violations

        #
        IDENTIFIER

{% for violation in not_resolved_violations %}

        {{ forloop.counter }}

            {{ violation.identifier }}

{% endfor %}

{% endif %}

{% if resolved_violations %}

Resolved Violations

        #
        IDENTIFIER

{% for violation in resolved_violations %}

        {{ forloop.counter }}

            <a href='#'

{% endfor %}

{% endif %}

{% else %}

This project doesn't have any violations associated it with it.

{% endif %}


texts: Sum of all arguments ever passed to counter

texts:
Q4. Define a function make_counter that returns a counter function,
  which takes an immutable key and a numerical value argument and
  returns the sum of all arguments ever passed to counter with that same
  key.

Below is the solution:

def make_counter():
    """Return a counter function.

    >>> c = make_counter()
    >>> c('a', 3)
    3
    >>> c('a', 5)
    8
    >>> c('b', 7)
    7
    >>> c('a', 9)
    17
    >>> c2 = make_counter()
    >>> c2(1, 2)
    2
    >>> c2(3, 4)
    4
    >>> c2(3, c('b', 6))
    17
    """
    dict = {}
    def counter(key, value):
        if key in dict:
            dict[key].append(value)
        else:
            dict[key] = [value]
        lst = dict[key]
        total = 0
        length = len(lst)
        for index in range(length):
            total = total + lst[index]
        return total
    return counter
    """-m doctest gives some weird failure despite all above test case pass"""

Can we improve this solution?


texts: Determining if a connection has been made to a communications device

texts:
I am unsure if my use of Monitor.Wait and Monitor.Pulse is correct. It seems to work alright, but there is a nagging doubt I am doing something wrong.

Am I dealing with a timeout OK, or is there a better way to do it?

All examples I have seen use Monitor.Wait with a while loop, and not with an if to re-check the blocking condition after Pulse, but I need to determine if a timeout occurred.

_cmdDispatcher.EnqueueCommand(cmd) sends a command to the device, and it responds with an event that executes the CommResponseReceived method on another thread.

private readonly object _connectLock = new object();

public bool Connect()
{
    if (this._connected) throw new InvalidOperationException("Plc is already connected.");

    ICommand cmd = new Command(MessageIdentifier.Name);

    try
    {
        if (this._channel.Open() && !this._connected)
        {
            // Wait for communications to be fully established or timeout before continuing.
            lock (this._connectLock)
            {
                this._cmdDispatcher.EnqueueCommand(cmd);

                if (!this._connectSignal)
                {
                    if (Monitor.Wait(this._connectLock, this._timeout))
                    {
                        this._connected = true;
                        this._connectSignal = false;
                        Debug.WriteLine("Connection succeeded.");
                    }
                    else
                    {
                        //TODO Log timeout.
                        Debug.WriteLine("Connection timed out.");
                    }
                }
            }

            if (this._connected) this.OnConnectionChangedEvent(ConnectionStatus.Connected);
        }
    }
    catch (Exception ex)
    {
        //TODO Log errors.
        Debug.WriteLine("Connection failed.");
    }

    return this._connected;
}

Executed in another thread when the device responds:

private void CommResponseReceived(object sender, CommsResponseEventArgs e)
{
    //

    // Signal that communications are successfully established.
    lock (this._connectLock)
    {
        this._connectSignal = true;
        Monitor.Pulse(this._connectLock);
    }
}


texts:
I tried to create a class which downloads the HTML source from a link and saves it. I'm a newbie to all this Android stuff, even new to Java, but this is what I have so far.

It seems to work at least, although I cannot see the file since it is hidden.

package com.example.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class PageDownloader {

    String Filename;
    String urlString;
    Context context;

    public PageDownloader( Context ctx) {
        Filename = "tmpPage.html";
        context = ctx;
    }

    public void download( String _url ){
        urlString = _url;
        testClass t = new testClass();
        t.execute();

    }
    public void _download(){
        /*
         * First Download content
         * Then Save File
         *
         */
        String result = null;

        //DOWNLOAD
        try {
            URL url = new URL( urlString );
            URLConnection con = url.openConnection();
            con.connect();
            InputStream in = con.getInputStream();
            byte[] data = new byte[ in.available() ];

            while( in.read(data) != -1 ){
                result += new String(data);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //SAVE
        saveFile( result );
    }

    private void saveFile( String r )
    {
        try {
            File f = new File( context.getFilesDir(), "myfile" );
            if( !f.exists() )
                f.createNewFile();

            FileOutputStream fos = new FileOutputStream(f);//context.openFileOutput(Filename, context.MODE_PRIVATE);
            fos.write( r.getBytes() );
            fos.close();

            Log.w( "PageDownloader", "got it!" );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.w("PageDownloader", e.getMessage());
        }

    }

    public class testClass extends AsyncTask<Void, Integer, Void>
    {

        @Override
        protected Void doInBackground(Void... params) {
            _download();
            return null;
        }

    }
}

I call it from my onCreate method in my MainActivity.java :

PageDownloader p = new PageDownloader(this);
String url = "www.google.com/";
p.download( url );

How is this class written? Anything wrong or to improve?

I want to use this code to download several (maybe 5 up to 20) pages when I click on something. After I downloaded the source I want to extract information out of it. Maybe there is a way to make it faster.


texts:
The expected functionality is that a user/vehicle interacts with a ParkingLot and it allots the space in Park method based on type of vehicle (here I can expect a few changes, like increase from regular and handicapped to one more functionality for celebrities etc). What would be the route to perfect object oriented code?

class Vehicle
 attr_accessor :regno,:type
 def initialize(regno,type)
     @regno=regno
     @type=type
 end
end

class ParkingLot
 attr_accessor :size , :handicapped_size , :regular_size

 def initialize(size)
    @lot={}
    @size=size
    @handicapped_size=(0.1)*size
    @regular_size=size-@handicapped_size

 end
 def check_regular
    @regular_size>0 ? @regular_size-=1 : false
 end
 def check_handicapped
    @handicapped_size>0 ? @handicapped_size-=1 : false
 end

 def park(vehicle,hour)
    case vehicle.type
    when "regular"
        check_regular ? @lot[vehicle.regno]=Regular_ParkingSpace.new(hour).payment : error()
    when "handicapped"
        check_handicapped ? @lot[vehicle.regno]=Handicapped_ParkingSpace.new(hour).payment : error()
    end
 end

 def unpark(vehicle)
    pay=@lot[vehicle.regno]
    puts "Pls pay us #{pay} rupees"
    @lot.delete(vehicle.regno){|el| puts "#{el} not found in this parking lot \n"}
 end

 def error
    raise "No more vehicles can be parked !! \n"
 end
end
class ParkingSpace
 attr_accessor :hour,:rate
 def initialize(hour,rate)
    @hour=hour
    @rate=rate
 end
 def payment
    @hour * @rate
 end
end

class Regular_ParkingSpace < ParkingSpace
 def initialize(hour,rate=20)
    super
 end
 def payment
    super
 end
end
class Handicapped_ParkingSpace < ParkingSpace
 def initialize(hour,rate=5)
    super
 end
end

Please  mention the principle in use too.


texts:
In the bit of code below:

How can I make add_day, add_ week and add_month work as a single function? They are almost copy-paste of one another. I'm trying to follow the DRY rule.
How can I set this so that I don't use the variables day/week/cur_day?

import datetime
from collections import defaultdict

class ParsedData:
    def __init__(self, date, score, status, item_name):
        year, month, self.day = date.split("-")
        self.month = datetime.date(int(year), int(month), int(self.day)).strftime("%B")
        self.score = int(score)
        self.status = status
        self.item_name = item_name

class Log:
    def __init__(self):
        self.day = {}
        self.week = {}
        self.month = {}
        self.counter = {}

        self.default_data

    def add_day(self, day, status, item_name, score):
        day = 'Day %i' % day
        if day not in self.day:
            self.day[day] = {"Comp": defaultdict(int),
                         "Miss": defaultdict(int),
                         "Post": defaultdict(int),
                         "Add": defaultdict(int),
                         "Score": 0}

        self.day[day][status][item_name] += 1
        self.day[day]['Score'] = score

    def add_week(self, week, status, item_name, score):
        week = 'Week %i' % week
        if week not in self.week:
            self.week[week] = {"Comp": defaultdict(int),
                         "Miss": defaultdict(int),
                         "Post": defaultdict(int),
                         "Add": defaultdict(int),
                         "Score": 0}

        self.week[week][status][item_name] += 1
        self.week[week]['Score'] = score

    def add_month(self, month, status, item_name, score):
        if month not in self.month:
            self.month[month] = {"Comp": defaultdict(int),
                         "Miss": defaultdict(int),
                         "Post": defaultdict(int),
                         "Add": defaultdict(int),
                         "Score": 0}

        self.month[month][status][item_name] += 1
        self.month[month]['Score'] = score

def update_views(log_file):
    log = Log()
    day = 0
    cur_day = None
    week = 1

    for line in log_file:
        parsed = ParsedData(*line.strip().split(","))

        if cur_day != parsed.day:
            cur_day = parsed.day
            day += 1
            if day % 7 == 0:
                week += 1

        log.add_day(day, parsed.status, parsed.item_name, parsed.score)
        log.add_week(week, parsed.status, parsed.item_name, parsed.score)
        log.add_month(parsed.month, parsed.status, parsed.item_name, parsed.score)

log_file =   """2015-01-1,0,Add,DW_05
                2015-01-2,-1,Post,CR_02
                2015-01-3,-1,Comp,DIY_01
                2015-01-3,-1,Post,CD_01
                2015-01-4,-1,Miss,D_03
                2015-01-4,0,Miss,D_03
                2015-01-4,-1,Miss,CD_01
                2015-01-4,0,Miss,LS_04
                2015-01-5,1,Comp,DW_05
                2015-01-6,1,Comp,ANI_06
                2015-01-6,1,Comp,LS_04
                2015-01-7,1,Comp,NMW_07
                2015-01-7,1,Post,DW_05
                2015-01-7,1,Miss,LP_08
                2015-01-8,2,Post,CR_02
                2015-01-8,2,Miss,SEV_09
                2015-01-10,3,Comp,M_10
                2015-01-10,3,Add,NID_11
                2015-01-11,2,Add,ANI_06
                2015-01-12,1,Add,VF_12
                2015-01-12,0,Miss,DIY_01
                2015-01-12,1,Add,NID_11
                2015-01-12,0,Miss,D_03
                2015-01-13,1,Miss,SEV_09
                2015-01-13,2,Add,DW_05
                2015-01-13,1,Comp,NMW_07
                2015-01-13,1,Add,CPC_12""".splitlines()

update_views(log_file)


texts: Simplifying logic of overlapping predicates

texts:
I have 3 simple predicates and 3 simple actions to be taken based on those predicates. In my actual application they are not based on integer arithmetic, and in fact are rather expensive to compute (in comparison to the actions taken), but their dependency chain is the same.

#include <iostream>
#include <tuple>

bool pred1(int x) { return x % 30 == 0; }
bool pred2(int x) { return x % 15 == 0; }
bool pred3(int x) { return x %  5 == 0; }

void fun1(int x) { std::cout << "divisible by 30 \n"; }
void fun2(int x) { std::cout << "divisible by 15 \n"; }
void fun3(int x) { std::cout << "divisible by  5 \n"; }

void fun(int x)
{
    if (pred1(x)) {
        fun1(x);
        fun2(x);
        fun3(x);
        return;
    }
    if (pred2(x)) {
        fun2(x);
        fun3(x);
        return;
    }
    if (pred3(x))
        fun3(x);
}

Note that pred1 requires all 3 actions, pred2 the last 2 actions, and pred3 only the 3rd action. I was not happy with this code: while efficient in avoiding extra work, it seems overly repetitive.

However, the following straightforward try at refactoring is a lot more concise but also less efficient as it computes all 3 predicates for all inputs:

// exposition only: will compute pred1, pred2 and pred3 for all inputs
void hun(int x)
{
    if (pred1(x)) fun1(x);
    if (pred2(x)) fun2(x);
    if (pred3(x)) fun3(x);
}

So I came up with the idea of caching the predicate values in a std::tuple and dispatch the various actions based on that:

using Triple = std::tuple<bool, bool, bool>;

auto preds(int x) -> Triple
{
    if (pred1(x)) return Triple{ true,  true, true };
    if (pred2(x)) return Triple{ false, true, true };
    return Triple{ false, false, pred3(x) };
}

void gun(int x)
{
    auto const p = preds(x);
    if (std::get<0>(p)) fun1(x);
    if (std::get<1>(p)) fun2(x);
    if (std::get<2>(p)) fun3(x);
}

Live Example.

So the repetitive logic is hidden inside the repeated values of true in the std::tuple, and the duplicate predicate computation is now reduced to simple lookups into the std::tuple.

Looking at the assembler from gcc.godbolt.org, it seems that the compiler even optimizes away all unnecessary calls to std::get in gun() (e.g. it sees that the remaining fields of the std::tuple will be true if the first one is), essentially reducing the code to that of fun().

Questions:

are there other approaches to simplying the logic of overlapping predicates?
is the gun() version considered more readable and maintainable than the fun() original?
how smart are compilers in eliminating unnecessary lookups when the underying predicates and actions are not so trivial as the ones above?


texts: FizzBuzz Optimisation | Modulus vs Decrement Operator Performance

texts:
This is not the typical debate in FizzBuzz code about how to handle repeated if statement. I believe that it is a matter of personal preference.
I am here to ask about the choice of repeated mathematical operation.
Usually the solution to a FizzBuzz code is to use the modulus operator on every iteration. However, I'm concerned with its performance impact.
From my knowledge, modulus operator is tightly connected with division operator, and has a considerable performance overhead compared to simple increment and decrement operator.
In addition, I don't believe compiler has the ability to analyse and optimise the use of modulus operator in a loop.
Hence, I give the alternative solution that uses only simple decrement operator. The following code are written in C++.
I seek insight on whether my approach will provide performance benefit, or if it is actually a horrible idea that worsen performance.
And if there are other ways I can optimize a FizzBuzz code even further. (I think in a modified FizzBuzz puzzle with lots of cases to compare against, a lookup table might be preferable)

Typical FizzBuzz solution.
for (unsigned int i = 1; i <= 1000000; ++i) {
    if (!(i % 15))
        std::cout << "FizzBuzz\n";
    else if (!(i % 3))
        std::cout << "Fizz\n";
    else if (!(i % 5))
        std::cout << "Buzz\n";
    else
        std::cout << i << '\n';
}

My optimized code.
static const unsigned int fa {3};
static const unsigned int fb {5};

unsigned int a {fa};
unsigned int b {fb};

for (unsigned int i = 1; i <= 1000000; ++i) {
    --a, --b;
    if (!a && !b) {
        a = fa;
        b = fb;
        std::cout << "FizzBuzz\n";
    } else if (!a) {
        a = fa;
        std::cout << "Fizz\n";
    } else if (!b) {
        b = fb;
        std::cout << "Buzz\n";
    } else {
        std::cout << i << '\n';
    }
}
```


texts: Unit tests for a function that calculates demerit points for speeding

texts:
I'm currently working on a unit testing course (NUnit 3.x). I've been tasked with a simple class to test all edge cases.

using System;

namespace TestNinja.Fundamentals
{
    public class DemeritPointsCalculator
    {
        private const int SpeedLimit = 65;
        private const int MaxSpeed = 300;

        public int CalculateDemeritPoints(int speed)
        {
            if (speed < 0 || speed > MaxSpeed)
                throw new ArgumentOutOfRangeException();

            if (speed <= SpeedLimit) return 0;

            const int kmPerDemeritPoint = 5;
            var demeritPoints = (speed - SpeedLimit)/kmPerDemeritPoint;

            return demeritPoints;
        }
    }
}

And -

using System;
using NUnit.Framework;
using TestNinja.Fundamentals;

namespace TestNinja.UnitTests
{
    [TestFixture]
    public class CalculateDemeritPointsTests
    {
        private DemeritPointsCalculator _demeritPointsCalculator;

        [SetUp]
        public void SetUp()
        {
            _demeritPointsCalculator = new DemeritPointsCalculator();
        }

        // my solutions
        [Test]
        [TestCase(65,0)]
        [TestCase(70,1)]
        [TestCase(75,2)]
        [TestCase(80,3)]
        [TestCase(0,0)]
        [TestCase(60,0)]
        [TestCase(66,0)]
        public void CalculateDemeritPoints_WhenCalled_ReturnsExpectedInt(int speed, int expectedResult)
        {
            var result = _demeritPointsCalculator.CalculateDemeritPoints(speed);
            Assert.That(result, Is.EqualTo(expectedResult));
        }

        [Test]
        public void CalculateDemeritPoints_SpeedLessThan0_ThrowsException()
        {
            Assert.That(() => _demeritPointsCalculator.CalculateDemeritPoints(-1), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }

        [Test]
        public void CalculateDemeritPoints_SpeedGreaterThan300_ThrowsException()
        {
            Assert.That(() => _demeritPointsCalculator.CalculateDemeritPoints(301), Throws.InstanceOf<ArgumentOutOfRangeException>());
        }
    }
}

Am I using to many test cases for CalculateDemeritPoints_WhenCalled_ReturnsExpectedInt?

I was thinking about merging the final two tests into one as they would also work with test cases, but I wasn't sure if I was doing to many.


texts:
I made this generic class which helps me reading values from user defaults. Besides it abusing several UserDefaults... what do you see? Can I make some instances share a reference?

class DefaultValue<V> {
    var userDefaults = UserDefaults()
    let name : String
    let defValue : V

    init(name: String, defValue: V) {
        self.name = name
        self.defValue = defValue
    }

    func get() -> V {
        if userDefaults.object(forKey: name) == nil {
            return defValue
        }
        switch defValue {
        case is Int:
            return userDefaults.integer(forKey: name) as! V
        case is Bool:
            return userDefaults.bool(forKey: name) as! V
        case is String:
            return userDefaults.string(forKey: name) as! V
        default:
            return defValue
        }
    }

    func set(value: V) {
        userDefaults.set(value, forKey: name)
    }

    func reset() {
        userDefaults.set(defValue, forKey: name)
    }
}

Usage:

class MyDefaults {
    let LOGGED_IN = DefaultValue<Bool> (name: "logged_in", defValue: false)
    let USERNAME = DefaultValue<String> (name: "username", defValue: "")
}

var settings = MyDefaults()
if settings.LOGGED_IN.get() {
    settings.LOGGED_IN.set(value: true)
} else {
    settings.LOGGED_IN.reset()
}


texts: Most Effective way of fetching data and then notating html table with JavaScript

texts:
I want to notate Stock prices with html table.
The Number of rows (tickers) will be fixed.
and order of Response is also same always.
I want to Just updating Price Cell continuously.
Price data is come from other REST API server and I'll fetch this data on every 2 seconds.
and The Data will be notate on HTML table and Price Cell also will be updated every 2 seconds.
I coded and It works well, but I have a doubt on this DOM Operation. (seems uneconomic)
My codes work like below:

JSON response from the REST API server will be like this:

[
 {"ticker": "stack", "price": "$3.4"},
 {"ticker": "over", "price": "$5.2"},
 {"ticker": "flow", "price": "$6.4"}
]

HTML table will be like below:

  TICKER
  PRICE

  STACK
  $3.4

  OVER
  $5.2

  FLOW
  $6.4

TICKER
PRICE

STACK
$3.4

OVER
$5.2

FLOW
$6.4

On this condition, My JavaScript code like below.

function fetchAndNotateData(){
   fetch(apiURL, {
    method: "GET",
  })
  .then((res) => {
    return res.json();
  })
  .then((data) => {
    data.forEach(element => {
     document.getElementById(`${element.ticker}Price`).innerText = element.price; // seems inefficient
    });
    setTimeout(fetchAndNotateData,2000);
  })
  .catch((err) => {
    console.log(err);
  });
}

There is even 100 over tickers to notate in practice.
so There will be many DOM Operation (e.g. document.getElementById).
and Giving id on each table price cell seems not that efficient.
Is there any other more effective way of fetching data and notating table?
(maybe I need Server-side Rendering ?)


texts:
As a programming exercise I made a square root function in C# using recursion, here is the function:

static double root(double x, double increment, double num)
{
    num += increment;
    if ((num * num).ToString() == x.ToString())
        return num;
    else if (num * num < x)
        return root(x, Math.Abs(increment), num);
    else if (num * num > x)
        return root(x, Math.Abs(increment / 2) * -1, num);
    else
        return double.NaN;
}

static double sqroot(double x)
{
    return root(x, 10, 0);
}

It is able to do int.MaxValue without a problem, but my question is, how can this be improved?


texts:
I have a method that takes a model object, reads through its children and returns a hash of status counts. It should only return a count on a status if one exists.

This method works, but I was wondering if there are a cleaner, more Rubyish way to write it.

The batch_details table is getting very large, so if possible I'd like not to access it twice.

def batch_status
   batch_status = {
      'ready' => 0,
      'processing' => 0,
      'error' =>  0,
      'purchase' => 0,
      'completed' => 0
   }

   self.batch_details.each do |bd|
      batch_status[bd.status] = batch_status[bd.status] + 1
   end
   batch_status['count'] = self.batch_details.count
   batch_status.delete_if {|k, v| v == 0 }
   return batch_status
end

2.1.2 :002 > b.batch_status
 => {"completed"=>4, "count"=>4}


texts: Using Javascript FileWriter with minimal use of closures

texts:
I'm currently writing a WebGL HTML5 game, and large part of the game initialization involved loading assets streamed over a websocket, and saving them to disk using the FileSystem API.

As part of optimizing the code, we're trying to eliminate as many memory allocations as we can, which means cutting down on the use of closures, object/array creation during the main game loop and so on.

One of the biggest uses of closures left is our interaction with the FileSystem API, namely the part where we write the assets to disk:

//Write file to disk
directory.getFile(
    filename,
    CREATE_TRUE,
    function(fileEntry) {
        fileEntry.createWriter(
            function(fileWriter) {
                fileWriter.onwriteend=function(e) {
                    finishedRequest(filename);
                    if (onSuccess!==undefined) onSuccess(filename);
                };
                fileWriter.onerror=function(e) {
                    finishedRequest(filename);
                    if (onError!==undefined) onError(filename, "Write error: "+directoryRoot+"/"+filename);
                };
                var dataBlob=new Blob([new Uint8Array(data)]);
                if (append) fileWriter.seek(fileWriter.length);
                fileWriter.write(dataBlob,"application/octet-stream");
             },
             function(e) {
                 finishedRequest(filename);
                 if (onError!==undefined) onError(filename,"File writer creation error: "+directoryRoot+"/"+filename:"");
             }
        );
    },
    function(e) {
        finishedRequest(filename);
        if (onError!==undefined) onError(filename,DEVELOPMENT_MODE?"File not found: "+directoryRoot+"/"+filename:"");
    }
);

As you can see, this code involves the creation of something like six new closures for every file write, which isn't the greatest when we're trying to cut down on memory allocation.

I initially tried to pull each of the closures out into standalone functions, but obviously I then needed to be able to get references to things like the filename and onSuccess callback function from those standalone functions (whereas previously they would have been able to have access to them from their outer closures):

...
fileWriter.onwriteend=onFileWrite;
...

function onFileWrite=function(e) {
    finishedRequest(filename);  //filename needs to be retrieved from somewhere...
    if (onSuccess!==undefined) onSuccess(filename);
}

The problem is that the onFileWrite callback is only supplied with the event object, which contains a reference to the target fileWriter, but nothing higher.  Crucially, there seems to be no way to link the fileEntry with the fileWriter that it creates, as the createWriter callback only gets given the FileWriter object - with no meta data about what created it.

My question is this: is it possible to rewrite this without using quite some many closures - or ideally none at all?

Edit: I'm convinced that it is (unfortunately) impossible to do this without creating some kind of container for the details of the request, be it a new function whose closure includes the request details, or a new object whose properties have the details.  So, this question really then becomes about the best way to achieve the file write with the smallest amount of memory churn.


texts:
This is a code to calculate somebody's age. It takes 2 inputs:

A specific date (to calculate your age at a specific time or the current time).
The birth date.

print('''# This is Age Calculator Program.
# This program is written by Mahmoud Naguib and it will be improved.
# You can contact me at : https://www.facebook.com/naguibarea
--------------------------------------------------------------------''')
import re

while True:
    spefic_date = input('Enter a spefic date (like this format: day/month/year): ')
    birth_date = input('Enter the birth date (like this format: day/month/year): ')
    print('--------------------------------------------------------------------')
    # This line makes sure that the user's inputs are correct
    # if not it will print a message and the user will enter them again.
    if re.search(r'\d{1,2}/\d{1,2}/\d{4}', spefic_date) is None or re.search(r'\d{1,2}/\d{1,2}/\d{4}', birth_date) is None:
        print('You have entered a wrong format! ')
        print('--------------------------------------------------------------------')
        continue
    # This will convert the user's input into lists to use them in assigning values.
    spefic_date = spefic_date.split('/')
    birth_date = birth_date.split('/')

    # This line assigns spefic year's, month's and day's values.
    spefic_year, spefic_month, spefic_day = int(spefic_date[2]), int(spefic_date[1]), int(spefic_date[0])
    # This line specifies birth year's, month's and day's values.
    birth_year, birth_month, birth_day = int(birth_date[2]), int(birth_date[1]), int(birth_date[0])
    # These lines are for math rules.
    if spefic_day < birth_day:
        spefic_day += 30
        spefic_month -= 1
    if spefic_month < birth_month:
        spefic_month += 12
        spefic_year -= 1
    # These lines calculate years, months and days.
    year = str(spefic_year - birth_year) + ' years, '
    month = str(spefic_month - birth_month) + ' months and '
    day = str(spefic_day - birth_day) + ' days. '
    # These lines are for grammar rules.
    if spefic_year - birth_year < 2:
        year = year.replace('years', 'year')
    if spefic_month - birth_month < 2:
        month = month.replace('months', 'month')
    if spefic_day - birth_day < 2:
        day = day.replace('days', 'day')
    print('Your age is: ' + year + month + day)
    print('--------------------------------------------------------------------')


texts:
I've recently started to check out Angular 2 and TypeScript that comes with it, and I guess I'm kinda into it. However I'm not too sure about the whole "TypeScript way" of doing things, specifically the typing of variables and such.

I wrote this simple modal component which displays a modal when the ModalApiService has its open function called from anywhere in the application. There can be multiple modals on the same page that's why I had to also include the passing of a modalId to the modal so I could identify them correctly.

Can this code be optimized in any way?
Do I set the types in a correct way? Are there more things I should set a type for?
Does TypeScript have any features that I'm not taking full advantage of here?

Component:

export class ModalComponent {
  public isOpen: boolean = false;

  constructor(private _modalApi: ModalApiService, private _elementRef: ElementRef) {

    let overlay = <HTMLScriptElement>document.getElementsByClassName('modal-overlay')[0];

    if (overlay) {

      overlay.addEventListener('click', (e: any) => {

        // Close the modal if a click is made on the modal overlay itself, not its children
        if ((e.target.getAttribute('class') || []).indexOf('modal-overlay') !== -1) {
          _modalApi.close(this.modalId);
        }
      });
    }

    _modalApi.isOpen$.subscribe(
      modal => {
        this.isOpen = modal.id === this.modalId ? modal.isOpen : false;
      }
    )
  }
}

Component API service:

@Injectable()

export class ModalApiService {
  private _isOpen = new Subject<boolean>();

  isOpen$ = this._isOpen.asObservable();

  open(id: string) {
    this._isOpen.next({isOpen: true, id: id});
  }

  close(id: string) {
    this._isOpen.next({isOpen: false, id: id});
  }
}


texts: Created a serializable object that can handle primitive types

texts:
I don't need a lot and I don't need for my code to handle everything.  Even now, I'm just looking at handling serialization.  I'm pretty much building on it as needed.  I am trying to support vectors right now and am looking for an idea on how to extend what I have a little to support this.  Basically I've created a property class that has a callback function when the property changes (keeping it simple with equals operator for now).  This updates a dictionary object that can be serialized.  Below is my code.  It's my first time posting.  If I didn't follow some rules by accident, I'd love some guidance.  Working sample here: https://onlinegdb.com/H10iJVC3f

#include <iostream>
#include <functional>
#include <sstream>
#include <map>

using namespace std;

template <class T>
class Prop
{
public:
   Prop(const std::string &key, const std::function<void(std::string, std::string)> &changed);

private:
   std::string Key;
   T Value;
   std::function<void(std::string, std::string)> changed;

public:
   void operator=(const T &value) {
      this->Value = value;
      this->changed(this->Key, static_cast<ostringstream&>(ostringstream() << value).str());
   }
};

template <class T>
Prop<T>::Prop(const std::string &key, const std::function<void(std::string, std::string)> &changed)
{
   this->Key = key;
   this->changed = changed;
}

class TheList
{
private:
   std::map<std::string, std::string> theList;

protected:
   void Update(const std::string &key, const std::string &value);

public:
   std::string ToJson();
};

void TheList::Update(const std::string &key, const std::string &value)
{
   theList[key] = value;
}

// TODO: body of this method will change and will use a processing library.
std::string TheList::ToJson()
{
   std::string json = "{\n";

   for (auto it : theList)
   {
      json += "\t\"" + it.first + "\": " + "\"" + it.second + "\",\n";
   }

   json.pop_back();
   json.pop_back();

   json += "\n}";

   return json;
}

// A Serializable object.
class User : public TheList
{
public:
   User();

public:
   Prop<std::string> Name;
   Prop<short> Age;
   Prop<std::string> Address;
};

User::User() : Name("Name", std::bind(&User::Update, this, std::placeholders::_1, std::placeholders::_2)),
Age("Age", std::bind(&User::Update, this, std::placeholders::_1, std::placeholders::_2)),
Address("Address", std::bind(&User::Update, this, std::placeholders::_1, std::placeholders::_2))
{
}

int main()
{
    User user;

    user.Name = "Pamela";
    user.Age = 25;
    user.Address = "USA";

    std::string json = user.ToJson();

    cout << json << endl;

    return 0;
}


texts:
Written in Python 3.6 and I must admit, this might be too far...

Tell me what you think of this code. There must be a better way...

It's (another decorator...) that allows you to compose functions that perform operations on pandas DataFrames.

Kinda like a reduce for performing sequential functions.

from functools import reduce, partial, wraps
import pandas as pd

class Meta(type):
    """This metaclass's purpose is to define behavior for adding it's subtypes
    """

     def __add__(typ, other):
    bases = tuple(sorted([typ, other], key=lambda x: len(x.__mro__), reverse=True))
    return type('{}_{}'.format(typ.__name__, other.__name__), bases, {})

class DefaultFunc(metaclass=Meta):
    """Abstract base class to be the end item of a Func __mro__
    """

    @staticmethod
    def default_func(dataframe):
        return dataframe

    func = default_func

    def __new__(cls, dataframe):
        return dataframe

class Func(DefaultFunc):
    """Wrapper for a DataFrame function. It's doesn't create an object like a normal class def
    this way it behaves more like an actual function
    """
    def __new__(cls, dataframe):
        return reduce(lambda x, y: y.func(x), list(reversed(list(cls.__mro__)[:-1])), dataframe)

    @property
    def __name__(self):
        return self.func.__name__

def depends(func=None, *, on=Func):
    """Wrap a function in a class that resolves dependencies
    for the operation of the wrapped function

    Arguments:
        func -- the function that is being wrapped
        dependencies -- functions that need to have been previously computed
            prior to this wrapped function being executed

    Returns the result of the wrapped function
    """
    if not func:
        return partial(depends, on=on)

    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    try:
        on = tuple(on)
    except TypeError:
        on = (on,)

    return type(func.__name__, on, {'func': wrapper})

if __name__ == '__main__':

    df = pd.DataFrame([{'a': 1, 'b': 2}, {'c': 3, 'd': 2}])

    @depends
    def example(dataframe):
        dataframe[example.__name__] = dataframe['d'] * 2
        return dataframe

    @depends(on=example)
    def example_2(dataframe):
        dataframe[example.__name__] = dataframe['example'] * 2
        return dataframe

USAGE

df
Out[1]:
     a    b    c    d
0  1.0  2.0  NaN  NaN
1  NaN  NaN  3.0  2.0

example(df)
Out[2]:
     a    b    c    d  example
0  1.0  2.0  NaN  NaN      NaN
1  NaN  NaN  3.0  2.0      4.0

example_2(df)
Out[3]:
     a    b    c    d  example
0  1.0  2.0  NaN  NaN      NaN
1  NaN  NaN  3.0  2.0      8.0

example_3 = example + example_2
example_3(df)
Out[5]:
     a    b    c    d  example
0  1.0  2.0  NaN  NaN      NaN
1  NaN  NaN  3.0  2.0     16.0


texts:
Something that bothers me a lot when coding is best practice. I am completely self taught and I find it difficult to know whether I am doing things in the 'right way'.

Let's say I have a Gridview on a page which displays data from the following list:

(from foo in someContext.foobars select foo).ToList

Regardless or how simple or complex the query is, can I just bind the Gridview in the page code behind file as below (in Page.Load or wherever else I want it to run):

gvSomeGridview.DataSource = (from foo in someContext.foobars select foo).ToList();
gvSomeGridview.DataBind();

Or, should I have a class elsewhere that performs the query and returns a list and then bind the Gridview like:

gvSomeGridview.Datasource = helperClass.GetGridviewData
gvSomeGridview.DataBind()

Perhaps go one further and also pass the GridView to the helper class as such:

helperClass.BindGridView(gvSomeGridview)

If I am going to require this list elsewhere in my application or bind a different Gridview with the same data then clearly a class is the way forward, however if I do not, is it fine to just bind the GridView using the query in the code behind as per the first example, or is it recommended to keep all such operations in separate classes regardless?