texts: SICP exercise 1.28 - miller-rabin primality test part II

texts:
This is a follow-up to SICP exercise 1.28 - miller-rabin primality test.

  Exercise 1.28:

  One variant of the Fermat test that cannot be fooled is
  called the Miller-Rabin test (Miller 1976; Rabin 1980). This starts
  from an alternate form of Fermat’s Little Theorem, which states that
  if \$n\$ is a prime number and \$a\$ is any positive integer less than \$n\$, then
  \$a\$ raised to the \$n-1\$-st power is congruent to \$1 \mod n\$.

  To test the
  primality of a number \$n\$ by the Miller-Rabin test, we pick a random
  number \$a < n\$ and raise \$a\$ to the \$n-1\$-st power \$\mod n\$ using the expmod
  procedure. However, whenever we perform the squaring step in expmod,
  we check to see if we have discovered a “nontrivial square root of \$1
\mod n\$,” that is, a number not equal to \$1\$ or \$n-1\$ whose square is
  equal to \$1 \mod n\$.

  It is possible to prove that if such a nontrivial
  square root of \$1\$ exists, then \$n\$ is not prime. It is also possible to
  prove that if \$n\$ is an odd number that is not prime, then, for at least
  half the numbers \$a < n\$, computing \$a^{n-1}\$ in this way will reveal a
  nontrivial square root of \$1 \mod n\$. (This is why the Miller-Rabin
  test cannot be fooled.)

  Modify the expmod procedure to signal if it
  discovers a nontrivial square root of \$1\$, and use this to implement the
  Miller-Rabin test with a procedure analogous to fermat-test. Check
  your procedure by testing various known primes and non-primes.

  Hint:
  One convenient way to make expmod signal is to have it return \$0\$.

Changes:

Avoid redundant modulo computations
Corrected use of base modulo n in expmod to avoid computing extremely large numbers
for any number greater than 2, prevent use of 1 as random base in the expmod because I think it will always return true when the random chosen number is 1. Is this needed?

While fixing my previous code, I already saw a procedure with recursive process that fixed all my problems above. I can't really call it my own, so to keep the spirit of the exercise, I rewrote my horrible recursive process code and turned it into a procedure that generates an iterative process.

Please review my code.

(define (square x) (* x x))

(define (expmod base exp m)
  (define (expmod-iter a base exp)
    (define squareMod (remainder (square base) m))
    (cond ((= exp 0) a)
          ((and (not (= base (- m 1)))
                (not (= base 1))
                (= squareMod 1))
           0)
          ((even? exp)
           (expmod-iter
            a
            squareMod
            (/ exp 2)))
          (else
           (expmod-iter
            (remainder (* a base) m)
            base
            (- exp 1)))))
  (expmod-iter
   1
   base
   exp))

(define (miller-rabin-test n)
  (define (try-it a)
    (if (and (= a 1)
             (> n 2))
        (miller-rabin-test n)
        (= (expmod a (- n 1) n) 1)))
  (try-it (+ 1 (random (- n 1)))))

(define (fast-prime? n times)
  (cond ((= times 0) true)
        ((miller-rabin-test n)
         (fast-prime? n (- times 1)))
        (else false)))

Did I improve on my previous code? Did I follow all the requirements in the exercise this time? How can I improve this code and make it faster?


texts: Comparing run-length decoding algorithms

texts:
I'm working on Ocaml.org 99 problems, and I solved the run-length decode one.

Here is the solution given by the site:

let decode l =
    let rec many acc n x =
            if n = 0 then acc else many (x :: acc) (n-1) x in
    let rec aux acc = function
            | [] -> acc
            | One x :: t -> aux (x :: acc) t
            | Many (n,x) :: t -> aux (many acc n x) t  in
    aux [] (List.rev l);;

And here is mine:

let decode l =
    let rec aux acc = function
            | [] -> acc
            | One elem :: t -> aux (elem :: acc) t
            | Many(cnt, elem) :: t -> if cnt > 0 then aux (elem::acc) (Many(cnt - 1, elem) :: t) else aux acc t in
    List.rev (aux [] l);;

Test:

type 'a rld =
    | One of 'a
    | Many of int * 'a;;

(* result expected : ["a"; "a"; "a"; "a"; "b"; "c"; "c"; "a"; "a"; "d"; "e"; "e"; "e"; "e"] *)
decode [Many (4,"a"); One "b"; Many (2,"c"); Many (2,"a"); One "d"; Many   (4,"e")];;

Could my solution become more optimal?


texts:
I have the following code which attempts to match all strings like "*SOMESTRING" (which can include numeric values), but not "*SOMESTRING*". For this I am using a negative lookahead as follows;*SEX and *AN01ZORA should match, \*PCCL\* should not match.

string s = "   if 'L,....' MDC = '13' Then " +
           "  if 'B,960.' SEX NOT = '2' AND *SEX NOT = '3' Then " +
           " DRG = 960Z (UNGROUPABLE) " +
           "    GoTo MDC FldErr " +
           "Else if 'B,N01.' SRG IN TABLE(*AN01ZORA) Then " +
           "  if '.,N01.' *PCCL* > 2 Then ";
Regex rr = new Regex(@"(?i)(?!\*\w+\*)\*\w+");
MatchCollection mc = rr.Matches(s);
foreach (Match m in mc)
    m.ToString().Dump();

  Output:
  *SEX
  *AN01ZORA

This seems to produce the correct output, but feels nasty and not correct. Is this right and what could I do to make the Regex better?


texts:
I am working on an algorithm, which should group connected Arcs. The situation is described via code examples below.

I have Arcs:

public class Arc
{
    public Point StartPoint { get; set; }
    public Point EndPoint { get; set; }
    public bool Visited { get; set; }
    public Arc Successor { get; set; }
    public Arc Predecessor { get; set; }
}

that consist of Points:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public override bool Equals(Object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        return obj.GetType() == GetType() && Equals((Point)obj);
    }

    protected bool Equals(Point other)
    {
        return X.Equals(other.X) && Y.Equals(other.Y);
    }

    public override int GetHashCode()
    {
        unchecked
        {
        return (X.GetHashCode() * 397) ^ Y.GetHashCode();
        }
    }
}

Given these Points and resulting Arcs:

var p1 = new Point {X = 0, Y = 0};
var p2 = new Point { X = 0, Y = 1 };
var p3 = new Point { X = 0, Y = 2 };
var p4 = new Point { X = 1, Y = 0 };
var p5 = new Point { X = 1, Y = 1 };

var arc1 = new Arc { StartPoint = p1, EndPoint = p2};
var arc2 = new Arc { StartPoint = p4, EndPoint = p5};
var arc3 = new Arc { StartPoint = p2, EndPoint = p3};

I would like to end up with groups of connected Arcs as a list of list:

var arcListOfList = new List<List<Arc>>();

This is the crude algorithm I came up with so far:

foreach (var arc in arcList)
{
    var successor = arcList.FirstOrDefault(x => x.StartPoint.Equals(arc.EndPoint));
    var predecessor = arcList.FirstOrDefault(x => x.EndPoint.Equals(arc.StartPoint));
    arc.Successor = successor;
    arc.Predecessor = predecessor;
}

Arc next;
do
{
    next = arcList.FirstOrDefault(x => x.Visited == false);
    var temp = new List<Arc>();

    if (next == null) continue;
    do
    {
        next.Visited = true;
        temp.Add(next);
        if (next.Successor != null)
        {
        next = next.Successor;
        }
        else
        {
        break;
        }
    } while (true);

    arcListOfList.Add(temp);
} while (next != null);

I would appreciate any help/suggestions to improve it.


texts: Extension methods for ReaderWriterLockSlim

texts:
In current project I'm using a lot ReaderWriterLockSlim for synchronizing reading and writing values. Handling try { EnterReadLock(); .... } finaly { ExitReadLock(); } every time I need access value seems to me as copying code. So I created extension methods for ReaderWriterLockSlim which makes me coding much easer and faster (and reusable i think).

However I would like know, if you found some disadvantages in the extension methods I missed or forgot.
There are three extension methods:

ReadOnly<T>(this ReaderWriterLockSlim self, Func<T> readFunc) // calls EnterReadLock()
Read<T>(this ReaderWriterLockSlim self, Func<T> readFunc) // calls EnterUpgradeableReadLock()
Write(this ReaderWriterLockSlim self, Action writeAction) // calls EnterWriteLock()
Write<T>(this ReaderWriterLockSlim self, Func<T> writeAction) // calls EnterWriteLock()

There is code of ReadOnly<T>(...) method. All methods looks similar.

public static T ReadOnly<T>(this ReaderWriterLockSlim self, Func<T> readFunc) {
    if (object.ReferenceEquals(self, null)) { throw new ArgumentNullException("self"); }
    if (object.ReferenceEquals(readFunc, null)) { throw new ArgumentNullException("readFunc"); }

    T result;

    // flag, if lock was entered
    bool lockEntered = false;
    try {
        // I don't want the ThreadAbortException during claiming the lock
        Thread.BeginCriticalRegion();
        try {
            self.EnterReadLock();
            lockEntered = true;
        }
        finally {
            Thread.EndCriticalRegion();
        }

        result = readFunc();
    }
    finally {
        // I don't want the ThreadAbortException during releasing the lock
        Thread.BeginCriticalRegion();
        try {
            if (lockEntered) {
                self.ExitReadLock();
            }
        }
        finally {
            Thread.EndCriticalRegion();
        }
    }

    return result;
}


texts: Test for Array vs Range in my TEXTJOIN UDF

texts:
I use the following code in many of my answers on Stack Overflow, to mimic the new TEXTJOIN function available in Office 365 Excel:

Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function

I have successfully made it so it works with both ranges and arrays, so it works with:

=TEXTJOIN(",",TRUE,A1:B7)

As well as

{=TEXTJOIN(",",TRUE,IF(A1:A7 = "x",B1:B7,""))}

The question is:  Is this the best method to check for array vs. range?  Is there a better method?

As stated this works, nicely with both, but I have to think that I am doing it in a round about manner.


texts:
I'm attempting to speed up some python code that is supposed to automatically pick the minimum samples argument in DBSCAN. Currently the execution time grows exponentially as the number of training samples increases:

0.128999948502 seconds for 100 training examples
0.281999826431 seconds for 1000 training examples
11.5310001373 seconds for 10000 training examples

  min_samples is the number of samples (or total weight) in a
  neighborhood for a point to be considered as a core point. This
  includes the point itself.

Can anyone make some suggestions for how to speed up the code?

As a bonus, adding the n_jobs argument to DBSCAN doesn't seem to affect the execution time of DBSCAN.

import numpy as np
from sklearn.metrics.pairwise import euclidean_distances
from time import time

def autoselect_minsamps_orig(D_sym,eps,K,kmedian_thresh):
   min_samps = 10
   kmedian_dist_prev = 0
   for k in range(2,K):
      k_avg = []
      # For each row, compute median distance to k nearest neighbors
      for row in D_sym:
         flat_row = np.squeeze(np.asarray(row))
         row_nonzero = flat_row[np.flatnonzero(flat_row)]
         # Some nodes aren't connected to anything
         if len(row_nonzero) == 0: continue
         sorted_row = np.sort(row_nonzero)
         sorted_row_t = sorted_row[0:k]
         k_avg.append(np.median(sorted_row_t))
      kmedian_dist = np.median(k_avg)
      kmedian_delta = abs(kmedian_dist - kmedian_dist_prev)

      if kmedian_delta <= kmedian_thresh:
         min_samps=k
         break
      kmedian_dist_prev = kmedian_dist
   return min_samps

num_training_examples = 100
num_features = 10
X = np.random.randint(5, size=(num_training_examples, num_features))

# generate a symmetric distance matrix
D = euclidean_distances(X,X)
eps = 0.25
kmedian_thresh = 0.005
K = num_training_examples

start = time()
result = autoselect_minsamps_orig(D,eps,K,kmedian_thresh)
end = time()
total_time = end - start
print('autoselect_minsamps took {} seconds for {} training examples'.format(total_time,num_training_examples))

num_training_examples = 1000
num_features = 10
X = np.random.randint(5, size=(num_training_examples, num_features))

# generate a symmetric distance matrix
D = euclidean_distances(X,X)
eps = 0.25
kmedian_thresh = 0.005
K = num_training_examples

start = time()
result = autoselect_minsamps_orig(D,eps,K,kmedian_thresh)
end = time()
total_time = end - start
print('autoselect_minsamps took {} seconds for {} training examples'.format(total_time,num_training_examples))

num_training_examples = 10000
num_features = 10
X = np.random.randint(5, size=(num_training_examples, num_features))

# generate a symmetric distance matrix
D = euclidean_distances(X,X)
eps = 0.25
kmedian_thresh = 0.005
K = num_training_examples

start = time()
min_samples = autoselect_minsamps_orig(D,eps,K,kmedian_thresh)
end = time()
total_time = end - start
print('autoselect_minsamps took {} seconds for {} training examples'.format(total_time,num_training_examples))

# min_samples is used here
db = DBSCAN(eps=eps,
            min_samples = min_samples,
            metric='precomputed',
            n_jobs=-1).fit(D)


texts: How can a code that takes dict as input and validates it based on multiple conditions be further optimized?

texts:
I have a piece of code that takes a dictionary as input and validates it based on the following rules:

The dictionary has a key named items and its value must be a list
Now, the list from point 1 must be a nested list with the length of each list should be 2
The first element ([0]) of every nested list must be of type int and the second element ([1]) must be float

The input to validate:
json_to_test = {
    "items": [
        [
            1577837700,
            63.2
        ],
        [
            1577838600,
            61
        ],
        [
            1577839500,
            58.9
        ],
        [
            1577840400,
            57
        ],
        [
            1577841300,
            55.3
        ]
    ]
}

My code
def get_element(lst, num):
    return [item[num] for item in lst]

json_input = json_to_test['items']
if any(isinstance(i, list) for i in json_input):
    if all(len(i) == 2 for i in json_input):
        if all(isinstance(j, int) for j in get_element(json_input, 0)) and all(isinstance(j, float) for j in get_element(json_input, 1)):
            print('Data ready to be saved to DB')
            return json_input
        else:
            abort(400, 'Check data type')
    else:
        abort(400, 'Nested list but not lenghth 2')
else:
    abort(400, 'Not list')

The abort in the else statements is being imported from flask: https://flask.palletsprojects.com/en/1.1.x/api/#flask.abort
Is there a way the above code of mine be more efficient or further improved?


texts:
I wrote this code to solve a problem from a John Vuttag book:

  Ask the user to input 10 integers, and then print the largest odd number that was entered.  If no odd number was entered, it should print a message to that effect.

Can my code be optimized or made more concise?  Any tips or errors found?

{
    a = int (raw_input("enter num: "))
    b = int (raw_input("enter num: "))
    c = int (raw_input("enter num: "))
    d = int (raw_input("enter num: "))
    e = int (raw_input("enter num: "))
    f = int (raw_input("enter num: "))
    g = int (raw_input("enter num: "))
    h = int (raw_input("enter num: "))
    i = int (raw_input("enter num: "))
    j = int (raw_input("enter num: "))

    num_List = {a,b,c,d,e,f,g,h,i,j }
    mylist=[]

    ## Use for loop to search for odd numbers

    for i in num_List:

                 if i&1 :
                     mylist.insert(0,i)
                     pass

                 elif i&1 is not True:
                     continue
    if not mylist:
        print 'no odd integers were entered'
    else:
        print max (mylist)

}


texts:
I'm trying to read two sufficiently large binary files, comparing them and printing the offset at which they differ. I'm using fread to read the binary files and memcmp to compare them.

#include<stdio.h>
#include<time.h>

clock_t start, end;
int main(int argc, char *argv[])
{
    double cpu_time_taken;
    FILE *fp1, *fp2;
    printf("\nArgument count:  %d", argc);
    printf("\nFile 1 is: %s", argv[1]);
    printf("\nFile 2 is: %s\n", argv[2]);
    if (argc < 3)
    {
        printf("\nInsufficient Arguments: \n");
        printf("\nHelp:./executable <filename1> <filename2>\n");
        return 0;
    }
    else
    {
        fp1 = fopen(argv[1],  "rb");
        if (fp1 == NULL)
        {
            printf("\nError in opening file %s", argv[1]);
            return 0;
        }

        fp2 = fopen(argv[2], "rb");

        if (fp2 == NULL)
        {
            printf("\nError in opening file %s", argv[2]);
            return 0;
        }

        if ((fp1 != NULL) && (fp2 != NULL))
        {
            start = clock();
            compare_two_binary_files(fp1, fp2);
            end = clock();
            cpu_time_taken = ((double) (end - start)) / CLOCKS_PER_SEC;
            printf("\nTime taken to compare: %f", cpu_time_taken*1000);
        }
    }
}

int compare_two_binary_files(FILE *fp1, FILE *fp2)
{
    char tmp1[16], tmp2[16];

    size_t bytes = 0, readsz = sizeof tmp1;
    int count = 0;
    while (!feof(fp1) || !feof(fp2)){
        fread (tmp1, sizeof *tmp1, readsz, fp1);
        fread (tmp2, sizeof *tmp2, readsz, fp2);
        count += 16;
        if(memcmp(tmp1, tmp2, readsz)){
            for(int i=0; i < readsz; i++){
                printf ("%d: 0x%02x ",i, tmp1[i]);
            }
            printf("\n%x", count);
            return 0;
        }
    }
}


texts:
I need to be able to atomically add a 32-bit floating point value to a location in memory. Here is what I came up with. While the code is Windows-specific, I'll extend it with Linux support using __sync_bool_compare_and_swap().

While I tested this code and it appeared to work fine, I'll appreciate a fresh look from another pair of eyes to make sure this code is 100% safe.

I'm also very much interested in any performance advice as this code is used in a hot code path in a performance-sensitive application (interactive rendering).

atomic_float_add(), the main function:

__forceinline void atomic_float_add(volatile float* ptr, const float operand)
{
    assert(is_aligned(ptr, 4));

    volatile LONG* lptr = reinterpret_cast<volatile LONG*>(ptr);
    LONG lorg, lnew;

    do
    {
        const float forg = *ptr;
        const float fnew = forg + operand;
        lorg = binary_cast<LONG>(forg);
        lnew = binary_cast<LONG>(fnew);
    } while (InterlockedCompareExchange(lptr, lnew, lorg) != lorg);
}

binary_cast() is implemented in such a way that it obeys strict aliasing rules:

template <typename Target, typename Source>
inline Target binary_cast(Source s)
{
    BOOST_STATIC_ASSERT(sizeof(Target) == sizeof(Source));

    union
    {
        Source  m_source;
        Target  m_target;
    } u;

    u.m_source = s;
    return u.m_target;
}

is_aligned():

template <typename T>
inline bool is_aligned(const T ptr, const size_t alignment)
{
    assert(alignment > 0);
    assert(is_pow2(alignment));

    const uintptr_t p = (uintptr_t)ptr;
    return (p & (alignment - 1)) == 0;
}

is_pow2():

template <typename T>
inline bool is_pow2(const T x)
{
    return (x & (x - 1)) == 0;
}

Assembly output for atomic_float_add() (Visual Studio 2013, full optimization):

lorg$ = 8
ptr$ = 8
lnew$ = 16
operand$ = 16
?atomic_float_add@?A0x1534477b@foundation@@YAXPECMM@Z PROC

    prefetchw BYTE PTR [rcx]
    npad    13

$LL3@atomic_flo:
    movss   xmm0, DWORD PTR [rcx]
    movss   DWORD PTR lorg$[rsp], xmm0
    addss   xmm0, xmm1
    mov eax, DWORD PTR lorg$[rsp]
    movss   DWORD PTR lnew$[rsp], xmm0
    mov edx, DWORD PTR lnew$[rsp]
    lock cmpxchg DWORD PTR [rcx], edx
    jne SHORT $LL3@atomic_flo

    ret 0

?atomic_float_add@?A0x1534477b@foundation@@YAXPECMM@Z ENDP

EDIT: here's a bit of context on how this code is used:

As you can see, atomic_float_add() is taking the bulk of the time of FilteredTile::add(), which itself is the most expensive function of the whole program in this particular setup, taking nearly 27% of the overall time.


texts:
I'm trying to improve my code to find all the prime numbers within a set range as fast as possible, and I am trying to make it even faster. On my github page here, I have some optimization settings within Visual Studio that help improve the speed.

#include <iostream>
#include <fstream>
#include <Windows.h>
#include <conio.h>
#include <bitset>
#include <string>
#include <math.h>

#define RUNS 10000  // How many times the code will runs. I use run each section of code a set number of times, divide by that number
// to get the average. I had to to this because the program was running too fast for the GetTickCount() to get a speed.
#define RANGE 100000 // What number of primes to search up to
#define R2 RANGE/2
#define BRUNS 100000

int main()
{
    //Set up varibles
    int count;
    char primes[RANGE];
    int searchRange = sqrt(R2) + 1;
    DWORD starttime, endtime;

    //############################ SIEV #################################
    starttime = GetTickCount();

    for (int k = 0; k<RUNS; ++k)
    {
        count = 0;
        memset(primes, 0, R2);
        for (int i = 0; i < searchRange; ++i)
        {
            if (primes[i] == 0)
            {
                for (int j = (i << 1)*i + (i << 2) + (i << 1) + 3; j<R2; j += i * 4 + 6)
                {
                    primes[j] = 1;
                    primes[j + i * 2 + 3] = 1;
                }
            }
        }
    }
    endtime = GetTickCount();
    for (int i = 0; i<R2; i++) if (primes[i] == 0) count++;

    float totalOp = ((float)endtime - starttime) / (1000 * RUNS);
    //#####################################################################

    //#################### MEMSET FUNCTION TIMING TEST ####################
    // Here I am timing how long the memset function takes, so I can take that off the time for the sieve

    float totalMemset = ((float)endtime - starttime) / (1000 * RUNS);
    //#####################################################################

    //####################  OUTPUT TIME AND PRIMES  ######################
    std::cout << "Optimised Sieve Time:  ";
    std::cout << totalOp;
    std::cout << "\nPrimes Found: ";
    std::cout << count + 1;
    //#####################################################################
    _getch();
    return 0;
}


texts: Google OAuth Boilerplate in Python Tornado

texts:
I recently started a project using python-tornado, and needed to implement google OAuth to manage user logins. I struggled getting this working in the context of the project, and decided to abstract it out to a simple working demo. Since it was such a bear to get up and running in the first place, I wanted to seek feedback regarding my specific implementation, to have the best fleshed-out boilerplate I can to quickly get a new project up and running. Any advice regarding performance/security/maintainability are greatly appreciated.

Below is the code, which a working demo can be found on Github.

import os
import tornado.auth
import tornado.autoreload
import tornado.ioloop
import tornado.web
import json

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("user")

class TestHandler(BaseHandler):
    def get(self):
        name = tornado.escape.xhtml_escape(self.current_user)
        print self.get_current_user()
        self.write("Hello, " + name)

class MainHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/")
            return

class GoogleOAuth2LoginHandler(BaseHandler, tornado.auth.GoogleOAuth2Mixin):
    @tornado.gen.coroutine
    def get(self):
        if self.get_argument('code', False):
            access = yield self.get_authenticated_user(
                redirect_uri=os.environ['REDIRECT_URI'],
                code=self.get_argument('code'))
            user = yield self.oauth2_request("https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"])
            self.set_secure_cookie("user", json.dumps(user))
            self.current_user = user
            self.redirect('/test')
        else:
            yield self.authorize_redirect(
            redirect_uri=os.environ['REDIRECT_URI'],
            client_id=os.environ['CLIENT_ID'],
            client_secret=os.environ['CLIENT_SECRET'],
            scope=['profile', 'email'],
            response_type='code',
            extra_params={'approval_prompt': 'auto'}
        )

def make_app():
    settings = {
    'google_oauth' : {
            'key': os.environ['CLIENT_ID'],
            'secret': os.environ['CLIENT_SECRET'],
    },
    'redirect_uri': os.environ['REDIRECT_URI'],
    'login_url': '/',
    'cookie_secret': os.environ['COOKIE_SECRET']
    }
    return tornado.web.Application([
        (r"/", GoogleOAuth2LoginHandler),
        (r"/test", TestHandler)], **settings)

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    print "Listening on port 8888"
    tornado.autoreload.start()
    for dir, _, files in os.walk('./'):
        [tornado.autoreload.watch(dir + '/' + f) for f in files if not f.startswith('.')]

    tornado.ioloop.IOLoop.current().start()


texts: Binary Search For Data Types With Relation Operators

texts:
I am trying to write a binary search algorithm to work with any data type that is defined to work with the relational operators and returns the position of the found element. I want to know if there is anything I need to be aware of when dealing with user defined types. As well as any flaws or improvements that I can make. Also one other question is how does my search compare to the built in binary_search function?

#include <iostream>
#include <iomanip>
#include <type_traits>

template<typename T, typename U>
U BinarySearch(T *arr, T toFind, U _size){ //make return type same as size for overflow issues
    static_assert(std::is_integral<U>::value, "Integral type required for size of array");

    U mid, low = 0, high = _size-1; //maintain same integral types
    T m, l = arr[low], h = arr[high]; //maintain same T types

    while(l<=toFind && h>=toFind){
        mid = (high + low)/2;
        m = arr[mid];
        if(m > toFind){
            h = arr[high = mid - 1];
        }
        else if(m < toFind){
            l = arr[low = mid + 1];
        }
        else
            return mid; //postion point + 1
    }

    //exits if not found
    return -1;
}

const auto SIZE = 10;

int main()
{
    double arr[SIZE] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1};
    auto pos = BinarySearch(arr, 1.1, SIZE);
    std::cout << pos << '\n';
    return 0;
}

Thanks for all your advice in advance.


texts: Multiply a 2D array by 1D array to get a third (2D) array

texts:
I've working with three dynamic arrays (all are datatype Double) - they are

  OriningalArray

This will be assigned from a range that the end user will see and will be 2 dimension

  MultiplierArray

This will be multipliers as (most of which will be 1 but some will be between +-5% and will always be same length as one of the dimensions in OriningalArray.

  NewArray

This is required as there will be certain discounts that will need to be applied to the OriningalArray and both dimension will be the same size as it.

Here's a sample for a visual reference:

I have code that works (below) and have commented it also to explain why I'm doing it that way (this is just an example and actual data size will be much bigger) but was hoping someone could tell me how to optimize it further:

Sub Test()
Dim OriningalArray() As Double ' I can't declare it a Variant and then assign it straight from the range (OriningalArray = Rng) because there may be "N/A" values in the range which, when put into an Variant Array, gives false Double value
Dim MultiplierArray() As Variant
Dim NewArray() As Double
Dim Rng As Range
Dim MultiplierRng As Range
Dim x As Long, y As Long

Set Rng = Range("D4:I9")
Set MultiplierRng = Range("D12:I12")

ReDim OriningalArray(1 To Rng.Rows.Count, 1 To Rng.Columns.Count) ' 2D Array the sze of the range
ReDim NewArray(1 To Rng.Rows.Count, 1 To Rng.Columns.Count) ' 2D Array the sze of the range

MultiplierArray = MultiplierRng

On Error Resume Next ' Turn off error handler to stop macro crashing when trying to assign "N/A" as a Double
For x = 1 To Rng.Columns.Count
    For y = 1 To Rng.Rows.Count
        OriningalArray(y, x) = Rng.Cells(y, x).Value
        NewArray(y, x) = OriningalArray(y, x) * MultiplierRng(1, x)
        'Debug.Print OriningalArray(y, x)
        'Debug.Print NewArray(y, x)
    Next y
Next x
On Error GoTo 0

End Sub


texts: Reading MultiPart From Data with descriptors

texts:
I am new to C# and I have a simple /upload controller to upload an image to S3.   Everything seems to work, just fine but it seems messy.

The function:

Takes multipart form data
Reads it async
Picks out the image
Picks out the associated identity of the image
Reads the identity as a stream
Gets a stream of the image by reading the byte array.
sends the image on its way.

Seems pretty ugly.  Anything I can do to make it more efficient with less code?

Sample payload

------WebKitFormBoundaryRmgsjwjP3nVPh7C7
Content-Disposition: form-data; name="file"; filename="10385095.jpeg"
Content-Type: image/jpeg

------WebKitFormBoundaryRmgsjwjP3nVPh7C7
Content-Disposition: form-data; name="ident"

someguid

------WebKitFormBoundaryRmgsjwjP3nVPh7C7--

Code

    [HttpPost, Route("api/aws/upload")]
    public async Task<IHttpActionResult> Upload()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        var file = provider.Contents[0];
        var identity = provider.Contents[1];
        Stream _id = postId.ReadAsStreamAsync().Result;
        StreamReader reader = new StreamReader(_id);
        string identity = reader.ReadToEnd();
        string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            var buffer = await file.ReadAsByteArrayAsync();
            string mime = file.Headers.ContentType.ToString();
            Stream stream = new MemoryStream(buffer);
            AwsStore store = new AwsStore();
            object response = store.UploadMultiple(stream, filename, mime, identity);

        return Ok(response);
    }


texts: Simplified error handling when reading from stdin and parsing to a type

texts:
I've recently started learning Rust, and I've managed to whip up this function, which reads and parses a thing from stdin. I don't like it though, and I feel it could be further simplified. What do you think?

fn read_thing<T: str::FromStr>() -> Result<T, &'static str> {
    let mut buffer = String::new();
    match io::stdin().read_line(&mut buffer) {
        Ok(_)  => match buffer.trim().parse() {
            Ok(n)  => Ok(n),
            Err(_) => Err("Failed parsing input.")
        },
        Err(_) => Err("Failed reading from stdin."),
    }
}


texts: Count words that are longer than a set Length

texts:
This is working, but I want to know if is this a place where IEnumerable can be used?

public static int LongerThanStingCompair(string s, int n)
    {

        int counter = 0;
        // splits based on nextLine break
        var sCount = s.Split('\n');
        // Cast to list
        sCount.ToList();
        foreach (var item in sCount)
        {
            //checks to see if words are a certain charLength
            if (item.Length > n)
            {
                counter++;
            }
        }

        return counter;
    }

Test class gives it the input like

  Lion, Ape, Tiger, Zebra and 4

So it would return 2 since there are two words with more than 4 letters


texts:
I have made this small checkout stepper with Vue (v 2.x.x):

var app = new Vue({
  el: "#cart",
  data: {
    stepCounter: 1,
    steps: [{
        step: 1,
        completed: false,
        text: "Cart"
      },
      {
        step: 2,
        completed: false,
        text: "Shipping"
      },
      {
        step: 3,
        completed: false,
        text: "Payment"
      },
      {
        step: 4,
        completed: false,
        text: "Confirmation"
      }
    ]
  },
  methods: {
    doPrev: function() {
      if (this.stepCounter > 1) {
        this.stepCounter--;
        this.doCompleted();
      }
    },
    doNext: function() {
      if (this.stepCounter <= this.steps.length) {
        this.stepCounter++;
        this.doCompleted();
      }
    },
    doCompleted: function() {
      this.steps.forEach(item => {
        item.completed = item.step < this.stepCounter;
      });
    }
  }
});
* {
  margin: 0;
  padding: 0;
  font-family: "Poppins", sans-serif;
}

.progressbar {
  display: flex;
  list-style-type: none;
  counter-reset: steps;
  padding-top: 50px;
  justify-content: space-between;
}

.progressbar li {
  font-size: 13px;
  text-align: center;
  position: relative;
  flex-grow: 1;
  flex-basis: 0;
  color: rgba(0, 0, 0, 0.5);
  font-weight: 600;
}

.progressbar li.completed {
  color: #ccc;
}

.progressbar li.active {
  color: #4caf50;
}

.progressbar li::after {
  counter-increment: steps;
  content: counter(steps, decimal);
  display: block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border: 2px solid rgba(0, 0, 0, 0.5);
  background: #fff;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  margin-left: -15px;
  margin-top: -60px;
}

.progressbar li.active::after,
.progressbar li.completed::after {
  background: #4caf50;
  border-color: rgba(0, 0, 0, 0.15);
  color: #fff;
}

.progressbar li.completed::after {
  content: '\2713';
}

.progressbar li::before {
  content: "";
  position: absolute;
  top: -26px;
  left: -50%;
  width: 100%;
  height: 2px;
  background: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.progressbar li.active::before,
.progressbar li.completed::before,
.progressbar li.active+li::before {
  background: #4caf50;
}

.progressbar li:first-child::before {
  display: none;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

{{step.text}}

      <button type="button" class="btn btn-sm btn-success" v-bind:class="{ disabled : stepCounter === 1}" @click="doPrev()">Prev</button>
      <button type="button" class="btn btn-sm btn-success" v-bind:class="{ disabled : stepCounter > steps.length}" @click="doNext()">Next</button>

Questions

Is there any room for "shortening" the code?
Anything inconsistent at the logic level?


texts: Generate all combinations of certain digits

texts:
Related to another answer of mine on Project Euler 35, I found the need to calculate all combinations of certain digits, i.e. 1, 3, 7 and 9, below a given n. I looked around, and didn't find any really good premade solutions, but found some bits and pieces related to Cartesian products, and collated my findings into the following code:

import itertools

def all_digit_combinations(allowed_digits, maximum):
    """Yield all combinations of allowed_digits below maximum.

    For allowed_digits being a list of single digits, i.e. [1, 3, 7, 9],
    combine all variants of these digits until we pass the maximum value.
    """
    no_of_digits = 1

    while True:
        for digit_tuple in itertools.product(allowed_digits, repeat=no_of_digits):
            new_number = reduce(lambda rst, d: rst * 10 + d, digit_tuple)
            if new_number < maximum:
                yield new_number
            else:
                raise StopIteration

        no_of_digits += 1

if __name__ == '__main__':
    print ', '.join(map(str, all_digit_combinations([1, 3, 7, 9], 100)))
    print ', '.join(map(str, all_digit_combinations([3, 5], 1000)))

Which indeed prints the expected output of:

1, 3, 7, 9, 11, 13, 17, 19, 31, 33, 37, 39, 71, 73, 77, 79, 91, 93, 97, 99
3, 5, 33, 35, 53, 55, 333, 335, 353, 355, 533, 535, 553, 555

I first tried using itertools.combinations_with_replacement() and other variations from itertools, but some of those versions failed to include numbers like 31 and 73. But it I could very well simply not use the correct parameters.

Can you review this code, suggesting any optimalisations or improvements?


texts:
I'm looking to achieve a time format that looks like this: 2d 4h remaining; or 1h 36m remaining; or 35s remaining, etc. So that it only displays the two largest values of time (this is how Clash of Clans and some other mobile games format wait times.)

Currently my code is below, but I'm wondering if there might be a shorter way to format the timespan in this manner? I'm not fully sure if String.Format will work…

public string FormatRushTime ( System.TimeSpan span )
{
    string t1;
    string t2;
    if ( span.Days > 0 )
    {
        t1 = span.ToString("%d") + "d";
        t2 = span.Hours > 0 ? span.ToString("%h") + "h" : String.Empty;
    }
    else if ( span.Hours > 0 )
    {
        t1 = span.ToString("%h") + "h";
        t2 = span.Minutes > 0 ? span.ToString("%m") + "m" : String.Empty;
    }
    else if ( span.Minutes > 0 )
    {
        t1 = span.ToString("%m") + "m";
        t2 = span.Seconds > 0 ? span.ToString("%s") + "s" : String.Empty;
    }
    else if ( span.Seconds > 0 )
    {
        t1 = span.ToString("%s") + "s";
        t2 = String.Empty;
    }
    else
    {
        t1 = String.Empty;
        t2 = String.Empty;
    }

    return t1+" "+t2;
}


texts: Mean of combined sublists with different lengths

texts:
I have a seemingly simple issue. Consider this list:

a = [[12.0, 5.0, 63.0], [0.1, 2.0, 7.1, 3.0, 2.3, 5.0, 8.4]]

I want to find the mean (using numpy) of all the elements in its sublists combined. In this case the result should be:

10.79

obtained as:

np.mean([12.0, 5.0, 63.0, 0.1, 2.0, 7.1, 3.0, 2.3, 5.0, 8.4])

The solution I've found is to flatten the list first and then obtain the mean, as:

np.mean([item for sublist in a for item in sublist])

but this seems unnecessarily complicated. I would've assumed that numpy.mean() could handle this case without the need to modify the list first. I tried using the argument axis to no avail.

Am I missing some functionality here?


texts:
I need a simple singly-linked list to help implement some memory management functionality. I just finished writing it up and would really like a code review since I haven't written this particular data structure in a long time.

struct pid_node {

  int PID;
  struct pid_node* next;

};

 struct pid_node* pid_node_create(int PID) {
   struct pid_node* new;
   new = kmalloc(sizeof(struct pid_node));
   if (new == NULL) return NULL;
   new->PID = PID;
   new->next = NULL;
   return new;
 }

 void add_pid_node(struct pid_node* head, struct pid_node* new) {
   struct pid_node* temp;
   temp = head;
   while(temp->next != NULL) temp = temp->next;
   temp->next = new;
 }

 void remove_pid_node(struct pid_node* head, struct pid_node* dead) {
   struct pid_node* temp, other_part_of_list, delete_node;
   temp = head;
   while(temp->next != NULL) {
     if (temp->next == dead) {
       delete_node = temp->next;
       other_part_of_list = temp->next->next;
       temp->next = other_part_of_list;
       kfree(delete_node); //don't leak memory
       return;
     }
     temp = temp->next;
   }
   kprintf("Got to end of PID list, didn't remove 'dead'!\n");
 }

 //returns true or false (1 or 0) if a particular PID is within my list
 int query_pid(int PID, struct pid_node* head) {
   struct pid_node* temp;
   temp = head;
   while(temp->next != NULL) {
     if (temp->PID == PID) return 1;
     temp = temp->next;
   }
   return 0; //didn't find it
  }

It doesn't have to be super fancy or anything. It just has to properly carry out the four functions.


texts: Project Euler Problem 12 - triangle number with 500 divisors

texts:
I've just done Problem 12 of Project Euler:

  What is the value of the first triangle number to have over five hundred divisors?

  The \$N\$'th triangle number is the sum of all natural numbers from \$1\$ to \$N\$, for example, the 5th triangle number is \$1 + 2 + 3 + 4 + 5 = 15\$

I get the correct answer in around 2.5 seconds.

I was wondering if anyone could suggest anything that could improve the performance of the program, or improve the code in general.

public class Problem12 {

public static void main(String[] args) {
    double startTime = System.currentTimeMillis();
    run();
    double endTime = System.currentTimeMillis();
    System.out.println("Took "+((endTime - startTime) / 1000)+" seconds");
}

public static void run() {
    boolean go = true;
    long number = 1;
    long nextNum = 2;
    int maxDivisors = 500;
    while (go) {
        if (countDivisors(number) > maxDivisors) {
            System.out.println("The first triangle number with over "+maxDivisors+" divisors is: "+number);
            go = false;
        }
        else {
            number += nextNum;
            nextNum++;
        }
    }
}

public static long countDivisors(long number) {
    long divisors = 0;
    for (int i = 1; i*i <= number; i++) {
        if (number % i == 0) {
            divisors+=2;
        }
    }
    return divisors;
}
}


texts:
I took a challenge from a web site. I aim to have a runtime performance as good as possible. My solution was accepted, though I think it is not the most efficient because I saw others having a faster solution.
Are there dos and don'ts in regard to C++ programing in order to try to get the best performance possible.
This question is about coding optimally. I have no means to tweak around with compiler options or so.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* res = NULL;

        if (size(l1) < size(l2))
            res = add(l1, l2);
        else
            res = add(l2, l1);

        return res;
    }

private:

    /**
     * Input: A list
     * Output: size of the list
     */
    static int size(const ListNode *l) {
        int size = 0;
        while(l != NULL)
            ++size, l = l->next;
        return size;
    }

    /**
     * Input: Two lists l1 and l2 with size(l1) <= size(l2)
     * Output: result list
     */
    ListNode* add(const ListNode *l1, const ListNode *l2) {
        ListNode *head, *l;
        register bool carry_over = false;
        int x = l1->val + l2->val + carry_over;

        if (x > 9) {
            carry_over = true;
             x -= 10;
        }
        head = l = new ListNode(x);
        l1 = l1->next;
        l2 = l2->next;

        while (l1 != NULL) {
            x = l1->val + l2->val + carry_over;
            if (x > 9) {
                carry_over = true;
                x -= 10;
            } else
                carry_over = false;
            l = l->next = new ListNode(x);
            l1 = l1->next;
            l2 = l2->next;
        }

        while(l2 != NULL) {
            x = l2->val + carry_over;
            if (x > 9) {
                carry_over = true;
                x -= 10;
            } else
                carry_over = false;
            l = l->next = new ListNode(x);
            l2 = l2->next;
        }

        if (carry_over)
            l->next = new ListNode(1);

        return head;
    }

};


texts: Generic logging class for tracing the function calls

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

// Generic class for tracing the function call
class functionlogging {
private:
    string name;
    string in{ ">>" };
    string out{ "<<" };
public:
    functionlogging(string x) :name(x) {
        cout << in << name << endl;
    }
    ~functionlogging(){
        cout << out << name << endl;
    }
};

//uses
void generic_function() {
    functionlogging logger{ __func__ };
    int a = 10;
    int b = 100;
    a += b;
}

int main() {
    generic_function();
}

Many times, we do need to log when function call starts and ends for better understanding.  With modern C++ concepts like __funct__/RAII, I wrote the small class which can be used to achieve trace. With this I was able to achieve this for above "generic_function()".

Output

>>generic_function
<<generic_function

I wanted others opinion about the functionlogging class and how to make it in such a way that user of this class would have to do the minimal work/code changes in his/her code base.

At present user of this class needs to create a object of this class and pass the __func__ information. Is it acceptable or in a way can it be embed inside something by which user of the class almost do not require to do anything?.


texts:
I have a CheckChanged method that I would like to improve as it takes a lot of space in my program and really hurts readability.

The method prompts the user for input "Comments" and that is stored. However the below code is being used up to 70 times so any way to optimize would be great.

  private void checkBox45_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox45.Checked == true)
        {
            // Create an instance of the dialog
            frmInputBox input = new frmInputBox();
            // Show the dialog modally, testing the result.
            // If the user cancelled, skip past this block.
            if (input.ShowDialog() == DialogResult.OK)
            {
                // The user clicked OK or pressed Return Key
                // so display their input in this form.
                hash.Add("5", input.txtInput.Text);
                problems = problems + "5. Check Auger Motor: " + input.txtInput.Text + Environment.NewLine;
                this.txtProblems2.Text = problems;
                txtProblems2.Visible = true;
            }

            // Check to see if the dialog is still hanging around
            // and, if so, get rid of it.
            if (input != null)
            {
                input.Dispose();
            }
        }
    }

  private void checkBox47_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox47.Checked == true)
        {
            // Create an instance of the dialog
            frmInputBox input = new frmInputBox();
            // Show the dialog modally, testing the result.
            // If the user cancelled, skip past this block.
            if (input.ShowDialog() == DialogResult.OK)
            {
                // The user clicked OK or pressed Return Key
                // so display their input in this form.
                hash.Add("26", input.txtInput.Text);
                problems = problems + "24. Service Access : " + input.txtInput.Text + Environment.NewLine;
                this.txtProblems5.Text = problems;
                txtProblems5.Visible = true;
            }

            // Check to see if the dialog is still hanging around
            // and, if so, get rid of it.
            if (input != null)
            {
                input.Dispose();
            }
        }
    }


texts:
I decided it would be interesting to simulate a game of Poker. Baby steps at the moment, and eventually I'll attempt to turn it into a GUI. The code I have so far is very basic such as populating a deck, shuffling the deck, and distributing two cards to a player. Trying to understand how inheritance works, the proper use of Java generics, and grasping the concept of how powerful/fun OOP can be. The Collections Framework is also something I'm beginning to experiment with.

I would really appreciate anything that will help me better understand Java.

import java.util.*;

class Deck {
    // create possible card combinations
    public final String[] SUITS = { "H", "D", "C", "S" };
    public final String[] RANKS = { "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2" };

    // maximum number of cards
    public final int deckLength = SUITS.length * RANKS.length;
    public List<String> fullDeck = new ArrayList<>();

    public Deck() {
        for(int i = 0; i < SUITS.length; i++) {
            for(int j = 0; j < RANKS.length; j++) {
                fullDeck.add(RANKS[j] + SUITS[i]);
            }
        }
   }

    public Deck(List<String> fullDeck) {
        this.fullDeck = fullDeck;
        for(int i = 0; i < SUITS.length; i++) {
            for(int j = 0; j < RANKS.length; j++) {
                fullDeck.add(RANKS[j] + SUITS[i]);
            }
        }
    }

    public List<String> shuffle(List<String> fullDeck) {
        this.fullDeck = fullDeck;
        Collections.shuffle(fullDeck);
        return fullDeck;
    }

    // this was mainly used for testing purposes
    // to ensure shuffling was indeed taking place
    public void showDeck(List<String> fullDeck) {
        this.fullDeck = fullDeck;
        for(int i = 0; i < deckLength; i++) {
            System.out.printf("%s ",fullDeck.get(i));
        }
    }
}

class Hands extends Deck {

    public String[] hand = new String[2];
    Random random = new Random();

    // select 2 cards to distribute to player
    public String[] getHand(List<String> fullDeck) {
        super.fullDeck = fullDeck;
        for(int i = 0; i < this.hand.length; i++) {
            this.hand[i] = fullDeck.get(random.nextInt(super.deckLength));
        }
        return this.hand;
    }

    // show player hand
    public void showHand() {
        for(int i = 0; i < this.hand.length; i++) {
            System.out.printf("%s ", this.hand[i]);

        }
    }
}

public class Cards {
    public static void main(String[] args) {

        List<String> cards = new ArrayList<>();
        Deck deck = new Deck(cards);
        deck.shuffle(cards);

        Hands hands = new Hands();
        hands.getHand(cards);
        hands.showHand();

    }
}


texts: Checking if the site resolve a DNS or not

texts:
I've written code to check whether a domain resolves DNS or not like follows. It is working fine, but I doubt whether there is a simple way to check this by using `dns_get_record'

$url = 'http://www.example.com';
$get = get_headers($url); //Fetches all the headers sent by the server in response to a HTTP request
if (preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $get[0])){
$parse = parse_url($url); //Parse a URL and return its components
$ip = gethostbyname($parse['host']);  // Get the IPv4 address corresponding to a given Internet host name
//ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address
return (ip2long($ip) == true) ? true : false;

Any suggestions would be much appreciated.


texts: Print sum of numbers 1 to 200 except mults of 4 or 7 in Python

texts:
I had a question about using the modulus operator in Python and whether I have used it in a understandable way.

This is how I've written the script:

#sum numbers 1 to 200 except mults of 4 or 7
def main():
    sum = 0
    for x in range(200+1):
        if (x % 4 and x % 7): #is this bad???
            sum = sum + x
    print sum

if __name__ == '__main__':
    main()

So my questions are:

Should I spell out the modulo more clearly? ie if x % 4 != 0 and x % 7 != 0
Should I be approaching this in a very different way?


texts:
I often have the need to take some type and stream it to something as a sequence of character byte values, so I came up with this to accomplish the task:

#include <iostream>
#include <iterator>

/// This provides a way of getting the byte representation of an
/// object of underlying type T.
///
/// This is an alternative to memcopying bytes into a string, stream,
/// character array...
template<typename inT, typename outT = char>
struct byte_streamer
{
    byte_streamer(inT ref)
      : data(ref)
    {}
    const inT data;
    outT placeholder;
};

template<typename inT, typename outT>
std::ostream& operator<<(std::ostream& strm, const byte_streamer<inT, outT> val)
{
    std::copy(reinterpret_cast<const char*>(&val.data),
              reinterpret_cast<const char*>(&val.data) + sizeof(inT),
              std::ostream_iterator<decltype(val.placeholder)>(strm, ""));
    return strm;
}

int main()
{
    std::cout << "Here's the bytes of 42 copied directly: " << byte_streamer(42) << std::endl;
    std::cout << "Here's the bytes of 42 copied as their numerical values: "
              << byte_streamer<int, int>(42);
}

You can run it online on Coliru or just look at the output here:

Here's the bytes of 42 copied directly: *
Here's the bytes of 42 copied as their numerical values: 42000


texts:
I have a piece of bash code that works fine.
for thing in "$things"; do
    output=$(my_program "$thing" 2>&1)

    if [[ $? -eq 0 ]]; then
        echo "$(echo "$output" | tail -1)"
    else
        echo "$(echo "$output" | tail -1)" 1>&2
    fi
done

The idea is to echo the last line of the output from the subcommand to stdout if it worked and to stderr if it didn't work.
Is there a better way to achieve this?


texts: Clean code attempt on codechef.com FCTRL

texts:
I have been reading Clean Code and decided to start working problems on Codechef.com attempting to apply some of what I have learned.

Do I seem to be on the right track or am I way off?

The challenge is to find the number of trailing zeroes in the decimal form of N!, where 1 ≤ N ≤ 109.

I am more concerned with the coding style than the way I solved the problem but any comments are appreciated.

#include <iostream>
#include <vector>

int requestNumInts();
bool validateInputSize(const int totalNumInts);
std::vector<int>* createVector(int totalNumInputs);
void loadVector(std::vector<int>* numbersEntered);
void printNumTrailingZeros(const std::vector<int>* numbersEntered);
int findTrailingZeros(int numberToCalculateZeros);

int main() {
    std::ios::sync_with_stdio(false);
    std::vector<int>* numbers;
    numbers = createVector(requestNumInts());
    loadVector(numbers);
    printNumTrailingZeros(numbers);
    delete numbers;
    return 0;
}

int requestNumInts() {
    int totalNumInts = 0;
    while(!validateInputSize(totalNumInts))
    {
        std::cin >> totalNumInts;
    }
    return totalNumInts;
}

bool validateInputSize(const int totalNumInts) {
    const int MAX_NUMBER_OF_INPUTS = 1000000000;
    const int MIN_NUMBER_OF_INPUTS = 1;
    if(totalNumInts >= MIN_NUMBER_OF_INPUTS && totalNumInts <= MAX_NUMBER_OF_INPUTS) {
        return true;
    }
    else {
        return false;
    }
}

std::vector<int>* createVector(int totalNumInts) {
    std::vector<int>* numbers = new std::vector<int>(totalNumInts);
    return numbers;
}

void loadVector(std::vector<int>* numbersEntered) {
    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {
        std::cin >> (*numbersEntered)[count];
    }
}

void printNumTrailingZeros(const std::vector<int>* numbersEntered) {
    for(unsigned int count = 0; count < numbersEntered->size(); ++count) {
        std::cout << findTrailingZeros((*numbersEntered)[count]) << std::endl;
    }
}

int findTrailingZeros(int numberToCalculateZeros) {
    int totalTrailingZeros = 0;
    const int FACTOR = 5;
    while(numberToCalculateZeros >= FACTOR) {
        numberToCalculateZeros /= FACTOR;
        totalTrailingZeros += numberToCalculateZeros;
    }
    return totalTrailingZeros;
}


texts:
This is my first routing system on PHP. As you can see it's very simple. Any advice or tip about it that can make it better? I want to make it better so I could use it in real websites.

First I include db connect, then get the URL, if the URL have special index like post id or post name, then include post.php or if $sp_link[4] == profile then load the profile.php.

<?php
    require_once 'inc/header.php';
    include_once 'inc/nav.php';

    $actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    // echo $actual_link;
    $sp_link = explode("/", $actual_link);
    print_r($sp_link);

    $sql ='SELECT * from posts WHERE post_id=? AND post_name=?';
    $stmt=$pdo->prepare($sql);
    $stmt->execute([@$sp_link[5], @$sp_link[6]]);
    $post=$stmt->fetch();

    if ($sp_link[4] == 'blog' && @$sp_link[5] == '' ) {
        // @include 'blog.php';
        //$page_title = $post->post_title;
    }
    else if ($sp_link[4] == 'profile' && @$sp_link[5] == '' ) {
        @include_once 'profile.php';
    }
    else if ($sp_link[4] == 'login' && @$sp_link[5] == '' ) {
        @include 'login.php';
        $page_title = 'ورود';
    }
    else if ($sp_link[4] == 'signup' && @$sp_link[5] == '' ) {
        @include 'signup.php';
        $page_title = 'ورود';
    }
    else if ($sp_link[4] == 'blog' && @$sp_link[5] == $post->post_id && @$sp_link[6] ==     $post->post_name) {
        @include 'post.php';
        $page_title = $post->post_title;

    }
    else if (($sp_link[4] == '' || $sp_link[4] == 'index' || $sp_link[4] == 'index.php') &&     @$sp_link[5] == '') {
           $page_title = 'سکان آکادمی | آموزش برنامه نویسی';
            include 'home.php';
    }
    else if (($sp_link[4] == 'blog' && $sp_link[5] == '12342') && @$sp_link[6] == '') {
        include_once 'post.php';
    } else {
        include_once '404.php';
    }


texts: Preventing resubmission of form using timestamp

texts:
I am working on a method to prevent users from resubmitting a PHP form and I thought of many methods, but this one seemed to be the most reliable in my tests. I did not want to create redirects for development purposes, and transferring data around.

I create a hidden input with the form holding the time() of which the page loads. Then when the form is submitted I check for the time_stamp + int < time().

This is what it looks like in practice:

$unix = $_POST['unix_timeStamp'];
if($unix + 1800 > time())
{
    echo "You too long friend
";
    echo 'start time: '. $unix . '
';
    echo 'end time: '. time();
    exit;
}

It works fine, after 1800 seconds (30 minutes) the form will simply indicate that the time has expired and they have to start again.

I am just wondering if this is a fool-proof system. Not security wise, but just to prevent double-submits or users taking too long.


texts: Light setup bash script for an ubuntu server

texts:
I'm trying to create a setup script for our projects in an ubuntu server. This is what I have now, but I don't know if its correct, or can I do it differently/better ? If someone could take a look pls. Thanks
#!/usr/bin/env bash
set -e

# ==================
# Step Functions
# ==================

# create_user() {
#   echo "
# ----------------------
#   1. Creating a new user with name `<user>` and gives correct access.
# ----------------------
# "
#  # [ASK]: How to make <user> a variable I read from STDIN
#  #        and  pass it around in the following commands

#   # add new user with the name of `user`
#   sudo "adduser --ingroup www-data --disabled-password $user"

#   # copy ssh/ folder from `ubuntu` user to new user
#   # and gives the right permissions/privileges
#   sudo cp -R ".ssh/" "/home/$user/"
#   sudo chown -R "$user:www-data" "/home/$user/.ssh/"
# }

function update_pkgs() {
  echo "
  ----------------------
    Prerequisites : Making sure everything is up to date
  ----------------------
  "
  # checks is all pkgs are up to date
  sudo apt-get update -y

  # installing necessary pkgs
  sudo apt-get install build-essential libssl-dev -y
}

function installing_nginx() {
  echo "
  ----------------------
    3. Installing Nginx...
  ----------------------
  "
  sudo apt update
  sudo apt install nginx
  sudo ufw allow 'Nginx HTTP'
}

function installing_node() {
  echo "
  ----------------------
    4. Installing NVM & Node
  ----------------------
  "
  # install nvm
  curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

  # verifies installation
  nvm --version

  # install node the latest stable version
  nvm install stable

}

function installing_yarn() {
  echo "
----------------------
  6. Installing Yarn
----------------------
"

  # updating pakages
  sudo apt-get update

  # installs yarn
  sudo apt-get install yarn

  # checks yarn version
  which yarn
  yarn --version
}

function installing_pm2() {
  echo "
  ----------------------
    7. Installing PM2 via YARN
  ----------------------
  "

  # install pm2 with npm
  yarn global add pm2

  # set pm2 to start automatically on system startup
  pm2 startup systemd
}

function parting_words(){
  echo "
  ----------------------
    Things left to Do

    1. Clone the repositories from devtools
    2. Add the ssh keys of developers to the .ssh/ folder
    3. Configure nginx
    4. Install cerbot for nginx and generate certificates
    5. Make sure everything is working correctly
    6. Delete user ubuntu
    7. Have a cup of coffee
  ----------------------
  "
}

# ==================
# MAIN SCRIPT
# ==================

echo "
----------------------
  Server Setup Bash Script
----------------------
"

read -p "Do You Wish to run this Script ? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
update_pkgs
echo "
----------------------
  Let's create a new user
----------------------
"
read -p "What should we call the new user ?" user
sudo "adduser --ingroup www-data --disabled-password $user"
sudo cp -R ".ssh/" "/home/$user/"
sudo chown -R "$user:www-data" "/home/$user/.ssh/"
echo "$user ALL=(ALL) NOPASSWD: ALL" >> "/etc/sudoers.d/90-cloud-init-users"
installing_nginx
installing_node
installing_yarn
installing_pm2
parting_words
fi
```


texts: Check if given number can be expressed as sum of 2 prime numbers

texts:
Similar problem: Sum Of Prime

I've done the given problem in roughly \$\mathcal{O}(n\sqrt{n})\$.

How can I improve this algorithm?

#include <stdio.h>
int isPrime(long long int n)
{
    long long int i;
    for(i=2;i*i<=n;i++)
    {
        if(n%i==0)
            return 0;
    }
    return 1;
}
int main(void) {
    int i, t, prime;
    long long int n, start, end;
    scanf("%d", &t);
    for(i=0;i<t;i++)
    {
        prime = 0;
        scanf("%lld", &n);
        if(n<4)
            printf("No\n");
        else
        {
            if(n%2==0)
                printf("Yes\n");
            else
            {
                start = 2;
                end = n-2;
                while(start<=end)
                {
                    if(isPrime(start) && isPrime(end))
                    {
                        printf("Yes\n");
                        prime = 1;
                        break;
                    }
                    else
                    {
                        start++;
                        end–-;
                    }
                }
                if(prime==0)
                    printf("No\n");
            }
        }
    }
    return 0;
}


texts: Making a directory structure for a web project

texts:
I have always been into HTML and CSS so I decided to give programming a try. I installed Python because I heard it is the best first programming language. So I made this program just now and I'm super excited and happy about it. I would like to have your criticism or feedback and tell me how I can make it better or add more functionality to it.

import os

name = input("Enter the name of your project here: ");

os.makedirs(name);

os.chdir(name);

os.makedirs('css');
os.makedirs('resources');

os.chdir('resources');

os.makedirs('img');
os.makedirs('js');

os.chdir('../');

html = input("Enter name of html file: ")+".html";
open(html, 'a');

os.chdir('css');

css = input("Enter name of css file: ")+".css";
open(css, 'a');


texts: Querying a phone directory until end of input is reached

texts:
I need to create a phone directory with given inputs, then I need to
  query the dictionary for unknown number of given keys, if not found,
  print Not found. Link of Original HackerRank Problem here

I have written this code in Python3, and it's working fine. Please review, and suggest other ways of taking unknown number of inputs. Should it be done without using sys?

import sys
phone={}
n = int(input())
for _ in range(n):
    line = input().split()
    phone[line[0]] = line[1]
for line in sys.stdin:
    key=line.strip('\n')
    try:
        print(key+'='+phone[key])
    except KeyError:
            print('Not found')


texts: Reading data from a CSV and pushing it to a Salesforce application

texts:
I'm trying to write code that reads data from a CSV and pushes it to a Salesforce application using the API. My code processes the data in a for loop, but it takes a long time (3 hours) to run the function. What can I do to optimize my code to run faster?
Here's an example of my code which reads Patient Diagnosis data from a flatfile which us more than 200k records. Inside the for loop, I query the patient list which has 100k+ records, transform the object then add it to a list for bulk processing. My code looks like this:
Iterating over ptdiag which contains flatfile data
for (int i = 0; i < ptdiags.Count; i += BATCH_SIZE)
{
  var batchContents = SFToBTMapping.Bulk_PtDiag_Content(ptdiags.Skip(i).Take(BATCH_SIZE).ToList(),sfPatients);
  var batch = BulkUpsert(job.Id, batchContents);
}

Function that transforms the object. Here I query sfpatients to link a patientid to the diagnosis object
    public static string Bulk_PtDiag_Content(List<Ptdiag> ptdiags, List<SfPatient__c> sfpatients)
    {
        string res = "Patient__c,DiagKey__c,NickName__c" +
            ",Sequence__c,ShortDescr__c,PTDiagKey__c" + Environment.NewLine;

        foreach (var d in ptdiags)
        {
            var sfd = Map_BTSQL_Patientdiag_To_SF_Patientdiag(d);
            sfd.Patient__c = sfpatients.FirstOrDefault(c => c.PatientKey__c == d.Ptkey.ToString())?.Id;

            res += string.Join(",", sfd.Patient__c, sfd.DiagKey__c, sfd.NickName__c
                                , sfd.Sequence__c, sfd.ShortDescr__c.Replace(",",""), sfd.PTDiagKey__c);
            if (ptdiags.Last() != d)
                res += Environment.NewLine;
        }

        return res;
    }

Method that creates a mapping for Ptdiag
    public static SfPatientDiag__c Map_BTSQL_Patientdiag_To_SF_Patientdiag(Ptdiag d)
    {
        return new SfPatientDiag__c
        {
            DiagKey__c = d.Diagkey.ToString(),
            Diagnosis__r = new SfDiagnosis__c { Diagnosis_Key__c = d.Diagkey.ToString() },
            NickName__c = d.Nickname,
            Patient__r = new SfPatient__c { PatientKey__c = d.Ptkey.ToString() },
            Sequence__c = d.Sequence != null ? Convert.ToDouble(d.Sequence) : 0,
            ShortDescr__c = d.Shortdescr,
            PTDiagKey__c = d.Ptdiagkey.ToString()
        };

    }


texts: Faster solution for row-wise matrix subtraction

texts:
I have 2 matrices. I have to calculate the euclidean distance between every row of matrix A and every row of matrix B.

In the first solution I loop over the rows of the two matrices and for each row in matrix A, I take a row from B, take the square of the element wise subtraction, then sum it and take the square root.

I end up with a matrix of the size #rows in A x #rows in B:

import numpy as np

A = np.random.random((50, 3072))
B = np.random.random((500, 3072))

# First solution
d = np.zeros((50, 500))
for i in range(50):
    for j in range (500):
        d[i,j] = np.sqrt(np.sum(np.square(B[j] - A[i])))

In the second solution I did this by broadcasting, and it works. But when I increase the amount of rows in A and B ... it becomes very very slow. Is there a faster way without looping?

Solution 2:

# Second solution
test = np.sqrt(np.sum(np.square(A[:,np.newaxis]-B),axis=2))

#print check
print np.unique(test==d)


texts: Iteratively process an identically named file all subdirectories and plot analysis to root directory

texts:
This script can successfully go through all of the subdirectories in a root directory, and then process a specific file that exists in all of them and output the file in the root directory as a .png named after the subdirectory. I am hoping to get some advice for the end of the script in formatting the name of the image since I do a quick post-processing step with imageMagick but the naming convention of the folders when they are generated is such that they do not have preceeding zeros:

Checkpoint0
Checkpoint1000
...
Checkpoint10000
...

Does anyone have a suggestion for how to nicely parse the number of digits in the longest foldername and use that to add an appropriate number (either exact or one additional) of zeros to the corresponding image names?
close all;
clear all;
pkg load all;
addpath("~/workspace/PetaVision/mlab/util");

dirData = dir(pwd);
dirIndex = [dirData.isdir];
folderList = {dirData(dirIndex).name};

pvpFile = "W1_W.pvp"
nbins = 100;
xmin = -15;xmax = 15;
ymin = 0;ymax = 150000;

for i = 3:size(folderList,2)
filename{i-2} = strcat(folderList(1,i),"/",pvpFile);
temppvp = readpvpfile(cell2mat(filename{i-2}));
cpList{i-2} = temppvp{1}.values{1};
end

for i = 1:size(cpList,2)
    histfit(cpList{i}(:),nbins);
    xlim([xmin xmax]);
    ylim([ymin ymax]);
    xlabel('Weight');
    ylabel('Frequency');
    title(folderList(1,i+2));
    imgTitle = cell2mat(strcat(folderList(1,i+2),"_",pvpFile))
    print(imgTitle)
end


texts:
I had an exercise to solve, written in German. I try to translate it:

  Write a program that takes an amount of seconds. The program than has to output the number of years, days, hours and seconds.

My Solution

public class Main {
  public static void main(String[] args) {
    final int HOUR_IN_SECONDS = 60 * 60;
    final int DAY_IN_SECONDS = HOUR_IN_SECONDS * 24;
    final int YEAR_IN_SECONDS = DAY_IN_SECONDS * 365;

    int seconds = 1000000000;

    // Jahre berechnen
    int years = seconds / YEAR_IN_SECONDS;
    seconds = seconds - years * YEAR_IN_SECONDS;
    System.out.println("Jahre: " + years);

    // Tage berechnen
    int days = seconds / DAY_IN_SECONDS;
    seconds = seconds - days * DAY_IN_SECONDS;
    System.out.println("Tage: " + days);

    // Stunden berechnen
    int hours = seconds / HOUR_IN_SECONDS;
    seconds = seconds - hours * HOUR_IN_SECONDS;
    System.out.println("Stunden: " + hours);

    // Minuten berechnen
    int minutes = seconds / 60;
    seconds = seconds - minutes * 60;
    System.out.println("Minuten: " + minutes);

    // Sekunden ausgeben
    System.out.println("Sekunden: " + seconds);
  }
}

This code works, but is it also beautiful enough and easy to read?


texts: complicated pascal triangle using JavaScript

texts:
I wrote a function to generate a complicated version of the pascal triangle. The generated triangle should look like that:

┌─────────┬───┬───┬────┬────┬────┬────┬────┬───┬───┐
│ (index) │ 0 │ 1 │ 2  │ 3  │ 4  │ 5  │ 6  │ 7 │ 8 │
├─────────┼───┼───┼────┼────┼────┼────┼────┼───┼───┤
│    0    │ 1 │   │    │    │    │    │    │   │   │
│    1    │ 1 │ 1 │ 1  │    │    │    │    │   │   │
│    2    │ 1 │ 2 │ 3  │ 2  │ 1  │    │    │   │   │
│    3    │ 1 │ 3 │ 6  │ 7  │ 6  │ 3  │ 1  │   │   │
│    4    │ 1 │ 4 │ 10 │ 16 │ 19 │ 13 │ 10 │ 4 │ 1 │
└─────────┴───┴───┴────┴────┴────┴────┴────┴───┴───┘

My implementation is like that

function createTriangle (n) {
// initialize the holding matrix
  let matrix = [];

// iterate over the matrix rows, and for each row construct a new array of row number + 1

  for (let row = 0; row < n; row++) {
    matrix[row] = new Array(row+1);
// iterate over each row and check conditions

    for (let col = 0; col <= 2*row; col++) {
      if ((col === 0 && row >= 0) || (col === 2 * row)) {
        matrix[row][col] = 1;
// first case
      } else if(col === row && col === 1){
                matrix[row][col] = 1;
// second case ;
            } else if(row > col && matrix[row][col-1]=== 1 ) {
            matrix[row][col] =
            1 + matrix[row-1][col];
// third case
            } else if(row > col && matrix[row][col-1]!== 1 ) {
            matrix[row][col] =
            matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// fourth case
     } else if((row === col && (matrix[row][col-1] !== 1))) {
                matrix[row][col] =
                matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];

// fifth case
       // if the col number is even, add only the previous 2 elements in the previous row
            } else if(row < col && col % 2 === 0){
                matrix[row][col] = matrix[row-1][col-2] + matrix[row-1][col-1] + matrix[row-1][col];
// sixth case

      // if the col number is odd add the previous 3 elements in the previous row
            } else if(row < col && col % 2 === 1){

            matrix[row][col] = matrix[row-1][col-2] + matrix[row-1][col-1];
            }
        }
    }
  return matrix;
}

console.table(createTriangle(5))

I feel that my code is a bit confusing. In addition, there is a bug on matrix[4, 5] it should be 16,but it is 13?? Could anyone advise if there is a more refactored elegant solution? Appreciate your time and help.

Edit
The algorithm should generate a matrix that have number of columns twice number of rows. The elements before the element at matrix[row][col] where col = row should be the same but reversed in a desc. order. for example, matrix[4,4] => [1,4,10,16,19,16,10,4,1]. element at matrix[4,4] 19 should be equal to 6+7+6


texts: Flux & async communication with websockets

texts:
I want to arrange async server-client communication with websockets and vanilla flux architecture. There is an excellent article about "Async Server-Side Communication with the Flux Architecture". I gonna implement it analogue with SockJS and ES6 promises:

TodoActionCreator.js

import { dispatchAsync } from '../AppDispatcher';
import ActionTypes from '../constants/ActionTypes';
import TodoService from '../services/TodoService'

export function addTodo(text) {
  var that = this;
  TodoService.addTodo({text: text}).then(function(todo) {
    that.dispatch(ActionTypes.ADD_TODO, todo);
  });
}

TodoService.js

import WebSocketWrapper from '../communication/WebSocketWrapper';

export function addTodo(todo) {
    //maybe do something with todos before send them to the server
    return WebSocketWrapper.send(todo);
}

WebSocketWrapper.js

/**
 * Due fact that SockJS provide raw websocket API and do not implement pub/sub, we need to do wrapper, which will corellate request/response
 */
import SockJS from 'sockjs-client';
import selectn from 'selectn';

var responseDeffers = {},
    requestId = 1;

var webSocketWrapper = {

    join: function(url) {
        this.ws = new SockJS(url);
        this.ws.onopen = this.onOpen;
        this.ws.onmessage = this.onMessage;
        this.ws.onclose = this.onClose;
        this.ws.onerror = this.onError;
    },

    onMessage: function(message) {
        let requestId = selectn('message.data.request_id');
        if (!requestId) return;
        //resolve or reject the promise which is kept in ActionCreator
        if (message.data.result === 'Ok') resolveRequest(requestId, message);
        else rejectRequest(requestId, message.error);
    },

    /**
     * Return Promise, which will be resolved/rejected on server response with the same requestId
     */
    send: function(request) {
        return new Promise(function(resolve, reject) {
            //npm run build
            // cache resolve/reject function to be able to invoke themn on server response
            responseDeffers[requestId++] = {
                resovle,
                reject
            };
            //send message via websockets
            if (this.ws.readyState == this.ws.OPEN) {
                this.ws.send(JSON.stringify(request));
            } else {
                reject('Websocket connection is closed');
            }
        });
    },

    resolveRequest: function(requestId, message) {
        let response = JSON.parse(message.data);
        responseDeffers[request_id].resolve(response);
        delete responseDeffers[request_id];
    },

    rejectRequest: function(requestId, message) {
        responseDeffers[requestId].reject(message);
    },

    onOpen: function() {},

    oClose: function() {},

    onError: function(e) {}
}

webSocketWrapper.join('http://localhost:3000/sjs');

export default webSocketWrapper;


texts:
I'm writing a small PHP framework to help me develop Web applications. The framework is split into numerous components, each of which are automatically loaded according to the configuration settings. This is my component base class:

class Component {
    public static void init() {}
}

When I create new components, I extend them from Component. For example, I have an Authenticator component that handles user login, logout and some other related functions. Here's an example of the code:

class Authenticator extends Component {
     public static void login($u, $p) {}
     public static void logout() {}
     ...
}

As you can see my methods are static, so when it comes time to use the component, I can easily call the component's functions using Authenticator::METHOD() in the scope of my controller class. There is no need to create an instance of the components since they are in a static context.

But should I make them more OO (eg: make the methods non-static) using DI or some other means? What would be the advantages of this? And considering how I have several components, how would I do this without making things overly complex?


texts: Check if IP address list has subnet or is supernet

texts:
I need to iterate over a list of IP addresses, to check if the elements inside are subnets/supernets between them, for this I use the  IP-address library.
Currently I have the following problem: my second iterator (which I use to iterate over the rest of the list) always starts at 0 and therefore compares each element of the list twice (which I think can be avoided).
Here is part of the txt file from which I create the list:
Name
10.104.181.0/23
10.104.180.0/24
10.132.83.112/32
10.104.183.0/24
10.104.185.0/24
10.104.185.32/24
174.28.164.30/24
178.38.233.0/24
10.104.186.0/24
10.132.208.0/24
10.104.185.42/24
10.130.217.88/32
10.104.24.108/24
10.134.213.84/32
10.134.205.18/32
10.104.182.145/32
10.123.232.95/32
10.130.236.0/24
10.105.26.245/32
10.134.65.250/32
10.134.222.120/32
10.104.184.62/32
10.104.184.61/32
10.105.121.0/24

And here is my python code:
import ipaddress
import sys

fileobj=open("test.txt")
for line in fileobj:
    lines.append(line.strip())#create the list from the txt file
lines.pop(0)#remove line "name"
for line in lines:
    for j in range(1,len(lines)):
        if(line==lines[j]):#problem here: j start always at 1
            print('comparing same line.... skipping')
            pass
        elif(ipaddress.ip_network(line,False).subnet_of(ipaddress.ip_network(lines[j],False))):#check if subnet
            print(line+' is subnet of network'+lines[j])
        elif(ipaddress.ip_network(line,False).supernet_of(ipaddress.ip_network(lines[j],False))):#check if supernet
            print(line+' is super of network'+lines[j])

What I'm looking for:

How to solve the problem of my second iterator.
Any other improvement (whatever it is, formatting, algorithm,...) is appreciated.


texts: Tableview Subclass implementing delegate datasource

texts:
I have two view controllers which have same tableview. One is for Post and one is for Profile, which also contains a post by a user. I have decided to reuse the code, so I have created the class PostTableView.

class PostTableView: UITableView {

    var arrayPosts:[PostTableViewCompitible] = [] {
        didSet {
            self.reloadData()
        }
    }
    var btnCommentTapped:((ArrayInspireListCell) -> ())?
    var heightOfRows = Dictionary<IndexPath, CGFloat>()
    var indexOfCellBeforeDragging = 0

    override func awakeFromNib() {
        super.awakeFromNib()
        setupTableView()
    }

    private func setupTableView() {
        self.register(UINib.init(nibName: StoryBoard.Cells.ArrayInspireListCell, bundle: nil), forCellReuseIdentifier: StoryBoard.Cells.ArrayInspireListCell)
        self.dataSource = self
        self.delegate = self
        self.estimatedRowHeight = 470
        //    self.tableView.decelerationRate = UIScrollViewDecelerationRateFast
        self.rowHeight = UITableViewAutomaticDimension
        self.separatorStyle = .none

    }

}

With Delegate / Data source:

extension PostTableView:UITableViewDataSource,UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrayPosts.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let post = self.arrayPosts[indexPath.row]
        let cell = post.cellForTableView(tableview: tableView, atIndexPath: indexPath)
        cell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.row)
        cell.layer.shouldRasterize = true
        cell.layer.rasterizationScale = UIScreen.main.scale

        cell.btnCommentTapped = self.btnCommentTapped

        cell.layoutIfNeeded()

        return cell
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height = self.heightOfRows[indexPath] {
            return height
        }
        return 470
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let height = cell.frame.size.height
        self.heightOfRows[indexPath] = height + 30
    }

}

Is it good practice to do so?


texts: Merging and sorting overlapped intervals

texts:
We are given an array of intervals we need to merge all overlapping intervals and sort the resulting non-overlapping intervals. When they "touch" in a single point, intervals are also considered to be overlapping .
class Span
{
    public uint Start { get; }
    public uint End { get; }

    private Span(uint start, uint end)
    {
        Start = start;
        End = end;
    }

    private static Span _default = new Span(0, 0);

    // To avoid constructor throwing an exception
    public static Span Create(uint start, uint end)
    {
        if (start > end) throw new ArgumentOutOfRangeException(nameof(start), "Begin cannot me more than end");
        return new Span(start, end);
    }

    public bool IsOverlapped(Span other)
    {
        return Start <= other.End && End >= other.Start;
    }

    public Span Merge(Span other)
    {
        if (!IsOverlapped(other)) throw new ArgumentOutOfRangeException(nameof(other), "Spans must overlap");
        return new Span(Math.Min(Start, other.Start), Math.Max(End, other.End));
    }

    public bool TryMerge(Span other, out Span mergedItem)
    {
        mergedItem = _default;
        if (!IsOverlapped(other)) return false;
        mergedItem = new Span(Math.Min(Start, other.Start), Math.Max(End, other.End));
        return true;
    }
}

// In reality this method will be in a different class where it belongs
class Util
{
    public static Span[] Normalise(Span[] spans)
    {
        var results = new List<Span>();
        foreach (var item in spans.OrderBy(x => x.Start))
        {
            var lastResultIndex = results.Count - 1;
            if (lastResultIndex >= 0 && results[lastResultIndex].TryMerge(item, out Span mergedItem))
            {
                results[lastResultIndex] = mergedItem;
            }
            else
            {
                results.Add(item);
            }
        }
        return results.ToArray();
    }
}


texts: Insert, update and get in the same php file?

texts:
I'm creating a CRUD page. My first approach was use the same class editCategory.php for doing these actions:

If this file is called via GET and categoryId parameter doesn't exist -> shall show a empty form
If this file is called via GET and categoryId parameter is provided -> shall show a form with the data of this category.
If this file is called via POST and there is no categoryId parameter -> shall create a new category.
If this file is called via POST and categoryId parameter is provided -> shall update this category.

The code works ok, but I have the sense that the code is cluttered and that it could be organized better.

    <?php
        require_once "../include_dao.php";
        $action = isset($_POST["action"]);

        $category = new Category();
        $categoryDao = new CategoryMySqlDAO();

        $categoryName = "";
        if ($action == "save") {                                        // DO_POST
            $categoryName = $_POST["name"];
            $category->name=$categoryName;

            if (isset($_POST["categoryId"])) {                              // update
                $categoryId = (int) $_POST["categoryId"];
                $category->categoryId=$categoryId;
                $categoryDao->update($category);
            } else {                                                        // insert
                $categoryDao->insert($category);
            }
            $messageSuccess = "Category saved";
        } else {                                                        // DO_GET
            if (isset($_GET["categoryId"])) {
                $categoryId = (int) $_GET["categoryId"];

                $category = $categoryDao->load($categoryId);
                $categoryName = $category->name;
            }

        ?>
<html>
 HTML code here showing the form
</html>


texts: Count reoccurring elements in multiple lists in Python

texts:
I have a number of names divided into several lists. I am printing all the names which occur in more than one list, sorted by the number of occurrences.

What is a better/easier/more pythonic way of doing this? I feel like my solution is overly complicated.

import numpy as np

list_1 = ['John Cleese', 'Terry Gilliam']
list_2 = ['Eric Idle', 'Terry Jones', 'Michael Palin']
list_3 = ['Graham Chapman', 'Sir Lancelot the Brave', 'Terry Jones']
list_4 = ['Arthur, King of the Britons', 'Terry Jones', 'John Cleese']
list_5 = ['Michael Palin', 'Sir Robin the Not-Quite-So-Brave-as-Sir-Lancelot']

all = sorted(np.unique(list_1+list_2+list_3+list_4+list_5))

def in_how_many(name):
    result = 0
    if name in list_1:
        result += 1
    if name in list_2:
        result += 1
    if name in list_3:
        result += 1
    if name in list_4:
        result += 1
    if name in list_5:
        result += 1

    return result

names_list = []

for name in all:
    if in_how_many(name) > 1:
        name_dict = {'name': name, 'value': in_how_many(name)}
        names_list.append(name_dict)

for person in sorted(names_list, key=lambda k: k['value'], reverse=True):
    print '\'%s\' is in %s lists' % (person['name'], person['value'])

This prints:

'Terry Jones' is in 3 lists
'John Cleese' is in 2 lists
'Michael Palin' is in 2 lists


texts:
I have written the following JavaScript code and want to ask if it is written as per best practices. Please recommend any changes to be made in the code. The code is taking a few variables as input and then validating if all of them have some value and not blank/null.

var var1 = false;
var missingVAL = false;
var validationMsg = "";

host       = scriptletContext.get("host");
user    = scriptletContext.get("user");
serverID        = scriptletContext.get("serverId");
runID              = scriptletContext.get("runId");

if (host == false)
{
  validationMsg = "serverHostName (serverHostName) is missing.";
  var1 = true;
}

if (user == false)
{
    if (var1 == true)
    {
        validationMsg = validationMsg + " Requestor user name (requestorUserName) is missing.";
    }
    else
    {
        validationMsg = "Requestor user name (requestorUserName) is missing.";
    }
    var1 = true;
}

if (serverID == false)
{
    if (var1 == true)
    {
        validationMsg = validationMsg + " (vascoServerId) is missing.";
    }
    else
    {
        validationMsg = "(vascoServerId) is missing.";
    }
    var1 = true;
}

if (runID == false)
{
    if (var1 == true)
    {
        validationMsg = validationMsg + " OAC run type (runTypeId) is missing.";
    }
    else
    {
        validationMsg = "OAC run type (runTypeId) is missing.";
    }
    var1 = true;
}

if (var1 == true)
{
    scriptletContext.putGlobal("validationMsg", validationMsg);
}

scriptletContext.putGlobal("missingVAL", var1);


texts: Macro to distribute data within the sheets based on tabs name

texts:
I wrote a macro which works, but given the large amount of data, it takes a lot of time. I wonder if there is a way to speed it up. Here is a summary of what it does:

In "Summary (All)" tab I have global sheet with all the data.
I have several tabs corresponding to the each months.
I want to have the data distributed to those tabs, based on the value in one column (should match the tab name).

My code

Option Explicit

Sub CopyDataOutToSheets()
    Dim sh As Worksheet
    Dim SourceSh As Worksheet
    Dim Last As Long
    Dim shLast As Long
    Dim CopyRng As Range
    Dim StartRow As Long
    Dim lrow As Long
    Dim r As Long

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Set SourceSh = ActiveWorkbook.Worksheets("Summary (All)")
    Application.DisplayAlerts = False
    On Error Resume Next
    On Error GoTo 0

    For Each sh In ActiveWorkbook.Worksheets
        If IsError(Application.Match(sh.Name, _
                                     Array(SourceSh.Name, "List Data", _
                                     "Lists", "Summary (Filtered)"), 0)) Then
            lrow = lastRow(sh)
            If lrow > 6 Then
                sh.Rows("7:" & lrow).Delete
            End If

            If lastRow(SourceSh) < 7 Then
                MsgBox ("Nothing to move")
                Exit Sub
            End If

            For r = lastRow(SourceSh) To 7 Step -1
                'Finding the first empty row in column A on destination worksheet
                If SourceSh.Range("N" & r).Value = sh.Name Then
                    SourceSh.Rows(r).Copy Destination:= _
                                                  sh.Range("A" & lastRow(sh) + 1)
                End If
            Next r
        End If
    Next

ExitTheSub:
    Application.Goto SourceSh.Cells(1)
    Application.DisplayAlerts = True
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub

There are few thousands rows in global tab, so I'm expecting to have roughly 1000 in each tab after distribution. Could you please let me know what would be the best way to make it happen more quickly?


texts: Laravel model and controller interaction

texts:
I want to know if I'm going about creating and calling two functions from my model to my controller in the simplest and cleanest way.

Model:

public function getPosts()
{
    $post = $this->paginate(4);
    return $post;
}

public function getMonth($post)
{
    $post->month = date('M', strtotime($this->created_at));
    $post->month = strtoupper($post->month);
    return $post->month;
}

public function getDay($post)
{
    $post->day = date('d', strtotime($this->created_at));
    return $post->day;
}

Controller:

public function index()
{
    $post = $this->post->getPosts();
    $post->month = $this->post->getMonth($post);
    $post->day = $this->post->getDay($post);

    return View::make('posts.index', compact('post'));
}

I am unsure about if my controller is acting in a strict MVC way, being that I thought it's only job is to direct traffic, but it's doing more by calling functions from my model. Is this the best way to go about this?


texts:
The function's job is to load a vertex attribute buffer or an element buffer from a specified path, and upload it to OpenGL. Also, optionally, return the number of vertices/indices loaded through an output parameter.

Signature:

GLuint loadBufferFromFile(std::string const& bufferPath, unsigned char vertexElementCount, GLenum vertexFormat, GLenum bufferType=GL_ARRAY_BUFFER, GLuint *vertexCount=NULL, GLenum usageHint=GL_STATIC_DRAW);

Body:

GLuint loadBufferFromFile(std::string const& bufferPath, unsigned char vertexElementCount, GLenum vertexFormat, GLenum bufferType, GLuint *vertexCount, GLenum usageHint)
{
    const std::unordered_set<GLenum> VALID_VERTEX_FORMATS = {GL_FLOAT, GL_UNSIGNED_INT, GL_UNSIGNED_BYTE};
    //bufferType and usageHint will be validated by OpenGL

    if(vertexElementCount < 1 || vertexElementCount > 4)
    {
        throw std::invalid_argument("Vertex element count must be in range <1,4>");
    }

    if(bufferType == GL_ELEMENT_ARRAY_BUFFER && vertexElementCount != 1)
    {
        throw std::invalid_argument("Buffer of type GL_ELEMENT_ARRAY_BUFFER must have element count of 1");
    }

    if(VALID_VERTEX_FORMATS.find(vertexFormat) == VALID_VERTEX_FORMATS.end())
    {
        throw std::invalid_argument("Invalid vertex format");
    }

    std::ifstream file;
    file.open(bufferPath, std::ios::binary | std::ios::in);

    if(!file.is_open())
    {
        throw std::runtime_error(std::string("Buffer file ") + bufferPath + " could not be opened");
    }

    file.seekg(0, file.end);
    unsigned int length = file.tellg();
    file.seekg(0, file.beg);

    if(vertexCount != NULL)
    {
        std::size_t vertexSize;

        switch(vertexFormat)
        {
            case GL_FLOAT:
                vertexSize = sizeof(GLfloat);
                break;
            case GL_UNSIGNED_INT:
                vertexSize = sizeof(GLuint);
                break;
            case GL_UNSIGNED_BYTE:
                vertexSize = sizeof(GLubyte);
                break;
        }

        vertexSize *= vertexElementCount;
        *vertexCount = length/vertexSize;
    }

    char *buffer = new char [length];
    file.read(buffer, length);
    file.close();

    GLuint bufferID;
    glGenBuffers(1, &bufferID);

    glBindBuffer(bufferType, bufferID);
    glBufferData(bufferType, length, buffer, usageHint);

    delete[] buffer;
    return bufferID;
}

Specific questions:

Is it appropriate to fine-tune data types when it is not strictly necessary, like I did with vertexElementCount? int would have also worked just fine.
Is this level of error handling/validation appropriate?
Is it good to use a const collection for validation in this way? Are there runtime costs beyond the act of validation itself?
If yes, unordered_set or vector? On one hand, a set seems a logical choice for this, on the other, wisdom of the ancients says "Use vector for everything unless you absolutely can't!"
Are those appropriate exceptions to use?
Even though in this case I can be certain it will not lead to a memory leak (nothing in between new and delete throws exceptions), directly using dynamic allocation rubs me the wrong way. Can I avoid it in a reasonable way?


texts: Adding Reversed Numbers - ADDREV on SPOJ

texts:
Today I tried solving this problem on SPOJ, in which you reverse the digits of two numbers, add them, and print the reversed digits of the sum.  (When reversing, leading zeroes in the result should be dropped, and trailing zeroes in the result shouldn't happen.)

I used C++ to write the code for this problem. My code got accepted in the first go and I was happy about it but I feel my code is way too long for a problem of this kind. I would like some suggestions on how to reduce the code and make it more readable at the same time.

#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>

using namespace std;

#define ALL(C)  (C).begin(), (C).end()
#define LN(str) (int)(str).length()

// this function gets the reversed form of the input number, the function is coded assuming that the input number has both trailing and leading 0's
string getReverseNum(string& num) {

  string reversedNum = "";
  // find the index of last leading 0
  int index1 = -1;
  for(int i = 0; i < LN(num); ++i) {
     if(num[i] == '0')
        continue;
     else {
    index1 = i;
    break;
     }
  }

  // find the index of the first trailing 0
  int index2 = -1;
  for(int i = LN(num)-1; i >= 0; --i) {
    if(num[i] == '0')
     continue;
    else {
       index2 = i+1;
       break;
    }
  }

  reversedNum = num.substr(index1, index2-index1);

  if(reversedNum == "")
    return "0";
  return reversedNum;
}

// this function is used to convert an integer to a string
string convertIntToString(int num) {

  ostringstream oss;
  oss << num;
  return oss.str();
}

// this function is used to add the two input numbers and return the result as a string
string addNumbers(string& num1, string& num2) {

  int carry = 0;
  string result = "";

  for(int i = 0; i < LN(num2); ++i) {
    int dig1 = num1[i]%48;
    int dig2 = num2[i]%48;
    int temp = dig1+dig2+carry;
    carry = temp/10;
    result += convertIntToString(temp%10);
  }

  for(int i = LN(num2); i < LN(num1); ++i) {
    int dig = num1[i]%48;
    int temp = dig+carry;
    carry = temp/10;
    result += convertIntToString(temp%10);
  }

  if(carry != 0)
   result += convertIntToString(carry);

  return getReverseNum(result);
}

// this function is used to return the reversed sum of the two input numbers it receives as parameters
string getReversedSum(string& num1, string& num2) {

  // first we get the reverse of two numbers
  string reversedNum1 = getReverseNum(num1);
  string reversedNum2 = getReverseNum(num2);

  string reversedNum = "";

  int len1 = LN(reversedNum1), len2 = LN(reversedNum2);

  if(len1 < len2)
    return addNumbers(reversedNum2, reversedNum1);
  return addNumbers(reversedNum1, reversedNum2);

}

int main() {

  // this variable stores the number of test cases on which the program is run
  int N;
  cin >> N;

  // clear the input stream
  cin.ignore();

  // program execution begins here
  while(N--) {
    string num1, num2;
    cin >> num1 >> num2;
    cout << getReversedSum(num1, num2) << endl;
  }
  return 0;
}

Code is hosted here.