texts: Low-latency implementation of converting non null terminated char* to unsigned int

texts:
How would you rewrite this code which I have now:

uint32_t Utils::stringToInt(unsigned char const* buffer, int len)
{
    uint32_t result = buffer[0] - '0';
    for (int i = 1; i < len; i++) {
        result *= 10;
        result += buffer[i] - '0';
    }
    return result;
}

I need the lowest possible latency. It's very simple, and we don't need to care about '-', so I expect some faster implementation is possible.


texts: Three variations on a Webpack build script

texts:
I am new to "modern" Javascript, and I am reviewing some code from a frontend contractor. I'd like to make the sequential code more descriptive/procedural.

The following code is a from a file called build.js, which is used to start a new project build (via Webpack). I guess we could call that a "build script" of sorts:

import path from 'path';
import webpack from 'webpack';
import fse from 'fs-extra';
import config from './../webpack/webpack.config.production';
import paths from './../paths';

fse.emptyDirSync(paths.distPath, (err) => {
  if (err) console.error(err);
});

fse.copySync(
  paths.staticPath,
  path.join(paths.distPath, 'static'),
  { clobber: true },
  (err) => { if (err) console.error(err); }
);

webpack(config).run((err, stats) => {
  if (err) console.error(err);
  else console.log(stats.toString());
});

This glue code is sort of simple, if you know modern JS. Still, I find that the lack of high-level description or modularity will be a problem later on for junior JS people, or for bigger and more complicated scripts.

It looks like in the JavaScript world, people like to comment, and I often find this version:

Version 1

... imports ...

// Empty build folder
fse.emptyDirSync(paths.distPath, (err) => {
  if (err) console.error(err);
});

// Copy in static files
fse.copySync(
  paths.staticPath,
  path.join(paths.distPath, 'static'),
  { clobber: true },
  (err) => { if (err) console.error(err); }
);

// Build
webpack(config).run((err, stats) => {
  if (err) console.error(err);
  else console.log(stats.toString());
});

This seems to be the "most idiomatic JavaScript" code when looking at other open source codebases.

I am not used to writing scripts, but in my Ruby/Rails community, a lot of people prefer to write self-descriptive code instead of comments, at least for their business logic. I know this is a script and it differs from business logic, but the following makes me more comfortable:

Version 2

... imports ...

function main() {
  emptyBuildFolder();
  copyStaticFilesToBuildFolder();
  build();
}

function emptyBuildFolder() {
  fse.emptyDirSync(paths.distPath, (err) => {
    if (err) console.error(err);
  });
}

function copyStaticFilesToBuildFolder() {
  fse.copySync(
    paths.staticPath,
    path.join(paths.distPath, 'static'),
    { clobber: true },
    (err) => { if (err) console.error(err); }
  );
}

function build() {
  webpack(config).run((err, stats) => {
    if (err) console.error(err);
    else console.log(stats.toString());
  });
}

main();

Basic main() or init() technique. I like the modularity and it feels more maintainable.

Here's an OO version which is the same but with more syntactic sugar:

Version 3

... imports ...

new class {

  constructor() {
    this.emptyBuildFolder();
    this.copyStaticFilesToBuildFolder();
    this.build();
  }

  emptyBuildFolder() {
    fse.emptyDirSync(paths.distPath, (err) => {
      if (err) console.error(err);
    });
  }

  copyStaticFilesToBuildFolder() {
    fse.copySync(
      paths.staticPath,
      path.join(paths.distPath, 'static'),
      { clobber: true },
      (err) => { if (err) console.error(err); }
    );
  }

  build() {
    webpack(config).run((err, stats) => {
      if (err) console.error(err);
      else console.log(stats.toString());
    });
  }

};

(or we could explicitly define a Build class and then call new Build() right away).

I prefer version 2 or 3, but in the JavaScript ecosystem I see a huge amount of code like Version 1. At least that was my feeling after reviewing ~ 50 real world open source JS React+Webpack projects.

I don't want to be the one guy writing non-idiomatic JS, but on the other hand, I find Version 2 or 3 so much better. I would only use comments to describe actually complicated things, or to explain the whys (and let variable/function/class names describe the hows). Why am I the only one thinking like this? Which version should I use?


texts: Is my Node/Express-based authentication implementation with session properly done?

texts:
I know that Passport.js exists, however, I wanted to code my own implementation using express-session module.

I'm using:

Express
Mongoose
express-session

So I basically have 2 routes for handling auth, POST /signup and POST /login.

This is what I've got, which I think is actually working but what I'm more concerned about is the session-handling.

var Account = require('../models/account');

app.route('/login')

    .post(function (request,response,next) {

        var email = request.body.email
        var password = request.body.password
        var login = new Account({"local.email":email,"local.password":password})

        Account.findOne({"local.email":email}, function (err,user) {

            if (err) {
                                response.send(500).end()
                                next();
            }

            if (!user) {
                                response.send(404).end();
                                next();
            }

            user.validPassword(password, function (err,matched) {

                if (err) {

                                response.status(500).end();
                                next();
                }

                if (matched) {

                                var session = request.session
                                session.name = email
                                response.redirect('/start')
                                next();
                }
                else {
                                response.redirect('/')
                                next();
                }
            })
        })
    })

    .delete(function (request,response) {

        request.session.destroy(function (err) {
            response.redirect('/')
        })
    })

app.route('/signup')

    .post(function (request,response) {

        var doc = new Account({"local.email":request.body.email,"local.password":request.body.password})

        doc.save(function (err,saved) {

            if (err) response.status(500).end();

            response.status(200).end();
        })
    })


texts: Creating restrictions for a sprite's possible position on the screen

texts:
The great feedback I got on my first post on Code Review made me wary of code repetition. This code does what it is supposed to, which is to create restrictions for a sprite's possible position on the screen.

Is this a neat looking solution, or can it be considered code repetition?

public void move(int x, int y) {
    int maxX = screenWidth - image.getWidth()/2;
    int minX = image.getWidth() / 2;
    int maxY = screenHeight - image.getHeight()/2;
    int minY = image.getHeight() / 2;

    if (x > maxX)
        this.x = screenWidth - image.getWidth();
    else if (x < minX)
        this.x = 0;
    else
        this.x = x - image.getWidth() / 2;

    if (y > maxY)
        this.y = screenHeight - image.getHeight();
    else if (y < minY)
        this.y = 0;
    else
        this.y = y - image.getHeight() / 2;
}


texts: Start an EventHandler in different Thread

texts:
I just stumbeled accross some code and I would do it in a different way. Since I am quite new to programming, I just wanted to know if I understand it right.

Original Code:

protected void FireStateChange(LightCommunicationState OldState, LightCommunicationState NewState)

    {
        if (StateChanged != null && OldState != NewState)
        {
            Thread t = new Thread(StateChangeThread);
            uint u = ((uint)OldState * 0x10000) + (uint)NewState;
            t.Start(u);
        }
    }

    protected void StateChangeThread(object o)
    {
        uint u = (uint)o;
        ushort Old = (ushort)((u & 0xFFFF0000) >> 16);
        ushort New = (ushort)(u & 0xFFFF);

        StateChanged(this, (LightCommunicationState)Old, (LightCommunicationState)New);

    }

My personal solution would be:

protected void FireStateChange (LightCommunicationState OldState, LightCommunicationState NewState)
    {
        if (StateChanged != null && OldState != NewState)
        {
            new ThreadStart(
                delegate
                {
                    StateChanged(this, OldState, NewState);
                }).Invoke();
        }
    }

It seems a bitshift and cast an object to a uInt back an forth looks freaky but is unnecessary. Maybe I am missing some benefits on the original solution?

The LightCommunicationState enum is defined as follows:

public enum LightCommunicationState: ushort
{
    notChoosen, Waiting, Communicating
}

And the StateChanged event like this:

public delegate void LightCommunicationStateChanged(LightCommunicationStateMachine Sender, LightCommunicationState OldState, LightCommunicationState NewState);

public event LightCommunicationStateChanged StateChanged;


texts:
Here's a perhaps naive but simple implementation of Radix sort in Java.
It works with any radix, and both positive and negative numbers.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class RadixSortWithDivision {

    public static final int DEFAULT_RADIX = 10;

    public static void sort(int[] arr) {
        sort(arr, DEFAULT_RADIX);
    }

    public static void sort(int[] arr, int radix) {
        int maxDigits = 1 + (int) (Math.log(max(arr)) / Math.log(radix));
        int divisor = 1;
        for (int pos = 0; pos < maxDigits; ++pos) {
            List<List<Integer>> buckets = splitToBuckets(arr, divisor, radix);
            flattenBuckets(arr, buckets);
            divisor *= radix;
        }
        List<List<Integer>> buckets = splitBySign(arr);
        flattenBuckets(arr, buckets);
    }

    private static List<List<Integer>> splitToBuckets(int[] arr, int divisor, int radix) {
        List<List<Integer>> buckets = new ArrayList<>();
        for (int i = 0; i < radix; ++i) {
            buckets.add(new LinkedList<>());
        }
        for (int num : arr) {
            int bucketIndex = Math.abs(num) / divisor % radix;
            buckets.get(bucketIndex).add(num);
        }
        return buckets;
    }

    private static List<List<Integer>> splitBySign(int[] arr) {
        List<Integer> positive = new LinkedList<>();
        List<Integer> negative = new LinkedList<>();
        for (int num : arr) {
            if (num >= 0) {
                positive.add(num);
            } else {
                negative.add(0, num);
            }
        }
        return Arrays.asList(negative, positive);
    }

    private static void flattenBuckets(int[] arr, List<? extends List<Integer>> buckets) {
        int i = 0;
        for (List<Integer> bucket : buckets) {
            for (int num : bucket) {
                arr[i++] = num;
            }
        }
    }

    private static int max(int[] arr) {
        int max = Integer.MIN_VALUE;
        for (int num : arr) {
            if (num > max) {
                max = num;
            }
        }
        return max;
    }
}

Unit tests:

import org.junit.Test;

import java.util.Arrays;
import java.util.Random;

import static org.junit.Assert.assertArrayEquals;

public abstract class SortTest {

    abstract void sort(int[] arr);

    private int[] newRandomArray(int num) {
        Random random = new Random(0);
        int[] arr = new int[num];
        for (int i = 0; i < arr.length; ++i) {
            arr[i] = random.nextInt();
        }
        return arr;
    }

    private void sortAndVerify(int[] arr) {
        int[] copy = arr.clone();
        Arrays.sort(copy);
        sort(arr);
        assertArrayEquals(copy, arr);
    }

    @Test
    public void test_empty() {
        sortAndVerify(new int[0]);
    }

    @Test
    public void test_1() {
        sortAndVerify(new int[]{1});
    }

    @Test
    public void test_1_2() {
        sortAndVerify(new int[]{1, 2});
    }

    @Test
    public void test_2_1() {
        sortAndVerify(new int[]{2, 1});
    }

    @Test
    public void test_1_2_3() {
        sortAndVerify(new int[]{1, 2, 3});
    }

    @Test
    public void test_3_2_1() {
        sortAndVerify(new int[]{3, 2, 1});
    }

    @Test
    public void test_random_10() {
        sortAndVerify(newRandomArray(10));
    }

    @Test
    public void test_random_1000() {
        sortAndVerify(newRandomArray(1000));
    }

}

public class RadixSortWithDivisionTest extends SortTest {
    @Override
    void sort(int[] arr) {
        RadixSortWithDivision.sort(arr);
    }
}

How would you improve this?

How would you improve the unit test cases?


texts:
I have designed a small method to generate a salt for a password. All this does is create a random salt and does nothing to add it to the password. I have a few questions regarding my very simple method:

Is this a secure generator?
Currently, it encodes in base64. Is this an issue in any way?
Are there any other potential issues? How could I improve this in terms of security, speed, etc...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Security.Cryptography;

namespace Test
{
    public class Program
    {
        // Here is a method to generate a random password salt
        private static string getSalt()
        {
            var random = new RNGCryptoServiceProvider();

            // Maximum length of salt
            int max_length = 32;

            // Empty salt array
            byte[] salt = new byte[max_length];

            // Build the random bytes
            random.GetNonZeroBytes(salt);

            // Return the string encoded salt
            return Convert.ToBase64String(salt);
        }

        static void Main(string[] args)
        {
            System.Console.WriteLine(getSalt());
            System.Console.ReadKey();
        }
    }
}


texts: Flattening a 2D array to a 1D array based on indexes

texts:
I am certain there is a better way to flatten the array with an optimized approach for the solution.

Example:

  [[1,2,24],[12,1241,122],[3,2],[7]] => 1 12 3 7 2 1241 2 24 122

public class flattenArray {

public static void main(String args[]) {

    int inputLists[][] = {{1,2,24},{12,1241,122},{3,2},{7}};

    flattenList(inputLists);

}

public static void flattenList(int input[][]){
    List result = new ArrayList();
    Map<Integer, List<Integer>> elements = new HashMap<Integer,List<Integer>>();
    for(int i=0;i<input.length;i++){
        for(int j=0;j<input[i].length;j++){

            List<Integer> temp = new ArrayList<Integer>();

            if(elements.get(j)!=null) {
                temp=elements.get(j);
                temp.add(input[i][j]);
                elements.put(j, temp);
            }

            else {
                temp.add(input[i][j]);
                elements.put(j,temp);
            }
        }
    }

    for(int i=0;i<input.length;i++){
        if(elements.get(i)!=null)
        result.addAll(elements.get(i));
    }

    for(int i=0;i<result.size();i++){
        System.out.println(result.get(i)+" ");
    }
}
}


texts: Creating bootstrap modals that can run JavaScript in MVC5

texts:
I have an MVC5 & C# application using the Razor engine.

In my application I have a view, called "Index.cshtml". In this view I want to present a bootstrap modal to the user.

When presented to the user, this modal will have buttons that should be capable of running JS functions and methods using jQuery.

I have achieved this in the past using a dynamic method.

This means that I have a Main view (Index.cshtml), that contains an empty element (

):

Package List

This empty tag is then filled via an Ajax request to the server:

//Show Edit Package modal
    $(".btn.btn-default.editPackage").click(function () {

        $.ajax({
            url: $(this).data('url'),
            type: 'GET',
            cache: false,
            success: function (result) {
                $('#editModal').html(result).find('.modal').modal({
                    show: true
                });
            }
        });
        return false; //prevent browser defualt behavior
    });

This Ajax request returns the Modal that I want to show:

Edit Package MyPackage

          <form class="form-horizontal">

              Package Name:

                <input type="text" class="form-control" id="package-name" placeholder="MyPackageName">

          </form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" id="savePackageChangesBtn">Save changes</button>

And then the user can have fun clicking in the modal's buttons and seeing how things change. This is achieved via jQuery linked to the modals save button:

$(document).ready(function() {
  $("#savePackageChangesBtn").click(function() {
    $('.modal').modal({
      show: true
    });
    return false; //prevent browser defualt behavior
  });
});

However, after discussion with the community (see this answer), we concluded that was a poor design pattern.
Therefore, I must ask, what is the easiest way of achieving this objective?


texts:
public static DateTime ObjectToDateTime(object o, DateTime defaultValue)
{
    if (o == null) return defaultValue;

    DateTime dt;
    if (DateTime.TryParse(o.ToString(), out dt))
        return dt;
    else
        return defaultValue;
}

The code feels too wordy and smells bad.  Is there a better way?


texts: Modelling an automation test controller and test steps

texts:
I'm trying to break up some procedural JavaScript code used for running an automation test.

The code is a series of steps that execute selenium webdriver commands within the neustar load testing framework. The framework is not too important for the purposes of this review, except to know this code is not run in a browser. Its more the structure of the javascript I'm after feedback on, in terms of encapsulating the steps.

The controller initializes the test, retrieves parameters for the virtual user and orchestrates running the steps. The steps object is a container for the individual steps in the test.

Note the 'test' object is a global object provided by the framework, which I have mocked for the purpose of the review. See it in action here.

I want the steps object to contain some reusable functions. I've added one called utilityFunction and called it from a step.

The code is a wrapper around a selenium automation test that is run in the cloud using neustar. I'm looking for a way to break up multiple steps in the test into a clean, maintainable structure to allow me to better re-use and encapsulate distinct steps in the test automation.

The 'test' object can be ignored, it's simply there to mock the neustar global object.
This is a simple framework to run step 1, then step 2 through to step n, e.g. navigate to site, logon, create new order, submit order etc...
Please evaluate the quality of the JavaScript, as well as the pattern for running a series of steps while being able to control what happens before and after each step.

function testController(steps) {
    this.steps = steps;
    // simplified params this will be read from a service
    this.params = { Param1: "Value1", Param2: "Value2" };

    this.runAll = function () {

        test.beginTransaction();

        for (var s in this.steps) {
            test.beginStep(this.steps[s].description, this.steps[s].timeout);
            this.steps[s].execute(this.params);
            test.endStep();
        }
        test.endTransaction();
    }
}

function testSteps() {
    var utilityFunction = function (v) {
        console.log("** calling util with value: " + v + " ***");
    }

    this.step1 = {
        description: "first step",
        timeout: 1000,
        execute: function (params) {
            console.log("executing " + this.description);
        }
    }

    this.step2 = {
        description: "second step",
        timeout: 30000,
        execute: function (params) {
            console.log("executing " + this.description);
            utilityFunction("hello");
        }
    }
}

// mock test object
var test = {
    beginTransaction: function () {
        console.log("beginning transaction");
    },
    endTransaction: function () {
        console.log("ending transaction");
    },
    beginStep: function (name, timeout) {
        console.log("begin step " + name);
    },
    endStep: function () {
        console.log("end step");
    }
}

var steps = new testSteps();

//steps.utilityFunction("world");
var tc = new testController(steps);
tc.runAll();


texts:
I have this code which compares two adjacent time stamps. If they are less than 15 min apart, it adds a new time stamp (row) in between with the new time stamp equal to the previous time + 15 min and value equal to the previous time stamp. If there is more than one-time stamp missing (more than 15 min interval), it adds a number of time stamps with + 15 min interval each. Sample value equal to last recorded value.

CSV file looks something like this:

"Time stamp","Value","Events","Comment","User"
"5/07/2016 7:07:54 PM","7.00","","",""
"5/07/2016 6:37:52 PM","14.00","","",""
"5/07/2016 6:22:51 PM","26.00","","",""
"5/07/2016 6:07:50 PM","9.00","","",""
"5/07/2016 7:22:06 AM","0.00","","",""
"5/07/2016 7:07:05 AM","16.00","","",""
"5/07/2016 6:52:04 AM","25.00","","",""

At the moment it is doing what it suppose to do but in wrong direction, because the .csv file was created from bottom up.

for (var currentRow = 0; currentRow < dgvValues.Rows.Count; currentRow++)
    {
        for (var cellIndex = 0; cellIndex < dgvValues.Rows[currentRow].Cells.Count; cellIndex++)
        {
            if (cellIndex > 0 && cellIndex < dgvValues.Rows[currentRow].Cells.Count)
            {
                buffer += ",";
            }
            buffer += dgvValues.Rows[currentRow].Cells[cellIndex].Value.ToString();
        }
        buffer += "\n";

        pleasewait.LabelText = (currentRow.ToString() + " of " + numRows + " rows processed");
        Application.DoEvents();

        if (currentRow + 1 >= dgvValues.Rows.Count) continue;
        {
            var firstDate = Parse(dgvValues.Rows[currentRow].Cells[0].Value.ToString());
            var secondDate = Parse(dgvValues.Rows[currentRow + 1].Cells[0].Value.ToString());

            var timespan = firstDate - secondDate;
            double min = -15;
            firstDate = firstDate.AddMinutes(min);

            if (timespan.TotalMinutes > 15)
            {
                if (firstDate == secondDate)
                    @equals = true;
                while (timespan.TotalMinutes > 15 && !@equals)
                {
                    timespan = firstDate - secondDate;
                    for (var cellIndex = 0;
                        cellIndex < dgvValues.Rows[currentRow].Cells.Count;
                        cellIndex++)
                    {
                        if (cellIndex > 0 && cellIndex < dgvValues.Rows[currentRow].Cells.Count)
                        {
                            buffer += ",";
                        }
                        if (cellIndex != 0)
                        {
                            buffer += dgvValues.Rows[currentRow].Cells[cellIndex].Value.ToString();
                        }
                        else
                            buffer += Parse(firstDate.ToString(CultureInfo.CurrentCulture));
                    }
                    buffer += "\n";
                    min = -15;
                    firstDate = firstDate.AddMinutes(min);
                }
            }
        }
    }


texts:
I'm learning JavaScript and have tried making a simple quiz from scratch.

JS Bin

//Define global variables
    var count = 0,
          zCount = 0,
          yCount = 0,
          sumPoints = 0,
          aQuestion,
          allQuest,
          aChoices,
          bChoices,
          allQuestions,
          finishedDoc,
          someValue;

    allQuestions = [
            {
            question: "What is the capital of Peru?",
            choices: ["Buenos Aires", "La Paz", "Lima", "Quito"],
            correctAnswer: 2
        },
            {
            question: "What is the capital of Bolivia?",
            choices: ["La Paz", "Buenos Aires", "Quito", "Lima"],
            correctAnswer: 0
        },
            {
            question: "What is the capital of Ecuador?",
            choices: ["Lima", "Quito", "Buenos Aires", "La Paz"],
            correctAnswer: 1
        },
            {
            question: "What is the capital of Argentina?",
            choices: ["Quito", "La Paz", "Lima", "Buenos Aires"],
            correctAnswer: 3
        }
    ];

    function renderQuestions() {
        aQuestion = document.getElementById("thisQuestion");
        aChoices = document.getElementsByTagName("label");
        bChoices = document.getElementsByTagName("input");
        if(count < allQuestions.length){
            allQuest = allQuestions[count].question;
            count++;
        }
        else{
            alert("You have a total of " + sumPoints + "/4" + " correct answers!");
            finished();
        }
        aQuestion.innerHTML = allQuest;
        //render the choices and structure
        for(var i = 0; i < allQuestions.length; i++){
            aChoices[i].innerHTML = allQuestions[zCount].choices[i];
        }
        zCount++;

    }
    renderQuestions() //render first question
    function checkAnswer() {

        someValue = allQuestions[yCount].correctAnswer;
        if(bChoices[someValue].checked == true){
            alert("That's correct!");
            sumPoints += 1;
        }
        else{
            alert("Nope, sorry!");
        }
        yCount++;
        renderQuestions();
    }

    function finished(){
        finishedDoc = document.getElementById("thisCont");
        finishedDoc.innerHTML = "<h1>Finished!<\/h1>";
    }


texts: Justify text from a file using a LaTeX method

texts:
I wrote a bit of code that takes a file, justifies the text and writes to another file.

It uses a DP approach to minimise a badness metric, which is the amount of undershoot of the line length, cubed (see my answer below, the badness function isn't quite right if there is an overshoot, the badness should be inf - I believe this is how LaTeX justifies its text).

I encapsulated it in a class (which is the bit I'm least confident about). Be careful running it on big files, because I think it's got a pretty nasty complexity (\$O(n^2)\$ maybe).

class justifyText:
    def __init__(self, inFileName, outFileName, pageWidth):
        with open(inFileName, "r") as fp:
            self.words = [word for line in fp for word in line.split()]
        self.outFileName = outFileName
        self.pageWidth = pageWidth
        self.memo = {}
        self.breakPointTrack = {}
        self.n = len(self.words)

    def badness(self, i, j):
        totalWidth = 0;
        for word in self.words[i:j]:
            totalWidth += len(word)
        return abs((self.pageWidth - totalWidth)**3)

    def minBadness(self, i):
        if i in self.memo:
            return self.memo[i]
        if i == self.n:
            f = 0
            j_min = self.n
        else:
            f = None
            for j in range(i + 1, self.n + 1):
                temp = self.minBadness(j) + self.badness(i, j)
                if (f is None) or (temp < f):
                    f = temp
                    j_min = j
        self.memo[i] = f
        self.breakPointTrack[i] = j_min
        return f

    def justify(self):
        self.minBadness(0)
        fOut = open(self.outFileName, "w")
        brk = 0
        while brk < self.n:
            start = brk
            brk = self.breakPointTrack[brk]
            line = " ".join(self.words[start:brk]) + "\n"
            fOut.write(line)
        fOut.close()

test = justifyText("test.txt", "out.txt", 80)
test.justify()

Is this a standard way to implement a DP program? I know that global variables are evil, so I was mainly trying to avoid my memo etc. being that.


texts: Using a Closure to generate express route handler function

texts:
I'm using a lambda function to generate the callback handler for each list page in a group of routes, because the sql is very repetitive for each of these routes. The lambda function uses a callout to a formatter to generate a sql statement.

I wanted to know if anything I'm doing is bad practice or a vulnerability.

function genBrowseListQuery(f, g) {
    return util.format('SELECT %s AS id, ' +
        '%s as name ' +
        'FROM %s ' +
        'ORDER BY %s ASC ' +
        'LIMIT 30 OFFSET $1 * 30',
        f[0], f[1], g, f[1]);
}

function prepareBrowseList(groupName, shortName, fields) {
    return (req, res) => {
        var x = [(req.query.page - 1) || 0];
        pool.query(genBrowseListQuery(fields, groupName), x)
        .then((items) => {
            res.render('browse', {
                shortName: shortName,
                thingName: groupName,
                view: 'list',
                items: items.rows
            })
        });
    }
}

// Then I use it like so.
app.get('/browse/uni', prepareBrowseList('Universes', 'uni',
    ['unv_id', 'unv_name']));

pool is the database connection object.


texts: Simplifying multiple mouseover and mouseout functions

texts:
I am trying to hide and show tooltips depending on what element is hovered over.  This works as expected and I could continue to rinse and repeat. However, I am wondering if there is a good way to simplify this or make it more compact. Also I was assuming I could use .hover(), but that didn't seem to work for me. So instead I am using mouseover and mouseout.

$('.remove').eq(0).mouseover(function(){
    $('.tooltip').eq(0).show();
});

$('.remove').eq(0).mouseout(function(){
    $('.tooltip').eq(0).hide();
});

$('.remove').eq(1).mouseover(function(){
    $('.tooltip').eq(1).show();
});

$('.remove').eq(1).mouseout(function(){
    $('.tooltip').eq(1).hide();
});


texts: JS create array by comparing 2 dictionaries

texts:
I have 2 dictionaries that I have to compare, if an element of one dictionary exists in the other dictionary, then add the element to an array but only one time...
here the working code
const getFavouriteShows = (graphql, favouriteShows) => {
    const arraya = [];

    //iterate trough favouriteShows
    for (let item in favouriteShows) {
      //iterate trough graphql
      for (let itemGQL in graphql) {
        //if same slug, add the item to new array JUST ONE TIME
          if(favouriteShows[item].slug === graphql[itemGQL].show?.slug){
            arraya.push(graphql[itemGQL])
            break
          }
      }
    }
       return Object.assign(arraya)
  }

So, how to express this in a more inline functional way? using map, filter.
Thanks!
Edit, examples for the data coming in and out https://gist.github.com/mako34/44301d3c96249de9a07aa2550ca1172a


texts: Find common elements in a list of arrays

texts:
I need to find the common elements present in all the given arrays. All the arrays are present in another array.

I have come up with this solution and it's working. I tried to remove the usage of indexOf, but I could not. Could someone help me optimize this?

var findCommonElements= function(arrs) {
    var resArr = [];
    for (var i = arrs[0].length - 1; i > 0; i--) {

        for (var j = arrs.length - 1; j > 0; j--) {
            if (arrs[j].indexOf(arrs[0][i]) == -1) {
                break;
            }
        }

        if (j === 0) {
            resArr.push(arrs[0][i]);
        }

    }
    return resArr;
}

Input Array of arrays:

var arrays  = [
    [1, 4, 6, 78, 8, 9, 124, 44],
    [44, 6, 9],
    [124, 44, 16, 9]
]

Output:

findCommonElements( arrays )
[44, 9]


texts: C# Winforms MVP (avoiding circular dependencies)

texts:
I asked the following question on stackoverflow  and as a result came up with the following code to avoid circular event logic when using winforms.

There are two occasions where my model can be updated, either programmatically via some application logic, or by the user via a view.

There is no longer any circular logic but there is still superfluous behaviour.  When I update my model via the property in the presenter, the view gets updated, which in turn fires an event to update the model in the presenter (again).  I can probably just about live with that, but it still irks me. (EDIT: Actually I can't live with that.  It's not too bad here because the view has only two TextBoxes, hence the text changed event gets fired twice, updating the model two different times.  This would be even worse if the control had multiple textboxes).

Is it correct to expose my model via a property in the presenter?  Should I always use this instance to refer to the actual model? How else can I programmatically update my model and have the view updated?

public partial class View : UserControl
{
    private Model model = new Model();

    public View()
    {
        InitializeComponent();
    }

    public event EventHandler<Model> DataUpdated;

    public Model Model
    {
        get
        {
            return model;
        }
        set
        {
            if (value != null)
            {
                model = value;
                UpdateTextBoxes();
            }
        }
    }

    private void UpdateTextBoxes()
    {
        if (InvokeRequired)
        {
            Invoke(new Action(() => UpdateTextBoxes()));
        }
        else
        {
            textBox1.Text = model.Text1;
            textBox2.Text = model.Text2;
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        model.Text1 = ((TextBox)sender).Text;
        OnModelUpdated();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        model.Text2 = ((TextBox)sender).Text;
        OnModelUpdated();
    }

    private void OnModelUpdated()
    {
        DataUpdated?.Invoke(this, model);
    }
}

public class Model
{
    public string Text1 { get; set; }
    public string Text2 { get; set; }
}

public class Presenter
{
    private Model model;
    private View view;

    public Presenter(Model model, View view)
    {
        this.model = model;
        this.view = view;

        view.DataUpdated += View_DataUpdated;
    }

    public Model Model
    {
        get
        {
            return model;
        }
        set
        {
            model = value;
            view.Model = model;
        }
    }

    private void View_DataUpdated(object sender, Model e)
    {
        //This is fine.
        model = e;

        //This causes the circular dependency.
        //Model = e;
    }
}


texts: Compare Oracle Table with SQL Server Table and Update/Insert

texts:
Below is the current code which is used to update/insert records from Oracle view to SQL Server table using Dapper. There is not a field to check last record updated date in the oracle view so I have added a method to get hashcode by using property values. Since Oracle table has more than 15k records and each record has more more than 60 columns, this approach take more than 5 minutes. Any ideas/suggestions to improve below code?

using System;
using System.Configuration;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using Dapper;

namespace SyncSQLSvrWithHRDB
{
    internal class Program
    {
        public static PropertyInfo[] PropertyNames = typeof(Employee).GetProperties();

        private static void Main(string[] args)
        {
            var OracleConStr = ConfigurationManager.ConnectionStrings["OracleCon"].ConnectionString;
            var SqlSvrConStr = ConfigurationManager.ConnectionStrings["SqlSvrCon"].ConnectionString;
            using (OracleConnection OraCon = new OracleConnection(OracleConStr))
            {
                var res = OraCon.Query<Employee>(Constants.SelectSql).ToList();

                res = res.GroupBy(x => x.EmpNumber.ToUpper()).Select(x => x.LastOrDefault()).ToList();
                using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))
                {
                    Sqlcon.Open();
                    for (int i = 0; i < res.Count; i++)
                    {
                        var item = Sqlcon.Query<Employee>(Constants.SelectEmpSql, new { EmpNumber= res[i].EmpNumber}).FirstOrDefault();
                        if (item == null) // new record found
                        {
                            Sqlcon.Execute(Constants.InsertSql, res[i]);
                        }
                        else if (GetHashcode(res[i]) != GetHashcode(item)) // record updated
                        {
                            Sqlcon.Execute(Constants.UpdateSql, res[i]);
                        }
                    }
                }
            }
        }

        public static int GetHashcode(Employee o)
        {
            int ret = 0;
            foreach (var prop in PropertyNames)
            {
                object propValue = o.GetType().GetProperty(prop.Name).GetValue(o, null);

                if (propValue != null)
                {
                    ret += propValue.GetHashCode();
                }
            }

            return ret;
        }
    }

    public class Employee
    {
        public String EmpNumber{ get; set; }

        // ... other properties (70)
    }
}


texts: String converting and parsing a few rows of a .csv file

texts:
There are not many available resources for refactoring go code.  I'm a novice gopher who would appreciate any feedback on a small program which reads a .csv file, string converts and parses a few rows in order to perform a sub method.

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "os"
    "strconv"
)

const file = "csvdata/csvtest.csv"
// what should stay in main()?  What should be refactored?
func main() {
    f, err := os.Open(file)
    if err != nil {
        log.Fatalf("Error reading all lines: %v", err)
    }
    defer f.Close()

    reader := csv.NewReader(f)
    reader.Comma = ';'

    for {
        record, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            log.Print(err)
            os.Exit(-1)
        }
        // need to refactor variables, could I use a type struct?
        var num string = (record[2])
        var name string = (record[3])
        var eia string = (record[5])
        var cia string = (record[6])
        var inc_percent = (record[7])
        var estIncTxn string = (record[8])
        var inc_diff float64
        // I would like to turn this chunk into it's own function
        for i := 0; i < len(record[i]); i++ {
            estInc, err := strconv.ParseFloat(eia, 64)
            actInc, err := strconv.ParseFloat(cia, 64)
            inc_diff = (actInc - estInc)
            if err == nil {
        //How could I turn the following into a template?
                fmt.Println("============================================================\n")
                fmt.Printf("Account: %+s - %+s exceeded the IncAmt by %+v same as $%+v\n", num, name, inc_percent, inc_diff)
                fmt.Printf("over the monthly incoming amount of $%+v. Currently, the declared\n", actInc)
                fmt.Printf("profile is established at $%+v with an expectancy of (%+v).\n", estInc, estIncTxn)
            } else {
                log.Fatalf("Error converting strings: +v", err)
            }

        }
        fmt.Println()
    }
}

Here is a single line of the csv file.

30;4;102033657;COCACOLA;53764;15000.00;73010.58;387%;4;30;650%;15000.00;89558.96;497%;3;5;66%;DDA

Sample of the output:

  ==============================================================================

  Account: 102033657 - COCACOLA exceeded the IncAmt by 387% same as
  $58010.58 over the monthly incoming amount of $73010.58. Currently,
  the declared profile is established at $15000 with an expectancy of
  (4).

  ==============================================================================

Eventually I would be capturing the outgoing amount as well for each record (just to give everyone an idea of where I'm going with this).  I'm assuming a template would be the best way to approach this situation?  How could this be refactored?


texts: Is there a performance difference using AS keyword in SQL?

texts:
I'm working on a project in which the previous programmer seems to have loved using the AS keyword in the SELECT part of queries. I really don't like how it's written but if there is no performance difference I won't change existing code.

My tests did give a slight advantage to not using the AS keyword but I'm clueless on how to properly test it(I ran the different queries using Navicat)

And maybe there is also a difference between different types of databases and engines. I'm using MySQL InnoDB.

Simplified query:

SELECT DISTINCT
    `sometable`.`id` AS `id`,
    `sometable`.`name` AS `name`,
    `sometable`.`description` AS `description`,
    `sometable`.`price` AS `price`,
    `sometable`.`size` AS `size`,
    `sometable`.`area` AS `area`,
    `sometable`.`center` AS `center`
FROM `sometable`


texts:
So I'm trying to code a navigation scroll bar like that looks like this:

This is the code:

<!DOCTYPE html>

How does it look? Should I remove the scroll bar? If so, how do I do that?


texts:
I use the following which works( I remove the unnnecery parts to the question)
https://play.golang.org/p/OozjexJ4hZk
The program is doing the following:

run concurrent functions
each function should return response
calculate the response

I will add a logs and comments but I want to get feedback on the code.
What Im not sure if I use clientA and clientB in a clean way,but it works...
 package main

import (
    "context"
    "fmt"
    `net/http`

    "time"

    "github.com/gammazero/workerpool"
    `k8s.io/client-go/kubernetes`

)

type JobReact struct {
    name     string
    Duration time.Duration
    Info     interface{}
    Error    error
}

func (m *JobReact) Name() string {
    return m.name
}

type GenClient struct {
    ClientA http.Client
    ClientB kubernetes.Clientset
}

type ResultList struct {
    response http.Response
}

// Jobs holds job data
type Jobs struct {
    Name   string
    Runner func(*GenClient) JobReact
}

func wrapper(timeDuration time.Duration, reacts chan JobReact, jobs Jobs, genClient GenClient, ) func() {
    contextWithTimeout, tc := context.WithTimeout(context.Background(), timeDuration)
    return func() {
        now := time.Now()
        go func(contx context.Context, cancelFunc context.CancelFunc, jobReacts chan JobReact, jobs Jobs, timer time.Time,
        ) {
            // Here I need to use the combined clients , should I use some interface? if yes how?
            runner := jobs.Runner(&genClient)
            runner.Duration = time.Since(timer)
            runner.name = jobs.Name
            if contextWithTimeout.Err() == nil {
                jobReacts <- runner
            }
            cancelFunc()
        }(contextWithTimeout, tc, reacts, jobs, now)
        select {
        case <-contextWithTimeout.Done():
            switch contextWithTimeout.Err() {
            case context.DeadlineExceeded:
                reacts <- JobReact{
                    name:     jobs.Name,
                    Error:    context.DeadlineExceeded,
                    Duration: time.Since(now),
                }
            }
        }
    }
}

func main() {
    // init clients
    genClients := GenClient{ClientA: ClientA(), ClientB: ClientB()}

    jobs := []Jobs{
        {
            Name: "job1",
            Runner: func(GenClient *GenClient) JobReact {
            // In this func I need to use client A
                GenClient.ClientA
                ...
            },
        },
        {
            Name: "job2",
            Runner: func(genClient *GenClient) JobReact {
            // In this func I need to use client b
                GenClient.ClientB
                ...
            },
        },
        {
            Name: "job3",
            Runner: func(genClient *GenClient) JobReact {
            // In this func I need to use Client A & client B
                GenClient.ClientB
                GenClient.ClientA
                ...
            },
        },
    }

    JobRes := make(chan JobReact, len(jobs))
    pool := workerpool.New(5)

    for _, worker := range jobs {
        pool.Submit(wrapper(time.Duration(time.Second * 10), JobRes, worker, genClients))
    }
    pool.StopWait()
    GetAllResponses(JobRes)
}

func GetAllResponses(wr chan JobReact) ResultList {
    for jobChannel := range wr {
        if jobChannel.Info != 200 {
            fmt.Printf("job %s: took '%d' sec response: %s\n", jobChannel.Name(), jobChannel.Duration.Seconds(), jobChannel.Error)
            return ResultList{response: http.Response{StatusCode: 500}}
        }
        fmt.Printf("job %s: took '%d' sec response: %s\n", jobChannel.Name(), jobChannel.Duration.Seconds(), jobChannel.Info)
    }
    return ResultList{response: http.Response{StatusCode: 200}}
}

func ClientA() http.Client {
    c := &http.Client{}
    return *c
}

func ClientB() kubernetes.Clientset {
    ....
    return *clientset
}


texts: Bash script to send emails when web server does not respond

texts:
I've made a simple bash script to check if a web server responds, and to send emails to a list of addresses if the website is down. Any suggestions as to how to improve it/ edge cases that I missed/ better styling/ etc? I'm not very familiar with idiomatic bash.

#!/bin/sh

output=$(wget http://lon3213:8111 2>&1)
pattern="connected"
path="/remote/users/my_user/projects/cmb_pinger/"
# File where I check and write the status of the server
# so I don't end up sending more e-mails for the same
# downtime. It writes 0 if no email has been sent yet
# and 1 if the email has been already sent.
log="check"
emails="email1@example.com,email2@example.com"

# Create file if it doesn't exist
if ! [[ -f "$path$log" ]]
then
    echo "0" > "$path$log"
fi

# Website cannot be reached
if [[ ! "$output" =~ "$pattern" ]]
then
    # Emails have not yet been sent
    if [[ $(cat "$path$log") == "0" ]]; then
        echo "$output" | mail -s "Dashboard is down" $emails
        echo "1" >| "$path$log"
    fi
else
    echo "0" >| "$path$log"
fi


texts: Generating a musical scale from a root note

texts:
I'm looking to improve my coding skills. I am new to programming, and after weeks of research and trial and error - I have successfully wrote this basic program to find a music scale by inputting a Root note and Scale.

Since I am pretty much teaching my self - I am looking for criticism to improve my syntax/programming. I compressed the code listed below and localized variables into a 46 line version of this program but really like the layout of the original, so please be brutally honest. Pros and Cons with explanations please?

Note: I was purely being lazy by using #define and plan to replace all strings and vectors with their correct std::typename.

#include <iostream>
#include <string>
#include <vector>
#include <map>

#define astring std::string
#define cvector std::vector

astring rootnote = "";
astring scale = "";
void notation();
int root;
cvector<astring> notes;
cvector<astring> order;
void scaler();

int main()
{
    while (rootnote != "null") {

        std::cout << "Please enter your root note and scale: " << std::endl;
        std::cin >> rootnote >> scale;

        std::cout << "\nroot scale: " << rootnote << " " << scale << std::endl;
        std::cout << std::endl;

        notation();
        scaler();
    }

    return 0;
}

void notation()
{
    notes.clear();

    cvector<astring> chromatic = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };

    root = std::distance(chromatic.begin(), std::find(chromatic.begin(), chromatic.end(), rootnote));

    for (int i = root; i < chromatic.size(); i++) { notes.push_back(chromatic[i]); }
    for (int j = 0; j < root; j++) { notes.push_back(chromatic[j]); }

    return;
}

void scaler() {
    order.clear();

    std::map<astring, cvector<int>> scales;
    scales["Major"] = { 0, 2, 4, 5, 7, 9, 11 };
    scales["Minor"] = { 0, 2, 3, 5, 7, 8, 10 };
    scales["Melodic"] = { 0, 2, 3, 5, 7, 9, 11 };
    scales["Harmonic"] = { 0, 2, 3, 5, 7, 8, 11 };

    for (auto i : scales[scale])
        order.push_back(notes[i]);
    for (int j = 0; j < order.size(); j++)
        std::cout << order[j] << " ";

    std::cout << "\n\n" << std::endl;

    return;
}


texts:
Restricting types not related through inheritance without using instanceOf by creating own class hierarchy. It needs to interact with a key value data store, will convert to object before putting, but needs to convert back to fields after getting from DB with Function<Object,Field>. Something about this with regards to inheritance doesn't seem right, although it works.

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;

/**
 * Field, placeholder for a type that can be stored in db
 */
@EqualsAndHashCode
public class Field<T> {
    @Getter
    private T featureValue;

    Field(@NonNull T value) {
        this.featureValue = value;
    }

    public static class Factory {
    }
}
//convert object to feature value (since ddb returns Map<String, Object> on Item.asMap)
//convert particular type of object to feature value (say Integer, String)
//abstract Field from(T value);
//convert feature value to particular type, call from drvd (from base => obj)
//enum or getEnum for some type expressed as string factory

/**
 * Field for a boolean type
 */
public class BooleanField extends Field<Boolean> {
    public BooleanField(Boolean value) {
        super(value);
    }

    public static BooleanField fromObject(Object value) {
        return new BooleanField((Boolean) value);
    }
}

import java.util.List;

/**
 * Field for a list data type, holds a list of Field
 */
public class ListField extends Field<List<Field>> {
    public ListField(List<Field> value) {
        super(value);
    }

    public static ListField fromObject(Object value) {
        return new ListField((List<Field>) value);
    }
}

import java.util.Map;

/**
 * Field for a map type, holds a map of String to Field
 */
public class MapField extends Field<Map<String, Field>> {
    public MapField(Map<String, Field> value) {
        super(value);
    }

    public static MapField fromObject(Object value) {
        return new MapField((Map<String, Field>) value);
    }
}

/**
 * Field for a Numeric type
 */
public class NumericField extends Field<Number> {
    public NumericField(Number value) {
        super(value);
    }

    public static NumericField fromObject(Object value) {
        return new NumericField((Number) value);
    }
}

import java.util.Set;

/**
 * Field for a set data type
 */
public class SetField extends Field<Set<Field>> {
    public SetField(Set<Field> value) {
        super(value);
    }

    public static SetField fromObject(Object value) {
        return new SetField((Set<Field>) value);
    }
}

/**
 * Field for a string type
 */
public class StringField extends Field<String> {
    public StringField(String value) {
        super(value);
    }

    public static StringField fromObject(Object value) {
        return new StringField((String) value);
    }
}


texts:
I use the module os specifically for Windows since I am familiar with Batch. Batch alone didn't allow me to execute more complicated mathematical functions, I began to use Python.

import os
import math
os.system('cls')
os.system('')
os.system('color a')
os.system('title Quadratic Equation Solver')
#This is used for presentation of the function for WINDOWS cmd
#------------------------------------------------
def QuadSolve():
    os.system('cls')
    print("         Quadratic Equation Solver 1")
    print("")
    print(" X = (-b +/- sqrtb^2 + sqrt4ac)/div/2a ")
    print("")
    print("    Quadratic equation: ax^2 + bx + c")
    print("")
    print("")
    print("")
    a = int(input(" What is the value of a? ---> "))
    b = int(input(" What is the value of b? ---> "))
    c = int(input(" What is the value of c? ---> "))
    firstsec = -1 * b #first second and third "sectors" of the expression
    secsec = math.sqrt(b ** 2 - 4 * a * c)
    thirdsec = 2 * a
    Plussl = firstsec + secsec #Pluss1 is where -b and root b^2 + 4ac are added to give a value of X
    X = Plussl / thirdsec
    Negsl = firstsec - secsec #Same purpose as Plussl but subtraction is used instead to give the other solution of X
    X2 = Negsl / thirdsec
    print("")
    print("         X=%d  OR  X=%d ") % (X, X2)
    os.system('pause >nul')
    QuadSolve()

QuadSolve()

I am very interested to know if anyone has any alternatives.


texts: CompletableFuture in Java, code that gets responses from different websites using HttpClient in Java. What can I do better?

texts:
I have a static list of Strings (website urls), I am trying to connect to them and get responses, in syncRequests method, I am using HttpClient in synchronous manner, in asyncRequests method, I am using HttpClient in asynchronous manner. I am seeing some time differences between syncRequests and asyncRequests time, but I have a hunch I maybe doing something wrong or I can do something better.
Fellow stackexchange users, kindly review my code and let me know any changes or improvements that I can make.
Syntax wise I can make some changes related to modularizing the code, but what I want to understand is, improvements in terms of performance related to Completable Future and HttpClient. Below code is sort of a POC to understand CompletableFuture and check for any performance gains on response related processing.
Below is my code.
Thanks in advance.
`
    public class ProcessingList {

    static List<String> urls = Arrays.asList("https://www.google.com", "https://www.reddit.com", "https://www.yahoo.co.in", "https://www.hackerrank.com", "https://devrant.com",
            "https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html",
            "https://bing.com", "https://xkcd.com", "https://www.facebook.com", "https://www.amazon.co.in",
            "https://www.flipkart.com");

    public static void main(String[] args) {

        long start = System.currentTimeMillis();

        List<String> resp1 = syncRequests();

        System.out.println("time taken 1:" + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();

        List<String> resp2 = asyncRequests();

        System.out.println("time taken 1:" + (System.currentTimeMillis() - start));
    }

    private static List<String> syncRequests() {
        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL)
                .version(HttpClient.Version.HTTP_2)
                .build();

        return urls.stream().map(url -> {
            try {
                HttpRequest request = HttpRequest.newBuilder().uri(new URI(url)).build();
                HttpResponse<String> resp = client.send(request, HttpResponse.BodyHandlers.ofString());
                return resp.body();
            } catch (URISyntaxException | InterruptedException | IOException e) {
                e.printStackTrace();
            }
            return "";
        }).collect(Collectors.toList());//.forEach(System.out::println);
    }

    private static List<String> asyncRequests() {

        List<CompletableFuture<String>> list = new ArrayList<>();
        List<String> responses = new ArrayList<>();
        ExecutorService service1 = Executors.newCachedThreadPool();
        ExecutorService service2 = Executors.newCachedThreadPool();

        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL)
                .version(HttpClient.Version.HTTP_2)
                .build();

        urls.parallelStream().forEach(url -> {
            try {
                HttpRequest request = HttpRequest.newBuilder().uri(new URI(url)).build();
                list.add(
                        client
                                .sendAsync(request, HttpResponse.BodyHandlers.ofString())
                                .thenApplyAsync(HttpResponse::body, service1)
                                .whenCompleteAsync((resp, err) -> {
                                    responses.add(resp);
                                }, service2)
                );
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

        });

        list.forEach(cf -> {
            responses.add(cf.join());
        });

        service1.shutdown();
        service2.shutdown();

        return responses;
    }

`


texts: Creating vector of primes using Sieve of Eratosthenes

texts:
Please review my Sieve of Eratosthenes implementation.

std::vector<int> generate(const int& n) {
    std::vector<bool> input(n+1, true);
    for (int i = 2; i * i<= n; ++i) {
        for (int j = i; i*j <= n    ; ++j) {
            input[i*j] = false;
        }
    }
    std::vector<int> primes{};
    for (auto i = 1; i <= n; ++i) {
        if (input[i]) {
            primes.push_back(i);
        }
    }
    return primes;
}

How can I improve and make this faster?


texts:
I'm imagining go generate would be a good tool for this. I want to convert strings to ints to save space.

type Source int

func NewSource(s string) Source {
    switch s {
    case "Twitter":
        return Twitter
    case "Facebook":
        return Facebook
    case "Gplus":
        return Gplus
    case "Spotify":
        return Spotify
    case "Linkedin":
        return Linkedin
    case "Github":
        return Github
    case "Lastfm":
        return Lastfm
    default:
        panic(ErrUnknownSourceType)
    }
}

const (
    Twitter Source = iota
    Facebook
    Gplus
    Spotify
    Linkedin
    Github
    Lastfm
)


texts:
I wrote this in order to get a list of network interfaces on Linux. In the past, I have used publicly available methods from, say, ActiveState, which uses ioctl and was annoying to get working under Python 3. This version simply uses regular expressions on the output of ifconfig.

The documentation style used here follows the numpy documentation guide.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Get a list of network interfaces on Linux.

This code is compatible with Python versions 2 and 3.

"""
from collections import namedtuple
import re
import subprocess

def get_interfaces(external=False, ip=False):
    """
    Get a list of network interfaces on Linux.

    To access the MAC address and/or the IP address, set the relevant keyword
    arguments to True.

    Parameters
    ----------
    external : bool, optional
        Only show external interfaces, and ignore virtual (e.g. loopback)
        devices, and return their MAC addresses.
    ip : bool, optional
        Only show interfaces which are UP and have an IP address, and return
        their IPv4 addresses.

    Returns
    -------
    interfaces
        list of str containing the interface name by default, or list of
        namedtuple containing `name`, `mac`, and `ip` as requested.

    Examples
    --------
    >>> print(get_interfaces())
    ['eth0', 'lo', 'wlan0']
    >>> print(get_interfaces(external=True))
    [Interface(name='eth0', mac='a0:b1:c2:d3:e4:f5'), Interface(name='wlan0', ma
    c='f5:e4:d3:c2:b1:a0')]
    >>> print(get_interfaces(ip=True))
    [Interface(name='lo', ip='127.0.0.1'), Interface(name='wlan0', ip='192.168.1
    1.2')]
    >>> print(get_interfaces(external=True, ip=True))
    [Interface(name='wlan0', mac='f5:e4:d3:c2:b1:a0', ip='192.168.11.2')]

    """
    name_pattern = "^(\w+)\s"
    mac_pattern = ".*?HWaddr[ ]([0-9A-Fa-f:]{17})" if external else ""
    ip_pattern = ".*?\n\s+inet[ ]addr:((?:\d+\.){3}\d+)" if ip else ""
    pattern = re.compile("".join((name_pattern, mac_pattern, ip_pattern)),
                         flags=re.MULTILINE)

    ifconfig = subprocess.check_output("ifconfig").decode()
    interfaces = pattern.findall(ifconfig)
    if external or ip:
        Interface = namedtuple("Interface", "name {mac} {ip}".format(
            mac="mac" if external else "",
            ip="ip" if ip else ""))
        return [Interface(*interface) for interface in interfaces]
    else:
        return interfaces

if __name__ == "__main__":
    interfaces = get_interfaces(external=True, ip=True)
    for interface in interfaces:
        print("{name}: {ip}".format(name=interface.name, ip=interface.ip))


texts: Python Firewall-Connection-Event Filter too slow

texts:
I've written a little piece of code to filter Firewall-Connection-Events by a certain group of IPs. But the code can't keep up since the input is fairly huge. I am looking for ways to make this code more efficient in order to handle the Firewall-Connection-Events.

[READ_CLIENTS]
The code starts with an empty list (client_IPs). The list is getting filled with unique IPs (read_clients), if the size of the file changes "read_clients" is called again to alter the list.

[READ_EVENTS]
To get the events, I've used While True to loop over the event-File and return the events with yield - if there is no new input, then sleep for 0.1 seconds.

[PROCESS_AND_FILTER]
After this I loop over the generator object to compare each event to each Unique-IP and seperate the result in two files.

    # -*- coding: utf-8 -*-

from IPy import IP
import os
import time

# Create String-Array to compare
path_unique_ips = '/var/log/unique.log'
# Sophos-UTM Packet-Accepted-Event | Connections to Customer-Net
path_sophos_to_customer = '/var/log/packet-accepted-sophos.log'
# match logs
match_log = '/var/log/matched.log'
no_match_log = '/var/log/not_matched.log'
# IP-Filter-Array
client_IPs = []
#get file size of unique ips file
size_ip_file = os.stat(path_unique_ips).st_size

def read_clients(path_unique_ips):
     client_IPs_file = open(path_unique_ips, "r")
     if client_IPs_file.mode == 'r':
               # read all line from client_IPs_file
               new_client_IPs = client_IPs_file.readlines()
               #check for new clients and fill array
               for new_client_IP in new_client_IPs:
                    if new_client_IP not in client_IPs:
                        client_IPs.append(IP(new_client_IP).strNormal())

def read_events(path_sophos_to_customer):
     connection_event_to_customer = open(path_sophos_to_customer, 'r')
     connection_event_to_customer.seek(0, 2)
     if connection_event_to_customer.mode == 'r':
         while True:
            new_event = connection_event_to_customer.readline()
            if not new_event:
                time.sleep(0.1)
                continue
            yield new_event
            #file size of unique IP File changed, re-run the function read_clients
            if size_ip_file is not os.stat(path_unique_ips).st_size:
                read_clients(path_unique_ips)

def process_and_filter(my_events):
    #get events in generator-object from function read_events
    # loop over generator-object, filled with events
    for new_event in my_events:
        print(new_event)
        # loop over event with all ips
        for client in client_IPs:
            # if client-ip found in event write to match.log and break loop to go for next event
            if client in new_event:
                with open(match_log, 'a+') as matched:
                    matched.write(new_event)
                break
        # if ip wasn't in event write event to no_match.log
        else:
             with open(no_match_log, 'a+') as no_match:
                no_match.write(new_event)

if __name__ == '__main__':
     read_clients(path_unique_ips)
     new_events=read_events(path_sophos_to_customer)
     process_and_filter(new_events)

Log_Event_Example :

  Jan 18 14:14:14 17.17.17.17 2019: 01:18-14:14:14 firewall-1
  ulogd[5974]: id="2002" severity="info" sys="SecureNet"
  sub="packetfilter" name="Packet accepted" action="accept" fwrule="653"
  initf="eth1" outitf="eth0" srcmac="aa:bb:cc:dd:ee:ff"
  dstmac="00:11:22:33:44:55" srcip="10.10.10.10" dstip="10.10.10.11"
  proto="6" length="52" tos="0x00" prec="0x00" ttl="127" srcport="58589"
  dstport="22" tcpflags="ACK"


texts:
Below is a netstring parser I wrote in Common Lisp. The docstring contains the usage and return.

(defun parse-netstring (netstring acc)
  "recursively parses netstring of the form
   size1:string1,size2:string2,size3:string3,
   acc can be any list, or nil
   returns -> (string3 string2 string1)"
  (if (equalp netstring "")
      acc
      (let* ((netstring-split
          (split-on-first-char #\: netstring))
         (comma-index
          (parse-integer (first netstring-split)))
         (netstring-body
          (second netstring-split)))
    (if (not (char= #\, (aref netstring-body comma-index)))
      (error 'malformed-netstring-error :netstring netstring)
      (parse-netstring
       (subseq netstring-body (1+ comma-index))
       (cons (subseq netstring-body 0 comma-index) acc))))))


texts: Project Euler Problem 18 (Haskell) - Maximum path sum I

texts:
I've implemented the solution to Project Euler Problem 18 in Haskell and I'd like to get some thoughts on my implementation.  Its the dynamic programming solution, working from the bottom up.

Basically, given a set of numbers in a triangular shape, the path whose numbers add up to the greatest possible sum from the top to the bottom must be found.

I believe its correct, but with Project Euler being partially down, I couldn't plug-in the answer so I had to rely on Google.  I get the following result: 1074.

My code reads in a text file that contains the problem data and looks like this:

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

Here is my full implementation:

-- Project Euler
-- Problem 18 (http://projecteuler.net/problem=18)
-- Nathan Jackson

import System.Environment
import System.IO

-- Read in a text file containing the problem data, run the algorithm and
-- print the result to the console.
main :: IO ()
main = do
    cmdargs <- getArgs
    withFile (head cmdargs) ReadMode (\handle -> do
        contents <- hGetContents handle
        let inputData = parse contents
        putStrLn $ show $ maxPathSum inputData)

-- Given a string whose format looks something like this:
--   1
--   2 3
--   4 5 6
--   7 8 9 0
-- Convert it to a list of lists that contains integers where each nested list
-- represents a line from the original string.
parse :: String -> [[Int]]
parse s  = map (map (read :: String -> Int)) (map words $ lines s)

-- Reduces a list of lists containing integers to its maximum path sum.
maxPathSum :: [[Int]] -> Int
maxPathSum [[x]] = x
maxPathSum xs =
    let maxPairs ys = zipWith max ys $ tail ys
        sx = reverse xs
    in maxPathSum $ ((init . init) xs) ++ [zipWith (+) (maxPairs (head sx)) $ sx !! 1]


texts:
I'm trying to implement a simple name search using elasticsearch and a java app as the client.

Schema:

{
    "firstname": {
        "type": "string",
        "analyzer": "standard"
    },
    "lastname": {
        "type": "string",
        "analyzer": "standard"
    },
    "fullname": {
        "type": "string",
        "analyzer": "standard"
    }
}

Query:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "fullname": {
              "query": "Michael Jordan",
              "type": "boolean",
              "fuzziness": 1,
              "minimum_should_match": "100%"
            }
          }
        },
        {
          "match": {
            "lastname": {
              "query": "Michael Jordan",
              "type": "boolean",
              "fuzziness": 1
            }
          }
        }
      ]
    }
  }
}

Code:

String fullname = QueryParser.escape(queryFullname);
BoolQueryBuilder queryBuilder = boolQuery()
  .must(matchQuery("fullname", fullname).fuzziness(fuzziness).minimumShouldMatch("100%"))
  .must(matchQuery("lastname", fullname).fuzziness(fuzziness));

Requirements:

Use the existing mapping. This means that I can't change the analyzer. This doesn't affect a lot, as the only thing I would add is asciifolding.
Return results when searching only with lastname, but do not when searching only with firstname
Allow space for errors in the query param. This is the reason for the fuzziness, it also takes care the absence of asciifolding, although it narrows the window error.

Explanation:

I'm using must in fullname and lastname only, since searching with firstname would break one of the requirements.
I'm using minimum should match of 100% in fullname since I want all query terms to have a match with the document terms in order to mark it as a result. There is a window of error through fuzziness.
The reason I'm using fullname too, and not only last name is because I want to get better scores when the whole fullname is a match.
The reason I'm using the lastname can be better explained through an example

Documents:

fullname: Paul Foo Bar, firstname: Paul, lastname: Foo Bar
fullname: Paul Alkis Desk, firstname: Paul, lastname: Alkis Desk

Query:

Paul Bar

The query as is, will bring Paul Foo Bar which I want.
If I use only the fullname and remove minimum should match it will bring both (because of Paul) which I don't want. If I keep and play with minimum should match the results will become very inconsistent.

My question is, is the logic good enough? Is there a better (i.e. faster or more reliable) way to do what I need without changing the mapping? I haven't tested the performance yet, but can you spot any major performance pitfalls?

I'm using ElasticSearch 1.7.5

p.s. If you find this to be utterly wrong and for a variety of reasons, then feel free to say so and point me to some useful reading material. I'm a new to elasticsearch.


texts: Iterative Implementation of Towers of Hanoi

texts:
Here is an implementation of Towers of Hanoi based on few observed patterns1 from the easier recursive solution:

function [] = myTowersOfHanoi(N, from, to, alt)
  % Accepts three integers: N - number of disks
  % from - number of start tower, to - number of end tower, alt - free tower.
  % Returs string outputs with succesive moves to complete the task of solving
  % the Towers of Hanoi with N disks moved from tower with number stored
  % in the second argument to one with number in third arg.

  totalNumberOfMoves = (2 ^ N) - 1;

  M = generateDiskMoves(totalNumberOfMoves);

  % These are the paths of disks if N is odd.
  path1 = [from, alt, to];  % Path of disk with odd number: from->alt->to
  path2 = [from, to, alt];  % Path of disk with even number.

  currentPositions = ones(1, N); % index-disk number, value-number of moves

  len = numel(path1);

  % If N (numer of disks) is even the paths are swapped.
  if mod(N, 2) == 0
    [path2, path1] = swapArrays(path1, path2);
  end

  % Solve
  for i = M
    from = -1;
    to = -1;

    if mod(i, 2) == 0  % if number of disk, i is even
      j = currentPositions(i); % j - number of moves for i-th disk

      % In C++ indexes: [0, size - 1] in Octave: [1, size]
      % so: mod(j - 1, len) + 1, to avoid index = 0.
      from = path1( mod(j - 1, len) + 1); % Cycle over 1->2->3

      j = j + 1;

      to =  path1( mod(j - 1, len) + 1);

      currentPositions(i) = j; % update moves of i-th disk

    else
      k = currentPositions(i);

      from = path2( mod(k - 1, len) + 1);
      k = k + 1;
      to =  path2( mod(k - 1, len) + 1);

      currentPositions(i) = k;
    end
      disp(sprintf('Move disk %d from %d to %d.', i, from, to))
  end

end

function [a2, a1] = swapArrays (a1, a2)
  [a2, a1] = deal(a1, a2);
end

% From: http://mathworld.wolfram.com/BinaryCarrySequence.html
function [M] = generateDiskMoves(N)
  % Accepts integer: N - total number of moves.
  % Returns a 1xN integer array with the first N consecutive disk moves
  % in Tower of Hanoi where the index is the move number
  % and the value is the disk number. m - is discarded.

  [m, M] = Omega2(N); % Generate the first N terms of: "Binary Carry Sequence".

  M = M .+ 1;         % Add one and get moves of disk in Tower of Hanoi.

  if N < 2            % Get only the first move.
    M = M(1);
  end
end

% From : https://oeis.org/A007814
function [m, M] = Omega2(n)
  % Accepts an integer: n.
  % Returns m: max power of 2 such that 2^m divides n, and
  % M: 1-by-K matrix where M(i) is the max power of 2 such
  % that 2^M(i) divides n.

  M = NaN * zeros(1, n);

  M(1) = 0;
  M(2) = 1;

  for k = 3 : n
    if M(k - 2) ~= 0
      M(k) = M(k - k / 2) + 1;
    else
      M(k) = 0;
    end
  end

  m = M(end);
end

Input: Move 4 disks from 1st to 3rd peg, 2nd is free.

myTowersOfHanoi(4, 1, 3, 2)

Output:

Move disk 1 from 1 to 2.
Move disk 2 from 1 to 3.
Move disk 1 from 2 to 3.
Move disk 3 from 1 to 2.
Move disk 1 from 3 to 1.
Move disk 2 from 3 to 2.
Move disk 1 from 1 to 2.
Move disk 4 from 1 to 3.
Move disk 1 from 2 to 3.
Move disk 2 from 2 to 1.
Move disk 1 from 3 to 1.
Move disk 3 from 2 to 3.
Move disk 1 from 1 to 2.
Move disk 2 from 1 to 3.
Move disk 1 from 2 to 3.

I would appreciate your opinion and suggestions related to:

MATLAB / Octave coding style and readability.
thoughts on / possible improvements of the algorithm.

1. The observations were that firstly: the sequence of transitions could be  described by a slightly modified formula: "Binary Carry Sequence" and secondly: individual disk transitions are following only two different cyclic paths which were based on the parity of the total number of the disks, N, and the parity of the number of the currently moving disk, i.e:


texts: Checking for required text fields for login

texts:
I wrote this script and it's working quite well however I think there's too much if else statements on it. How could I change them for a switch statement?

@IBAction func sendLoginParameters(_ sender: UIButton) {

    if correoTextField.text?.isEmpty == true && contrasenaTextField.text?.isEmpty == true {
        let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (CORREO Y CONTRASEÑA) antes de continuar", preferredStyle: .alert)
        alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))
        self.present(alertMessage, animated: true, completion: nil)
        return

    } else if correoTextField.text?.isEmpty == true  {

        let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (CORREO) antes de continuar", preferredStyle: .alert)
        alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))
        self.present(alertMessage, animated: true, completion: nil)
        return

    } else if contrasenaTextField.text?.isEmpty == true {

        let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (CONTRASEÑA) antes de continuar", preferredStyle: .alert)
        alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))
        self.present(alertMessage, animated: true, completion: nil)
        return
} else {
...


texts: Writing FizzBuzz like this makes me feel like a small child

texts:
For the sake of full disclosure, this was written with bananas, not apples.  The doctor may not be kept away.
With AppleScript highlighting:

For Copy&Pasting:
activate application "TextEdit"
tell application "System Events"
    repeat until first window of application "TextEdit" exists
        tell application "TextEdit" to make new document at the front
        delay 1.0E-3
    end repeat
    repeat until process "TextEdit" is frontmost
        set frontmost of process "TextEdit" to true
        delay 1.0E-3
    end repeat
    set focused of first window of process "TextEdit" to true

    repeat with i from 1 to 100
        if i mod 15 is 0 then
            keystroke "FizzBuzz"
            keystroke return
        else if i mod 3 is 0 then
            keystroke "Fizz"
            keystroke return
        else if i mod 5 is 0 then
            keystroke "Buzz"
            keystroke return
        else
            keystroke i
            keystroke return
        end if
    end repeat
end tell

I borrowed the logic for appropriately waiting for "TextEdit" to be ready to receive text from this excellent Code Review answer.
I feel like I want to write functions... but I don't know what's available in AppleScript for modularizing code... err script... I'm just getting my toes wet here.


texts:
I have created a module that validates the credentials against different databases.
module Authentication

  DATABASES = %w[mysql mssql oracle].freeze

  DATABASES.each do |database|
    define_method("#{database}_connect") do |args|
      client = case database
               when 'mysql' then Mysql2::Client.new args.merge(ssl_mode: :disabled)
               when 'mssql' then TinyTds::Client.new args
               when 'oracle' then OCI8.new(args[:username], args[:password], "//#{args[:host]}:#{args[:port]}/#{args[:service_name]}")
               end
      case database
      when 'mysql', 'oracle' then true
      when 'mssql' then client.active?
      end
    end
  end

  def database_authentication_success?(database:, host:, port:, service_name:, username:, password:)
    options = {host: host, port: port, service_name: service_name, username: username, password: password}
    case database
    when 'mysql' then mysql_connect(options)
    when 'mssql' then mssql_connect(options)
    when 'oracle' then oracle_connect(options)
    end
  end
end

Please let me know, how can it be improved?


texts: Best practice to upload files on server using Rest Service

texts:
I am using building REST services for file upload on the server. Here is some code of that

[OprationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadFile/{fileName}")]
public string UploadFile(string fileName, Stream fileStream)
{
  string filePath = serverDirectory + "\\" + fileName;
  using (var output = File.Open(filePath, FileMode.Create))
  {
     fileStream.CopyTo(output);
  }
  return "success";
}

However this method works fine when file size is small. but when the file size is large say 30-40 Mb then the performance become low.

So I want to know what are the best practices to upload the files on the server with speed.


texts:
I am working on an implementation of the minimalist compression method.
The method is based on context modeling, followed by a simple entropy coder (Golomb-Rice coder).
The context model uses a single previous byte in the uncompressed symbol stream to predict the next byte.
At the moment, my implementation works quite well.
However, I wonder if it is possible to make it faster or more concise.
Basically, any suggestions for improvement are welcome.

Prerequisites

The implementation uses the following data structure:

struct context {
    size_t freq[256];          /* char -> frequency */
    unsigned char sorted[256]; /* index -> char */
    unsigned char order[256];  /* char -> index */
} table[256];

The functions bio_open, bio_write_gr, bio_read_gr, and bio_close implement the entropy (Golomb-Rice) coding.

Moreover, the function void update_model(unsigned char delta) updates the entropy model according to the newly encoded byte delta (not the subject of this review).

Code

I use several two auxiliary functions:

static void swap_symbols(struct context *context, unsigned char c, unsigned char d)
{
    assert(context != NULL);

    unsigned char ic = context->order[c];
    unsigned char id = context->order[d];

    assert(context->sorted[ic] == c);
    assert(context->sorted[id] == d);

    context->sorted[ic] = d;
    context->sorted[id] = c;

    context->order[c] = id;
    context->order[d] = ic;
}

static void increment_frequency(struct context *context, unsigned char c)
{
    assert(context != NULL);

    unsigned char ic = context->order[c];
    size_t freq_c = ++(context->freq[c]);

    unsigned char *pd;

    for (pd = context->sorted + ic - 1; pd >= context->sorted; --pd) {
        if (freq_c <= context->freq[*pd]) {
            break;
        }
    }

    unsigned char d = *(pd + 1);

    if (c != d) {
        swap_symbols(context, c, d);
    }
}

The main entry functions are defined as follows:

void init()
{
    opt_k = 3;

    for (int p = 0; p < 256; ++p) {
        for (int i = 0; i < 256; ++i) {
            table[p].sorted[i] = i;
            table[p].freq[i] = 0;
            table[p].order[i] = i;
        }
    }
}

void *compress(void *iptr, size_t isize, void *optr)
{
    struct bio bio;
    unsigned char *end = (unsigned char *)iptr + isize;
    struct context *context = table + 0;

    bio_open(&bio, optr, BIO_MODE_WRITE);

    for (unsigned char *iptrc = iptr; iptrc < end; ++iptrc) {
        unsigned char c = *iptrc;

        /* get index */
        unsigned char d = context->order[c];

        bio_write_gr(&bio, opt_k, (uint32_t)d);

        assert(c == context->sorted[d]);

        /* update context model */
        increment_frequency(context, c);

        /* update Golomb-Rice model */
        update_model(d);

        context = table + c;
    }

    /* EOF symbol */
    bio_write_gr(&bio, opt_k, 256);

    bio_close(&bio, BIO_MODE_WRITE);

    return bio.ptr;
}

void *decompress(void *iptr, void *optr)
{
    struct bio bio;
    struct context *context = table + 0;

    bio_open(&bio, iptr, BIO_MODE_READ);

    unsigned char *optrc = optr;

    for (;; ++optrc) {
        uint32_t d = bio_read_gr(&bio, opt_k);

        if (d == 256) {
            break;
        }

        assert(d < 256);

        unsigned char c = context->sorted[d];

        *optrc = c;

        increment_frequency(context, c);

        update_model(d);

        context = table + c;
    }

    bio_close(&bio, BIO_MODE_READ);

    return optrc;
}


texts: C# MySQL library: How can I reduce bundling and abstraction?

texts:
I'm a teen developer who just does this as a hobby, but I still care about good practice even if I don't fully understand it. Two of the most used phrases when sharing the code of my C# MySQL library is bundling and abstraction,
First of all... do I need to reduce said phrases? If so, how can I do that? Among any other general recommendations on areas, I can improve.
DatabaseProvider: This simply just holds state for database settings (host, name, port, etc) and returns a new instance of DatabaseConnection whenever the application needs one.
public class DatabaseProvider : IDatabaseProvider
{
    private readonly string _connectionString;

    public DatabaseProvider(string databaseName, string password, uint port, string host, string username)
    {
        _connectionString = new MySqlConnectionStringBuilder
        {
            Database = databaseName,
            Password = password,
            Port = port,
            Server = host,
            UserID = username,
            SslMode = MySqlSslMode.None,
            DefaultCommandTimeout = 30,
            CharacterSet = "utf8mb4",
            AllowUserVariables = true,
            MinimumPoolSize = 1,
        }.ToString();
    }

    public DatabaseConnection GetConnection()
    {
        var connection = new MySqlConnection(_connectionString);
        var command = connection.CreateCommand();

        return new DatabaseConnection(connection, command);
    }
}

DatabaseConnection: Also pretty simple, although very different from the provider. This is the actual abstracted instance of MySqlConnection with utility methods to perform frequent operations like fetching rows or collections of rows or just running general queries. It also supports parameters although they aren't type-safe.
public class DatabaseConnection : IDisposable
{
    private readonly MySqlConnection _connection;
    private readonly MySqlCommand _command;

    public DatabaseConnection(MySqlConnection connection, MySqlCommand command)
    {
        _connection = connection;
        _command = command;

        _connection.Open();
    }

    public void SetQuery(string commandText)
    {
        _command.Parameters.Clear();
        _command.CommandText = commandText;
    }

    public void ExecuteQuery()
    {
        _command.ExecuteNonQuery();
    }

    public DataTable ExecuteTable()
    {
        var dataTable = new DataTable();

        using var adapter = new MySqlDataAdapter(_command);
        adapter.Fill(dataTable);

        return dataTable;
    }

    public DataRow ExecuteRow()
    {
        DataRow dataRow = null;

        var dataSet = new DataSet();

        using (var adapter = new MySqlDataAdapter(_command))
        {
            adapter.Fill(dataSet);
        }

        if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count == 1)
        {
            dataRow = dataSet.Tables[0].Rows[0];
        }

        return dataRow;
    }

    public void AddParameter(string name, object value)
    {
        _command.Parameters.AddWithValue(name, value);
    }

    public void Dispose()
    {
        if (_connection.State != ConnectionState.Closed)
        {
            _connection.Close();
        }

        _connection.Dispose();
        _command.Dispose();
    }
}


texts: Reducing using/foreach/using nesting with a helper extension

texts:
Problem statement

There are sometimes foreach scenarios that require deep nesting due to multiple disposable objects involved that look like this:

using(..)
{
    foreach(..)
    {
        using(..)
        {

        }
    }
}

or a real-world example from one of my applications:

using (_logger.BeginScope().CorrelationHandle("TestBundle").AttachElapsed())
using (Disposable.Create(() =>
{
    foreach (var item in cache.Values) item.Dispose();
}))
{
    _logger.Log(Abstraction.Layer.Service().Meta(new { TestBundleFileName = testBundle.FileName }));
    foreach (var current in tests)
    {
        using (_logger.BeginScope().CorrelationHandle("TestCase").AttachElapsed())
        {
            // body
        }
    }
}

I find this code is very ugly and there is virtually no other way of writing this (or it's just me and I cannot think of any).

Suggested solution

So, in order to make it prettier I created the Using extension that encapsulates the outer and inner usings within the loop.

Its body is identical to the using/foreach/using pattern I'd like to get rid of elsewhere:

public static class EnumerableExtensions
{
    public static IEnumerable<(TItem Current, TInner Context)> Using<TItem, TOuter, TInner>
    (
        this IEnumerable<TItem> source,
        TOuter outer,
        Func<TItem, TInner> inner
    )
    {
        using (new Disposer<TOuter>(outer))
        {
            foreach (var item in source)
            {
                using (var context = new Disposer<TInner>(inner(item)))
                {
                    yield return (item, context);
                }
            }
        }
    }
}

This is using a helper struct for disposing TOuter and TInner

public readonly struct Disposer<T> : IDisposable
{
    public Disposer(T value)
    {
        Value = value;
    }

    public T Value { get; }

    public void Dispose()
    {
        if (Value is IDisposable disposable)
        {
            disposable.Dispose();
        }
        else
        {
            foreach (var property in typeof(T).GetProperties())
            {
                if (property.GetValue(Value) is IDisposable disposableProperty)
                {
                    disposableProperty.Dispose();
                }
            }
        }
    }

    public static implicit operator T(Disposer<T> disposer) => disposer.Value;
}

And here is the Disposable helper:

public class Disposable : IDisposable
{
    private readonly Action _dispose;

    private Disposable(Action dispose)
    {
        _dispose = dispose;
    }

    public static IDisposable Empty => new Disposable(() => { });

    public static IDisposable Create(Action dispose)
    {
        return new Disposable(dispose);
    }

    public void Dispose()
    {
        _dispose();
    }
}

Example usage

Now, when I have such a scenario, I can put everything inside the loop:

void Main()
{
    var numbers = new[] { 1, 2, 3 };

    foreach (var (item, context) in numbers.Using
    (
        outer: Disposable.Create (() => Console.WriteLine("Outer disposed.")),
        inner: _ => Disposable.Create (() => Console.WriteLine("Inner disposed.")))
    )
    {
        item.Dump();
        context.Dump();
    }
}

Then, when I refactor the previous ugly piece of code with this extension it turns into this:

foreach (var (current, context) in tests.Using
(
    outer: new
    {
        Scope = _logger.BeginScope().CorrelationHandle("TestBundle").AttachElapsed(),
        CleanUp = Disposable.Create(() =>
        {
            foreach (var item in cache.Values) item.Dispose();
        })
    },
    inner: _ => _logger.BeginScope().CorrelationHandle("TestCase").AttachElapsed())
)
{
    // body
}

Questions

What do you think of this helper?
Would you say the code is now easier to read?
Can the Using extension or the Disposer<T> be improved?


texts: Replace all occurrence of REP [block] with value of the block

texts:
I have a block with an undefined data and a pair of REP [code]:

arr: [
    REP ["code1"]
    | 'something
     "f"
    | [ f | 3 ]
    REP [40 + 2]
    ]

The pair can be everywhere in the arr.
I replace every occurrence of a pair REP [code] with a value from evaluating the code.

t: true

while [t == true] [
    f: find arr 'REP
    either f [
        t: true
        change/part f do first next f 2
        ][
        t: false
        ]
]

Does this code follow common best practices? Does it have some security issues? Is there any problems with a performance using this code?


texts: Implementing the React contexts and useMemo

texts:
I use to create react contexts this way. It was a way I found on the internet when I was starting with hooks. I use useMemo in every context I create. I want to know what are the problems in the code and also is it necessary to use useMemo like this in every contexts.
import React, { useMemo, useReducer, useEffect } from 'react';

const ProductContext = React.createContext();

const ProductContextProvider = (props) => {

    const [state, dispatch] = useReducer(
        (prevState, action) => {
            switch (action.type) {
                case 'LOAD_PRODUCTS':
                    return {
                        ...state,
                        products: action.payload,
                        productsLoadingError: false,
                    };
                case 'LOAD_PRODUCTS_ERROR':
                    return {
                        ...state,
                        productsLoadingError: true,
                    };
            }
        },
        {
            products: [],
            productsLoadingError: false,
        },
    );

    useEffect(() => {
        const bootstrapAsync = async () => {
            await getProducts(dispatch);
        };
        bootstrapAsync();
    }, []);

    const productContext = useMemo(
        () => ({
            getAllProducts: async () => {
                await getProducts(dispatch, productsCollection);
            },
            products: state.products,
            productsLoadingError: state.productsLoadingError,
        }),
        [state.products, state.productsLoadingError],
    );

    return (
        <ProductContext.Provider value={productContext}>
            {props.children}
        </ProductContext.Provider>
    );
};

const getProducts = async (dispatch) => {
    try {
        // await for products;
        dispatch({ type: 'LOAD_PRODUCTS', payload: products });
    } catch (error) {
        console.log(error);
        dispatch({ type: 'LOAD_PRODUCTS_ERROR' });
    }
};

export { ProductContextProvider, ProductContext };


texts: Multithreaded Python implementation of a Sudoku validator

texts:
I've just come across these day with the multithreading subject in Python. I remembered @200_success's answer and I thought of making that multithreaded as it follows:

one thread to check that each column contains the digits 1-9 only once
one thread to check that each row contains the digits 1-9 only once
another nine threads to check each 3x3 sub-grid for the digits 1-9

I know multithreading won't bring any speed improvement in this case but I wanted to start learning about this subject and this looked like a good starting point.

from itertools import product
from threading import Thread
from timeit import default_timer as timer
import queue

DIGITS = set(range(1, 10))

def check_grid_size(grid):
    """Check that the grid is 9x9."""
    well_formed = len(grid) == 9 and all(len(row) == 9 for row in grid)
    return well_formed or None

def check_rows(grid, q):
    """Check that each number appears exactly once per row."""
    q.put(all(set(row) == DIGITS for row in grid))

def check_columns(grid, q):
    """Check that each number appears exactly once per column."""
    columns = [[row[c] for row in grid] for c in range(9)]
    q.put(all(set(col) == DIGITS for col in columns))

def check_3x3_grid(grid, q):
    """Check that each number appears exactly once per 3x3 grid."""
    threes = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
    for row_block, col_block in product(threes, threes):
        block = [grid[r][c] for r, c in product(row_block, col_block)]
        if set(block) != DIGITS:
            q.put(False)
            return

    q.put(True)

def check_sudoku(grid):
    """
    Validate a sudoku solution.

    Given a grid as a list of lists, return None if it is ill-formed,
    False if it is invalid, or True if it is a valid solution.
    """
    assert isinstance(grid, list)

    q = queue.Queue()

    if not check_grid_size(grid):
        return None

    row_thread = Thread(target=check_rows, args=(grid, q))
    row_thread.start()

    columns_thread = Thread(target=check_columns, args=(grid, q))
    columns_thread.start()

    grid_threads = []
    for _ in range(9):
        t = Thread(target=check_3x3_grid, args=(grid, q))
        t.start()
        grid_threads.append(t)

    row_thread.join()
    columns_thread.join()

    [t.join() for t in grid_threads]

    results = []
    while not q.empty():
        results.append(q.get())

    return all(results)

def main():
    ill_formed = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
                  [6, 7, 2, 1, 9, 5, 3, 4, 8],
                  [1, 9, 8, 3, 4, 2, 5, 6, 7],
                  [8, 5, 9, 7, 6, 1, 4, 2, 3],
                  [4, 2, 6, 8, 5, 3, 7, 9],  # <---
                  [7, 1, 3, 9, 2, 4, 8, 5, 6],
                  [9, 6, 1, 5, 3, 7, 2, 8, 4],
                  [2, 8, 7, 4, 1, 9, 6, 3, 5],
                  [3, 4, 5, 2, 8, 6, 1, 7, 9]]

    # check_sudoku should return True
    valid = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
             [6, 7, 2, 1, 9, 5, 3, 4, 8],
             [1, 9, 8, 3, 4, 2, 5, 6, 7],
             [8, 5, 9, 7, 6, 1, 4, 2, 3],
             [4, 2, 6, 8, 5, 3, 7, 9, 1],
             [7, 1, 3, 9, 2, 4, 8, 5, 6],
             [9, 6, 1, 5, 3, 7, 2, 8, 4],
             [2, 8, 7, 4, 1, 9, 6, 3, 5],
             [3, 4, 5, 2, 8, 6, 1, 7, 9]]

    # check_sudoku should return False
    invalid = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
               [6, 7, 2, 1, 9, 5, 3, 4, 8],
               [1, 9, 8, 3, 8, 2, 5, 6, 7],
               [8, 5, 9, 7, 6, 1, 4, 2, 3],
               [4, 2, 6, 8, 5, 3, 7, 9, 1],
               [7, 1, 3, 9, 2, 4, 8, 5, 6],
               [9, 6, 1, 5, 3, 7, 2, 8, 4],
               [2, 8, 7, 4, 1, 9, 6, 3, 5],
               [3, 4, 5, 2, 8, 6, 1, 7, 9]]

    print(check_sudoku(valid))
    print(check_sudoku(invalid))
    print(check_sudoku(ill_formed))

if __name__ == '__main__':
    main()

This is working nice when I'm profiling to see how fast it works, but I need to know if I implemented the threads correctly, especially when talking about the 9 threads from the 3x3 sub-grids.


texts: Implementing a generic and covariant Set in Scala

texts:
I'm struggling with manually implementing a simple purely functional Set that's also generic and covariant on its type parameter:

Set must be a trait, allowing for multiple implementations.
it must be covariant on the type of the element it contains.
an implementation's type must not be lost when calling methods that return a new Set.

The first two points are fairly trivial and simply mean that the trait should look something like:

trait Set[+A] {
  def isEmpty: Boolean
  def insert[B >: A](b: B)(implicit order: Ordering[B]): Set[B]
  def contains[B >: A](b: B)(implicit order: Ordering[B]): Boolean
}

The problem with this implementation is that insert, for example, will always return an instance of Set. If I were to write a specialised implementation of Set with useful helper methods, its type would be lost as soon as an element was inserted in it.

This is what I've come up with, which seems to work but I still find confusing and can't help but feel is over-complicated (recursive higher kinded types!):

trait Set[+A, Repr[+X] <: Set[X, Repr]] {
  this: Repr[A] =>

  def isEmpty: Boolean
  def insert[B >: A](b: B)(implicit order: Ordering[B]): Repr[B]
  def contains[B >: A](b: B)(implicit order: Ordering[B]): Boolean
}

Here's a sample implementation using a simple binary tree:

sealed trait CustomSet[+A] extends Set[A, CustomSet]

case class Node[A](value: A, left: CustomSet[A], right: CustomSet[A]) extends CustomSet[A] {
  override def isEmpty = false

  override def insert[B >: A](b: B)(implicit order: Ordering[B]) =
    if(order.lt(b, value))      Node(value, left.insert(b), right)
    else if(order.gt(b, value)) Node(value, left, right.insert(b))
    else                        this

  override def contains[B >: A](b: B)(implicit order: Ordering[B]) =
    if(order.lt(b, value))      left.contains(b)
    else if(order.gt(b, value)) right.contains(b)
    else                        true
}

case object Leaf extends CustomSet[Nothing] {
  override def isEmpty                                        = true
  override def insert[B](b: B)(implicit order: Ordering[B])   = Node(b, Leaf, Leaf)
  override def contains[B](b: B)(implicit order: Ordering[B]) = false
}

The questions that I have are:

I don't believe the self-type is strictly necessary here. Are there good reasons to leave it? to remove it?
is this the correct / best / simplest way to implement what I'm trying to write? Are there any alternatives?