texts: Shuffling algorithm for a "guess that tune" game

texts:
I'm making a "guess that tune" game in Visual Basic 6 that is supposed to play each song in a random order:

' from frmGuessGame.frm
Private Sub Swap(ByRef Value1 As Variant, ByRef Value2 As Variant)
Dim Temporary As Variant
Temporary = Value1
Value1 = Value2
Value2 = Temporary
End Sub

Private Sub ShuffleList()
Dim LoopCtr As Integer, SwapWith As Integer
For LoopCtr = LBound(InnerPlaylist) To UBound(InnerPlaylist)
SwapWith = (Rnd * (UBound(InnerPlaylist) - LBound(InnerPlaylist))) + LBound(InnerPlaylist)
Swap InnerPlaylist(LoopCtr), InnerPlaylist(SwapWith)
Next
End Sub

My initialization function does include the Randomize statement, so it should be a good, even shuffle.

' from mdiMain.frm
Private Sub MDIForm_Load()
'initialize pseudo-random number generator
Randomize
frmMusiguess.Show
frmSplash.Show
End Sub

I'm not sure, however, that this is the best way to do it. Am I on the right track?


texts: Comparing triangles using Java 8 streams

texts:
I'm trying to get more familiar with Java 8 streams as they seem to be very powerful (and shorter), so I rewrote a method to use streams. However I'm not very satisfied with it and would like some suggestions on how to make better use of streams. The code itself has multiple nested loops, so it's not very easy. Also I'm forced to use final arrays to write the variables inside the lambda loops.

// t1, t2 are List<Triangle> passed as parameter
Triangle original = t1.get(0);
t2.forEach(transformed ->
{

    for (int[] permutation : permutations)
    {
        Matrix trial = calculateMatrix(original.getVertices(), applyPermutation(transformed.getVertices(), permutation));

        final double[] sum = {0};
        points1.stream().map(v -> v.extend(1)).map(trial::multiply).forEach(v -> sum[0] += points2.stream().mapToDouble(v2 -> distanceCheated(v, v2)).min().orElse(0));

        if (bestDeviation[0] == null || sum[0] < bestDeviation[0])
        {
            second[0] = transformed;
            bestDeviation[0] = sum[0];
            bestMatrix[0] = trial;
        }
    }
});

EDIT: So as I aparently left out many important information, i try to provide them here:

The first obvious missing information is the connection between points1/2 and t1/2. points1/2 are plain two lists of points contained in two images (original and transformed). t1/2 are lists of triangles built with delauney triangulation using the points from points1/2. The goal is to calculate the transformation matrix used, to create the second set of points.

I posted the whole class here: https://gist.github.com/anonymous/8f21597d8a51c8960de7
Vertex is used as a Vector (mathematical)
Triangle consists of 3 Vertices


texts:
Before I begin using this code in vital systems, I wanted to quadruple-check that it was soundproof. I plan to implement this as part of a larger program, obviously not by itself. Are there any clear flaws (output is incorrect) or optimization issues in this code?

#include <iostream>

using namespace std;

int main() {
    int convertFromCopy, digit, convertTo;
    unsigned int convertFrom;
    string stringDigit, answer;

    cout << "Num (base 10): ";
    cin >> convertFrom;
    cout << "Base: ";
    cin >> convertTo;

    convertFromCopy = convertFrom;

    while (convertFrom != 0){
        digit = convertFrom % convertTo;

        if (digit < 10)
            stringDigit = '0' + digit;
        else
            stringDigit = digit - 10 + 'A';

        answer = stringDigit + answer;

        convertFrom /= convertTo;
    }
    cout << convertFromCopy << " written in base " << convertTo << " is: " << answer;
    return 0;
}

And as a note, the input will always be int, so I do not need to account for an incorrect input (i.e. if a char is entered where an int should go).


texts:
I'm using a third-party library which utilizes boost::shared_ptr for memory management.

The problem is that I need to allocate many objects and I have detected that the allocation and deallocation is rather resource-demanding. So I thought I should utilize a smart-pointer memory pool to reduce the overhead.

#include <boost/smart_ptr/make_shared_array.hpp>

template <class T, size_t pool_size>
class shared_ptr_pool
{
   boost::shared_ptr<T[]> pool;
   size_t avail = 0;

public:
   boost::shared_ptr<T> make_shared()
   {
      if (!avail)
      {
         pool = boost::make_shared<T[]>(pool_size);
         avail = pool_size;
      }

      return boost::shared_ptr<T>(pool, &pool[--avail]);
   }
};

The solution is to utilize make_shared for arrays and the shared_ptr aliasing constructor. The solution in inherently thread-unsafe, but for my needs that is okay.

Any thoughts, comments or pretty much anything would be appreciated.


texts: Retrieving a substring from an exponentially growing string

texts:
For integer A, the base level of 1 is "XYZ"
For subsequent levels, the levels become "X" + Level (A - 1) + "Y" + Level (A - 1) + "Z".
So for level 2, the string would be "XXYZYXYZZ"
The objective is to return the substring from the Level string using the Start and End Index.
Example: If entering 2 3 7, it would Level 2, 3rd character to the 7th character and the result would be "YZYXY" from "XXYZYXYZZ"
The following constraints are given:

1 ≦ Level K ≦ 50,
1 ≦ start ≦ end ≦ length of Level K String,
1 ≦ end - start + 1 ≦ 100.

I have written a brute force approach for this problem in Python as follows
def my_substring():
    level = int(input())
    start_index = int(input()) - 1
    end_index = int(input())
    strings_list = [None] * level
    strings_list[0] = "XYZ"

    for i in range(1, level):
        strings_list[i] = "X" + strings_list[i - 1] + "Y" + strings_list[i - 1] + "Z"

    return "".join(strings_list[-1])[start_index:end_index]

if __name__ == '__main__':
    print(my_substring())

As shown, the length of the string will increase by (base string * 2) + 3 for each iteration.  Past the 20th iteration, my program starts running into issues from having to deal with the enormous final string.  I would like to learn how I can reduce my complexity from what I think is O(N^2).
What alternative approaches are there for me to handle/concatenate very long strings in Python?  Is there a way for me to reduce the loading time/resources for doubling my strings?
Or is my current approach flawed and should I be approaching this issue from a different angle (one that I am so far unable to come up with an alternative for).
Edit: I have been told that this problem can be solved in O(1) - O(logn) time.


texts: A piece of Python code to compute a frequency table of a list of values

texts:
I have written a Python 2.5.4 function which accepts as input a list of numbers alongwith the desired number of classes and yields a frequency distribution (i.e. a histogram) of the same data.

While setting class boundaries, I've attempted to increase the accuracy (i.e. number of digits after the decimal point).

Here's my code:

def num_after_point(x):
    s = str(x)
    if '.' not in s:
        return 0
    return len(s) - s.index('.') - 1

def histogram(list, numBuckets):
    count = [0] * len(list)
    for i in range(len(list)):
        count[i] = num_after_point(list[i])
    lowest = min(list) - 10**(-max(count)-1)
    highest = max(list) + 10**(-max(count) -1)
    print "Lowest data value:", lowest
    print "Highest data value:", highest
    dataRange = highest - lowest
    bucketSize = dataRange / numBuckets
    print "Bucket Size:", bucketSize
    bucketCountList = [0] * numBuckets
    low = lowest
    high = lowest + bucketSize
    index = 0
    for i in range(len(list)):
        if low < list[i] < high:
            bucketCountList[index] += 1
    print "From", low, "to", high, ":", bucketCountList[index]
    while high < highest:
        low = high
        high = low + bucketSize
        index = index + 1
        for i in range(len(list)):
            if low < list[i] < high:
                bucketCountList[index] += 1
        print "From", low, "to", high, ":", bucketCountList[index]

histogram( [ 0.1, 0.22, 0.333, 0.4444, 0.55555, 0.666666,
             0.7777777, 0.88888888, 0.999999999, 1.0], 3)

Is this code error-free enough?

If not, where and how does it break down?

How can I improve its functionality and efficiency?


texts: Selectively printing elements on web page using a bookmarklet

texts:
There is a web page I visit which I would like to print. However, I only want to print a couple of things on it, not everything.
So, I am making a bookmarklet that I can use whenever I visit the page to hide everything from the printer except what I want to print.
The site already has a class, 'd-print-none', to hide an element from the printer.
The following code is the javascript I made to base my bookmarklet on.
My idea is to first apply the 'd-print-none' class to everything. Then selectively remove it.
I remove the class from the element that contains what I would like to print as well as any of its children.
Then I recursively remove it from the parents until I reach the document element.
function removeClass(t_selector, t_class){
    document.querySelectorAll(t_selector + ' *').forEach(x=>x.classList.remove(t_class))

    node = document.querySelector(t_selector)
    while (node && node.nodeType != Node.DOCUMENT_NODE) {
        node.classList.remove.(t_class);
        node = node.parentNode;
    }
}

document.querySelectorAll( '*' ).forEach(x=>x.classList.add('d-print-none'))
removeClass('app-flex-chart', 'd-print-none')
removeClass('app-flex-grid', 'd-print-none')

Adding the class to all elements was pretty straightforward and succinct as was removing it from all of the target element's children.
Climbing the tree to apply it to the element itself and any of its parents was more verbose and error prone. Sadly, there appears to be no css selector to find all parents of an element.
I paired the loop down to be as succinct and readable as I could.
I am looking for ideas on how to make it more robust, succinct, or readable. Open to any and all suggestions and criticisms.
For that while loop, I had to check if the node I was on existed and check to make sure it wasn't the document node, either case would cause an error.
EDIT: To show generic structure of page
<html>
    <head>...</head>
    <body>
        <many>
            <nested>
                <tags>
                    <app-flex-chart>
                        <many-more-nested-tags>Actual Content</many-more-nested-tags>
                    </app-flex-chart>
                </tags>
            </nested>
        </many>
    </body>
</html>

The app-flex-chart tag is the only unique piece along the chain to the content. All other classes and tags seem to be reused throughout the page.


texts:
“There are only two hard things in Computer Science: cache
  invalidation and naming things.” -- Phil Karlton

That being said, I created this SimpleCache class which I intend to use to cache database queries and results over a relatively short period of time.

I'm just asking if there are any immediate faults or errors with this?

(The class is internal because I'm using it inline in another class)

internal sealed class SimpleCache
{
    private static Dictionary<string, CacheItem> _cache = new Dictionary<string, CacheItem>();

    public void Add(string key, object value)
    {
        _cache.Add(key, new CacheItem() { Value = value, Created = DateTime.Now.Ticks });
    }

    public object this[string key]
    {
        get
        {
            if(_cache.ContainsKey(key))
            {
                if ((_cache[key].Created + 30000) > DateTime.Now.Ticks) //30000 was chosen by magic
                {
                    return _cache[key].Value;
                }
                    _cache.Remove(key);
            }
            return null;
        }
    }

    internal sealed class CacheItem
    {
        public object Value { get; set; }
        public long Created { get; set; }
    }
}


texts: Implementation of Gitlab CI + Docker + Spring Boot

texts:
i would really appreciate if anyone could invest a bit of time to review what i did. Basically this is first time i do this, and that is reason why i need another set of eyes.

I have Spring Boot application and i decided to use docker containers on my server to run applications across multiple environments (DEV, QA and PROD). I invested a lot of time to properly research everything and at the end i was able to achieve what i wanted from the beginning.

Basically my code is on GitLab and instead of using jenkins i wanted to take advantage of GitLab CI and simply automatize deployment of my app.

Lets begin, i will start from Dockerfile and it looks like this:

FROM maven:3.6.3-jdk-11-slim AS MAVEN_BUILD

ARG SPRING_ACTIVE_PROFILE

MAINTAINER jmj
COPY pom.xml /build/
COPY src /build/src/
WORKDIR /build/
RUN mvn clean install -Dspring.profiles.active=$SPRING_ACTIVE_PROFILE && mvn package -B -e -Dspring.profiles.active=$SPRING_ACTIVE_PROFILE
FROM openjdk:11-slim
WORKDIR /app

COPY --from=MAVEN_BUILD /build/target/storm-*.jar /app/storm.jar
ENTRYPOINT ["java", "-jar", "storm.jar"]

Dockerfile notes: I had one major issue here, and that is passing dynamically ARG in ENTRYPOINT, to be more specific i wanted to pass active profile, i was able to fix it by passing active profile when doing docker run, which you will see below.
Dockerfile question: I am using Java 11 on my project, because it is last LTS version of Java, what i have noticed compared when i used Java 8, is that docker image is really large, a lot of larger than when using Java 8. If i am correct, that is because there is no safe and tested Java 11 alpine image, which at the end produce smaller docker images. My actual question here is: Is my choice of images fine, and is it expected to have image size of ~450MB (on java 8 it was below ~200)

Next lets jump on my .gitlab-ci.yml file.

services:
  - docker:19.03.7-dind

stages:
  - build and push docker image
  - deploy

docker build:
  image: docker:stable
  stage: build and push docker image
  before_script:
    - source .${CI_COMMIT_REF_NAME}.env
  script:
    - docker build --build-arg SPRING_ACTIVE_PROFILE=$SPRING_ACTIVE_PROFILE -t $DOCKER_REPO .
    - docker login -u $DOCKER_USER -p $DOCKER_PASSWORD docker.io
    - docker push $DOCKER_REPO

deploy:
  image: ubuntu:latest
  stage: deploy
  before_script:
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
    - source .${CI_COMMIT_REF_NAME}.env
  script:
    - ssh root@$SERVER "docker stop $APP_NAME; docker system prune -a -f; docker pull $DOCKER_REPO; docker container run -d --name $APP_NAME -p $PORT:8080 -e SPRING_PROFILES_ACTIVE=$SPRING_ACTIVE_PROFILE $DOCKER_REPO"

Its important to mention that as extension for this file i also have 3 files, with names: .develop.env,.qa.env and .master.env. They represent dynamic variables that i need on different enviorements.

export SPRING_ACTIVE_PROFILE='development'
export DOCKER_REPO="$DOCKER_DEV_REPO"
export APP_NAME="$DEV_APP_NAME"
export PORT='8080'

That is basically it, if anyone can see something that i could improve please let me know.
Thank you all in advance.


texts:
squish is an onomatopoeic string function provided by Ruby on Rails that works on strings.

Given a string, squish condenses all the consecutive spaces into one.1 (Imagine that you take a string at both ends and compress it with both hands, spaces will be merged and you will hear the typical squish sound).

I went I little overboard and wrote three variations of this function:

squishAll that will squish together all repeated chars:
squishAll "aaabbbccc" -> "abc"
squishOn that will squish together any specified char:
squishOn 'a' "aaabbbccc" -> "abbbccc"
squish for spaces only: squish "foo   bar   baz" -> "foo bar baz"

import Data.List
import Data.Foldable

squishAll :: Eq a => [a] -> [a]
squishAll = (map head) . group

squishOn :: Eq a => a -> [a] -> [a]
squishOn item = Data.List.concat . (map firstIfEqualElseAll) . group
  where firstIfEqualElseAll (x:xs) = if x == item then [x] else (x:xs)

squish = squishOn ' '

main = print $ [squishAll "aaabbbccc", squishOn 'a' "aaabbbccc", squish "foo   bar   baz"]

1 The Ruby function that this is modelled on would also remove any spaces at the start and at the end.  I've chosen not to implement this.


texts:
I am doing the following about 10 times with other strings, so the code is duplicated.  How can I refactor this?

queryWhere is a Dictionary<string,string> that contains parameters that will be passed to a query.

string account = string.Empty;

if (queryWhere.ContainsKey("account")
&& queryWhere["account"] != null
&& !string.IsNullOrEmpty(queryWhere["account"].ToString()))
    account = queryWhere["account"].ToString();

string customer = string.Empty;

if (queryWhere.ContainsKey("customer ")
&& queryWhere["customer "] != null
&& !string.IsNullOrEmpty(queryWhere["customer "].ToString()))
    customer = queryWhere["customer "].ToString();

string balance = string.Empty;

if (queryWhere.ContainsKey("balance ")
&& queryWhere["balance "] != null
&& !string.IsNullOrEmpty(queryWhere["balance "].ToString()))
    balance = queryWhere["balance"].ToString();


texts: Reducing memory footprint with queue of classes

texts:
I hope I've asked this in the right area. I'm writing a program that deals with enqueueing a class on STL queue in C++. Initially it queues initializations of the class. Then while the queue is not empty, it performs some operations on the class and then checking if an inequality works it either pops the queue or passes the class into function that creates more versions of the class and then queues the extra versions. It then pops the original initialization.

I'm trying to change this so it suits the format, I've also changed the title. At this stage I'm looking to minimize memory footprint mainly and maximize speed as a secondary. I'm basically looking for advice on lines I can remove or where it's inefficient. int main() would also include code to initially queue Subcubes. I hope this is more what you're looking for but if not just let me know.

Vec map(const Vec &g,const int &p);      \\I haven't added these as I dont think theyre massicaly important
double pnorm(const Vec &s,const int &p);
typedef vector<double> Vec;
typedef vector<Vec> Mat;
typedef queue< Subcube>  SUBQUEUE;

void subdivide(Subcube &nw, const Subcube &f ,const Vec &t)
{
 // cout << "running subdivide" << endl;

 Vec v = t;
 v.insert(v.begin() + f.k, 0);

int n = f.e.size();
nw.e.assign(n,0);  //just to avoid runtime error
nw.hside = (f.hside/2);
nw.k= f.k;

for(int j=0;j<n;j++)
{
    nw.e.at(j) = f.e.at(j) +(f.hside/2)*v.at(j);
    }
  }

int main(){
while(!q.empty())
{
    double upperb=0;
    upperb = 2*pow(double(n),0.25)*q.front().hside;
    Vec radmap = map(q.front().e,p);   // taking the vector from front subcube and maping it radially from the l-infy to the l4 unit ball
    double temp = pnorm(a*radmap,p);   // taking  a nomrm of matrix a multiplied by radmap
    if(temp>M)
        {M=temp;
        final = radmap;}               // to see what vector maximised it at the end
    if(temp>= M*(1+e)*(1-(((p-1)/2)*pow(upperb,2)))){
        int tr = pow(2,n-1);
        for(int j =0;j<tr;j++)
        {
            q.push(subdivide(q.front(),set.at(j))); // splits subcube into 2^n-1 subcubes
        }
        counter++;                  //counts related to number of subcubes created
       }
       q.pop();}
}

class Subcube
{
  public:
    Subcube();
    void printvector(const int& n);
    void Subcubeset(const int& i,const int& n);
    vector<double> e;
    double hside;
    char k;
    virtual ~Subcube();

protected:
private:
};


texts: Normalizing data in Excel table column with multiple values

texts:
I have a table in excel which has 11 columns and 50,000 rows of data.

One of the columns contains email addresses and in some instances multiple addresses, separated with a ; character. Eg. a cell in that column might look like a@gmail.com;b@gmail.com;x@gmail.com .

In those instances where I have multiple addresses, I need to delete the row with the multiple addresses and create new rows in the table with each one of those addresses, also copying and pasting the rest of the columns.

An example of how originally the data might look like and how it should look like after processing:

Before:

After:

In order to accomplish that I wrote this piece of code:

Sub Fix_Table()
i = 1
table_size = Range("Table1").Rows.Count
'Goes through Table1 in "To" column and fixes the recipients
Do While i <= table_size

   cell_value = Range("Table1[To]")(i)

   If InStr(Range("Table1[To]")(i), ";") Then
        from_table = Range("Table1[From]")(i)
        subject_table = Range("Table1[Subject]")(i)
        receivedDate_table = Range("Table1[Received_Date]")(i)
        infolder_table = Range("Table1[In_Folder]")(i)
        size_table = Range("Table1[Size]")(i)
        weekday_table = Range("Table1[Weekday]")(i)
        date_table = Range("Table1[Date]")(i)
        month_table = Range("Table1[Month]")(i)
        year_table = Range("Table1[Year]")(i)
        time_table = Range("Table1[Time]")(i)
        inout_table = Range("Table1[In/out]")(i)

        recipients_table = Split(cell_value, ";")
        number_of_recipients = UBound(recipients_table, 1) - LBound(recipients_table, 1)
        Range("Table1[To]")(i).EntireRow.Delete

        For k = 1 To number_of_recipients + 1
            Range("Table1[To]")(i).EntireRow.Insert
            Range("Table1[From]")(i) = from_table
            Range("Table1[Subject]")(i) = subject_table
            Range("Table1[Received_Date]")(i) = receivedDate_table
            Range("Table1[In_Folder]")(i) = infolder_table
            Range("Table1[Size]")(i) = size_table
            Range("Table1[Weekday]")(i) = weekday_table
            Range("Table1[Date]")(i) = date_table
            Range("Table1[Month]")(i) = month_table
            Range("Table1[Year]")(i) = year_table
            Range("Table1[Time]")(i) = time_table
            Range("Table1[In/out]")(i) = inout_table
            Range("Table1[To]")(i) = recipients_table(k - 1)
            i = i + 1
            table_size = table_size + 1
        Next k

   Else
        i = i + 1
   End If

Loop
End Sub

The above code works , however it is extremely slow! Is there any faster way that I could do that for that size of data?


texts: Using QuickCheck to Verify Free Monad's Functor Instance

texts:
Given the Free Monad, and my Eq, Show, and Functor instances, I attempted to verify the first Functor law using QuickCheck:

data Free f a = Var a
               | Node (f (Free f a))

I defined the following Eq and Show instances (credit to duplode for helping me out on the Eq instance:

instance (Eq (f (Free f a)), Eq a) => Eq (Free f a) where
    (==) (Var x) (Var y)       = x == y
    (==) (Node fu1) (Node fu2) = fu1 == fu2
    (==) _ _                   = False

instance (Show (f (Free f a)), Show a) => Show (Free f a) where
  show (Var x)  = "Var " ++ (show x)
  show (Node x) = "Node " ++ (show x)

Then, I implemented a Functor instance:

instance Functor f => Functor (Free f) where
  fmap g (Var x)  = Var (g x)
  fmap g (Node x) = Node $ fmap (\y -> fmap g y) x

And now the QuickCheck work:

instance Arbitrary (Free Maybe Int) where
    arbitrary = do
        x <- arbitrary :: Gen Int
        y <- arbitrary :: Gen Int
        elements [Var x, Var y, Node (Nothing), Node (Just (Var y))]

--fmap id = id

functor_id_law ::  Free Maybe Int -> Bool
functor_id_law x = (fmap id x) == (id x)

Finally, run it in QuickCheck:

ghci> quickCheck functor_id_law
+++ OK, passed 100 tests.

However, I haven't included other Functor's, such as [], etc. Nor have I used other types, i.e. Char, String, etc.

What's a more rigorous approach to verifying that my definition of the Free Monad's Functor instance obeys the first Functor Law?


texts: Generate a series of random integers between 1 and 10

texts:
Is there a better way of generating a series of unique and random integers between 1 and 10 in JavaScript (ES6)?

const ran = [];

while (ran.length < 10) {
  x = Math.floor((Math.random() * 10) + 1);
  if (!ran.includes(x)) {
    ran.push(x);
  }
}
console.log(ran);


texts:
This method takes a text file of my work schedule and parses it.  It works, but is kind of kludgey, and I'm looking for feedback and suggestions.  My first attempt at a file parser, and my first look at Python (I have dabbled in Java/Android and JavaScript).  I'm hoping that between the pseudocode and the comments it will be clear what is going on.

Pseudocode:

def read_body():
    f = open('file')
    tempList = []
    d = custom data object()
    for line in f:
        if line not empty line:
            if begins with a macron:    #denotes new day in the file
                prepare new/empty data object
                for line in f:
                    split line for whitespace
                    if line not empty line
                        if line is work
                            log it in data object
                        else its another activity
                            if pay value, also log it
            elif begins with an equal sign: #denotes end of day
    else:
        clean up
    f.close()

Full Code (it works):

macron = '¯'
equalSign = '='
underscore = '_'

def read_body(path, month_year):
    '''Reads schedule detail text file and generates pairing data objects for each work day.
        path:   file to open 'monthYEAR.txt'
        date:   MonthYEAREMPNO (month, year, employee number)
                from file header
                '''
    f = open(path)
    tempList = []
    d = WorkDay()
    for line in f:
        tempList = line.rsplit()
        if len(tempList) > 0:
            if macron in tempList[0]:       #begin work day
                #prepare new data object
                d.clear()
                d.month_year(month_year)
                for line in f:
                    tempList = line.rsplit()
                    if len(tempList) > 0:
                        if isWorkingDay(tempList[0]):   #parse tempList[1] date block MM/dd/YYYY
                            d.activity_name(tempList[0])
                            d.date_of_month(tempList[1])
                            line = f.next()
                            tempList = line.rsplit()
                            d.hours_worked(tempList[1])
                            d.pay(tempList[3])
                            break
                        else:       #is other activity (sick, off, vacation, etc), log date/time/pay
                            d.activity_name(tempList[0])   #tempList[0] failed isWorkingDay(), so just print.  Human readable string
                            for line in f:
                                if underscore in line:
                                    break
                                elif 'Credit:' in line:
                                    d.pay(line[8:12])
                            break
            elif equalSign in tempList[0]:   #end work day
                #drop activity object in "write to db" queue
                add_to_db(d)
    else:
        '''end of file, clean up partial data objects.  necessary because schedule text file ends with a macron'''
        #discard d if empty, raise error if non-complete, write to db if complete
        pass
    f.close()


texts: Efficiently counting '1' bits in the first n bits

texts:
I have two functions to count the number of set '1' bits in the first offset bits of either a 64 bit number, or a bitmap struct.

After some profiling, particularly the latter is quite a bottleneck in our system.

What can we do to make it faster?

#define POPCOUNT16(x) __builtin_popcount(x)
#define POPCOUNT64(x) __builtin_popcountl(x)

static __always_inline __constant int32 count64(int64 const bitmap, int32 const offset) {
    return offset == 0 ? 0 : POPCOUNT64(bitmap & (0xffffffffffffffffUL << (64 - offset)));
}

typedef struct {
    int64 hi;
    int16 lo;
} __packed int80;

static __always_inline __constant int32 countBitmap(int80 const bitmap, int32 const offset) {
    int32 count = 0;
    if (offset > 0) {
        count += POPCOUNT64(bitmap.hi & (0xffffffffffffffffUL << (sizeof (bitmap.hi)*8 - MIN(offset, sizeof (bitmap.hi)*8))));
        if (offset > sizeof (bitmap.hi)*8)
            count += POPCOUNT16(bitmap.lo & ((int16)0xffff << (sizeof (bitmap.hi)*8+sizeof (bitmap.lo)*8 - offset)));
    }
    return count;
}


texts: Custom validator for reactive forms angular

texts:
I have created like this validator for reactive form, all working but I think I used so many statements, can somebody help me to make proper validation

Here is my validator

export function validateIfOneIsRequired(): ValidatorFn {
  return function validateIfOneIsRequired(formGroup: FormGroup) {
    const startTime = formGroup.controls.startTime.value;
    const endTime = formGroup.controls.endTime.value;
    if (startTime === '' && endTime === '') {
      return null;
    }
    if (startTime && endTime) {
      return null;
    }

    if (!startTime && endTime) {
      return { startTimeIsRequired: OperationalTime.startTimeIsRequired };
    }

    if (startTime && !endTime) {
      return { endTimeIsRequired: OperationalTime.endTimeIsRequired };
    }
  };
}


texts:
I need to store sensitive strings in DB, so decided to encrypt it in a DB and decrypt it at the application layer. And noticed that it is not so easy to find ready to use an example.  Please check my code below. It is based on this damienbod's topic, but I included IV to the string itself and also want to know if it is production-ready. And a somewhat unrelated question: probably I should use an old Rijndael solution like this?
public class SymmetricEncryptDecrypt
{
    private const int ivBytes = 128;

    public (string Key, string IVBase64) InitSymmetricEncryptionKeyIV()
    {
        var key = GetEncodedRandomString(32); // 256
        using (Aes cipher = CreateCipher(key))
        {
            cipher.GenerateIV();
            var IVBase64 = Convert.ToBase64String(cipher.IV);
            return (key, IVBase64);
        }
    }

    private byte[] GetNewIv()
    {
        using (Aes cipher = CreateCipher(GetEncodedRandomString(32)))
        {
            cipher.GenerateIV();
            return cipher.IV;
        }
    }

    /// <summary>
    /// Encrypt using AES
    /// </summary>
    /// <param name="text">any text</param>
    /// <param name="IV">Base64 IV string/param>
    /// <param name="key">Base64 key</param>
    /// <returns>Returns an encrypted string</returns>
    public string Encrypt(string text, string key)
    {
        var iv = this.GetNewIv();

        using (Aes cipher = CreateCipher(key))
        {
            cipher.IV = iv;

            ICryptoTransform cryptTransform = cipher.CreateEncryptor();
            byte[] plaintext = Encoding.UTF8.GetBytes(text);
            byte[] cipherText = cryptTransform.TransformFinalBlock(plaintext, 0, plaintext.Length);

            return Convert.ToBase64String(iv.Concat(cipherText).ToArray());
        }
    }

    /// <summary>
    /// Decrypt using AES
    /// </summary>
    /// <param name="text">Base64 string for an AES encryption</param>
    /// <param name="key">Base64 key</param>
    /// <returns>Returns a string</returns>
    public string Decrypt(string encryptedText, string key)
    {
        var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encryptedText);

        var ivStringBytes = cipherTextBytesWithSaltAndIv.Take(ivBytes / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip(ivBytes / 8).Take(cipherTextBytesWithSaltAndIv.Length - (ivBytes / 8)).ToArray();

        using (Aes cipher = CreateCipher(key))
        {
            cipher.IV = ivStringBytes;

            ICryptoTransform cryptTransform = cipher.CreateDecryptor();
            byte[] plainBytes = cryptTransform.TransformFinalBlock(cipherTextBytes, 0, cipherTextBytes.Length);

            return Encoding.UTF8.GetString(plainBytes);
        }
    }

    private string GetEncodedRandomString(int length)
    {
        var base64 = Convert.ToBase64String(GenerateRandomBytes(length));
        return base64;
    }

    /// <summary>
    /// Create an AES Cipher using a base64 key
    /// </summary>
    /// <param name="key"></param>
    /// <returns>AES</returns>
    private Aes CreateCipher(string keyBase64)
    {
        // Default values: Keysize 256, Padding PKC27
        Aes cipher = Aes.Create();
        cipher.Mode = CipherMode.CBC; // Ensure the integrity of the ciphertext if using CBC
        cipher.Padding = PaddingMode.ISO10126;
        cipher.Key = Convert.FromBase64String(keyBase64);
        return cipher;
    }

    private byte[] GenerateRandomBytes(int length)
    {
        var byteArray = new byte[length];
        RandomNumberGenerator.Fill(byteArray);
        return byteArray;
    }
}


texts: Grabbing city names and numbers from a CSV file

texts:
I've got information that is imported from a CSV file that my site grabs every day with PHP. I'm just learning RegEx so I'm able to do what I need to do but am looking to get more efficient with my coding.

Some of example of the kinds of strings that would come in would be:

15 SE NORFOLK
5 NNE OAKLAND
1 S LOS ANGELES
1 NW SACRAMENTO
BOSTON

It's basically numbers then directional letters then city name. Sometimes there aren't numbers and letters so I'm checking to see first and then just deleting them with preg_replace if there are (I just need the city name).

Here's the expression I have that works:

$location = preg_replace('/^[\d]+[\s]+[a-zA-z]+[\s]/', '', $string);

I know with regex there are a bunch of different ways to different things so I'm curious if there's a more efficient way to do what I'm doing.


texts:
I've written the following function which reads an authorization header, compares it and returns whether it is valid or not.

The function works correctly:

func Auth(req *http.Request) bool{
    sHeader := strings.SplitN(req.Header.Get("authorization"), " ", 2)
    if sHeader[0] != "" {
        fmt.Printf("sHeader: ", sHeader[1])
        devEnv := os.Getenv("authorization")
        if (devEnv == sHeader[1]) {
            fmt.Println("valid")
            return true
        } else {
            fmt.Println("Not valid: " + sHeader[1])
            return false
        }
    } else {
        log.Fatal("Missing Authorization Header")
        return false
    }
}

What can I improve?


texts: Python functions to fetch spreadsheets through SFTP and from Dropbox

texts:
I have written two functions- first one is to read files from SFTP and second one is to read files from Dropbox.

Both functions have some similar line of code like validating extension and reading/saving file that can be extracted into a separated function and thus need your suggestion how to do it.

PFB my both functions-

class SftpHelper:
    def fetch_file_from_sftp(self, file_name, sheet_name=0):
      valid_extensions = ['csv', 'xls', 'xlsx']
      extension = file_name.split('.')[-1]
      sftp, transport = self.connect_to_sftp()
      remote_path = self.remote_dir + file_name
      data = io.BytesIO()
      sftp.getfo(remote_path, data, callback=None)
      if extension == 'csv':
          file_df = pd.read_csv(io.BytesIO(data.getvalue()))
      else:
          file_df = pd.read_excel(io.BytesIO(data.getvalue()), sheet_name=sheet_name)
      self.close_sftp_connection(sftp, transport)
      return file_df

class DropBoxHelper:
    def read_file_from_dropbox(self, file_name, sheet_name=0):
      valid_extensions = ['csv', 'xls', 'xlsx']
      extension = file_name.split('.')[-1]
      dbx = self.connect_to_dropbox()
      metadata,data=dbx.files_download(file_name)
      if extension == 'csv':
          file_df = pd.read_csv(io.BytesIO(data.content))
      else:
          file_df = pd.read_excel((io.BytesIO(data.content)), sheet_name=sheet_name)
      return file_df

Can anyone please help me to extract the common logix to a seperate function and then use that one in my two functions?


texts:
I have written a fixed-size block allocator implementation and would like some feedback as to what I could improve in my code and coding practices. Your comments or notes are welcomed!

An auxiliary allocator (non-typed, instead unique for the given size of a chunk; without necessary interface for STL containers):

#include <iostream>
#include <list>
#include <vector>

template <size_t ChunkSize>
class TFixedAllocator {
    union TNode { // union
        char data[ChunkSize];
        TNode *next; // free chunks of memory form a stack; pointer to the next (or nullptr)
    };

    TNode *free; // the topmost free chunk of memory (or nullptr)
    std::vector<TNode*> pools; // all allocated pools of memory
    int size = 1; // size of the last allocated pool of memory
    const int MAX_SIZE = 1024;

    void new_pool() { // allocate new pool of memory
        if (size < MAX_SIZE) {
            size *= 2;
        }
        free = new TNode[size];

        // form a stack of chunks of this pool
        pools.push_back(free);
        for (int i = 0; i < size; ++i) {
            free[i].next = &free[i+1];
        }
        free[size-1].next = nullptr;
    }
    TFixedAllocator() { // private for singleton
        new_pool();
    }
public:
    TFixedAllocator(const TFixedAllocator&) = delete; // for singleton
    static TFixedAllocator& instance () { // singleton
        static TFixedAllocator instance;
        return instance;
    }
    void* allocate() {
        if (!free) {
            new_pool();
        }
        TNode* result = free; // allocate the topmost element (saved in free)
        free = free->next; // and pop it from the stack of free chunks
        return static_cast<void*>(result);
    }
    void deallocate(void* elem) {
        TNode* node = static_cast<TNode*>(elem);

        // add to the stack of chunks
        node->next = free;
        free = node;
    }
    ~TFixedAllocator() {
        for (auto ptr : pools) {
            delete ptr;
        }
    }
};

An allocator wrapper for STL containers:

template <class T>
class TFSBAllocator {
public:
    using value_type = T;
    using pointer = T*;
    using const_pointer = const T*;
    using reference = T&;
    using const_reference = const T&;
    template <class U>
    class rebind {
    public:
        using other = TFSBAllocator<U>;
    };

    pointer allocate(size_t n) {
        if (n == 1) {
            return static_cast<T*>(TFixedAllocator<sizeof(T)>::instance().allocate());
        } else {
            return std::allocator<T>().allocate(n);
        }
    }
    void deallocate(pointer p, size_t n) {
        if (n == 1) {
            TFixedAllocator<sizeof(T)>::instance().deallocate(static_cast<void*>(p));
        } else {
            return std::allocator<T>().deallocate(p, n);
        }
    }
    void construct(pointer p, const_reference t) {
        new (p) T(t);
    }
    void destroy(pointer p) {
        p->~T();
    }
};

A tester:

#include <chrono>
using namespace std::chrono;

template <class List>
void test(std::string comment, List l) {
    std::cout << comment;
    auto start_time = high_resolution_clock::now();
    for (int i = 0; i < 1e7; ++i) {
        l.push_back(i);
    }
    auto end_time = high_resolution_clock::now();
    std::cout << duration_cast<milliseconds>(end_time - start_time).count() << "ms" << std::endl;
}

int main() {
    // CodeBlocks 12.13, Release mode
    test("std::allocator: ", std::list<int>()); // std::allocator: 1816ms
    test(" TFSBAllocator: ", std::list<int, TFSBAllocator<int>>()); // TFSBAllocator: 204ms
}

By the way, what is about thread-safety?


texts:
I have a panel that has 4 images per row and a lot of rows. Each image has a 15 pixels separation and are 250,250 each.

Here is a screenshot:

I'd like to be able to click on a picture and identify the image number (from 0 top left to the right). Of course, avoiding the separation.

  protected override void OnMouseClick(MouseEventArgs e)
    {
        vsValue = VerticalScroll.Value;
        // what row ?
        double ScrollVposition = vsValue + e.Y;
        double row = Math.Floor(ScrollVposition / (BitmapHeight + BitmapSpacing)); // it's the right row, unless i clicked on the spacing
        int topEdge = ((BitmapHeight + BitmapSpacing) * (int)row) + BitmapSpacing; // the Y coordinate of the top of the image
        int bottomEdge = topEdge + BitmapHeight; // the bottom of that same image
        if (ScrollVposition < bottomEdge && ScrollVposition > topEdge) // check if the click happens between the top and the bottom of the image
        { } // row is the right row number
        else row = -1; // not an image
        // what column ? same logic as the row
        double width = e.X;
        double col = Math.Floor(width / (BitmapWidth + BitmapSpacing));
        col = Math.Min(col, perCol-1); // got space after the last col on the right
        int leftEdge = ((BitmapWidth + BitmapSpacing) * (int)col) + BitmapSpacing;
        int rightEdge = leftEdge + BitmapWidth;
        int ima;
        if (width < rightEdge && width > leftEdge && row >= 0)
            ima = ((int)row * perCol) + (int)col;
        else ima = -1;
        picture_id = ima;

        base.OnMouseClick(e);

    }

Do you think I can improve it?

EDIT : Here is the paint event :

        base.OnPaint(e);
        e.Graphics.TranslateTransform(this.AutoScrollPosition.X,
                       this.AutoScrollPosition.Y);
        First_id = getTopPictureId(VerticalScroll.Value);
        int buffer = 20;
        int limithaute = Math.Min(First_id + buffer, fp.Count());
        for (int i = First_id; i < limithaute; i++) //
        {
            System.Drawing.Image img = GetImage(fp[i]);
            e.Graphics.DrawImage(img, new PointF(BitmapSpacing + (BitmapSpacing * (i % perCol) + (BitmapWidth * (i % perCol))),
                BitmapSpacing + (BitmapSpacing * (i / perCol)) + (BitmapHeight * (i / perCol))));
       }

A bit of explanation, the for loop goes through the images i'd like to show (the list of 3000+ total, the scrolling have a disposition process). Fp is the list of files that contains the images.


texts: Program that provides diagrams for documentation

texts:
The general problem I'm trying to solve is that I have a code base that has zero documentation so I'm trying to automatically generate some diagrams of classes in package that I'm analyzing using erdantic.
Trying to make this as reusable as possible, so I have a generate_diagrams() function that should take in one argument, which is the package I want to iterate through.
I often feel like I throw the terms module and package around interchangeably — I might be doing it now — so I defaulted my argument to the name "directory".  But I feel that's not right since I'm not passing in a path.
Should I change the argument in generate_diagrams() below? What's a more accurate name?
import erdantic as erd
import glob
import importlib
import example.models

from os import path, makedirs

def draw_diagram(module, cls_name, output_path):
    """

    Args:
        module: module object
        cls_name: name of the class that's associated with  the module
        output_path: path where diagram to be saved

    Returns:
        void - outputs .png file at given path

    """
    try:
        diagram = erd.create(module.__getattribute__(cls_name))
        diagram.models
        diagram.draw(f"{output_path}/{cls_name}.png")

    except erd.errors.UnknownModelTypeError:
        pass

def generate_diagrams(directory):
    """

    Args:
        directory: package you have imported that contains module(s) you wish to diagram

    Returns:
        void - generates diagram using draw_diagram function

    """

    doc_path = path.dirname(__file__)
    modules = glob.glob(path.join(path.dirname(directory.__file__), "*.py"))
    module_names = [path.basename(f)[:-3] for f in modules if path.isfile(f) and not f.endswith('__init__.py')]

    for module_name in module_names:

        if not path.exists(path.join(doc_path, module_name)):
            print(f'Making {module_name} directory')
            makedirs(module_name)

        module = importlib.import_module(f'{directory.__name__}.{module_name}')
        classes = dict([(name, cls) for name, cls in module.__dict__.items() if isinstance(cls, type)])

        for name, cls in classes.items():
            print(f'Drawing {module_name}.{name} diagram')
            draw_diagram(module, cls_name=name, output_path=path.join(doc_path, module_name))

def main():
    generate_diagrams(directory=example.models)

if __name__ == "__main__":
    main()


texts: Sum the remainders of ai%aj given an array "a"

texts:
Given an array of numbers, I am creating a table where, the cell at the intersection of row i and column j contains a number ai % aj.
Numbers in the array can occur multiple times.

Example:
For numbers = [2, 5, 3, 3, 5], the output should be 32.
Here is the table that gets created:

  | 0 1 2 3 4
--------------
0 | 0 2 2 2 2
1 | 1 0 2 2 0
2 | 1 3 0 0 3
3 | 1 3 0 0 3
4 | 1 0 2 2 0

The sum of its elements is 32.

Guaranteed constraints:
1 ≤ numbers.length ≤ 10^5,
1 ≤ numbers[i] ≤ numbers.length.

function sumOfRemainders($numbers) {
    $resSum = 0;
    $len = count($numbers);

    if($len == 1)
        return 0;

    for($i=0; $i<$len; $i++)
        for($j=0; $j<$len; $j++)
            $resSum += $numbers[$i]%$numbers[$j];
    return $resSum;
}

The code works and is of course a brute force approach, but will take huge amount of time for large inputs, or will timeout in case of any testing environment.

How can I possibly make my code faster?
Any suggestions are most appreciated.


texts:
Challenge:

  Check if a string (first argument, str) ends with the given target
  string (second argument, target).

  This challenge can be solved with the .endsWith() method. But for the
  purpose of this challenge, do not use it.

I would like to especially have my solution critiqued.

function confirmEnding(str, target){
  let lengthOfString = str.length;
  let lengthOfTarget = target.length;
  let subtractLengths = lengthOfString - lengthOfTarget;
  let lastIndexOfString = str.lastIndexOf(target);

  if(str.includes(target) === true){
    if(lastIndexOfString === subtractLengths){
      return true;
    }
    else{
      return false;
    }
  }
  else{
    return false;
  }
}

Test Cases:

confirmEnding("Bastian", "n") should return true.
Passed
confirmEnding("Congratulation", "on") should return true.
Passed
confirmEnding("Connor", "n") should return false.
Passed
confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.
Passed
confirmEnding("He has to give me a new name", "name") should return true.
Passed
confirmEnding("Open sesame", "same") should return true.
Passed
confirmEnding("Open sesame", "pen") should return false.
Passed
confirmEnding("Open sesame", "game") should return false.
Passed
confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") should return false.
Passed
confirmEnding("Abstraction", "action") should return true.


texts:
Kata: https://www.codewars.com/kata/find-the-unknown-digit/train/python

  To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.

  You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest.

  The professor will give you a simple math expression, of the form

[number][op][number]=[number]

  He has converted all of the runes he knows into digits. The only operators he knows are addition (+),subtraction(-), and multiplication (*), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number.

  Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case.

  Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists.

My Solution

import re, operator as op

parse_op = re.compile(r"(-?[0-9?]+)([-+*])(-?[0-9?]+)(=)(-?[0-9?]+)")  #For parsing the LHS.
ops = {"*": op.mul, "+": op.add, "-": op.sub}

def solve_runes(s):
    search = set("0123456789") - set(c for c in s if c.isnumeric())
    n = [0]*3
    n[0], op, n[1], x, n[2] = parse_op.search(s).groups()
    if any(len(x) > 1 and x[0] == "?" for x in n):
        search -= {"0"}
    for digit in sorted(search):
        v = [int(x.replace("?", digit)) for x in n]
        if ops[op](v[0], v[1]) == v[2]:
            return int(digit)
    return -1

Sample Test Case

test.assert_equals(solve_runes("1+1=?"), 2, "Answer for expression '1+1=?' ")
test.assert_equals(solve_runes("123*45?=5?088"), 6, "Answer for expression '123*45?=5?088' ")
test.assert_equals(solve_runes("-5?*-1=5?"), 0, "Answer for expression '-5?*-1=5?' ")
test.assert_equals(solve_runes("19--45=5?"), -1, "Answer for expression '19--45=5?' ")
test.assert_equals(solve_runes("??*??=302?"), 5, "Answer for expression '??*??=302?' ")
test.assert_equals(solve_runes("?*11=??"), 2, "Answer for expression '?*11=??' ")
test.assert_equals(solve_runes("??*1=??"), 2, "Answer for expression '?*11=??' ")


texts: Convert sorted linkedlist into balanced binary search tree

texts:
Convert a sorted linkedlist into a balanced binary search tree. Looking for code-review, optimizations, and best practices.

public class SortedLinkedListToBalancedBST<T> {

    private TreeNode<T> root;

    private static class TreeNode<T> {
        TreeNode<T> left;
        T item;
        TreeNode<T> right;
    };

    public void convert(LinkedList<T> ll) {
        Iterator<T> itr = ll.iterator();
        root = inorder(0, ll.size() - 1, itr);
    }

    private TreeNode<T> inorder(int lb, int hb, Iterator<T> itr) {
        if (lb > hb) return null;
        // same as (lb+hb)/2, avoids overflow
        int mid = lb + (hb - lb) / 2;

        final TreeNode<T> treeNode = new TreeNode<T>();
        treeNode.left = inorder(lb, mid - 1, itr);
        treeNode.item = itr.next();
        treeNode.right = inorder(mid + 1, hb, itr);

        return treeNode;
    }

    public List<T> getInorderList() {
        final List<T> inorderList = new ArrayList<T>();
        inorder(root, inorderList);
        return inorderList;
    }

    private void inorder(TreeNode<T> node, List<T> list) {
        if (node != null) {
            inorder(node.left,  list);
            list.add(node.item);
            inorder(node.right, list);
        }
    }
}

public class SortedLinkedListToBalancedBSTTest {

    @Test
    public void testOne() {
        SortedLinkedListToBalancedBST<Integer> s = new SortedLinkedListToBalancedBST<Integer>();
        LinkedList<Integer> list1 = new LinkedList<Integer>(Arrays.asList(1, 2, 3, 4));
        s.convert(list1);
        assertEquals(list1,  s.getInorderList());
    }

    @Test
    public void testTwo() {
        SortedLinkedListToBalancedBST<Integer> s = new SortedLinkedListToBalancedBST<Integer>();
        LinkedList<Integer> list2 = new LinkedList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
        s.convert(list2);
        assertEquals(list2,  s.getInorderList());
    }

    @Test
    public void testThree() {
        SortedLinkedListToBalancedBST<Integer> s = new SortedLinkedListToBalancedBST<Integer>();
        LinkedList<Integer> list3 = new LinkedList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6));
        s.convert(list3);
        assertEquals(list3,  s.getInorderList());
    }

    @Test
    public void testFour() {
        SortedLinkedListToBalancedBST<Integer> s = new SortedLinkedListToBalancedBST<Integer>();
        LinkedList<Integer> list4 = new LinkedList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        s.convert(list4);
        assertEquals(list4,  s.getInorderList());

    }
}


texts: Fractional binary number to decimal number

texts:
Write and test your own double abc (char * b) function in the program, taking in the form of a string the fractional binary number of the form "1101.101" and returning an equal decimal number (here 1 * 2 ^ 3 + 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0 + 1 * 2 ^ -1 + 0 * 2 ^ -2 + 1 * 2 ^ -3 = 8 + 4 + 0 + 1 + 0.5 + 0 + 0.125 = 13.625). The function should return the special value -1 if an incorrect fractional binary number is entered (e.g. containing a different digit than 0, 1 or more than one period '.').

My solution:

#include <iostream>
#include <cmath>
using namespace std;
double abc(char* b);
int main() {
cout <<  abc("1101.101");
return 0;
}

double abc(char* b){
int i = 0;
int a = 0;
int dot = 0;
double sum=0;
int c = 0;
do{
    if ((b[a]=='1')||(b[a]=='0')||(b[a]=='.')){
        a++;
        if(b[a]=='.'){
            dot++;
        }
        if(dot==2){
            return -1;
        }
    } else {
        return -1;
    }
} while(b[a]!='\0');

while(b[i]!='.'){
    i++;
}
while(i!=0) {
    if(b[c]=='1'){
        sum = sum + pow (2, i-1);
    }
    c++;
    i--;
}
while(b[i]!='.'){
    i++;
}
if(b[i]=='.'){
    int m = 0;
    while(b[i]!='\0'){
        if(b[i]=='1'){
            sum = sum + pow (2, m);
        }
        m = m - 1;
        i++;
    }
}
return sum;
}

Problem:
Everything is fine, it gives me 13.625, but there is a lot of code. Is there any faster way to solve this exercise?


texts: Determine if an array is the reverse of a second array

texts:
I tried to do it by using ArrayUtils.reverse() but I couldn't figure out how to compare this with the other array. So I wrote this instead:

public class Main {

  public static void main(String[] args) {

int[] array = new int[] {1, 2, 3, 4, 5, 6};

int[] tempArray = new int[] {6, 5, 4, 3, 2, 1};

boolean result = true;

for (int i = 0; i < array.length / 2; i++) {
  int temp = array[i];
  array[i] = array[array.length - i - 1];
  array[array.length - i - 1] = temp;
}

for (int i = 0; i < array.length; i++) {
  if (array[i] != tempArray[i]) {
    System.out.println("nope,not reversed");
    result = false;
    break;
  }
}

if (result) {
  System.out.println("yep,reversed");
}
  }
}

Is there a simpler solution? I'm skeptic because I think breaking the loop and setting a boolean value is a bit unnecessary.


texts: How to fill in this HashMap neatly without code duplication?

texts:
I'm supplying a HashMap with data in the following way:

HashMap<String,MyClass> myHashMap = new HashMap<String,MyClass>();
myHashMap.put( "foo", new MyClass(2,4) );
myHashMap.put( "bar", new MyClass(0,10) );
myHashMap.put( "a",   new MyClass(0,0) );
myHashMap.put( "b",   new MyClass(0,1) );
myHashMap.put( "c",   new MyClass(0,0) );
myHashMap.put( "d",   new MyClass(0,42) );
// ...

There's around 20 lines, but a lot is duplicated text. The only interesting information in every line is foo,2,4, bar,0,10, a,0,0 and so on. How can I make this code neater?

If only the strings differed, I'd do it this way:

List<String> names = Arrays.aslist("foo","bar","a","b","c","d");
for ( String name : names )
    myHashMap.put( name, new MyClass(0,0) );


texts: Simple class to let a thread make a clean work

texts:
I was working on the last days with threads and I didn't want to use ugly methods like Abort(), etc.

So I did a simple class which does use one of the most performant and better alternative to Abort(). The class is named as CThread.cs which would stand for CleanThread.cs.

Class code:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class CThread
{
    public List<CancellationTokenSource> CreatedThreads = new List<CancellationTokenSource>();

    private void MyFunction(Action callback, bool inLoop, int currentIndex)
    {
        if (inLoop)
        {
            while (!CreatedThreads[currentIndex].IsCancellationRequested)
            {
                callback();
            }
        }
        else { callback(); }
    }

    private int getLastIndex()
    {
        int index = 0;
        foreach (CancellationTokenSource item in CreatedThreads)
        {
            ++index;
        }

        return (index - 1);
    }

    public new void Start(Action callback, bool inLoop)
    {
        CancellationTokenSource tokenSource = new CancellationTokenSource();

        CreatedThreads.Add(tokenSource);
        int currentIndex = getLastIndex();
        Task task = Task.Run(() => MyFunction(callback, inLoop, currentIndex)); // use Task.Factory.StartNew for .net 4.0
    }

    public new void Stop(int threadIndex)
    {
        CreatedThreads[threadIndex].Cancel();
        Console.WriteLine("Thread has been stopped successfully! Press any key to continue...");
        Console.ReadKey();
    }
}

and finally, how I use it:

using System;

namespace CThreadExample
{
    internal class Program
    {
        private static void printFunction()
        {
            Console.WriteLine("Hello world!");
            System.Threading.Thread.Sleep(120);
        }

        private static void Main(string[] args)
        {
            CThread myThread = new CThread();
            myThread.Start(printFunction, true);

            // when the user presses any key the thread will be stopped
            Console.ReadKey();
            myThread.Stop(0); // stops the thread 0
        }
    }
}

Well, as you can see I'm not able right now to start threads using multiple parameters, but I didn't need to pass parameter to my thread.

Since I want to make everything clean, I accept any suggestion to improve this, also small suggestions for the code to make me able to pass one, two or more parameters and for cross-threading too (the Control.CheckForIllegalCrossThread = false; alternative way - so using delegates with Invoke() or BeginInvoke()).


texts: Gather first letter from each string in a list of strings

texts:
I'm learning Haskell on my own, and I'm wondering if this is idiomatic Haskell.

In particular: is it a common pattern to "wrap" the result in a list in order to make a function total? (that's what I ended up doing to ensure the function was total and no compiler warnings about not matching a pattern).

safeHead :: [a] -> Maybe a
safeHead []     = Nothing
safeHead (x:_)  = Just x

firstLetters :: [String] -> [Char]
firstLetters ss = concat $
                     map (\s -> case safeHead s of
                                Nothing -> []
                                Just c  -> [c]) ss


texts:
I wrote this CRUD in Node. I know several things, for example, the parsing body can be simplified, but I would like to ask you to give me feedback from the point of view of error handling. Are errors handled well?

Other feedback is also welcome but please keep in mind I am beginner with node.

I will not post the database layer, let's assume it works.

const express = require('express');
const app = express();
const db = require('./database');

var userDatabase = new db.CreateUserDatabase();

app.get('/users', function (req, res) {

    var users = userDatabase.listUsers();
    res.send(users);

});

// Get user with some ID
app.get('/users/:id',function (req, res) {

    var user = userDatabase.find(req.params.id);
    res.send(user);

});

// Add handler for user add method.
app.post('/users', function (req, res) {

    //
    // Parse request body
    //
    var bodyStr = '';

    req.on("data",function(chunk){
        bodyStr += chunk.toString();
    });

    req.on("error", function(){
        throw new Error("Some error occured during user adding.");
        return;
    });

    req.on("end",function(){
        console.log(bodyStr);
        var requestJSON = JSON.parse(bodyStr);

        // Call function to create new user.
        userDatabase.addUser(requestJSON.name, requestJSON.surname);

        res.send("OK");
    });

});

// Add handler for user edit.
app.put('/users/:id', function (req, res) {

    //
    // Parse request body
    //
    var bodyStr = '';

    req.on("data",function(chunk){
        bodyStr += chunk.toString();
    });

    req.on("error", function(){
        throw new Error("Some error occured during user editing.");
        return;
    });

    req.on("end",function(){

        // The new user details should be send in the body as JSON. Only name and surname.
        var requestJSON = JSON.parse(bodyStr);

        // Call update method.
        var user = userDatabase.update(req.params.id, // ID is present in the URL.
                                       requestJSON.name,
                                       requestJSON.surname);

        // Send OK.
        res.send("OK");
    });

});

app.delete('/users/:id', function (req, res) {
    var user = userDatabase.delete(req.params.id);
    res.send(user);
});

app.listen(8000, function()
{
    console.log("Listening on port:8000");
})

OK here is also database layer

// Create user instances
function User(name, surname, id)
{
    this.name = name;
    this.surname = surname;
    this.id = id;
}

// Our database instance
function UserDatabase()
{
    this.index = 0;
    this.userDatabase = {};
}

UserDatabase.prototype.addUser = function(name, surname)
{
    var user = new User(name, surname, this.index++);
    this.userDatabase[user.id] = user;
}

// Return all users
UserDatabase.prototype.listUsers = function()
{
    return this.userDatabase;
}

// Find user by ID
UserDatabase.prototype.find = function(id)
{
    return this.userDatabase[id];

}

// Update user using ID.
UserDatabase.prototype.update = function(id, name, surname)
{
    var user = this.userDatabase[id];

    user.name = name;
    user.surname = surname;

}

// Delete user by ID
UserDatabase.prototype.delete = function(id)
{
    delete this.userDatabase[id];

}

exports.CreateUserDatabase = UserDatabase;


texts: Extending Exception: avoiding code duplication

texts:
I'm implementing a REST API in PHP 7.1. It is designed to throw Exceptions to print non-200 responses.

I decided to go with the following:

abstract class APIException extends \Exception
{
    public function __construct($message, $code, Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }

    public function parseException() {
        return ResponseParser::parseResponse($this->message, $this->code);
    }
}

And then I extended the BaseException with my various personal exceptions, like IncorrectMethodException here.

class IncorrectMethodException extends APIException
{
    public function __construct(String $expectedMethod, Exception $previous = null) {
        parent::__construct("Incorrect method, $expectedMethod expected", 405, $previous);
    }
}

Here is the code to my ResponseParser class:

class ResponseParser
{
    /**
     * @param $data
     * @param int $status
     * @return string
     */
    public static function parseResponse($data, $status = 200)
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: *");
        header("Content-Type: application/json");
        header("HTTP/1.1 " . $status . " " . self::_requestStatus($status));
        return json_encode($data);
    }

    /**
     * @param $code
     * @return string status code
     */
    private static function _requestStatus($code)
    {
        $status = array(
            200 => 'OK',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            500 => 'Internal Server Error',
        );
        return ($status[$code]) ? $status[$code] : $status[500];
    }
}

Is this a correct way to avoid code duplication here?


texts:
I'm wondering how I could improve my list's element-adding speed or just the whole list implementation.

The adding function first checks if the object is unique. If not, it will just check if the new data is better (the lower the value, the better) than the old one, then swap the values or just skip adding an element.

I have no idea how to make it work faster, but I know that something here is probably done terribly wrong. I need to use that list to add about 3 million elements in less than 4 seconds.

Note: Using std::string in my project is unfortunately forbidden.

#include <iostream>
struct node
{
    long shortestRoute;
    char* name;
    node *next;
    node()
    {
        next = 0;
    }
};
class List  {
public:
    node *first;
    List() { first = 0 ;}
    void add(long shortestRoute, char* name)
    {
        node *node = new node;
        node->name = name;
        node->shortestRoute = shortestRoute;
        if(first == 0)
            first = node;
        else
        {
            node *temp = first;
            while(temp)
            {
                if(!strcmp(temp->name, name) && temp->shortestRoute > shortestRoute)
                {
                    temp->shortestRoute = shortestRoute;
                    return;
                }
                else if (!strcmp(temp->name, name))
                    return;
                else if(temp->next)
                    temp = temp->next;
                else
                    break;
            }
            temp->next = node;
            node->next = 0;
        }
    }
    int size()
    {
        node *temp = first;
        int size;
        if(!first)
            size = 0;
        else
            size = 1;
        while(temp->next)
        {
            ++size;
            temp = temp->next;
        }
        return size;
    }
};
struct City
{
    City() { fastConnection = true; }
    int shortestRoute;
    char* name;
    Vector<char*> citiesSoFar;
    bool fastConnection;

};


texts: Checking if a file exists then do something if it's not a directory

texts:
While I'm aware that code with callbacks tends to be complex, I'm wondering if there are any patterns or something to improve my situation.

All I do here is check if a file exists and then print its name if it's not a directory:

var fs = require('fs'),
    filename = process.args[2];

fs.exists(filename, function(exists) {
  if (exists) {
    fs.stat(filename, function(err, stats) {
      if (stats.isDirectory()) {
        console.log(filename + ": is a directory");
      } else {
        // do something with file
        console.log(filename);
      }
    });
  } else {
    console.log(filename + ": no such file");
  }
});


texts: Given an array of strings, group the anagrams together

texts:
Scan the array of strings, for each string get the code(which is nothing but the summation of char values of the string) and add the string to TreeSet<String> corresponding to the code if the code exists in the hashmap and if the string is an anagram with the first string in the TreeSet corresponding to the code else create a new TreeSet<String> and add the string to it and put it in the HashMap<Integer, TreeSet<String>>. Finally convert the all the sets in the HashMap to list of lists and return the same.

import java.util.Arrays;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class Anagrams {
    public static boolean anagramsHelper(String[] words) {
        for (int i = 1; i < words.length; i++) {
            if (!areAnagrams(words[0], words[i])) {
                return false;
            }
        }
        return true;
    }

    public static boolean areAnagrams(String word1, String word2) {
        if (word1.length() != word2.length()) {
            return false; // anagrams are strings with same length
        }
        int[] charCount = new int[128]; // 128 unique chars in ASCII
        // count the chars in word1
        for (int i = 0; i < word1.length(); i++) {
            charCount[(int) word1.charAt(i)]++;
        }
        // decrement the char count for chars in word2
        for (int i = 0; i < word2.length(); i++) {
            if (charCount[(int) word2.charAt(i)] == 0) {
                return false;
            }
            charCount[(int) word2.charAt(i)]--;
        }
        // verify if any char count is non zero
        // for anagrams it should be zero else they are not anagrams
        for (int i = 0; i < 128; i++) {
            if (charCount[i] != 0) {
                return false;
            }
        }
        return true;
    }

    public static List<List<String>> groupAnagrams(String[] words) {
        Map<String, TreeSet<String>> anagramsGroup = new HashMap<String, TreeSet<String>>();
        TreeSet<String> listOfAnagrams;
        String keyValue;
        for (String word : words) {
            char[] charsInWord = word.toCharArray();
            Arrays.sort(charsInWord);
            keyValue = String.valueOf(charsInWord);
            if (anagramsGroup.containsKey(keyValue)) {
                listOfAnagrams = anagramsGroup.get(keyValue);
                if (areAnagrams(word, listOfAnagrams.first())) {
                    listOfAnagrams.add(word);
                    anagramsGroup.put(keyValue, listOfAnagrams);
                }

            } else {
                listOfAnagrams = new TreeSet<>();
                listOfAnagrams.add(word);
                anagramsGroup.put(keyValue, listOfAnagrams);
            }

        }
        List<List<String>> groupsOfAnagrams = new ArrayList<List<String>>();
        for (Set<String> setOfAnagrams : anagramsGroup.values()) {
            List<String> anagramsList = new ArrayList<>(setOfAnagrams);
            groupsOfAnagrams.add(anagramsList);
        }
        return groupsOfAnagrams;
    }

    public static void main(String[] args) {
        String[] words = { "man", "elephand", "nam", "viswa", "v", "i",
                "handelep", "aba", "baa", "aab", "xyz", "yyy" };
        System.out.println(groupAnagrams(words));
    }
}


texts:
I am working on some code that will generate a link with a relativly unique 10 character hash.  I am not worried to much about colisions as long as they are rare enough that I could have a couple thousand links out standing since I soft delete after they are used and a colision between an open item and a closed item is not an issue.  I would also like the method to be deterministic, the same input generates the same output so worst case I can recalculate the hash if needed.  Here is the code I have and it works but am wondering if there is a better way.

string input = //Some input text that includes the datetime the hash was created;

using (SHA1Managed sha1 = new SHA1Managed())
{
    var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));

   //make sure the hash is only alpha numeric to prevent charecters that may break the url
   return string.Concat(Convert.ToBase64String(hash).ToCharArray().Where(x => char.IsLetterOrDigit(x)).Take(10));
}


texts:
I am learning Java Collections Framework. Can someone look at this code for generating all subsets of a given set and tell me any issues with it.

import java.util.*;
public class AllSubsets {
    public static void main(String[] args) {
        Set<Integer> original = new HashSet<Integer>();
        for (int i = Integer.parseInt(args[0]); i > 0; i--) {
            original.add(i);
        }
        System.out.println(generateAllSubsets(original));
    }

    public static HashSet<HashSet<Integer>> generateAllSubsets(Set<Integer> original) {

        HashSet<HashSet<Integer>> allSubsets = new HashSet<HashSet<Integer>>();

        allSubsets.add(new HashSet<Integer>()); //Add empty set.

        Iterator it = original.iterator();
        while(it.hasNext()) {
            Integer element = (Integer) it.next();

            //Deep copy all subsets to temporary power set.
            HashSet<HashSet<Integer>> tempClone = new HashSet<HashSet<Integer>>();
            for (HashSet<Integer> subset : allSubsets) {
                tempClone.add((HashSet<Integer>)subset.clone());
            }

            //All element to all subsets of the temporary power set.
            Iterator it2 = tempClone.iterator();
            while(it2.hasNext()) {
                Set<Integer> s = (HashSet<Integer>) it2.next();
                s.add(element);
            }

            //Merge both power sets.
            allSubsets.addAll(tempClone);
        }
        return allSubsets;
    }
}


texts: Split Inputvalue into 2 hex encoded bytes if Input>255

texts:
I'm assigning a HEX-Value to a byte in a byte array and then send this byte array to a serial port. If the value is bigger than 255 the corresponding HEX-Value is supposed to be split into two.

Example: 750 = 0x2EE so A[0] = 0x2 and A[1] = 0xEE

Is this an efficient way to do the task that I want it to do? From what I read so far the conversion should be okay here or can I skip the 0x and still get the same result after the Convert.ToByte?

    private void button3_Click(object sender, EventArgs e)
    {
        byte[] A = new byte[2];
        string f = "0x" + Convert.ToInt32(textBox3.Text).ToString("X");
        textBox2.Text = Convert.ToString(f.Length);  //to test length
        if (f.Length < 5)
        {
            A[0] = 0x00;
            A[1] = Convert.ToByte(f,16);
            textBox1.Text = "A";
        }
        else if (f.Length == 5)
        {
            A[0] = Convert.ToByte(f.Substring(0,3),16);
            A[1] = Convert.ToByte("0x" + f.Substring(3),16);
            textBox1.Text = "B" + "Sub0: " + f.Substring(0, 3) + "\r\n Sub1 :" + "0x" + f.Substring(3); //to test
        }
        else
        {
            textBox1.Text = "Falsche Eingabe";
        }
    }


texts:
I've written a Python script that randomly selects radio buttons for each question, and submits the google form. My main questions for improvement are:

Algorithm: I collect all the buttons into a 2D array, then use random.choice to select the radio buttons based on each nested array. I'm sure there's a better way to do this, since my algorithm is basically hard coded.
Performance: I know random.choice takes a lot more time than other methods, but it's the only way I know enough to write with it.
Wait Time: Right now, I wait .75 seconds before entering in another form. I'm wondering if there's a way to wait for the page to load completely, rather than wait and hope that it loads fast enough to not generate a page not found error.

script.py

#run with python3
from selenium import webdriver
import random
import time

#Setup paths and open chrome browser
chrome_path = "desktop/code/python/driver/chrome/chromedriver"
website_path = "https://docs.google.com/forms/d/e/1FAIpQLSdcWrIYQlNbywuLg276z0CbBw-GyQOj_s2ncR9qVA7F7FPARQ/viewform"
driver = webdriver.Chrome(chrome_path)
driver.get(website_path)

#Define options based on each section

#EXCEPT: 9 18 25 28 31 (for text areas)
options = [
    [0, 1, 2, 3],
    [4, 5, 6],
    [7, 8],
    [10, 11],
    [12, 13, 14, 15],
    [16, 17],
    [19, 20, 21],
    [22, 23, 24],
    [26, 27],
    [29, 30],
    [32, 33]
]

#Main loop
def main(counter):
    count = counter + 1

    #Collect all buttons on page and submit button
    buttons = driver.find_elements_by_xpath("//*[@class='freebirdFormviewerViewItemsRadioOptionContainer']")
    submit = driver.find_element_by_xpath("//*[@class='quantumWizButtonPaperbuttonLabel exportLabel']")

    """
    Randomly chooses an option from the 2D array based on what i is, and that
    number is the index of `buttons`, which the button in that index will be clicked
    """
    for i in range(len(options)):
        buttons[random.choice(options[i])].click()

    #Submit form
    submit.click()

    #Go to previous page, which will be the form
    driver.execute_script("window.history.go(-1)")

    #Output how many forms have been submitted thus far
    print(f"Form #{count} has been submitted!")

    #Wait for page to load again, then call main to run again
    time.sleep(.75)
    main(count)

if __name__ == '__main__':
    main(0)


texts: JavaScript - Does this bookmarklet need some optimization?

texts:
I'm working on JavaScript bookmarklet that lets users send a text and link to a site.
This is the bookmarklet:
javascript:(function(){new_script=document.createElement('SCRIPT');new_script.src='http://bookmarklet.example.com/js/bookmarklet.js?v=1';document.getElementsByTagName('head')[0].appendChild(new_script);new_script.type='text/javascript';})();

This is the JavaScript for it:
if(frames.length>0){
      F=' (Frames not supported)'
  } else {
      F=''
  }
  Q=document.getSelection();
  if(!Q){
 void(Q=prompt('Enter a text...'+F+'',''))
  };
  if(Q){
      void (window.open('http://www.example.com/add?url='+encodeURIComponent(window.location)+'&text='+escape(Q)+'&title='+encodeURIComponent(document.title)))
  }

It's the first time I'm using JavaScript, so I would love to hear your feedback on the code. Is there anything that needs to be optimized?
Thanks.
Patrick


texts:
To get used to Haskell, I wrote a little program using the Diagrams package which generates 100 random dots (larger dots are more likely to be in the center).

Sample output:

My questions:

Is the program well structured with respect to the IO monad and the random values (see types for randomDot and randomDots)? Should I organize the code differently to keep more code out of the IO monad?
Other nitpicks?

module Main (main) where

import Data.Colour.SRGB
import Data.Random.Source
import Diagrams.Backend.SVG.CmdLine
import Diagrams.Prelude
import qualified Data.Random as R

data Dot = Dot { _dotCenter :: R2
               , _radius :: Double
               , _color :: Colour Double
               } deriving Show

colors :: [Colour Double]
colors = map sRGB24read [
          "bf3131",
          "f5b456",
          "a89178",
          "615b5b",
          "add274",
          "b9a1b9",
          "f0a2bc",
          "eb565c",
          "d15f69",
          "48bdbe",
          "f1ede2"]

-- |Generate a single dot with random location, radius, and color.
randomDot :: Double -> R.RVar Dot
randomDot x = do
  let mu_rad = 15 * exp (-4 * x)
      sigmaSq_rad = 0.3 * mu_rad
      sigmaSq_loc = 8 * exp (2.5*x)
  locX <- R.sample (R.normal 0 sigmaSq_loc)
  locY <- R.sample (R.normal 0 sigmaSq_loc)
  radius <- abs <$> R.sample (R.normal mu_rad sigmaSq_rad)
  color <- R.sample (R.randomElement colors)
  return $ Dot (r2 (locX, locY)) radius color

-- |Recursively generate random dots and check that they do not
-- overlap.
randomDots :: [Dot] -> [Double] -> IO [Dot]
randomDots dots [] = return dots
randomDots dots (x:xs) = do
  dot <- R.sample $ randomDot x
  if any (tooClose dot) dots
  then randomDots dots (x:xs)
  else randomDots (dot:dots) xs

tooClose :: Dot -> Dot -> Bool
tooClose x y = dist < 1.1 * radiusSum
    where
      dist = magnitude $ _dotCenter x ^-^ _dotCenter y
      radiusSum = _radius x + _radius y

dotsToDiagram :: [Dot] -> Diagram B R2
dotsToDiagram = mconcat . map fromDot

fromDot :: Dot -> Diagram B R2
fromDot c = circle (_radius c) # fc (_color c)
                               # lw none
                               # translate (_dotCenter c)

main :: IO ()
main = mainWith . dotsToDiagram =<< randomDots [] [0.01, 0.02..1.0]


texts: AngularJS constants depending on other constants - any established patterns?

texts:
I'd like to be able to define Angular constants in terms of other constants.

It's not possible to inject dependencies into Angular constant services.  When I want one of my constants to depend on another of my constants, I use a provider service.  This allows my constants to have dependencies (on other constants), but still be used in my .config method call.

This sets off my code smell for two reasons.

I'm using a full-blown call to provider when I'm really just defining a constant.  It's just that some constants are defined in terms of other constants, and I want to be able to use any of these constants in my .config call.
I'm injecting providers into my .config call and then manually calling their $get methods.  This seems to just be bypassing some of the tools Angular gives me.  It seems to me if I'm calling $get in my own code, it may be a sign that I'm fighting the framework.

Here's some sample code that shows the above in action.  It defines a constant service that's an enumeration type, then it defines another constant service that depends on the enumeration type, and last it calls the .config method, injecting the dependent constant service:

app.constant('authLevel', {
    Public: "Public",
    Admin: "Admin",
    SuperAdmin: "SuperAdmin"
});

app.provider("routes", function (authLevel) {

    var routes = [
        {
            path: "/",
            controller: "mapsController",
            templateUrl: "templates/mapsView.html",
            navBarLabel: "LEFT_NAV_BAR.MAPS_NAV_LABEL",
            navBarIconClass: "fa-map-marker",
            authLevels: [authLevel.Public, authLevel.Admin, authLevel.SuperAdmin],
        },
        {
            path: "/markers",
            controller: "markersController",
            templateUrl: "templates/markerListView.html",
            navBarLabel: "LEFT_NAV_BAR.TABLE_NAV_LABEL",
            navBarIconClass: "fa-table",
            authLevels: [authLevel.SuperAdmin],
        }
    ];

    this.$get = function () {
        return routes;
    };
});

app.config(function ($routeProvider, routesProvider) {

    var routes = routesProvider.$get();

    for (var i = 0; i < routes.length; i++) {
        var route = routes[i];
        $routeProvider.when(route.path, {
            controller: route.controller,
            templateUrl: route.templateUrl
        });
    }

    $routeProvider.otherwise({ redirectTo: "/" });
});

Am I right to have my code smell go off here?

Are there any sort of established patterns for defining Angular constants that use previously defined constants, and can still be used in the .config method?


texts: Find and extract delimited packet in buffer

texts:
I'm writing in VB.NET, using VS Community 2013.  I don't know much about this language. I have managed to make my code work, but I suspect it is possible to improve the code a lot.

This code extracts packets from some data I've received using TcpClient.

Private inbuf(10000) As Byte
Private inoff As Integer

Private Sub ProcessBuffer

    ' Buffer may contain multiple packets, delimited by a newline
    Do While 1
        Dim newline As Byte = 10
        Dim newline_index = System.Array.IndexOf(Of Byte)([inbuf], newline) ' I think this is zero-based index
        Dim Data As String = Nothing  ' if I leave this initializer out then Data seems to retain its value for next loop iteration

        If (newline_index >= 0 AndAlso newline_index < inoff) Then   ' packet found
            Data = Encoding.ASCII.GetString(inbuf, 0, newline_index)
            inbuf = inbuf.Skip(newline_index + 1).ToArray()
            ReDim Preserve inbuf(10000) ' the Skip shortened the array
            inoff = inoff - (newline_index + 1)
            If inoff < 0 Then inoff = 0 ' shouldn't happen but seems to happen sometimes?
        End If

        ' If we did not find a newline (or the input was empty string), it means we need to wait for more input
        If String.IsNullOrEmpty(Data) Then
            Return
        End If

        ' Process the response string
        handle_packet(Data)
    Loop
End Sub


texts:
I wrote a function which takes a byte and shifts the bits around. That is, there shall be the same number of 1 bits and 0 bits in the output but the bits will be shifted in position:

global _main
default rel

section .text

_main:
    ; Given 1 byte, shift the positions of the bits in the form 74652103
    mov bl, 0x5A
    ; 0101 1010

    shift_bits:
    ; 1. bit 7 stays same
    ; 2. bit 4 (0x10) gets shifted left by 2 - and with 0001 0000, shift left by 2, or with result
    ; 3. bit 6 (0x40) gets shifted right by 1
    ; 4. bit 5 (0x20) gets shifted right by 1
    ; 5. bit 2 (0x4) gets shifted left by 1
    ; 6. bit 1 (0x2) gets shifted left by 1
    ; 7. bit 0 (0x1) gets shifted left by 1
    ; 8. bit 3 (0x8) gets shifted right by 3
    ; begin 0101 1010
    ; expect: 0110 0101
    ; end 0110 0101
        mov al, bl
        mov cl, 0
        and al, 0x80
        or cl, al
        mov al, bl
        and al, 0x10
        shl al, 2
        or cl, al
        mov al, bl
        and al, 0x4
        shl al, 1
        or cl, al
        mov al, bl
        and al, 0x2
        shl al, 1
        or cl, al
        mov al, bl
        and al, 0x1
        shl al, 1
        or cl, al
        mov al, bl
        and al, 0x8
        shr al, 3
        or cl, al
        mov al, bl
        and al, 0x2
        shl al, 1
        mov al, bl
        and al, 0x40
        shr al, 1
        or cl, al
        mov byte [A], cl ; Store result in A

    go_out:
    mov     rax, 0x2000001 ; exit - macOS specific!
    mov     rdi, 0
    syscall

section .data
A: db 0

Is there a more efficient way to do this with fewer instructions or more performant ones?


texts: Exercism: Class representation of a matrix in Python

texts:
The task is to represent a Matrix as a class and to instantiate it from a string such as "1 2 3 4\n5 6 7 8\n9 8 7 6"
The class must provide methods for accessing individual rows and columns by index starting at 1.
While my solution is relatively short and more or less clear, I'm wondering about the ways to make it better.
One thing I'm not sure about is calling _get_rows() in different places inside the class, instead of assigning its result to class attribute.
Here is my code.
class Matrix:
    """Class representation of a matrix"""

    def __init__(self, matrix_string):
        self.matrix_string = matrix_string

    def _get_rows(self):
        """Produce a list of rows of the matrix."""

        rows = []
        for row_string in self.matrix_string.split('\n'):
            rows.append([int(char) for char in row_string.split()])

        return rows

    def _get_columns(self):
        """Produce a list of columns of the matrix."""

        rows = self._get_rows()

        return [list(row) for row in zip(*rows)]

    def row(self, index):
        """Produce i-th row of the matrix with first index being 1"""

        return self._get_rows()[index - 1]

    def column(self, index):
        """Produce i-th column of the matrix with first index being 1"""

        return self._get_columns()[index - 1]

And the unit tests provided by exercism.
import unittest

from matrix import Matrix

# Tests adapted from `problem-specifications//canonical-data.json` @ v1.3.0

class MatrixTest(unittest.TestCase):
    def test_extract_row_from_one_number_matrix(self):
        matrix = Matrix("1")
        self.assertEqual(matrix.row(1), [1])

    def test_can_extract_row(self):
        matrix = Matrix("1 2\n3 4")
        self.assertEqual(matrix.row(2), [3, 4])

    def test_extract_row_where_numbers_have_different_widths(self):
        matrix = Matrix("1 2\n10 20")
        self.assertEqual(matrix.row(2), [10, 20])

    def test_can_extract_row_from_non_square_matrix_with_no_corresponding_column(self):
        matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6")
        self.assertEqual(matrix.row(4), [8, 7, 6])

    def test_extract_column_from_one_number_matrix(self):
        matrix = Matrix("1")
        self.assertEqual(matrix.column(1), [1])

    def test_can_extract_column(self):
        matrix = Matrix("1 2 3\n4 5 6\n7 8 9")
        self.assertEqual(matrix.column(3), [3, 6, 9])

    def test_can_extract_column_from_non_square_matrix_with_no_corresponding_row(self):
        matrix = Matrix("1 2 3 4\n5 6 7 8\n9 8 7 6")
        self.assertEqual(matrix.column(4), [4, 8, 6])

    def test_extract_column_where_numbers_have_different_widths(self):
        matrix = Matrix("89 1903 3\n18 3 1\n9 4 800")
        self.assertEqual(matrix.column(2), [1903, 3, 4])

if __name__ == "__main__":
    unittest.main()
```


texts: For each of the visitors, find if they were present within a time period: code is running slow

texts:
I'm working with a pandas dataframe which describes the start and end time of visits. A toy example of the data could be as follows:
import pandas as pd
data = pd.DataFrame({"start": [pd.Timestamp("2020-01-01 01:23:45"), pd.Timestamp("2020-01-01 01:45:12")], "end": [pd.Timestamp("2020-01-01 02:23:00"), pd.Timestamp("2020-01-01 03:12:00")]})

I want to break down these visits into periods: from 01:00 to 02:00, there were two visitors, from 02:00 to 03:00, also two, and from 03:00 to 04:00, only one of the visitors was present. To achieve this, I'm generating bounds for my periods and generate a dataframe with overlaps:
periods = pd.DataFrame({"period_start": pd.date_range(start = "2020-01-01 01:00:00", end = "2020-01-01 03:00:00", freq = "1H"), "period_end": pd.date_range(start = "2020-01-01 02:00:00", end = "2020-01-01 04:00:00", freq = "1H")})

def has_overlap(A_start, A_end, B_start, B_end):
  latest_start = max(A_start, B_start)
  earliest_end = min(A_end, B_end)
  return latest_start <= earliest_end

periods_breakdown = pd.DataFrame()
for i in range(3):
  ps = periods.period_start[i]
  pe = periods.period_end[i]
  periods_breakdown["period" + str(i)] = data.apply(lambda row: has_overlap(row.start, row.end, ps, pe), axis = 1)

On the toy data, this code returns
  period0 period1 period2
0    True    True   False
1    True    True    True

The problem is that the actual data has 1M visits that I want to break down over 6000 periods, and the code runs for roughly 140 hours.

Is there a better way to count visitors from this sort of data?
Are there performance improvements to this code?


texts:
I have now written a simple square root calculator using the division method:

static void Main(string[] args)
{
    double num, sqrt = 0;
    int currentDecimal = 0, decimalAccuracyLevel, intAccuracyLevel = 5;

    do
    {
        Console.Write("Enter your number: ");
    } while (!double.TryParse(Console.ReadLine(), out num));

    do
    {
        Console.Write("Enter the number of decimal points you wish to be accurate to: ");
    } while (!int.TryParse(Console.ReadLine(), out decimalAccuracyLevel) && decimalAccuracyLevel >= 0);

    while (0 < intAccuracyLevel)
    {
        double currentIncrement = Math.Pow(10, intAccuracyLevel);

        while (Math.Pow(sqrt + currentIncrement, 2) <= num)
        {
            sqrt += currentIncrement;
        }

        intAccuracyLevel--;
    }

    while (currentDecimal <= decimalAccuracyLevel)
    {
        double currentIncrement = (double)1 / Math.Pow(10, currentDecimal);

        while (Math.Pow(sqrt + currentIncrement, 2) <= num)
        {
            sqrt += currentIncrement;
        }

        currentDecimal++;
    }

    Console.WriteLine(sqrt);
}

Is there anything I should do to improve performance or accuracy?


texts: Filtering out illegal moves from a map of available moves

texts:
I'm writing a console blackjack game.

To hold all the possible moves a player can make, I have a map that maps a keyboard key to a move keyword:

(def move-map {\s :stand
               \h :hit
               \p :split
               \d :double})

Splitting and doubling are only available options during the first move though, so I'd like to filter them out of the available moves before verifying the user's input if they aren't legal moves.

My current method is to indicate which are legal using a flag for doubling and one for splitting, then filtering the map if a flag isn't set:

(defn- filter-moves [moves can-split? can-double?]
  (let [r-split (if can-split? moves (filter #(not= :split (second %)) moves))
        r-doub (if can-double? r-split (filter #(not= :double (second %)) r-split))]
    (into {} r-doub)))

The problem is, this contains a fair amount of redundancy. It should only iterate the map once because filter is lazy, but I'm still not happy with this solution.

Usage:

(filter-moves move-map true false)

=> {"s" :stand, "h" :hit, "p" :split}

Any improvement suggestions would be appreciated. I'm not against redesigning the function if it helps readability and maintainability.


texts:
I made my own custom OpenGL shader loader for C++. Please tell me is I'm doing anything incorrectly or anything to improve on. I've tested this and it works perfectly fine.
main.cc
std::vector<ShaderInfo> shader_info {
    {GL_VERTEX_SHADER, "shader.vert"},
    {GL_FRAGMENT_SHADER, "shader.frag"}
};
GLuint shader_program {LoadShaders(shader_info)};
glUseProgram(shader_program);

shader-loader.hh
struct ShaderInfo {
    GLenum type;
    std::string file;
};

GLuint LoadShaders(const std::vector<ShaderInfo>&);

shader-loader.cc
GLuint LoadShaders(const std::vector<ShaderInfo>& shader_info) {
    GLuint program {glCreateProgram()};
    std::vector<GLuint> detach;

    for (auto info : shader_info) {
        std::ifstream file {info.file, std::ios_base::in};
        file.seekg(0, std::ios_base::end);
        std::string source(file.tellg(), '\0');

        file.seekg(0, std::ios_base::beg);
        file.read(&source[0], source.size());
        file.close();

        GLuint shader {glCreateShader(info.type)};
        GLchar* source_ptr {&source[0]};
        glShaderSource(shader, 1, &source_ptr, nullptr);

        glCompileShader(shader);
        glAttachShader(program, shader);
        glDeleteShader(shader);
        detach.push_back(shader);

        GLint status;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

        if (status == GL_FALSE) {
            GLint length;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);

            std::string log(length, '\0');
            glGetShaderInfoLog(shader, length, nullptr, &log[0]);

            glDeleteProgram(program);
            throw std::runtime_error(log);
        }
    }

    glLinkProgram(program);
    for (auto shader : detach)
        glDetachShader(program, shader);

    GLint status;
    glGetProgramiv(program, GL_LINK_STATUS, &status);

    if (status == GL_FALSE) {
        GLint length;
        glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);

        std::string log(length, '\0');
        glGetProgramInfoLog(program, length, nullptr, &log[0]);

        glDeleteProgram(program);
        throw std::runtime_error(log);
    }

    return program;
}
`````


texts:
I have a variable, which represents a date, but I have the need of keeping it in string format. I want to be sure that this string is in a specific format, in this specific case 'YYYY-MM-DD'.

In order to achieve that I used the following approach, taken from an article.

enum DateStringBrand { _ = '' }

export type DateString = string & DateStringBrand;

function checkValidDateString(str: string): str is DateString {
    return str.match(/^\d{4}-\d{2}-\d{2}$/) !== null;
}

export function toDateString(date: Date | moment.Moment | string): DateString {
    const dateString = moment(date).format('YYYY-MM-DD');
    if (checkValidDateString(dateString)) {
        return dateString;
    }
}

This allows me to do, for example, the following:

let startDate: DateString = toDateString(Date.new);

The discussion above this code raised if using this approach (Nominal Typing) is acceptable and should be encouraged in Typescript or if it's a trick, not designed in the language.

See also:

https://spin.atomicobject.com/2017/06/19/strongly-typed-date-string-typescript/
https://basarat.gitbooks.io/typescript/docs/tips/nominalTyping.html


texts: Finding as many perfect numbers as possible

texts:
I have tried to make a perfect number finder as efficient as possible in python. If anyone has any things I can add to make it more efficient or any problems with my code please say.

def is_prime(num):
    if num <= 1: return False
    elif num <= 3: return True
    elif num % 2 == 0 or num % 3 == 0: return False
    i = 5
    while i * i <= num:
        if num % i == 0 or num % (i + 2) == 0:
            return False
        i += 6
    return True

def is_mersenne_prime(prime, mersenne_prime):
    s = 4
    for i in range(prime - 2):
        s = (s*s - 2) % mersenne_prime
    if s == 0: return True
    else: return False

def calculate_perfects():
    print(6)
    prime = 3
    while True:
        if is_mersenne_prime(prime, 2**prime-1):
            print(2**(2*prime-1)-2**(prime-1))
        while True:
            prime += 2
            if is_prime(prime):
                break

calculate_perfects()