texts: Using C++ to check if string s is subsequence of string t

texts:
The problem I want to solve is very simple:

  Given a string s and a string t, check if s is subsequence of t. there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

  Example 1:
  s = "abc", t = "ahbgdc"
  Return true.

  Example 2:
  s = "axc", t = "ahbgdc"
  Return false.

I only learnt C++ for about 30 hours, so I am not sure whether my below solution is correct C++ style or not, especially when to free the pointer allocated space. I assigned two char pointer to each string and I do know I need to free them somewhere else. Since the return value depends on pointer, I don't know where to free the pointer allocated memory, which should be a big deal.

What I thought about this question is that there must be two pointers, each pointing one string. For these two strings, using pointers to compare character one by one.

#include <iostream>
#include <string.h>

using namespace std;

class Solution {
public:
bool isSubsequence(string s, string t) {
    char *sPtr = new char[s.size() + 1];
    char *tPtr = new char[t.size() + 1];

    bool returnVal = false;

    strcpy(sPtr, s.c_str());
    strcpy(tPtr, t.c_str());

    while (*sPtr && *tPtr){
        if (*sPtr == *tPtr++) {
            sPtr++;
        }
    }

    return !*sPtr;

   }
};

int main() {

    string s = "abc";
    string t = "ahbgdc";

    Solution sol = Solution();
    cout << sol.isSubsequence(s, t)<<endl;

    return 0;
}

After I talked to one of classmates, he suggests that to include  and use c++ string class to do this question. Following is my solution followed his suggestion, but for my above solution, he just said "I don't know dude, I just use c++ string class, that's simple. Your solution is just weird to me but I don't know why I feel weird."

class Solution {
public:
    bool isSubsequence(string s, string t) {
    int sIndex = 0;
    int tIndex = 0;

    while (sIndex < s.size() && tIndex < t.size()) {
        if (s[sIndex] == t[tIndex++]) {
            sIndex++;
        }
    }

    return sIndex >= s.size();
    }

};


texts: Finding pairs of Amicable Numbers, up to 10000

texts:
I have this program to find pairs of amicable numbers in C:

#include<stdio.h>

int main()
{
    printf("|---------- PROGRAM FOR AMICABLE NUMBERS.----------|");
    int num1,num2,sum=0;
    for(num1=1; num1<=10000; num1++)
    {
        for(num2=1; num2<=10000; num2++)
            {
                if ((num1==sum_of_divisors(num2)) && (num2==sum_of_divisors(num1)) && num1!=num2)
                {
                    printf("\n%d\t\t%d", num1,num2);
                }
            }
    }
    return 0;
}

int sum_of_divisors(int n)
{
    int sum=0,i;
    for(i=1; i<n; i++)
    {
         if(n%i==0)
         {
              sum=sum+i;
         }
    }
    return sum;
}

I'd like to improve the performance - it's taking around 10 minutes to find even the first 4 pairs.


texts: cross-platform stdlib-only aligned allocator in C++14

texts:
I'm writing a program which uses OpenCL, and the OpenCL types are mostly over-aligned. Sometimes when using stl containers with these types, I'd get segfaults, so I tried to write my own aligned allocator which I could use instead of the standard allocator.

I've done a bit of testing in valgrind etc. and so far everything looks OK, but I don't know whether I might have written something which will bite me in the future. I'm especially worried about some reinterpret_casts in my allocate and deallocate methods.

Any feedback appreciated.

Here's the code:

namespace mem {

template <typename T, std::size_t N = alignof(T)>
class aligned_allocator {
    //  helper type with the alignment we want
    using aligned_type = std::aligned_storage_t<sizeof(T), N>;

public:
    //  type to allocate
    using value_type = T;

    //  ensure basic special class methods are enabled
    aligned_allocator()                                         = default;
    aligned_allocator(const aligned_allocator&)                 = default;
    aligned_allocator& operator=(const aligned_allocator&)      = default;
    aligned_allocator(aligned_allocator&&) noexcept             = default;
    aligned_allocator& operator=(aligned_allocator&&) noexcept  = default;

    //  allow construction from an allocator for another type
    //  (with the same alignment)
    template <typename U>
    aligned_allocator(const aligned_allocator<U>&) {}

    //  implementations may derive from the allocator polymorphically
    virtual ~aligned_allocator() noexcept = default;

    //  rebinding the allocator for another type should respect the alignment
    //  of that other type
    template <typename U>
    struct rebind {
        using other = aligned_allocator<U>;
    };

    //  allocate a type that we know will have the correct alignment
    //  then reinterpret the pointer
    T* allocate(std::size_t n) {
        return reinterpret_cast<T*>(new aligned_type[n]);
    }

    //  deallocate previously allocated memory
    void deallocate(T* p, std::size_t) {  //  don't care about size here
        delete[] reinterpret_cast<aligned_type*>(p);
    }
};

template <typename T, typename U, std::size_t N>
constexpr bool operator==(const aligned_allocator<T, N>&,
                          const aligned_allocator<U, N>&) {
    return true;
}

template <typename T, typename U, std::size_t N>
constexpr bool operator!=(const aligned_allocator<T, N>&,
                          const aligned_allocator<U, N>&) {
    return false;
}

}  //  namespace mem


texts:
I have been working with where I use watchdogs to be able read whenever I have created a file by the name -> kill_.flag and it contains:
*kill_*.flag contains:

hello;https://www.google.se/;123

and my script is then going to read the created file, split the ";" between each other and give each a key where I later on print it out which I for now has the text "Deleting" where I will continue my script after I have completed this part.
# !/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import os.path
import time

import watchdog.events
import watchdog.observers

class AutomaticCreate(watchdog.events.PatternMatchingEventHandler):

    def __init__(self):
        self.delete_flag = "*kill_*.flag"
        watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]],
                                                             case_sensitive=False)

    def on_created(self, event):
        while True:
            try:
                with open(event.src_path) as f:
                    content = f.read().split(";")
                    payload = {
                        "name": content[0].strip(),
                        "link": content[1].strip(),
                        "id": content[2].strip()
                    }
                break
            except OSError:
                print(f"Waiting for file to transfer ->  {event.src_path}")
                time.sleep(1)
                continue

        while True:
            try:
                os.remove(event.src_path)
                break
            except Exception as err:
                print(f"Trying to remove file -> {err}")
                time.sleep(1)
                continue

        print(f'Deleting: {payload["name"]} - {payload["link"]} - {payload["id"]}')

    def main(self):
        observer = watchdog.observers.Observer()
        observer.schedule(AutomaticCreate(), path=os.path.split(self.delete_flag)[0], recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

if __name__ == "__main__":
    AutomaticCreate().main()

I wonder if there is a smarter or maybe even cleaner way to improve this code both performance and whatever it can be?


texts:
How can I improve this code so I do not use so many for loops in this?

public class Hangman {
   private String secretWord;
   private String disguisedWord ="";
   private String guessedLetters = "";
   private int numberOfGuesses = 0;
   private int numberOfIncorrectGuesses = 0;

   Hangman(String secretWord){
     this.secretWord = secretWord;
     for (int i = 0; i < secretWord.length(); i++){
       this.disguisedWord += "?";
     }
   }

   public String getSecretWord() {
        return secretWord;
   }

   public String getGuesses() {
        return guessedLetters;
   }

   public String getDisguisedWord() {
        return disguisedWord;
   }

   public int getGuessCount() {
        return numberOfGuesses;
   }

   public int getIncorrectGuessCount() {
        return numberOfIncorrectGuesses;
   }

   public boolean isFound() {
        if (secretWord.equalsIgnoreCase(disguisedWord)){
            return true;
        } else{
            return false;
        }
   }

   public boolean makeGuess(char guess) {

        for (int i = 0; i < guessedLetters.length(); i++){
            if (guess == guessedLetters.charAt(i)) {
                System.out.println("You have already guessed that letter.");
                return false;
             }
        }

        guessedLetters+= guess;
        String tempString = "";
        numberOfGuesses++;
        for (int i = 0; i < secretWord.length(); i++) {
                if (guess == secretWord.charAt(i)){
                    tempString += guess;
                } else {
                    tempString += disguisedWord.charAt(i);
                }
        }
        if (!tempString.equalsIgnoreCase(disguisedWord)) {
                disguisedWord = tempString;
                return true;
        } else {
                System.out.println("Incorrect Guess!");
                numberOfIncorrectGuesses++;
                return false;
        }
    }

    public static void main(String[] args) {
        java.util.Scanner keyboard = new java.util.Scanner(System.in);
        Hangman hangman = new Hangman("pirate"); // enter secret word as a string

        while (hangman.isFound()== false){
            System.out.println("The word is: " + hangman.getDisguisedWord());
            System.out.println("Guess a letter or type 'guesses' to see your guesses.");
            String input = keyboard.nextLine();
                if (input.equalsIgnoreCase("guesses"))
                {
                    System.out.println(hangman.getGuesses());
                }
                else
                {
                    hangman.makeGuess(input.charAt(0));
                }
            }

            System.out.println("The secret word was: " + hangman.getSecretWord());
            System.out.println("It took you " + hangman.getGuessCount() + " guesses to get the correct answer.");
            System.out.println("You had " + hangman.getIncorrectGuessCount()+ " incorrect guesses.");
    }
}


texts:
I'm writing a small custom DSL and interpreter as an exercise in understanding how the language stack (lexer/parser/(interpreter/compiler)) works. Because I want to be able to report the location of semantic errors, the AST needs to retain information about where the elements were in the source.

For this purpose I wrote a data class Point(val line: Int, val column: Int). All well and good, until I realized that manually specifying the position of EVERY node in the AST for unit tests on parsing would be prohibitively time consuming (and error prone). (Obviously, some tests need to do so to test the assigning of positions, but some is a lot fewer than all.)

To allow me to write more good unit tests quicker, I decided I wanted to default the position of all my nodes to a wildcard value that would match all valid Points. The parsed nodes would have the correct position, but the manually assembled AST to check against would not specify (and thus not test) the positions. This is the solution I came up with.

/**
 * DO NOT EXTEND THIS CLASS!!
 *
 * This is an custom open data class to allow a wildcard value.
 */
open class Point(val line: Int, val column: Int) {
    object Wildcard : Point(-1, -1) {
        override fun toString() = "Point.Wildcard"
        override fun copy() = this
    }

    override fun equals(other: Any?) = when {
        this === other         -> true
        other === Wildcard     -> true
        other !is Point        -> false
        this === Wildcard      -> true
        line != other.line     -> false
        column != other.column -> false
        else                   -> true
    }

    override fun hashCode(): Int { // generated
        var result = line
        result = 31 * result + column
        return result
    }

    override fun toString() = "Point(line=$line, column=$column)"
    operator fun component1() = line
    operator fun component2() = column
    open fun copy() = Point(line, column)
}

I wanted to keep all the behavior of a data class, but a data class cannot be open and this was the only way I could come up with of implementing the wildcard value. This solution still feels wrong and too much like a hack, however. It could easily be broken by outside code extending Point (as it must necessarily be available to be used) and so much of this code is just re-implementing what data class gives us for free. I feel like there must be a solution with a sealed class, but I haven't figured it out.

Recommended review points: idiomaticness (or not) of code, conventions, alternate solutions (and any other points)


texts: Scala mastermind solver, which is the most scala-ish

texts:
I am trying to express the classical TDD kata of mastermind in the most idiomatic scala I can. Here is a scalatest, test suite :

package eu.byjean.mastermind

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers

@RunWith(classOf[JUnitRunner])
class MastermindSpec extends FlatSpec with ShouldMatchers {
  behavior of "Mastermid"

  it should "find no good and no misplaced for a wrong guess" in {
    Mastermind.check (guess='red)(secret='blue) should equal (0,0)
  }

  it should "find all good if guess equals secret of one" in {
    Mastermind.check('blue)('blue) should equal (1,0)
  }

  it should "find one good if guess has one good in a secret of two" in {
    Mastermind.check('blue,'red)('blue,'green) should equal (1,0)
    Mastermind.check('green,'red)('blue,'red) should equal (1,0)
  }

  it should "find two good if guess has two good in a secret of three" in {
    Mastermind.check('blue,'red,'red)('blue,'green,'red) should equal (2,0)
  }

  it should "find one misplaced blue in a guess of two" in {
    Mastermind.check('blue,'red)('green,'blue) should equal (0,1)
  }

  it should "find two misplaced in a guess of four" in {
    Mastermind.check('blue,'blue,'red,'red)('green,'yellow,'blue,'blue) should equal (0,2)
  }
  it should "find two misplaced colors in a guess of four" in {
    Mastermind.check('green,'blue,'yellow,'red)('green,'yellow,'blue,'blue) should equal (1,2)
  }
}

and my current implementation

package eu.byjean.mastermind

object Mastermind {
  def check(guess: Symbol*)(secret: Symbol*): (Int, Int) = {
    val (goodPairs, badPairs) = guess.zip(secret).partition { case (x, y) => x == y }
    val(guessMiss,secMiss)=badPairs.unzip
    val misplaced=guessMiss.sortBy(_.toString).zip(secMiss.sortBy(_.toString())).filter{case (x,y)=>x==y}
    (goodPairs.size, misplaced.size)
  }

In the imperative form, some people employ a map and count for each color the number of occurences of the color in the secret and in the guess (only as far as misplaced go of course).
I tried an approach using foldLeft on the badPairs list of tuple, which lead me to variable naming problems and calling map.updated twice in the foldLeft closure which didnt seem right

Any thoughts on how to improve on the above code. It doesn't feel perfect. how would you improve it along the following axis:

bugs: have I missed something obvious ?
performance : this version with zip, unzip, sort, zip again most likely isn't the fastest
readability : how would I define an implicit ordering for Symbol so I don't have to pass _.toString ,
idiomatic scala: is there globally a more "scala-ish" way of solving this ?

Thanks


texts: Split an even length array in two such that each sub-arrays sum is as close as possible

texts:
I am currently iteratively forcing the solution by evaluating all of one elements possible coexisting elements for the closest combination to half of the initial arrays sum. Note: The initial array is assumed to be of length 8 in all cases (I'm not too sure how such an approach could be adapted to work for various array lengths without using recursion).
int target = team1.stream().mapToInt(Player::getElo).sum() / 2;
    int closest = Integer.MAX_VALUE;
    int[] best = new int[3];
    ArrayList<Player> team2 = new ArrayList<>();
    team2.add(team1.get(0));
    team1.remove(0);
    for (int i = 0; i < team1.size(); i++) {
        for (int j = 0; j < team1.size(); j++) {
            if (team1.get(j) == team1.get(i)) continue;
            for (int k = 0; k < team1.size(); k++) {
                if (team1.get(k) == team1.get(j) || team1.get(k) == team1.get(i)) continue;
                int elo = team2.get(0).getElo() + team1.get(i).getElo() +
                        team1.get(j).getElo() + team1.get(k).getElo();
                int dif = Math.abs(target - elo);
                if (dif < closest) {
                    closest = dif;
                    best[0] = i;
                    best[1] = j;
                    best[2] = k;
                }
            }
        }
    }
    team2.add(team1.get(best[0]));
    team2.add(team1.get(best[1]));
    team2.add(team1.get(best[2]));
    team1.removeAll(team2);


texts:
I am learning Java by reading source code of other authors. This Java method handles communication with SQL database. While the code does work several things concern me. For instance the try  catch block at the end of the file used as a workaround. What is the correct way of doing it? What other problems can you spot?

    public void run() {
        if (running) {
            return;
        }
        running = true;
        while(null == Common.server || null == Common.database || !ConnectionsPool.isInitialized()) {
            // Wait until the database is set before continuing...
            try {
                Thread.sleep(1000);
            }
            catch(Exception ex) {}
        }
        while(running) {
            final Connections cons = ConnectionsPool.getConnections();
            Connection  con  = null;
            while(!entries.isEmpty()) {
                if (null == con) {
                    con = cons.getConnection();
                }
                SQLLogEntry entry = entries.remove();
                if (null != entry) {
                    try {
                        write(entry, con); //find usages
                    }
                    catch (SQLException ex) {
                        writeLogFile("Could not write entry to SQL", ex);
                    }
                }
            }
            if (null != con) {
                try {
                    con.commit();
                }
                catch (SQLException ex) {
                    writeLogFile("Could not commit to SQL", ex);
                    try {
                        con.rollback();
                    }
                    catch (SQLException ex1) {
                    }

                    // log
                    final StringWriter errorOut = new StringWriter();
                    ex.printStackTrace(new PrintWriter(errorOut));
                    EditorTransactionUtil.writeLogFile(errorOut.toString());
                    // for user
                    final String msg = "Exception: " + EditorUtil.getErrorMessage(ex.getMessage());
                    try {
                        SwingUtilities.invokeAndWait(() -> {
                            JOptionPane.showMessageDialog(null, msg);
                        });
                    }
                    catch (Throwable ex1) {
                    }
                }
                finally {
                    cons.returnConnection(con);
                }
                con = null;
            }

            synchronized(entries) {
                try {
                    entries.wait(1000);
                }
                catch (InterruptedException ex) {
                    // This is a workaround to process this loop...
                }
            }
        }
        writeLogFile("SQLMsgLogger run stopping...");
    }


texts:
This code is for handling addition of two binary numbers, which can be as long as 100,000 bits... and up to 500,000 queries are performed.

High-level pseudocode:

First input N: number of bits in binary number A and B.
Second input Q: number of queries to be performed.
Next N inputs: 0/1s ... bits for A
Next N inputs: 0/1s ... bits for B
Next Q inputs are one of the following:

set_a INDEX VALUE: as a result I set a[INDEX] = VALUE
set_b INDEX VALUE: as a result I set b[INDEX] = VALUE
get_c INDEX: as a result I print c[INDEX] where C = A+B (binary addition, like 100 + 101 = 1001)

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <utility>  // For pair
#include <iterator> // For iterator, bidirectional_iterator_tag, reverse_iterator
#include <climits>  // For CHAR_BIT, ULONG_MAX
using namespace std;

class VanEmdeBoasTree {};

int main(int argc, char * argv[])
{
  int n, q;
  char c;
  bool a[100005] = {0}, b[100005] = {0};
  VanEmdeBoasTree equals;
  cin>>n;
  cin>>q;

  for(int i=0;i<n;i++){
    cin>>c;
    if(c=='1')
      a[n-i-1] = true;
  }
  for(int i=0;i<n;i++){
    cin>>c;
    if(c=='1')
      b[n-i-1] = true;
    if(a[n-i-1] == b[n-i-1]){
      equals.insert(n-i-1);
    }
  }

  string query;
  int index, val, lastval;
  for(int i=0;i<q;i++){
    cin>>query;
    cin>>index;
    if(query[4] == 'a'){
      cin>>val;
      if(a[index] != val){
        a[index] = val;
        if(a[index] == b[index]){
          equals.insert(index);
        }else{
          equals.erase(index);
        }
      }
    }else if(query[4] == 'b'){
      cin>>val;
      if(b[index] != val){
        b[index] = val;
        if(a[index] == b[index]){
          equals.insert(index);
        }else{
          equals.erase(index);
        }
      }
    }else if(query[4] == 'c'){
      int final = 0;
      if(index == n){
        if(equals.size() > 0){
          VanEmdeBoasTree::const_iterator it = equals.predecessor(index+1);
          if(it!=equals.end() && a[*it] == 1){
            final = 1;
          }
        }
      }else{
        final = (a[index] + b[index])%2;
        if(equals.size() > 0){
          VanEmdeBoasTree::const_iterator it = equals.predecessor(index);
          int last = -1;
          if(it != equals.end())
            last = *it;
          if( last!=-1 && index!=0 && it!=equals.end() &&  a[last] == 1){
            final = 1-final;
          }
        }
      }
      cout<<final;
    }
  }

  return 0;
}

My solution is not fast enough as the Judge says "time out" after some test cases.


texts: Transform a List of objects to a string of unique values for use in an SQL query

texts:
I have a List of Results. My goal is to extract the Result property Method from all elements of List<Result>, make extracted elements unique and prepare a string for SQL statements like WHERE method IN ('A','B','C').

Here is the Result class and a List<Result> example. The solution is in the ListTransformation() method.

Result.cs

public class Result
{
    public int Id { get; set; }
    public string Method { get; set; }
}

Program.cs

A method value can be one method ("A") or more methods separated by a colon ("A:B:C").

static void ListTransformationTest()
{
    const string separator = ":";

    List<Result> results = new List<Result>
                { new Result { Id = 1, Method = null },
                  new Result { Id = 1, Method = "" },
                  new Result { Id = 2, Method = "A:B" },
                  new Result { Id = 3, Method = "B:C" },
                  new Result { Id = 4, Method = "A:C:B" }
                };

    string methods = string.Join(separator,
                                 results.Where(x => x.Method?.Length > 0)
                                        .Select(r => r.Method).ToArray());
    var uniqueMethods = methods.Split(separator[0]).Distinct();
    string uniqueMethodsSqlFormat =
            string.Join(",", uniqueMethods.Select(m => string.Format($"'{m}'")).ToArray());
}

I guess there are a lot of operations. Do you have any suggestions on improving the code or any alternative code?


texts:
I use this code to generate time until some date:

 String dateStop = "25/11/17 09:00:00";

    // Custom date format
    SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");

    LocalDateTime d1 = LocalDateTime.now();
    Date d2 = null;
    try
    {
        d2 = format.parse(dateStop);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

    // Get msec from each, and subtract.
    long diff = d2.getTime() - d1.getTime();

    long days = TimeUnit.MILLISECONDS.toDays(diff);
    long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
    long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
    long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
    long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);

    System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);

How I can get the same result but with much more less code?


texts:
I want to remove the mail contact from all Groups in the "Member Of" tab. I am able to remove all MemberOf for mail contact. How can I improve the speed of the script?

Get-MailContact <name> | ForEach-Object { Get-ADObject $_.distinguishedname -Properties memberof } | Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $_.memberof


texts:
I have written a function that evaluates a contour integral in Python (Poincaré - Hopf index for 2D vector fields). It works, however is really slow if the arg res=N is chosen higher than 50. Input are two arrays of dimension N x N. As the integrals should lead to an integer, (usually -1, 0, or 1) only small accuracy is necessary. I believe that most time is lost doing the interpolation, but I don't know any other method.

Update: I have added a sample vector field \$ \mathbf{M} = (mx, my)^T \$. This produces output -1 if \$ (0, 0) \$ is included in the contour and 0 else. This works as a sample input. Real data is usually less smooth.

import numpy as np
from scipy.interpolate import interp2d
from scipy.integrate import quad
from scipy.misc import derivative

N = 100
xvec = np.linspace(-5, 5, N)
X, Y = np.meshgrid(xvec, xvec)
mx = Y / (X**2 + Y**2)**(1/2)
my = X / (X**2 + Y**2)**(1/2)

def partial_derivative(func, var=0, point=[]):
    args = point[:]

    def wraps(x):
        args[var] = x
        return func(*args)

    return derivative(wraps, point[var], dx=1e-6)

def poin_int(arr_x, arr_y, alpha=5, res=N, r=1, x0=0, y0=0):
    xvec = np.linspace(-alpha, alpha, res)
    X, Y = np.meshgrid(xvec, xvec)  # create grid
    x_func = interp2d(X, Y, arr_x, kind='cubic')  # interpolate data
    y_func = interp2d(X, Y, arr_y, kind='cubic')  # interpolate data

    def _x(t):  # x-coordinate of circular contour
        return np.cos(t) * r + x0

    def _dx(t):  # derivate of _x(t)
        return -np.sin(t) * r

    def _y(t):  # y-coordinate of circular contour
        return np.sin(t) * r + y0

    def _dy(t):  # derivative of _y(t)
        return np.cos(t) * r

    def _integrand1(t):  # integrand of first integral
        return (x_func(_x(t), _y(t)) *
                (partial_derivative(y_func, 0, [_x(t), _y(t)]) * _dx(t) +
                 partial_derivative(y_func, 1, [_x(t), _y(t)]) * _dy(t)) /
                (x_func(_x(t), _y(t))**2 + y_func(_x(t), _y(t))**2)  * 2 * np.pi)

    def _integrand2(t):  # integrand of second integral
        return (-y_func(_x(t), _y(t)) *
                (partial_derivative(x_func, 0, [_x(t), _y(t)]) * _dx(t) +
                 partial_derivative(x_func, 1, [_x(t), _y(t)]) * _dy(t)) /
                (x_func(_x(t), _y(t))**2 + y_func(_x(t), _y(t))**2 * 2 * np.pi))

    _int1 = quad(_integrand1, 0, 2*np.pi, epsabs=1e-2)
    _int2 = quad(_integrand2, 0, 2*np.pi, epsabs=1e-2)
    return (_int1[0] + _int2[0])  # should be an integer

poin_int(mx, my, res=N, r=1, x0=0, y0=0)


texts:
I am currently working on a class to make objects and vars available to child classes while attempting to avoid a singleton. Each child with dependencies extend this class and pass params (var names) of required dependencies. If parent construct is called and params is empty full registry is set.

Example of Registry:

class Registry {
public static $registry = [];

public function __construct($DI = '') {
    if (self::$registry) {

        /**
         *  $DI List Missing Pass Entire Registry
         */
        if (!$DI) {
            foreach (self::$registry as $var => $value) {
                $this->$var = $value;
            }
        }

        /**
         *  $DI List Set, Pass Specific Dependencies
         */
        else {
            foreach ($DI as $dependency) {

                    if (isset(self::$registry[$dependency])) {
                        $this->$dependency = self::$registry[$dependency];
                    }
                    else {
                        if (ENVIRONMENT == 'development') {
                            echo get_called_class().' Needs Dependency '.$dependency.'

';
                        }
                    }

            }
        }
    }
}

/**
 *  Add to Registry
 */
public static function add($array, $type = 'class', $namespace = '') {
    foreach ($array as $var => $value) {
        if (!isset(self::$registry[$var])) {

            switch ($type) {
                case 'class':
                    $class                  = $namespace.$value;
                    self::$registry[$var]   = new $class;
                    break;

                case 'var':
                    self::$registry[$var]   = $value;
                    break;
            }

        }
    }
}

private function __clone() {}
private function __wakeup() {}
}

Adding and using vars/objects from registry is easily done through static calling, but the main point of this class is to pass dependencies to child classes. I am wondering if there are drawbacks that someone with more experience would know of/find.


texts: Effective ways to find partial sha1 collision

texts:
I need to find 2 different string and compare their hash value. Both string must contain "abc". I looking for the first eight character that are the same and stop. I have been running for more than 24 hours and still not found. My code has no problem running but i am wondering is there any more effective ways to find the collision

public static void main(String[] args) {
String message1 = "abc";
String message2 = "abc";

int x=0;
if (message1.equals(message2)) {
    String temp1 = message1 + x;
    String temp2 = x + message2;
    String result1 = sha1Hashing(temp1);
    String result2 = sha1Hashing(temp2);
    while (!result1.equals(result2)){
        temp1 = message1 + x;
        temp2 = x + message2;
        result1 = sha1Hashing(temp1);
        result2 = sha1Hashing(temp2);
        System.out.println("First message = " + temp1 + " Second message = " + temp2 + "\n");
        System.out.println("First hash = " + result1);
        System.out.println("Second hash = " + result2 + "\n");
        x++;
        if(result1.equals(result2)){
            System.out.println("FOUND!!");
            System.exit(0);
        }
    }
}
}
public static String sha1Hashing (String message) {
String sha1 = "";
StringBuffer sb = new StringBuffer();
try {
    MessageDigest mDigest = MessageDigest.getInstance("SHA1");
    byte[] result = mDigest.digest(message.getBytes());

    for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
    }
} catch(NoSuchAlgorithmException e) {
    e.printStackTrace();
}
//return first 8 char
sha1 = sb.toString().substring(0,8);
return sha1;
}


texts:
I have this PHP curl function to check if a site is online or not:

function check($proc,$url,$keyword,$method,$timeout,$maxredirs) {
    // Format Link
    $link = $proc."://".$url;
    // Agent
    $user_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36';

    $options = array(
        CURLOPT_CUSTOMREQUEST  => $method,     //set request type post or get
        CURLOPT_POST           =>false,        //set to GET
        CURLOPT_USERAGENT      => $user_agent, //set user agent
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => $timeout,      // timeout on connect
        CURLOPT_TIMEOUT        => $timeout,      // timeout on response
        CURLOPT_MAXREDIRS      => $maxredirs,       // stop after 10 redirects
        CURLOPT_REFERER        => "http://example.com",
        CURLOPT_SSL_VERIFYPEER => false,
    );
    $ch      = curl_init( $link );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );
    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;

    // Time (ms)
    $totaltime = $header['total_time']*1000;
    $totaltime = number_format($totaltime, 0, "", "");
    // Handle keyword search
    $izkey = 1;
    if(!empty($keyword)) {
        if (strpos($header['content'],$keyword) !== false) {
            $izkey = 1;
        }
        else {$izkey = 0;}
    }

    // Return
    return $header['http_code']."|".$totaltime."|".$izkey;
}

The function variables are as follow:

$proc: not user input, will either be http or https
$url: user input and will be a full link except the http:// or https:// part at the beginning
$keyword: user input, just alphanumeric characters
$method: not user input, will be GET
$timeout: user input, only digits, no more than 60
$maxredirs: user input, only digits, no more than 60

My question is: with the above mentioned user input and returning just 3 variables (see last line of code) is this function safe for the server to run like it is now? Could a user pass a malicious link to harm the server?

I know it may be a silly question, but, I want to be sure. It's better safe than sorry, and it can't hurt to ask.


texts: Implementing secure API for use between other internal apps

texts:
My team and I are trying to implement a secure API and would appreciate some feedback on the following:

If there are areas of improvement in the current code to improve security
Recommendations on other secure API implementations, if any, that would fit our requirements better (see below)
If there are any major loopholes in security based on this module.

Here are some requirements, considerations, and caveats:

The API clients/consumers are other web apps from our same company (internal yet public facing apps on a different sub-domain)
We'd prefer not to go the OAuth2 route. We'd like this to be a programmatic interface using key-based authentication. Basically, it will be server to server authentication.
API is already https

We'd like this to be modular/flexible enough to use across different internal apps

Please read code comments. We've gotten inspiration from multiple sources, especially the implementation of JWT in a slightly different manner.

# Inspiration from:
#   - https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth
#   - https://codeburst.io/jwt-to-authenticate-servers-apis-c6e179aa8c4e
# Typically, JWT's are used to provide consumer an access token after successful login.
# Considering our use case, the consumer (another internal app) will initiate the JWT
# Server will verify authenticity of request if it is able to decode JWT
# We've also set specific headers that internal apps would need to provide

module SecureAPI
  # Generates a secure payload for outgoing requests
  def self.secure_payload(options = {}, method = "get")
    # Get or Post request
    param_type = method == "get" ? "query" : "body"
    iat = Time.now.to_i

    # Reserved and Private claims
    token_payload = {
      # The "iat" (issued at) claim identifies the time at which the JWT was issued.
      iat: iat,
      # Expiration
      exp: iat + 60,
      # Private claim
      client_id: options[:client_id]
    }

    encoded_token = encode_token(token_payload, options[:shared_secret])

    payload = {
      :headers => {
        "Authorization" => "Bearer" + ' ' + encoded_token,
        "JWT-Consumer" => options[:client_id]
      },
      param_type.to_sym => {
         client_token: options[:client_token]
      }
    }
    payload
  end

  # Verifies incoming requests/JWT verifier
  def self.authenticate_request(request)
    # Client must provide these headers
    jwt_token = request.headers['Authorization'].split(' ').last

    shared_secret = Rails.application.secrets[request.headers['JWT-Consumer']]

    # Token must be decoded, unexpired, and verified using same hashing algo for successful auth
    # else will return unauthorized response to client
    decode_token(jwt_token, shared_secret)
  end

  def self.encode_token(payload, secret)
    JWT.encode payload, secret, 'HS512'
  end

  def self.decode_token(token, shared_secret)
    JWT.decode token, shared_secret, true, algorithm: 'HS512'
  end
end


texts: Naive-Bayes classifier, to be packaged in a function

texts:
I need to create a Naive-Bayes classifier. I have eight labels (S) stored in tumors object, and 20531 attributes (A), I have stored the P(S,A) in objects of name Pg_label_state, where each row is one state of the attribute (rownmaes_m <- c("up", "down", "no_change")). And the probability of each state regardless of label stored in P_g.

I have the following code to calculate the relative entropy H(S|A) where "100130426" is one of the attributes:

val <- 0
for (state in rownames_m){
  for (cancer in tumors){
    data_o <- paste0("Pg_", cancer, "_state")
    if ("100130426" %in% colnames(get(data_o))){
      if (get(data_o)[state, "100130426"] != 0){
        new_val <- get(data_o)[state, "100130426"]*log2(get(data_o)[state, "100130426"]/P_g[state, "100130426"])
        val <- val + new_val
      }
    }
  }
}

Then I calculate the entropy H(S) using a function over an object where the probability of each label is stored:

partial_entropy <- function(x){
  if (x != 0){
    - x * log2(x)
  }
}

entropy <- sum(sapply(P_cancer,  partial_entropy))

Then the Mutual Information (or Information Gain) is the addition:

result <- val + entropy

I create function to calculate the relative entropy to be able to use *apply family functions.

So far I do the straightforward transformation:

mi.entropy <- function(gene, p_cancer, tumors){
  val <- 0
  for (state in c("up", "down", "no_change")){
    for (cancer in tumors){
      data_o <- paste0("Pg_", cancer, "_state")
      if (gene %in% colnames(get(data_o))){
        if (get(data_o)[state, gene] != 0){
          new_val <- get(data_o)[state, gene]*log2(get(data_o)[state, gene]/P_g[state, gene])
          val <- val + new_val
        }
      }
    }
  }
  return(val + sum(sapply(P_cancer,  partial_entropy)))
}

results <- lapply(colnames(Pg_brca), mi.entropy, P_cancer, tumors)

But it is still too slow/inefficient. How can I transform it correctly to a function?


texts: Returning index of nth occurrence of a substring

texts:
I've built a JavaScript function returning the index of the nth occurrence of a substring in a string.

$(document).ready(function() {

        var containingString = '.this.that.';
        subString = '.';

        var index = GetIndexOfSubstring(containingString, subString, 2);

    });

    function GetIndexOfSubstring(containingString, subString, occurrenceNumberOfSubString)
    {
        tokens = containingString.split(subString);
        var numberOfSubStrings = tokens.length - 1;

        if (occurrenceNumberOfSubString > numberOfSubStrings)
            return "Error";

        var index = 0 + occurrenceNumberOfSubString - 1;

        for(var c = 0; c < occurrenceNumberOfSubString; c++)
        {
            var i = containingString.indexOf(subString);
            var sub = containingString.substr(i + 1);
            containingString = sub;
            index += i;
        }

        return index;
    }

As far as I can see, the function works correctly.  Is there is an easier way to accomplish the goal? Also, can the function be improved?


texts: Get nth prime number using sieve of Eratosthenes

texts:
I am tasked with being able to find the \$n\$th prime number. I've tried to implement something like the sieve of Eratosthenes in increments of 200. The code works and returns the \$n\$th prime number. However, when asking for the 1000th prime number I already notice a significant lag on my box.

This code needs to be able to quickly return the \$n\$th prime where \$n\$ is a massive number. For the challenge I only need to get up to 200,000. However, being able to finalize this for efficient use for up to a million would be pretty awesome, I think.

This is what I have working so far:

def nthPrime(ind): #gets nth prime number. IE: 5th prime == 11. works based off very in-efficient version of Sieve of Eratosthenes. but in increments of 200
    p={}
    T = 2
    incST = 2
    incEND = incST + 200
    lenfinal = 1

    while lenfinal <= ind:
        for i in range(incST,incEND):
            p[i] = True
        T=2
        while T <= math.sqrt(incEND):
            l = 0
            while l <= incEND:
                if T**2 + (T*l) >= incST:
                    p[T**2 + (T*l)] = False
                l+=1
                if T**2+(T*l) > incEND:
                   break

            for k,v in sorted(p.items()):
                if v and k > T:
                    T = int(k)
                    break

        incST = incEND + 1
        incEND = incST + 200
        lenfinal = sum(1 for k,v in p.items() if v)

    final = [k for k,v in sorted(p.items()) if v]
    return final[ind-1]


texts:
Is this good OOP style? Do I need to split this class into two classes? If so, how do I do this? What methods should I need to add to the interfaces?

public sealed class DeferredResultCollection<TResult> : IEnumerable<TResult>, IDisposable
{
    private readonly IAsyncCursor<TResult> _asyncCursor;
    private readonly IList<TResult> _list;

    public DeferredResultCollection(IAsyncCursor<TResult> asyncCursor)
    {
        _asyncCursor = asyncCursor;
    }

    public DeferredResultCollection(IList<TResult> list)
    {
        _list = list;
    }

    public IEnumerator<TResult> GetEnumerator()
    {
        if (_list != null)
        {
            foreach (var item in _list)
            {
                yield return item;
            }
        }

        if (_asyncCursor != null)
        {
            for (; _asyncCursor.MoveNextAsync().Result;)
            {
                foreach (var result in _asyncCursor.Current)
                {
                    yield return result;
                }
            }
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Dispose()
    {
        if (_asyncCursor != null)
        {
            _asyncCursor.Dispose();
        }
    }
}


texts:
The task:

There is an AccountManager that makes transfers. It receives 2 arrays of the same size: accounts and sums. They need to be transferred to the accounts correspondingly.

public interface AccountManager {
    public boolean transfer(Account[] accounts, int[] deltas);
}

There is also an Account interface:

public interface Account {
    public void change(int delta) throws TryAgainException, BlockAccountException;
}

If change() throws TryAgainException, we just need to repeat the transfer operation. If change() throws BlockAccountException, we need to roll back the transfer operation. That is, reverse all changes to previous accounts.

AccountClass

public class AccountClass implements Account {

    // setting initial value to 100. so that account would not be empty
    private int accountNum;
    private int currentAccount = 100;

    public AccountClass(int accountNum) {
        this.accountNum = accountNum;
    }

    @Override
    public void change(int delta) throws TryAgainException,
            BlockAccountException {
        System.out.println("account before change" + toString());

        int newBalance = getCurrentAccount() + delta;
        if (newBalance < 0) {
            throw new BlockAccountException(
                    "money cannot be withdrawn as balance will be negative");
        } else if (delta == 100) {
            throw new TryAgainException();
        }
        setCurrentAccount(getCurrentAccount() + delta);

        System.out.println("account after change" + toString());
    }

    public int getCurrentAccount() {
        return currentAccount;
    }

    @Override
    public String toString() {
        return "Account" + accountNum + " [currentAccount=" + currentAccount + "]";
    }

    // making setter private so it will be impossible to modify account from
    // outside
    private void setCurrentAccount(int currentAccount) {
        this.currentAccount = currentAccount;
    }

AccountManagerClass

public class AccountManagerClass implements AccountManager {

    @Override
    public boolean transfer(Account[] accounts, int[] deltas) {
        for (int i = 0; i < accounts.length; i++) {
            int tryNum = 0;
            while (true) {
                try {
                    accounts[i].change(deltas[i]);
                    break;
                } catch (TryAgainException e) {
                    tryNum++;
                    if (tryNum == 5) {
                        break;
                    }
                    System.out.println("trying again");
                } catch (BlockAccountException e) {
                    // rollback
                    System.out.println(e.getMessage());
                    System.out.println("rolling back");
                    if (i > 0) {
                        for (int j = i - 1; j >= 0; j--) {
                            try {
                                accounts[j].change(-deltas[j]);
                            } catch (TryAgainException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            } catch (BlockAccountException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                        }
                    }
                    return false;
                }
            }
        }

        return true;
    }

Main

public class Main {

    public static void main(String[] args) {

        AccountManagerClass accountManagerClass = new AccountManagerClass();
        Account[] accounts = {new AccountClass(1), new AccountClass(2), new AccountClass(3), new AccountClass(4)};
        int[] deltas = {100, 200, -200, 99};
        accountManagerClass.transfer(accounts, deltas);
    }

}


texts:
During Jonathan Blow's video where he muses about a games-focused programming language, he presents C++ code that allocates a single big block of memory and has N pointers into that block. The purpose being to avoid heap allocating N blocks of memory for N arrays.

That code looked to me like it could use some genericity... so I first came up with the following where we would allocate three arrays into a single block of memory:

using memory_block = std::unique_ptr<char[]>;

template<typename A, typename B, typename C>
memory_block block_allocate(A*& p, size_t a, B*& q, size_t b, C*& r, size_t c)
{
    memory_block z = std::make_unique<char[]>(a * sizeof(A) + b * sizeof(B) + c * sizeof(C));

    p = reinterpret_cast<A*>(z.get());
    q = reinterpret_cast<B*>(p + a);
    r = reinterpret_cast<C*>(q + c);

    return z;
}

Improving for any number of arrays gives us:

using memory_block = std::unique_ptr<char[]>;

namespace detail
{
    template<typename T>
    size_t block_size(T* const, size_t const n)
    {
        return sizeof(T) * n;
    }

    template<typename T, typename U, typename... Args>
    size_t block_size(T* const t, size_t const m, U* const u, size_t const n, Args&&... args)
    {
        return block_size(t, m) + block_size(u, n, args...);
    }

    template<typename T, typename U>
    void block_assign(T* const p, size_t const offset, U*& u, size_t const)
    {
        u = reinterpret_cast<U*>(p + offset);
    }

    template<typename T, typename U, typename... Args>
    void block_assign(T* const p, size_t const offset, U*& u, size_t const n, Args&&... args)
    {
        block_assign(p, offset, u, n);
        block_assign(u, n, args...);
    }
}

template<typename T, typename... Args>
memory_block block_allocate(T*& t, size_t const n, Args&&... args)
{
    memory_block b = std::make_unique<char[]>(detail::block_size(t, n, args...));

    detail::block_assign(b.get(), 0, t, n, args...);

    return b;
}

It's understood that Jonathan's Blow's desire is for a language solution to this problem and not the library solution that I present but I had fun coming up with it nonetheless.

So, after simple testing the code appears to behave as expected but do you see something missing that would make production-ready?


texts: Button incrementing from 0 to 9 and repeating

texts:
I have to create a button which counts from 0 to 9, and after 9 come 0 again. One of my friends said that this code is not good enough. Can you explain to me why it's a problem to use -1?

int szám = 0;
private void counterButton_Click(object sender, EventArgs e)
{
    szám++;
    this.Text = szám.ToString();
    if (szám == 9)
    {
        szám = -1;
    }
}


texts: Which is the best approach for searching the dictionary items?

texts:
We can search for the list of dictionaries using the below some approaches, Can one please help me, which one is the memory efficient approach to use?

Provided that:

names are unique in the list
There will be definitely a name in each dictionary.

Where as:

items = [list_of_dicts]
name_to_b_searched = "some_name"

1 direct return from the for loop

def get_by_name(self, name_to_be_searched):
    for i in items:
        if i['name'] == name_to_be_searched:
              return i

2 Break from the for loop and return found dictionary

def get_by_name(self, name_to_be_searched):
    found = None
    for i in items:
        if i['name'] == name_to_be_searched:
              found = i
              break
    return found

3 A generator function

def get_by_name(self, name_to_be_searched):
    for i in items:
        if i['name'] == name_to_be_searched:
              yield i

4 An inline generator

get_by_name =next(i for i in items if i['name'] == name_to_be_searched, None)

Sometimes I could have a huge csv records (in items), so was thinking which approach would be better to search a record.
OR if there is any other approach you would recommend please let me know.


texts: Speed issue when controlling Excel from Access VBA

texts:
I have a very hard time figuring out how to proceed. I built an Access DataBase which I use to process data in order to build several weekly and monthly reports. I wrote VBA codes in Excel and in Access.

Basically, for now, Access VBA processes data, exports tables on temporary workbooks then runs macros on Excel to compile everything and make nice presentations.

Having to carry over two files (one Access, one Excel, each with its own VBA codes) does not bother me at all, but the end users being my colleagues, and them having to be able to debug those when I am not here, I am starting to consider merging my codes and controlling Excel directly from Access VBA. But when I tried to do so, everything became really slow!

Just so you get what I mean. Here is some useless code to illustrate what happens (the real code being too long).

First, the version in which Access VBA tells Excel to run VBA.

Access VBA:

Option Explicit
Sub SpeedTest_Access_And_Excel()

'Starting time
Dim startTime As Double
startTime = Round(timer)

'Variables
Dim xl As Excel.Application 'Excel
Dim xlBot As Workbook 'The workbook with VBA code to run

'Run Excel
Set xl = New Excel.Application

With xl
    Set xlBot = xl.Workbooks.Open(CurrentProject.Path & "\SpeedTest.xlsm") 'Open Workbook
    .Run "SpeedTest_In_Excel" 'Run Excel code
End With

xlBot.Close False 'Close Excel workbook

'End message
MsgBox (Round(timer) - startTime) \ 60 & "'" & Format((Round(timer) - startTime) Mod 60, "00") & "''"

'Quit Excel
xl.Quit
Set xl = Nothing

End Sub

Excel VBA (in a "SpeedTest.xlsm" file in the same folder as the Access DB):

Option Explicit
Sub SpeedTest_In_Excel()

    'Variables
    Dim wb As Workbook 'A new workbook
    Dim ws As Worksheet 'That new workbook's sheet
    Dim i As Integer, j As Integer 'Lines and columns

    'Excel optimisation
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With

    'Create new workbook
    Set wb = Workbooks.Add

    'Disable auto-calculation
    Application.Calculation = xlCalculationManual

    'Write useless stuff
    Set ws = wb.Sheets(1)
    i = 1
    Do Until i = 500
        j = 1
        Do Until j = 500
            ws.Cells(i, j) = "Useless stuff"
            j = j + 1
        Loop
        i = i + 1
    Loop

    'Close workbook
    wb.Close False

End Sub

Now the Access only version, that does exactly the same thing:

Sub SpeedTest_Access_Only()

'Starting time
Dim startTime As Double
startTime = Round(timer)

'Variables
Dim xl As Excel.Application
Dim wb As Workbook 'A new workbook
Dim ws As Worksheet 'That new workbook's sheet
Dim i As Integer, j As Integer 'Lines and columns

'Run Excel
Set xl = New Excel.Application

With xl
    'Excel optimisation
    .ScreenUpdating = False
    .DisplayAlerts = False
    .EnableEvents = False

    'Create New Workbook
    Set wb = .Workbooks.Add

    'Disable auto-calculation
    .Calculation = xlCalculationManual

End With

'Write useless stuff
Set ws = wb.Sheets(1)
i = 1
Do Until i = 500
    j = 1
    Do Until j = 500
        ws.Cells(i, j) = "Useless stuff"
        j = j + 1
    Loop
    i = i + 1
Loop

'Close workbook
wb.Close False

'End message
MsgBox (Round(timer) - startTime) \ 60 & "'" & Format((Round(timer) - startTime) Mod 60, "00") & "''"

'Quit Excel
xl.Quit
Set xl = Nothing

End Sub

My issue :

The 1st version (Access + Excel) takes 0 minutes and 8 seconds
The 2nd version (Access only) takes 1 minute and 25 seconds at best (up to 2 minutes and 20 seconds if I do something else at the same time)

Does anybody know anything I could do to speed this up? Is that even possible? Or should I keep my Access+Excel configuration that works quite well beside being a little more complex (and not enabling me to use class variables)?


texts:
I'm using Passport in Node.js app to authenticate user by email and password (login) and also by token.

Email and password are used only when user is logging in. Passport local strategy generates token when user email and password matched. Token will be later used for bearer token authentication.

It would be nice to hear if code style and structure are good. Is the flow control (Promise.reject with CancellationError) written well?

'use strict';

import {User} from '../models';
import passport from 'passport';
import local from 'passport-local';
import token from 'passport-http-bearer';
import Promise from 'bluebird';
import generateToken from '../helpers/token';

passport.use('local', new local.Strategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  (email, password, done) => {
    User.findOne({where: {email}})
      .then(user =>
        user ?
          user.comparePassword(password)
          : Promise.reject(new Promise.CancellationError('Wrong email or password'))
      )
      .spread((isMatch, user) =>
        isMatch ?
          generateToken()
            .then(token => user.update({token}))
            .then(done(null, user.token))
          : Promise.reject(new Promise.CancellationError('Wrong email or password'))
      )
      .catch(Promise.CancellationError, info => done(null, false, info))
      .catch(err => done(err));
  }));

passport.use('token', new token.Strategy((token, done) => {
  User.findOne({where: {token}})
    .then(user => user ? done(null, user, {scope: 'all'}) : done(null, false))
    .catch(err => done(err));
}));

export var tokenAuthentication = passport.authenticate('token', {session: false});
export default passport;


texts: Bash grep taking 3 days to finish. Any suggestions to enhance it?

texts:
I have a script like this that I would like to seek some suggestions on enhancing it.

cd /home/output/
cat R*op.txt > R.total.op.txt
awk '{if( (length($8)>9) || ($8 ~ /^AAA/) ) {print $0}}' R.total.op.txt > temp && mv temp R.total.op.txt

cat S*op.txt > S.total.op.txt
awk '{if( (length($8)>9) || ($8 ~ /^AAA/) ) {print $0}}' S.total.op.txt > temp && mv temp S.total.op.txt

cat R.total.op.txt S.total.op.txt | awk '{print $4}' | sort -k1,1 | awk '!x[$1]++' > genes.txt
rm *total.op.txt
head genes.txt

cd /home/output/
for j in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
do
***** for i in `cat genes.txt`; do cat $j'.op.txt' | grep -w $i >> $j'_'$i'_gene.txt';done
done
ls -m1 *gene.txt | wc -l
find . -size 0 -delete
ls -m1 *gene.txt | wc -l
rm genes.txt

cd /home/output/
for i in `ls *gene.txt`
do
paste <(awk '{print $4"\t"$8"\t"$9"\t"$13}' $i | awk '!x[$1]++' | awk '{print $1}') <(awk '{print $4"\t"$8"\t"$9}' $i | awk '{if( (length($2)>9) || ($2 ~ /^AAA/) ) {print $0}}' | sort -k2,2 | awk '{ sum += $3 } END { if (NR > 0) print sum / NR }') <(awk '{print $4"\t"$8"\t"$9}' $i| awk '{if( (length($2)>9) || ($2 ~ /^AAA/) ) {print $0}}' | sort -k2,2 | wc -l) <(awk '{print $4"\t"$8"\t"$9"\t"$13}' $i | awk '{if( (length($2)>9) || ($2 ~ /^AAA/) ) {print $0}}' | sort -k2,2 | grep -v ":::" | wc -l) > $i'_stats.txt'
done
rm *gene.txt

cd /home/output/
for j in R1_with-genename R2_with-genename S1_with-genename S2_with-genename
do
cat $j*stats.txt > $j'.final.txt'
done
rm *stats.txt

cd /home/output/
for i in `ls *final.txt`
do
sed "1iGene_Name\tMean1\tCalculated\tbases" $i > temp && mv temp $i
done
head *final.txt

The second for loop (marked with asterisks) that has cat genes.txt is the grep loop that is taking 3 days to finish. Can someone please advice any enhancements to the command and if this entire script can be made into a single command? Thanks in advance. I posted in stackoverflow and was asked to send it here. :)


texts:
Based on the great blog by Joel Grus, I implemented LogisticRegression, PCA, and LDA. I'd appreciate feedback as I'm not sure that the logistic classifier is good enough (as it supposed to achieve higher accuracy on training set).

    # This code was writen with inspiration from https://github.com/joelgrus/shirts/blob/master/visuals.py and with the help of my friend Jiaher.

from PIL import Image
from glob import glob
from random import shuffle, seed
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

STANDARD_SIZE = (138, 138)
HALF_SIZE = (STANDARD_SIZE[0] / 2, STANDARD_SIZE[1] / 2)

def img_to_array(filename):
    """
    takes a filename and turns it into a numpy array of RGB pixels
    """
    img = Image.open(filename)
    img_i = img.resize(STANDARD_SIZE)
    img.close()
    img_i = list(img_i.getdata())
    img_i = map(list, img_i)
    img_i = np.array(img_i)
    s = img_i.shape[0] * img_i.shape[1]
    img_wide = img_i.reshape(1, s)
    return img_wide[0]

male_files = glob('./images/boys/*')
female_files = glob('./images/girls/*')

process_file = img_to_array

raw_data = []
for filename in male_files:
    print (filename)
    raw_data.append((process_file(filename), 'male', filename))
for filename in female_files:
    print (filename)
    raw_data.append((process_file(filename), 'female', filename))

# randomly order the data
seed(0)
shuffle(raw_data)

# pull out the features and the labels
data = np.array([cd for (cd, _y, f) in raw_data])
labels = np.array([_y for (cd, _y, f) in raw_data])
labels = [1 if label == 'male' else 0 for label in labels]

X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2)

        # Simple Linear Model:
    clf = LogisticRegression(penalty='l2')
    clf.fit(X_train, y_train)

    print("linear model test score", clf.score(X_test, y_test))

# find the principal components
N_COMPONENTS = 4
pca = PCA(n_components=N_COMPONENTS, random_state=0, svd_solver='randomized')
X_train_pca = pca.fit_transform(X_train)
X_test_pca = pca.transform(X_test)

pcaclf = clf.fit(X_train_pca, y_train)
print("pca test score", pcaclf.score(X_test_pca, y_test))
print("pca train score", pcaclf.score(X_train_pca, y_train))

###LDA:
lda = LinearDiscriminantAnalysis(n_components=2)

X_train_lda = lda.fit_transform(X_train, y_train)
X_test_lda = lda.transform(X_test)

ldaclf = clf.fit(X_train_lda, y_train)
print("lda train score", ldaclf.score(X_train_lda, y_train))
print("lda test score", ldaclf.score(X_test_lda, y_test))

The data:

I'm using the data from ImageNet, nothing fancy.


texts: Menu-based Caesar Cipher with encryption and decryption

texts:
I am about to start a very large project in Ruby. To get myself in the Ruby mindset I have been doing all of my homework and other side work in Ruby. I am hoping that some of you who know Ruby very well can look at this small program I have written and point out areas that aren't written in a Ruby-like fashion. Any and all tips and criticisms would be appreciated.

This program is a menu-based Caesar Cipher with encryption and decryption.

KEY = 3
$caesar_map = {}

#initializes the caesar_map and reads input from the user
#starting point of the program
def init()
  #create empty hashes
  plain_alphabet  = {}
  cipher_alphabet = {}

  #fill in the alphabet hashes with the letter and its position
  #in the english alphabet
  "a".upto("z") {|x| plain_alphabet[x]  = ((x[0] - "a"[0]) % 26) }
  "A".upto("Z") {|x| cipher_alphabet[x] = ((x[0] - "A"[0]) % 26) }

  #fill in the caesar_map, maps every letter KEY positions
  #to the right in the alphabet
  plain_alphabet.each do |k,v|
    $caesar_map[k] = cipher_alphabet.index((v+KEY) % 26)
    #puts "key: #{k} mapped value: #{cipher_alphabet.index((v+3) % 26)}"
  end
  #special case, I want spaces to be maintained in the messages
  $caesar_map[" "] = " "

  #print menu
  choice = -1
  while(choice != 3)
    puts "What would you like to do?"
    puts "\n1. Encrypt a message"
    puts "\n2. Decrypt a message"
    puts "\n3. Exit\n"

    choice = Integer(gets.chomp)

    if(choice == 1)
      puts "Please enter a message you would like to Encrypt\n"
      message = gets.chomp
      encrypt(message)
    elsif(choice == 2)
      puts "Please enter a message you would like to Decrypt\n"
      message = gets.chomp
      decrypt(message)
    elsif(choice == 3)
      abort("Exiting...")
    else
      puts "You didn't enter a valid choice. Enter a number between 1..3\n"
    end
  end
end

#encrypts a plaintext message using the caesar cipher
def encrypt(plaintext)
  #make sure the message is in lowercase
  plaintext.downcase!
  ciphertext = ""

  #fill in the ciphertext with mapping information in the caesar_map
  plaintext.split("").each do |c|
    ciphertext += $caesar_map[c]
  end

  #print the encrypted ciphertext
    puts "\n plaintext: #{plaintext}\nciphertext: #{ciphertext}\n\n"
end

#decrypts a ciphertext message using the caesar cipher
def decrypt(ciphertext)
  #make sure the ciphertext is in uppercase
  ciphertext.upcase!
  plaintext = ""

  #fill in the plaintext with mapping information in the caesar_map
  ciphertext.split("").each do |c|
    plaintext += $caesar_map.index c
  end

  #print the decrypted plaintext
  puts "\n ciphertext: #{ciphertext}\n plaintext: #{plaintext}\n\n"
end

#start the program
init()


texts:
I've implemented a div_by_power_of_2() function, which lets me force the compiler to use left-shifting rather than proper division, in cases when the developer know the divisor will be a power of 2, but does not know which power of 2; and the compiler cannot prove to itself that this is the case.

template <typename P> constexpr P log2_of_power_of_2(P non_negative_power_of_2) noexcept
{
    static_assert(std::is_integral<P>::value, "Only integral types are supported");
    static_assert(sizeof(P) <= sizeof(unsigned long long), "Unexpectedly large type");
    using cast_target_type = typename
        std::conditional<sizeof(P) <= sizeof(unsigned),
            unsigned,
            typename std::conditional<sizeof(P) <= sizeof(unsigned long),
                unsigned long,
                unsigned long long
            >::type
        >::type;
    return log2_of_power_of_2<cast_target_type>(
        static_cast<cast_target_type>(non_negative_power_of_2));
}
template <>
constexpr unsigned
log2_of_power_of_2<unsigned>(unsigned non_negative_power_of_2) noexcept
{ return __builtin_ctz  (non_negative_power_of_2); }

template <>
constexpr unsigned long
log2_of_power_of_2<unsigned long>(unsigned long non_negative_power_of_2)  noexcept
{ return __builtin_ctzl (non_negative_power_of_2); }

template <>
constexpr unsigned long long
log2_of_power_of_2<unsigned long long>(unsigned long long non_negative_power_of_2) noexcept
{ return __builtin_ctzll(non_negative_power_of_2); }

template <typename I, typename P>
constexpr I div_by_power_of_2(I dividend, P power_of_2_divisor) noexcept
{ return dividend >> log2_of_power_of_2(power_of_2_divisor); }

Questions:

Is my approach to covering the possible types of power_of_2 appropriate? Can it perhaps be made less verbose but with the same effect?
Am I reinventing the wheel with this code?
Currently, this depends on certain compiler intrinsics available in GCC and clang but not necessarily elsewhere. I could generalize it a bit using this method to also support MSVC. Is there a better approach to generalizing the code?
Should I change the return type of log2_of_power_of_2 functions to be uniform rather than I? e.g. an unsigned?
Any other comments/suggestions are welcome.

Notes:

This is intended to be C++11; obviously with C++17 I could simplify it further
The constexpr qualifier is not very meaningful, since in a constexpr context we could just do plain division, but I've tacked it on nonetheless. To make the use of these utility function(s) more uniform.


texts:
For a site I wrote this JS contact parser. It simply reads contacts and parses links if a known service is identified. Could this be made more compact? How about robustness? (it cannot handle exceptions where the url does not begin with http for instance). What other services should I consider to add?

Here is jsfiddle. And the code is below:

Markup

CSS

span { padding: 10px; }

JS

var contacts = 'guy@gmail.com, guy@owndomain.com, http://twitter.com/guy, http://www.facebook.com/profile.php?id=100002877203519, http://www.linkedin.com/in/coolguy, http://www.myspace.com/coolguy, skype:cool.guy?call, aim:goim?screenname=cool.guy, http://coolguy.com';
var re = / /gi;
contacts = contacts.replace(re, "");
contacts = contacts.split(',');

var picBase = 'http://jqeedu.tuxfamily.org/images/media/';

jQuery(document).ready(function() {

    for (var i = 0; i < contacts.length; i++) {
        addContact(contacts[i]);
    }

});

function addContact(c) {
    cdiv = jQuery("#contacts");
    var i = false;
    var h = '';
    var n = '';

    if(c.indexOf('@gmail.com') != -1) {
        i = 'gmail.png';
        h = 'mailto:'+c;
    }

    if(!i && c.indexOf('http://www.facebook.com/profile.php?id=') == 0) {
        i = 'facebook.png';
        h = c;
    }

    if(!i && c.indexOf('http://www.linkedin.com/in/') == 0) {
        i = 'linkedin.png';
        h = c;
    }

    if(!i && c.indexOf('http://www.myspace.com/') == 0) {
        i = 'myspace.png';
        h = c;
    }

    if(!i && c.indexOf('skype:') == 0 && c.indexOf('?call') != -1) {
        i = 'skype.png';
        h = c;
    }

    if(!i && c.indexOf('aim:goim?screenname=') == 0 ) {
        i = 'aim.png';
        h = c;
    }

    if(!i && c.indexOf('http://twitter.com/') == 0) {
        i = 'twitter.png';
        h = c;
    }

    if(!i && c.indexOf('http://') == 0) {
        i = 'website.png';
        h = c;
    }

    if(!i) {
        i = 'email.png';
        h = 'mailto:'+c;
    }

    n = '';

    cdiv.append(n);

}


texts:
I'm trying to work with exception handling by displaying "No Such File" when the file doesn't exist.  I need to use a try statement.

import sys

try:
   f = open("h:\\nosuchdirectory\\nosuchfile.txt","w") # do not modify this line
    f.write("This is the grape file") # do not modify this line
    f.close() # do not modify this line

except IOError:
    print ("No Such File")

Started with:

f = open("h:\\nosuchdirectory\\nosuchfile.txt","w") # do not modify this line
f.write("This is the grape file") # do not modify this line
f.close() # do not modify this line


texts: Centering an item over an image with absolute positioning and flexbox

texts:
Here's how I'd usually center align an item with absolute positioning:

img {
 width: 100%;
 height: auto;
}

.cat {
 position: relative;
}

.center {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 z-index: 9999;
 background: #fff;
 padding: 12px;
}

a,
a:visited,
a:hover,
a:focus {
 color: #000;
 text-decoration: none;
}

 I want to center this

I've recently discovered that you can do the same with flexbox, like so:

img {
 width: 100%;
 height: auto;
}

.cat {
 position: relative;
 display: flex;
 justify-content: center;
 align-items: center;
}

.center {
 position: absolute;
 z-index: 9999;
 background: #fff;
 padding: 12px;
}

a,
a:visited,
a:hover,
a:focus {
 color: #000;
 text-decoration: none;
}

 I want to center this

Is there any benefit to using the flexbox solution? A major downside I'm seeing is browser compatibility. I can't find a solution that purely uses flexbox.


texts:
So I had this idea; what if I could decorate my Enum values with an attribute that cross-references a "default" value of another Enum that should be used when a variable of the current Enum type has this value?

The desired usage would look like:

public enum MyEnum
{
    Value1,
    Value2,
    Value3,
}

public enum ControllingEnum
{
    [LinkedValue(MyEnum.Value1)]
    ControllingValue1,
    [LinkedValue(MyEnum.Value2)]
    ControllingValue2,
    [LinkedValue(MyEnum.Value1)]
    ControllingValue3,
    [LinkedValue(MyEnum.Value3)]
    ControllingValue4,
}

...

var relatedValue = ControllingEnum.ControllingValue4.GetLinkedValue<MyEnum>();

I came up with the following:

public class LinkedValueAttribute:Attribute
{
    public LinkedValueAttribute(object value)
    {
        TypeOfValue = value.GetType();
        Value = (Enum)value;
    }

    public Type TypeOfValue { get; private set; }
    public Enum Value { get; private set; }
}

public static class AttributeHelper
{
    public static T GetLinkedValue<T>(this Enum enumValue) where T:struct
    {
        if (!typeof(Enum).IsAssignableFrom(typeof(T)))
            throw new InvalidOperationException("Generic type must be a System.Enum");

        //Look for LinkedValueAttributes on the enum value
        LinkedValueAttribute[] attr = enumValue.GetType().GetField(enumValue.ToString())
            .GetCustomAttributes(typeof(LinkedValueAttribute), false)
            .OfType<LinkedValueAttribute>()
            .Where(a=>a.TypeOfValue == typeof(T))
            .ToArray();

        if (attr.Length > 0) // a DescriptionAttribute exists; use it
            return (T)(object)attr[0].Value;
    }
}

It does the job, but the boxing and unboxing are generally to be avoided. The question is, how?


texts: Saving the contents of a TextArea to a file

texts:
Can this method be modified to be more efficient?

public void saveFile(File file, TextArea textArea) {
    if (file != null) {
        String filePath = file.getAbsolutePath();
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath))) {
            writer.write(textArea.getText());
        } catch (IOException e) {
            System.out.println("savefile exception");
        }
    }
}


texts: Is this the right way to write OOP PDO classes?

texts:
I have just begun to work with OOP and I am converting my current project into OOP classes. I have a few questions about this User class.

class User {
    private $db;

    public function __construct($db, $utilities) {
        $this->db = $db;
        $this->utilities = $utilities;
    }

    function set_user($input) {
        check if user exists and if yes set
        $this->user = $userid;
    }

    function info() {
        return user info
    }

    function awards() {
        return user awards
    }
}

I am wondering if this is the correct approach, and how should this be used. When a user is logged in I have a $logged_in = new User; variable set and then I go about setting the user and pulling required variables. When we get on certain pages there are specific sections that have foreach statements that display other users and their awards. Do I create a new instance of class User in each foreach or do I create one instance of the class and use that everywhere needed?

This project is a CMS and on nearly every page it displays multiple areas containing user info. I am wondering what the best way to do this is.


texts: Scaling decimal numbers up within bounds of limit

texts:
This code is part of a simulation and inputs will be positive values less than one and inputs are constrained elsewhere. The goal of the algorithm is to scale the inputs up to much larger numbers, although the total sum is bounded. These represent the number of entities in the simulation.

Conceptually it is best to remember that the value 0.001 can also be expressed as 10^-3 and 4.2*10^-3 is also written as 0.0042. What the algorithm is trying to do is determine the exponent needed such that all of the numbers are positive integer values. Once all of the inputs are integers is then ensures that they are scaled within the bound of the maximum entities.

For example, if the simulation has a limit of MAX_ENTITY_COUNT = 1000000 entities and the user enters input[0].raw = 0.01, and input[1] = 0.1 I would expect to see input[0].count = 90900 and input[1].count = 909000 for a total of 999,900 entities.

private void findEntityCount(List<Inputs> input) {
    // Find the smallest exponent based upon the natural log
    int smallest = Integer.MAX_VALUE;
    for (Inputs entry : input) {
        int exp = (int)Math.log(entry.raw);
        if (exp < smallest) {
            smallest = exp;
        }
    }

    // Calculate the scaling, note that this is closely related to finding the
    // mantissa of the input value, but subtracting one from the value helps
    // pack things a bit better
    long total = 0;
    double scaling = Math.pow(10, Math.abs(smallest) - 1);
    for (Inputs entry : input) {
        entry.count = (long)Math.ceil(entry.raw * scaling);
        total += entry.count;
    }

    // Use the initial total to find a multiplier that we can use to adjust
    // the initial counts to the final count for the simulation
    double multiplier = MAX_ENTITY_COUNT / total;
    for (Inputs entry : input) {
        entry.count *= multiplier;
    }
}

So far this code appears to be working well and resulting in quantities that are scaled correctly and pack the space fairly well. However, since it is playing around with how floating points are stored I'm looking for feedback that:

The approach makes sense (i.e., there isn't a better way to do it that is clearer).
What are some pitfalls that I should be aware of.

I haven't seen any issues yet, but generally I've also only seen a limited range of inputs.


texts: ActiveRecord Query for many to many association

texts:
I have two Models in my Rails 6 / PostgreSQL application which have a many to many relation; Car and Driver. The goal is to get all records (Cars) which have no association at all (Drivers). At the moment this is done using Ruby (2.6.3) like this:

result = []
Car.all.each do |car|
  result << car.id if car.drivers.empty?
end

Is there an ActiveRecord expression which avoids instantiating each record?


texts: Zig-zag child element with Flexbox and JavaScript

texts:
Recently I found a question on StackOverflow that seemed very interesting: How to make HTML elements "zig zag" this way:

 -----------------
|A > B > C > D > E|
|J < I < H < G < F|
 -----------------

 ---
|A H|
|B G|
|C F|
|D E|
 ---

I was able to implement a simple solution for this problem with Flexbox and a bit of JavaScript (works for any even number of elements):

var reverseBoxes = function () {

  var flexItems = document.querySelectorAll(".child"),
      flexItemsCount = flexItems.length,
      reverseAt = flexItems.length / 2,
      breakPoint = 480;

  for (var i = reverseAt; i < flexItemsCount; i++) {
    flexItems[i].style.order = flexItemsCount - i;
  }

  for (var j = 0; j < flexItemsCount; j++) {
    if (window.innerWidth > breakPoint) {
      flexItems[j].style.width = (100 / flexItemsCount) * 2 - 2 + "%";
      flexItems[j].style.height = "auto";
    } else {
      flexItems[j].style.height = (100 / flexItemsCount) * 2 - 2 + "%";
      flexItems[j].style.width = "auto";
    }
  }

}

reverseBoxes();
window.addEventListener("resize", reverseBoxes);
body {
  font-family: Arial, sans-serif;
  font-size: 18px;
  margin: 0;
  padding: 0;
}

.parent {
  display: flex;
  flex-wrap: wrap;
  list-style-type: none;
  padding: 0;
  height: 100vh;
}

.child {
  margin: 1%;
  text-align: center;
  background: #069;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-width: 480px) {
  .parent {
    flex-direction: column;
  }
  .child {
    width: 48%;
  }
}

A

B

C

D

E

F

G

H

I

J


texts:
I'm wondering and actually playing in typescript playground with generics functions. The question is, is the code below readable? If not what kind of approach I could use to make it more typescript way and more readable?
Working example here
I implemented some basic functions like foldl, map and filter to experiment generics, maybe the implementation don't satisfies all requirements in the sense of functionality.
type FoldlFunction<T> = (a: T, b: T) => T;

function Foldl<T>(f: FoldlFunction<T>, base: T, arr: T[]): T {
    const [head, ...rest] = arr;
    return !head ? base : Foldl(f, f(base, head), rest);
}

console.log(Foldl((a: number, b: number) => (a + b), 0, [1,2,3,4,12,14,15,16]));

type MMapFunction<T,R> = (a: T) => R;

function MMap<T,R>(f: MMapFunction<T,R>, arr: T[]): R[] {
    const [head, ...rest] = arr;
    return !head ? [] : [f(head), ...MMap(f, rest)];
}

console.log(MMap((x: number) => (x * x), [1,2,3,4,12,14,15,16]));

type FilterFunction<T> = (a: T) => boolean;

function Filter<T>(f: FilterFunction<T>, arr: T[]): T[] {
    const [head, ...rest] = arr;
    return !head ? [] :
        (f(head) ? [head, ...Filter(f, rest)] : [...Filter(f, rest)])
}

console.log(Filter((x: number) => (x % 2 === 0), [1,2,3,4,12,14,15,16]));


texts: Web scraping data from US postal zip codes

texts:
Web scraping county, population and median home value from United States postal zip codes.

I switched from using InternetExplorer.Application to New MSXML2.XMLHTTP60. For the first time, I broke code into smaller subs or functions, among other things.

This code ran successfully 1 time, with other tests returning only 70-100 records.
UsingInternetExplorer.Application, I projected the code to complete in 1H:45M by timing 20 records. With the XML method, I projected 25-30 min as it takes about 5 min to fetch 70-100 records.
Excel goes completely blank when running (white screen).

There appears to be several things I can do:

Early binding (which I didn't understand how to implement based on the thread)
Creating VBScripts to simulate multi-threading; I've not created VBScripts with Excel so this option is taking me a little bit as I try to read and study VBScripts more in depth.
Can't seem to find the link, but elsewhere, I read that jumping around would make things slow. According to the thread, I should store all values in an array first, after all values are retrieved, I then should input them into the corresponding cells, instead of retrieving and inputting right away. (I think I can handle this but not sure if anyone has any pointers as to whether this actually works).

Variables

'ZipCodeScrape Variables
    Public ZipCodeRange As Range
    Public cell as Variant

'Web Variables
    Public IE As MSXML2.XMLHTTP60
    Public url As String
    Public post As Object
    Public HTML As MSHTML.HTMLDocument
    Public HTMLbody As MSHTML.HTMLbody

Gathering zip codes and using a function to retrieve data

Sub ZipCodeScrape()

    Set IE = New MSXML2.XMLHTTP60
    url = "https://www.unitedstateszipcodes.org/"

    Set ZipCodeRange = Range("C2", Range("C2").End(xlDown))

    Dim TargetElement(1 To 3) As String
        TargetElement(1) = "County:"
        TargetElement(2) = "Population"
        TargetElement(3) = "Median Home Value"
    Dim i As Integer

    For Each cell In ZipCodeRange
        For i = 1 To 3
            cell.Offset(0, i).Value = dataScrape("th", TargetElement(i), "td")
        Next i
    Next cell
End Sub

Here is the function I'm using to retrieve the data

Private Function dataScrape(ByVal TagName As String, Element As String, targetTagName)

    IE.Open "GET", url & cell.Value, False
    IE.send

    While IE.readyState <> 4: DoEvents: Wend

    Set HTML = New MSHTML.HTMLDocument
    Set HTMLbody = HTML.body
    HTMLbody.innerHTML = IE.responseText

        For Each post In HTMLbody.getElementsByTagName(TagName)
            If InStr(post.innerText, Element) > 0 Then
                dataScrape = post.ParentNode.getElementsByTagName(targetTagName)(0).innerText: Exit For
            End If
        Next post

End Function


texts: Method naming and violating single responsibility

texts:
I need your opinion. Which way do you think is right?

The definition of message in this code bothers me because it is a single method that has two separate behaviors.  Depending on how many arguments are passed the method will do different things--that stinks.

On the other hand, calling message in the block just feels right. It is subtle. But the difference of assigning the message with or without the = seems more significant than it should.  I feel guilty for really wanting to code this way.

Here's a code example:

class Queue
    attr_accessor :id

    def initialize(id, &block)
      if block_given?
        instance_eval(&block)
      end
    end

    def message=(value)
        @message = value
    end

    # if no value is given then it reports the value
    def message(value=nil)
        value.nil? ? @message : @message = value
    end
end

Queue.new :test_queue do
    message "This is a test"
end

Alternatively, I could use another method for it.

set_message "This is a test"

This also doesn't have the same effect.

Opinions? Other options?


texts: Update machine settings at various moments over time period

texts:
I have the actions and the times in an instructions.js file:

module.exports = {
  temperature : {
    "00:00" : 100,
    "01:00" : 110,
    "02:00" : 120,
    "03:00" : 130
  },
  ventilation : {
    "00:00" : 0,
    "00:30" : 25,
    "01:30" : 75,
    "02:30" : 100
  },
  end : "03:30"
}

Then after importing the instructions,

function adjustMachineParams() {
  if (instructions.temperature[machineTime()]) {
    var temp = instructions.temperature[machineTime()];
    machine.setTemperature(temp);
  }
  if (instructions. ventilation[machineTime()]) {
    var vent = instructions.ventilation[machineTime()];
    machine.setVentilation(vent);
  }
  if (machineTime() == instructions.end) {
    machine.stop();
  }
}

function machineTime() {
  var date = new Date(null);
  date.setSeconds(machineTimer/10); // machineTimer is in deciseconds
  return date.toISOString().substr(14, 5);
}

And finally, the machine loop...

var machineLoop = setInterval(function() {
    adjustMachineParams()
    machineTimer += 10;
  }
}, 1000)

Looking for feedback on the way that I have set up the instructions and also the general strategy and elegance (or lack of it) of the code.


texts: Avoid code duplication if what changes is one argument type only

texts:
As you can see these functions differ only in keys []int and keys []*int (and in name).
func (db *myDB) QueryWithKeys(keys []int) ([]*models.Player) {
    var players = make([]*models.Player, len(keys))
  _ := db.Model(&players).Where("id in (?)", pg.In(keys)).Select()
  // several other equal code here
    return players
}

func (db *myDB) QueryWithPointerKeys(keys []*int) ([]*models.Player) {
    var players = make([]*models.Player, len(keys))
    _ := db.Model(&players).Where("id in (?)", pg.In(keys)).Select()
  // several other equal code here
    return players
}

Is there a way to avoid this code duplication?


texts:
The problem is :

  The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

  1: 1

  3: 1,3

  6: 1,2,3,6

  10: 1,2,5,10

  15: 1,3,5,15

  21: 1,3,7,21

  28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five divisors.

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

The code works now, when I set the condition in the last loop to 60, etc. instead of 500. But 500 is too big for it and it takes forever to answer (actually I didn't have enough patience to see how much time it takes, it takes a bit too much).

How can I make it faster?

def num_of_divisors(x):
    k=0
    b=x

    while x%2==0:
        x=x//2
        k=k+1
    z=1
    while x!=1:
        for y in range(3,b+1,2):
            a=0
            while x%y==0:
                x=x//y
                a=a+1
            z=z*(a+1)
    return(z*(k+1))

def triangular(n):
    return(n*(n+1)//2)

for n in range(1,10000):
    jk=triangular(n)
    if num_of_divisors(jk)>500:
        print(triangular(n))
        break


texts: Populate two arrays with two different SQL queries

texts:
I am using Joomla and connecting to an MSSQL database to store the resulting set(s) in arrays. I am utilizing this syntax, but there must be a more efficient way of coding this.

<?php
    $option = array();
    $option['driver'] = 'mssql';
    $option['host'] = '555.555.55.5';
    $option['user'] = 'username';
    $option['password'] = 'password';
    $option['database'] = 'database';
    $option['prefix'] = '';
    $db = JDatabaseDriver::getInstance($option);
    $sql = $db->getQuery(true);
    $sql = "Select ranchstyle from information";
    $db->setQuery($sql);
    $rows = $db->loadRowList();
    $output = array();
    foreach ($rows as $row) {
        array_push($output, $row);
    }
    $data = json_encode($output[0]);

    $query2 = $db->getQuery(true);
    $query2 = "Select maestro from musicinfo";
    $db->setQuery($query2);
    $rows1 = $db->loadRowList();
    $output1 = array();
    foreach ($rows1 as $r) {
        array_push($output1, $r);
    }

    $data1 = json_encode($output1[0]);
?>


texts:
I'm trying to design a mapper that will convert one object type to another shown in the diagram below:

The object has structure as follows (it's not a JSON):

{
"type": "DownloadAppComponent",
"name": "Download App",
"contentId": "download-app",
"properties": {
    "iosUrl": "http://apple.com",
    "androidUrl": "http: //google.com",
    "promoText": "Download our app",
    "hidden": false
}

My first solution was to have mapper for each type but this required a lot of code duplication to map common attributes (i.e. name, type, contentId).

public DownloadAppComponent map(CmsDocument cmsDocument) {
    DownloadAppComponent downloadAppComponent = new DownloadAppComponent();

    downloadAppComponent.setType(cmsDocument.getType()); // <-- this will be duplicated in each mapper
    downloadAppComponent.setName(cmsDocument.getName()); // <-- this will be duplicated in each mapper
    downloadAppComponent.setContentId(cmsDocument.getText(CONTENT_ID_PATH)); // <-- this will be duplicated in each mapper
    downloadAppComponent.setIosURL(cmsDocument.getText(IOS_URL_PATH));
    downloadAppComponent.setAndroidURL(cmsDocument.getText(ANDROID_URL_PATH));
    downloadAppComponent.setHidden(Boolean.parseBoolean(cmsDocument.getText(HIDE_PATH)));
    downloadAppComponent.setPromoText(cmsDocument.getText(DOWNLOAD_PROMO_TEXT_PATH));

    return downloadAppComponent;
}

I've been trying to refactor that code and I come up with generic BaseDocumentMapper:

public BaseDocument map(CmsDocument cmsDocument) {
    BaseDocument document = documentsMapperFactory.getMapper(cmsDocument.getType()).map(cmsDocument);
    document.setType(cmsDocument.getType());
    document.setName(cmsDocument.getName());
    document.setContentId(cmsDocument.getText(CONTENT_ID_PATH));
    return document;
}

The documentsMapperFactory returns specific mapper that will map only type related attributes and return that object instance.

However, there are still more levels in inheritance and I just have one type value which I can resolve to concrete mapper. So I'll have to repeat Component's specific fields mapping in each component mapper.

I was thinking that since I know the hierarchy I could create some mappers that will map the documents from Up to Bottom, i.e. create first DownloadAppComponent and then extend it with Component and then with BaseDocument specific properties. However, I have not found any good solution except using abstract classes and inheritance in mappers as well.

Could someone advise me if this is good approach or if there are any issues or other better solutions for my case?


texts: Python Method for Text Input from Project Euler

texts:
Method

Frequently input for problems is given as a 1D or 2D array in a text file.

Have knocked out a method to do so, but believe something shorter, clearer and cheaper can be written:

def read_array_from_txt(path, dim, typ, sep):
    '''
    @time: O(n)
    @space: O(n)
    '''
    txt_file_object = open(path,"r")
    text = txt_file_object.readlines()
    text = text[0]
    if dim == 1:
        if typ == "int":
            text = [int(num) for num in text.split(sep)]
        elif typ == "str":
            text = [let for let in text.split(sep)]
        else:
            raise ValueError("Unknown type.")
    elif dim == 2:
        if typ == "int":
            text = [[int(num) for num in line.split(sep)] for line in text]
        if typ == "str":
            text = [[let for let in line.split(sep)] for line in text]
        else:
            raise ValueError("Unknown type.")
    else:
        raise ValueError("Unknown dimension.")
    txt_file_object.close()
    return text

An Example:

Input: encrypted_message.txt

36,22,80,0,0,4,23,25,19,17,88,4,4,19

Output:

>>> read_array_from_txt("./encrypted_message.txt", 1, "int", ",")
[36,22,80,0,0,4,23,25,19,17,88,4,4,19]

Some Other Possible Inputs:

1   37  79  164 155 32  87  39  113 15  18  78  175 140 200 4   160 97  191 100 91  20  69  198 196
2   123 134 10  141 13  12  43  47  3   177 101 179 77  182 117 116 36  103 51  154 162 128 30
3   48  123 134 109 41  17  159 49  136 16  130 141 29  176 2   190 66  153 157 70  114 65  173 104 194 54

are,in,hello,hi,ok,yes,no,is


texts:
The following code will be used for educational purposes. It is to simply demonstrate how to apply a drop-shadow using a CSS3 filter. Any feedback on areas where I have not used best practices would be great.

JSBin

HTML:

<!DOCTYPE HTML>

    <title>Drop Shadow</title>
    <link rel="stylesheet" type="text/css" href="drop-shadow.css">

CSS:

    body{
            background: #ccc;
            margin: 0;
    }
    h1{
        font-size: 5em;
        font-family: Georgia;
    }
    .container{
        padding: 20px 50px;
    }
    .one img{
        -webkit-filter: drop-shadow(0 0 30px black);
    }
    .two{
        background: black;
    }
    .two img{
        -webkit-filter: drop-shadow(-15px 0px 20px white);
    }


texts: A beginner's first Tic Tac Toe implementation

texts:
I've been teaching myself Python and decided to make a Tic Tac Toe game for a bit of practice. Any criticisms or pointers are welcome!
class TicTacToe:
  """A class for playing tic tac toe"""

  def __init__(self):
    self.values = ["-", "-", "-",
                  "-", "-", "-",
                  "-", "-", "-"]
    self.player = "x"

  def show_board(self):
    print(f"{self.values[0]} | {self.values[1]} | {self.values[2]}")
    print(f"{self.values[3]} | {self.values[4]} | {self.values[5]}")
    print(f"{self.values[6]} | {self.values[7]} | {self.values[8]}")

  def play_game(self):
    # display initial board
    self.show_board()
    # play for 9 turns max
    for i in range(9):
      self.handle_turn(self.values)
      if self.check_tie() or self.winner():
        break

  def handle_turn(self, values):
    # get next move from a player
    try:
      turn = int(input(f"Player {self.player} pick a square (1-9) from left to right: "))
    except ValueError:
      self.handle_turn(self.values)
      return

    # change values to show the move made (check square empty)
    if self.values[turn-1] == "x" or self.values[turn-1] == "o":
      print("That square has been played already!")
      self.handle_turn(self.values)
    else:
      self.values[turn-1] = self.player
      self.show_board()
    # switch turns
    self.flip_player()

  def winner(self):
    # check all possible win methods
    self.row_winner = self.check_rows()
    self.column_winner = self.check_columns()
    self.diagonal_winner = self.check_diagonals()
    #declare a winner
    if self.row_winner:
      winner = self.check_rows()
      print(f"{winner} has won the game!")
      return True
    elif self.column_winner:
      winner = self.check_columns()
      print(f"{winner} has won the game!")
      return True
    elif self.diagonal_winner:
      winner = self.check_diagonals()
      print(f"{winner} has won the game!")
      return True

  def check_rows(self):
    # Check for a win in the rows
    row1 = self.values[0] == self.values[1] == self.values[2] != "-"
    row2 = self.values[3] == self.values[4] == self.values[5] != "-"
    row3 = self.values[6] == self.values[7] == self.values[8] != "-"
    # Return the player that has won
    if row1:
      return self.values[0]
    elif row2:
      return self.values[3]
    elif row3:
      return self.values[6]

  def check_columns(self):
    # Check for a win in the columns
    col1 = self.values[0] == self.values[3] == self.values[6] != "-"
    col2 = self.values[1] == self.values[4] == self.values[7] != "-"
    col3 = self.values[2] == self.values[5] == self.values[8] != "-"
    # Return the winning player
    if col1:
      return self.values[0]
    elif col2:
      return self.values[1]
    elif col3:
      return self.values[2]

  def check_diagonals(self):
    # Check for win in the diagonals
    dia1 = self.values[0] == self.values[4] == self.values[8] != "-"
    dia2 = self.values[2] == self.values[4] == self.values[6] != "-"
    # Return the player that has won
    if dia1:
      return self.values[0]
    elif dia2:
      return self.values[2]

  def check_tie(self):
    if "-" not in self.values:
      print("Game is a tie!")
      return True
    else:
      return False

  def flip_player(self):
    if self.player == "x":
      self.player = "o"
    else:
      self.player = "x"

if __name__ == "__main__":
  new_board = TicTacToe()
  new_board.play_game()


texts: Finding the second largest value In an Array

texts:
findSecondLargestNumberInTheArray() method returns the second highest number from an array.

Could you please review this code to enhance performance.

public static int findSecondLargestNumberInTheArray(int array[]) {
    // Initialize these to the smallest value possible
    int highest = Integer.MIN_VALUE;
    int secondHighest = Integer.MIN_VALUE;

    // Loop over the array
    for (int i = 0; i < array.length; i++) {

        // If current element is greater than highest
        if (array[i] > highest) {

            // assign second highest element to highest element
            secondHighest = highest;

            // highest element to current element
            highest = array[i];
        } else if (array[i] > secondHighest)
            // Just replace the second highest
            secondHighest = array[i];
    }

    // After exiting the loop, secondHighest now represents the second
    // largest value in the array
    return secondHighest;
}