texts:
I am studying mutual exclusion in college, and we just covered the producer/consumer problem.  The class does not involve writing code, but I decided to implement a bounded buffer version of this problem.  I have never written a multi-threaded program before, nor have I written a program with mutual exclusion before, so I decided to request a review here.

I implemented three variations, a busy-waiting variation, a Semaphore variation, and a Monitor variation.  All of these reside in a class named Program, which is needed for the threading.  The Monitor variation looks as if there should be a simpler solution with fewer variables. Is this so?

This is the part of the code that never changes:

const int buffSize = 10;
static char[] buffer = new char[buffSize];
static int valuesToProduce = 95;

static void Main(string[] args)
{
    Thread p = new Thread(new ThreadStart(Program.produce));
    Thread c = new Thread(new ThreadStart(Program.consume));
    p.Start();
    c.Start();
}

This is the busy-waiting producer/consumer and their related global variable:

static int avail = 0;

static void produce()
{
    for(int i=0; i<valuesToProduce; i++)
    {
        while (avail == buffSize) { };
        buffer[i % buffSize] = (char)(32 + i % 95);
        Console.WriteLine("Produced: {0}", buffer[i % buffSize]);
        avail++;
    }
}

static void consume()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        while (avail < 1) { };
        char c = buffer[i % buffSize];
        Console.WriteLine("Consumed: {0}", buffer[i % buffSize]);
        avail--;
    }
}

This is the Semaphore implementation:

private static Semaphore isFull = new Semaphore(buffSize, buffSize);
private static Semaphore isEmpty = new Semaphore(0, buffSize);

static void produce()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        isFull.WaitOne();
        buffer[i % buffSize] = (char)(32 + i % 95);
        Console.WriteLine("Produced: {0}", buffer[i % buffSize]);
        isEmpty.Release(1);
    }
}

static void consume()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        isEmpty.WaitOne();
        char c = buffer[i % buffSize];
        Console.WriteLine("Consumed: {0}", c);
        isFull.Release(1);
    }
}

And this is the Monitor implementation:

static int avail = 0;
private static object _buffer = new object();
private static object isFull = new object();
private static object isEmpty = new object();

static void produce()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        while (avail == buffSize)
        {
            Monitor.Enter(isFull);
            Monitor.Wait(isFull);
            Monitor.Exit(isFull);
        }

        Monitor.Enter(_buffer);
        buffer[i % buffSize] = (char)(32 + i % 95);
        avail++;
        Console.WriteLine("Produced: {0}", buffer[i % buffSize]);
        Monitor.Exit(_buffer);

        Monitor.Enter(isEmpty);
        Monitor.Pulse(isEmpty);
        Monitor.Exit(isEmpty);
    }
    avail++;
}

static void consume()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        while (avail < 1)
        {
            Monitor.Enter(isEmpty);
            Monitor.Wait(isEmpty);
            Monitor.Exit(isEmpty);
        }

        Monitor.Enter(_buffer);
        char c = buffer[i % buffSize];
        avail--;
        Console.WriteLine("Consumed: {0}", buffer[i % buffSize]);
        Monitor.Exit(_buffer);

        Monitor.Enter(isFull);
        Monitor.Pulse(isFull);
        Monitor.Exit(isFull);
    }
}


texts: Calculating and improving time and memory complexity

texts:
private static int Sum (int[] a, int from, int to){
   int total=0;
   for (int i=from; i <= to; i++)
       res += a[i];
   return total;
}

public static int Method3 (int []a){
    int temp=0;
    for (int i=0; i <= a.length; i++)
    {
        for (int j=0; j <= a.length; j++)
        {
           int c = Sum(a,i,j);
           if (c%3 == 0)
           {
            if (j-i+1 > temp)
            temp = j-i+1;
           }
        }
    }
return temp;
}

The purpose of Method3 method is to find the longest combination of a given array numbers', so that the sum of the numbers of the combination can be divided by 3 without remainder.

How do I make it more efficient in terms of both time and memory complexity?
How do I even approach to something like this?
ow can I know that the complexity I've reached is the best possible?


texts:
I am unhappy with my entity-relation-namings.

The underliyng tables are named TRANSLATION and LANGUAGE.

To contains translations like

German is German in English
Deutsch is German in German
English is English in English
Englisch is English in German

I have the table

LANGUAGE
  ID (int pk)               <-- 1,2,3, ...
  LANGTAG (varchar)         <-- en / de / fr / ...
TRANSLATION
  LOCAL_NAME (varchar 64)   <-- German, Allemand, Deutsch, ...

Now I need relations between them. In the Entity i have both sides, the owning side and the non-owning-side.

I started using this relations:

You see two FKs:

Translates (getter in Translations) -> Translations (getter in Language)
Into language (getter in Translations) -> Language Translations (getter in Language)

But I inspect my Language-Entity now and see this:

private Set<Translation> translations = new LinkedHashSet<>();

@OneToMany(mappedBy = Translation.PROP_TRANSLATES)
public Set<Translation> getTranslations() {
    return translations;
}

public Language setTranslations(final Set<Translation> translations) {
    this.translations = translations;
    return this;
}

private Set<Translation> languageTranslations = new LinkedHashSet<>();

@OneToMany(mappedBy = Translation.PROP_INTO_LANGUAGE)
public Set<Translation> getLanguageTranslations() {
    return languageTranslations;
}

public Language setLanguageTranslations(final Set<Translation> languageTranslations) {
    this.languageTranslations = languageTranslations;
    return this;
}

I think the naming is problematic because I do not know what getter to use if I need the translations.

Intuitivly, to get the Languages that has been translated from German I use

Language german = entityManager.createCriteria("FROM Language WHERE langtag='de'");
Set<Translations> languagesInGerman = german.getLanguageTranslations();

The getter looks absolutly strange but I have no idea for a renaming!


texts: JSON to CSV in python using json.loads and json_normalize

texts:
I am trying to convert a JSON file to CSV format using Python. I am using the JSON.loads() method and then using json_normalize() to flatten the objects. The code is working fine for few input rows.
I was wondering if there is better way of doing this. By better I mean:
Is it efficient in terms of time and space complexity? If this code has to process around 10K records in a file, is this the optimized solution?
This is the input file, one row format:
{"ID": "02","Date": "2019-08-01","Total": 400,"QTY": 12,"Item": [{"NM": "0000000001","CD": "item_CD1","SRL": "25","Disc": [{"CD": "discount_CD1","Amount": 2}],"TxLns": {"TX": [{"TXNM": "000001-001","TXCD": "TX_CD1"}]}},{"NM": "0000000002","CD": "item_CD2","SRL": "26","Disc": [{"CD": "discount_CD2","Amount": 4}],"TxLns": {"TX": [{"TXNM": "000002-001","TXCD": "TX_CD2"}]}},{"NM": "0000000003","CD": "item_CD3","SRL": "27"}],"Cust": {"CustID": 10,"Email": "01@abc.com"},"Address": [{"FirstName": "firstname","LastName": "lastname","Address": "address"}]}

Code
import json
import pandas as pd
from pandas.io.json import json_normalize
data_final=pd.DataFrame()
with open("sample.json") as f:
    for line in f:
        json_obj = json.loads(line)
        ID = json_obj['ID']
        Item = json_obj['Item']
        dataMain = json_normalize(json_obj)
        dataMain=dataMain.drop(['Item','Address'], axis=1)
        #dataMain.to_csv("main.csv",index=False)
        dataItem = json_normalize(json_obj,'Item',['ID'])
        dataItem=dataItem.drop(['Disc','TxLns.TX'],axis=1)
        #dataItem.to_csv("Item.csv",index=False)
        dataDisc = pd.DataFrame()
        dataTx = pd.DataFrame()
        for rt in Item:
            NM=rt['NM']
            rt['ID'] = ID
            if 'Disc' in rt:
                data = json_normalize(rt, 'Disc', ['NM','ID'])
                dataDisc = dataDisc.append(data, sort=False)
            if 'TxLns' in rt:
                tx=rt['TxLns']
                tx['NM'] = NM
                tx['ID'] = ID
                if 'TX' in tx:
                    data = json_normalize(tx, 'TX', ['NM','ID'])
                    dataTx = dataTx.append(data, sort=False)
        dataDIS = pd.merge(dataItem, dataDisc, on=['NM','ID'],how='left')
        dataTX = pd.merge(dataDIS, dataTx, on=['NM','ID'],how='left')
        dataAddress = json_normalize(json_obj,'Address',['ID'])
        data_IT = pd.merge(dataMain, dataTX, on=['ID'])
        data_merge=pd.merge(data_IT,dataAddress, on=['ID'])
        data_final=data_final.append(data_merge,sort=False)
data_final=data_final.drop_duplicates(keep = 'first')
data_final.to_csv("data_merged.csv",index=False)

this is the output:
ID,Date,Total,QTY,Cust.CustID,Cust.Email,NM,CD_x,SRL,CD_y,Amount,TXNM,TXCD,FirstName,LastName,Address
02,2019-08-01,400,12,10,01@abc.com,0000000001,item_CD1,25,discount_CD1,2.0,000001-001,TX_CD1,firstname,lastname,address
02,2019-08-01,400,12,10,01@abc.com,0000000002,item_CD2,26,discount_CD2,4.0,000002-001,TX_CD2,firstname,lastname,address
02,2019-08-01,400,12,10,01@abc.com,0000000003,item_CD3,27,,,,,firstname,lastname,address


texts: Recursive binary search implementation in Python

texts:
I have this (recursive) binary search implementation in Python, and I want you to criticize every aspect of it. It is a naive implementation, (drilling the basics and stuff), but, I want you to comment on the perceived clarity, maintainability of the code, defensive programming practices, test cases that could be useful but are missing, implicit assumptions that may not hold, pythonic-ness of the code, anything that could help me improve the code.

import unittest

def binary_search(collection, key):
    """ Search for a given key in the list of elements
    passed as a parameter.

    :param collection: The iterable to be searched.
    :param key: The search key.

    Returns the index where the key was found, else the symbolic string 'Not found'.
    """
    # First, make sure that the collection we have been given is truly
    # iterable
    try:
        iterator = iter(collection)
    except TypeError:
        raise TypeError("`collection` is not an iterable collection.")

    # if the collection is empty, it means that we have gone
    # past the boundaries and haven't found a value, so we can
    # safely assume there doesn't exist one in the original collection
    if not collection:
        return "Not found"

    collection_length = len(collection)
    mid = collection_length // 2

    # if we found it great, return the index
    if collection[mid] == key:
        return mid
    # now, if we haven't found it,
    elif collection[mid] < key:
        # if there was only 1 element in the collection before
        # the last call to binary search, this means that the
        # floor division above will have returned a mid == 0,
        # causing the recursive function below to bug out and
        # blow the stack. This is a sentinel to make sure this doesn't
        # happen
        if mid == 0:
            return "Not found"
        res = binary_search(collection[mid:], key)
        return mid + res if res != "Not found" else "Not found"
    elif collection[mid] > key:
        return binary_search(collection[:mid], key)

class BinarySearchTests(unittest.TestCase):
    def test_value_found(self):
        collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
        res = binary_search(collection, 3)
        self.assertEqual(res, 2, 'Binary search failed to return expected index of search key.')
        res = binary_search(collection, 5)
        self.assertEqual(res, 4, 'Binary search failed to return expected index of search key.')
        res = binary_search(collection, 11)
        self.assertEqual(res, 10, 'Binary search failed to return expected index of search key.')

    def test_value_not_found(self):
        collection = [1, 2, 3, 4, 5]
        res = binary_search(collection, -1)
        self.assertEqual(res, 'Not found', 'Binary search failed to return expected "Not found" value.')
        res = binary_search(collection, 6)
        self.assertEqual(res, 'Not found', 'Binary search failed to return expected "Not found" value.')

    def test_elements_is_not_iterable(self):
        import socket
        elements = socket.socket()
        key = 1
        self.assertRaises(TypeError, binary_search, (key, elements))
        elements.close()  # so that the interpreter doesn't give us a resource warning.

if __name__ == '__main__':
    unittest.main()


texts:
I have an abstract class Consumer:

abstract class Consumer
{
    const API_DOMAIN = 'https://test-api.com/v1/';

    private $client = null;
    private $credentials = [];

    public function __construct(array $credentials)
    {
        $this->client = new Client(); //This is GuzzleHttp/Client.
        $this->credentials = $credentials; // An array
    }

    abstract protected function getEndpoint();

    abstract protected function getHttpMethod();

    abstract protected function getParameter();

    abstract protected function getHeaders();

    abstract protected function getContent();

    abstract protected function parseResponse($result);

    protected function getUrl()
    {
        //This has to be fixed to accept an array of parameters: [key => value] format
        return implode('/', array_filter([self::API_DOMAIN, $this->getEndpoint(), $this->getParameter()]));
    }

    public function execute()
    {
        if (empty($this->credentials))
            throw new InvalidCredentialsException();
        try {
            $response = $this->client->request($this->getHttpMethod(), $this->getUrl(), [
                'auth' => $this->credentials,
                'form_params' => $this->getContent()
            ]);
            return $this->parseResponse(json_decode($response->getBody()->getContents()));
        } catch (\Exception $e) {
            throw new ErrorResponseException($e->getMessage(), $e->getCode());
        }
    }
}

And if I have an endpoint that needs to be accessed via GET I do the following:

class ListAll extends Consumer
{

    protected function parseResponse($result)
    {
        //Collection class from illuminate/support package
        //by the creators of Laravel.
        $collection = new Collection();
        foreach ($result as $item) {
            $collection->push(new Server($item));
        }
        return $collection;
    }

    public function getEndpoint()
    {
        return 'users';
    }

    public function getParameter()
    {
        return null; //No parameters required.
    }

    public function getHeaders()
    {
        return []; //No specific headers is going to be sent.
    }

    public function getContent()
    {
        return []; //No content is going to be sent.
    }

    public function getHttpMethod()
    {
        return 'GET';
    }
}

And the class above is pointing to an endpoint that requires no parameters, headers or content. However if it's a POST request (let's say the endpoint is for creating a user) I must have a set() method for content atleast. So I made a trait:

trait SetContentTrait
{
    protected $content = [];

    public function setContent($content)
    {
        $this->content = $content;
    }
}

And I'm using it in my Create class:

class Create extends Consumer
{
    use SetContentTrait;

    protected function parseResponse($result)
    {
        return new User($result);
    }

    protected function getEndpoint()
    {
        return 'users';
    }

    protected function getHttpMethod()
    {
        return 'POST';
    }

    public function getParameter()
    {
        return null;
    }

    public function getHeaders()
    {
        return [];
    }

    public function getContent()
    {
        return $this->content;
    }
}

Whenever I need to call that API I do the following:

$create = new Create($credentials);
$user = [
    'username' => 'Iv',
    'password' => 'SOMEHASH',
    'email' => 'my-email@gmai.com'
];

$create->setContent($user);
$user = $create->execute();

So is it a good approach to use traits in this case? Not every endpoint requires parameters, headers and content.


texts: Monitor progress of written lines of code

texts:
Not long ago, I was asked about how many lines of code I have written in C++ and could not answer that question. For this reason and to become more familiar with Bash shell scripting, I wrote a small system to monitor the lines of code written in a specific subdirectory.

Currently, I count the lines of code at 5 seconds interval and write the difference (if favorable) to a file.

As mention above, I am not familiar with bash scripting and hope to get some helpful feedback.

I would appreciate the advice, especially in the following areas:

Code style (readability, naming conventions)
Efficiency (how to avoid unnecessary complexity)
How can I prevent a long list of extension as used currently in my
approach (-name "*.py" -o -name "*.cpp" -o -name "*.h"). Can I do
something like [py, cpp, h, ...] instead?

count_lines () {
    N="$(find ./ -name "*.py" -o -name "*.cpp" -o -name "*.h" | \
    xargs grep -cve "^\s*$" | grep -oP '(?<=:).*' | \
    awk '{s+=$1} END {print s}')"
    echo "$N"
}

FILE_NAME="counter.log"
touch $FILE_NAME
SUM=0

while true; do
    NUM1=$(count_lines)
    sleep 5;
    NUM2=$(count_lines)
    DIFF=$((NUM2-NUM1))
    if [ "$DIFF" -gt 0 ]; then
        SUM=$((SUM+DIFF))
    fi
    echo "${SUM} ${NUM2}" >> $FILE_NAME
done


texts: Excel VBA to create a visual timeline of events using an XY scatter chart

texts:
I have details of key decisions made by a business in a worksheet "Decision Record."

My data is laid out as follows:

I have written some code to create a timeline of these decisions using an XY scatter chart, like this one:

The code works fine, but as with most of the code I write, it doesn't look tidy to me. Perhaps it's because of the long with statement, which seems like it could be simplified, maybe with a separate with statement for the DataLabels method.

Is this good practice? Is there something else I should be doing to tidy this up?

Sub UpdateDecisionTimelineChart()

    Dim scount As Integer
    Dim labelrotation As Integer
    Dim c As Range

    ActiveSheet.ChartObjects("chtDecisionTimeline").Activate
    scount = 0
        For Each c In Range(Worksheets("Decision Record").Range("C7"), Worksheets("Decision Record").Range("C7").End(xlDown))
        scount = scount + 1
        ActiveChart.SeriesCollection.NewSeries
        With ActiveChart.SeriesCollection(scount)
            .Name = "='Decision Record'!" & c.Offset(0, 1).Address
            .XValues = "='Decision Record'!" & c.Address
            .Values = "='Decision Record'!" & c.Offset(0, -1).Address
            .MarkerStyle = 8
            .MarkerSize = 7
            .MarkerBackgroundColor = RGB(228, 10, 56)
            .MarkerForegroundColor = -2
            .Format.Line.Visible = False
            .ApplyDataLabels
            .DataLabels.ShowValue = False
            .DataLabels.ShowSeriesName = True
            .DataLabels.Position = xlLabelPositionAbove
            .DataLabels.Orientation = -45
        End With
        Next
End Sub


texts: BouncyCastle Rijndael 256 Implementation

texts:
I modified the implementation from this website to include a salt:

package de.xxx.yyy.main;

import static org.junit.Assert.*;

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.digests.SHA3Digest;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;
import org.junit.Test;

public class test {

    private char[] password = "0123456789abcdef0123456789abcdef".toCharArray();
    private byte[] salt = "0123456789".getBytes();
    private int iterationCount = 5;

    @Test
    public void testEncryptRijndael() throws DataLengthException, IllegalStateException, InvalidCipherTextException {

        PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA3Digest(256));
        char[] passwordChars = password;

        final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
        pGen.init(pkcs12PasswordBytes, salt , iterationCount );

        BlockCipher engine = new RijndaelEngine(256);
        CBCBlockCipher cbc = new CBCBlockCipher(engine);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc, new PKCS7Padding());

        ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 256);
        cipher.init(true, aesCBCParams);

        byte[] input = "Hallo ich bin ein Test".getBytes();
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

        int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0);
        cipher.doFinal(cipherText, cipherLength);

        String result = new String(Base64.encode(cipherText));
        System.out.println("testEncryptRijndael result : " + result);
        assertEquals("cMoMSNMNsikAkLjaheE6iD48Xkfvo7Y6gS8/zroGfHc=",result);
    }

    @Test
    public void testDecryptRijndael() throws DataLengthException, IllegalStateException, InvalidCipherTextException {
        PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA3Digest(256));
        char[] passwordChars = password;

        final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
        pGen.init(pkcs12PasswordBytes, salt , iterationCount );

        BlockCipher engine = new RijndaelEngine(256);
        CBCBlockCipher cbc = new CBCBlockCipher(engine);
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc, new PKCS7Padding());

        ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 256);
        cipher.init(false, aesCBCParams);

        byte[] output = Base64.decode("cMoMSNMNsikAkLjaheE6iD48Xkfvo7Y6gS8/zroGfHc=".getBytes());
        byte[] cipherText = new byte[cipher.getOutputSize(output.length)];

        int cipherLength = cipher.processBytes(output, 0, output.length, cipherText, 0);
        int outputLength = cipher.doFinal(cipherText, cipherLength);
        outputLength += cipherLength;

        byte[] resultBytes = cipherText;
        if (outputLength != output.length) {
            resultBytes = new byte[outputLength];
            System.arraycopy(
                    cipherText, 0,
                    resultBytes, 0,
                    outputLength
                    );
        }

        String result = new String(resultBytes);
        System.out.println("testDecryptRijndael result : " + result);
        assertEquals("Hallo ich bin ein Test", result);
    }
}

Is this a good implementation, or are there some mistakes, logical errors or security risks?


texts: Send / receive wrapper for System.Net.Sockets - follow-up

texts:
I recently posted a question about improving thread and socket safety in my NetworkEndpoint class. previous post

I have implemented the changes suggested in the answer I got there. When I asked for a second look to confirm my changes I was told to post another question.

Included below is the code I changed as well as a few follow up questions. To see the entire class please refer to my previous post.

Is my use of locks in the Connected property and Send and Disconnect methods effective?

private object connectedLock = new object();
public bool Connected {
    get {
        lock (connectedLock) {
           if (connection == null) return false;
           return connection.Connected;
        }
    }
}

private object sendLock = new object();
public void Send(NetworkHeader header, byte[] data) {
    if (!Connected) throw new InvalidOperationException("NetworkEndpoint must be connected before sending.");
    try {
        lock (sendLock) {
            connection.Send(ByteUtils.Combine(header.Serialize(), data));
        }

    } catch (SocketException) {
        Disconnect();
    }
}

private object disconnectLock = new object();
public void Disconnect() {
   if (Connected) {
        lock (disconnectLock) {
            connection?.Shutdown(SocketShutdown.Both);
            connection?.Close();
            connection = null;
            OnDisconnected();
            Clear();
       }
    }
}

Is the lock I added to InitializeReceiveLoop redundant due to if (Receiving) return;?

private object initializeLock = new object();
public void InitializeReceiveLoop() {
    lock (initializeLock) {
        if (Receiving) return;
        Receiving = true;
    }
    BeginReceive();
}

Is this the best way to clear events? Would setting the events to null achieve the same goal?

public void Clear() {
    foreach (Delegate d in DataReceived.GetInvocationList())
        DataReceived -= (EventHandler<NetworkReceiveEventArgs>)d;
    foreach (Delegate d in Disconnected.GetInvocationList())
        Disconnected -= (EventHandler)d;
}

Is this implementation of EndReceive better than my previous?
Is EndReceive not already "thread-safe" by nature of how it is used? It is a private method only ever called by BeginReceive which is only called after the completion of a previous call to EndReceive or by InitializeReceiveLoop which can only be called once (returns imediately if Receiving is already true)

private void EndReceive(IAsyncResult result) {
    byte[] dataBuffer = null;
    NetworkHeader header = null;

    try {
        if (connection.EndReceive(result) > 0) {
            header = NetworkHeader.Deserialize(headBuffer);
            dataBuffer = new byte[header.DataSize];

            int offset = 0;
            while (offset < header.DataSize) {
                int lengthRead = connection.Receive(dataBuffer, offset,
                    (int)header.DataSize - offset, SocketFlags.None);

                if (lengthRead == 0) {
                    Disconnect();
                    return;
                }

                else offset += lengthRead;
            }
        }
    } catch (SocketException) {
        Disconnect();
        return;
    }

    OnDataReceived(header, dataBuffer);
    BeginReceive();
}


texts: Parse atom RSS feed with xml.dom.minidom

texts:
I had to parse a blogger RSS feed but I didn't have access to any third party modules like feedparser or lxml. I was stuck with the task of writing a library to parse RSS feeds; challenge accepted. I started by writing an RSS class and then an Entry class. I then realized that my classes only had two methods, one of them being __init__, so I scrapped the OOP approach and went for a more direct approach. I reduced everything down to one function parse_feed. parse_feed takes one positional argument: the URL to the RSS feed.

I'm curious what you think about the way I used type to create classes on the fly.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

import urllib.request
from xml.dom import minidom

def parse_feed(url):
    # This is what parse_feed returns.
    feed = type('Feed', (object,), {})
    feed.entries = []

    with urllib.request.urlopen(url) as res:
        dom = minidom.parseString(res.read().decode('latin-1'))
        feed.title = dom.getElementsByTagName('title')[0].firstChild.nodeValue
        feed.link = dom.getElementsByTagName('link')[0].getAttribute('href')
        feed.published = dom.getElementsByTagName('published')[0].firstChild.nodeValue

    for element in dom.getElementsByTagName('entry'):
        title = element.getElementsByTagName('title')[0].firstChild.nodeValue
        link = element.getElementsByTagName('link')[0].getAttribute('href')
        author = element.getElementsByTagName('name')[0].firstChild.nodeValue
        published = element.getElementsByTagName('published')[0].firstChild.nodeValue
        updated = element.getElementsByTagName('updated')[0].firstChild.nodeValue
        _id = element.getElementsByTagName('id')[0].firstChild.nodeValue
        category = element.getElementsByTagName('category')

        tags = []
        for node in category:
            tags.append(node.getAttribute('term'))

        article = element.getElementsByTagName('content')[0].firstChild.nodeValue

        entry_dict = dict(
                    title=title,
                    link=link,
                    author=author,
                    article=article,
                    tags=tags,
                    _id=_id)

        feed.entries.append(type('Entry', (feed,), entry_dict))

    return feed

# Example use.
feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&start-index=1&max-results=1000'
feed = parse_feed(feed_url)
print(feed.title)
print(feed.published)
for entry in feed.entries:
    print(entry.title)
    print(entry.link)


texts:
I'm attempting to make some ui tools for my python ncurses application, and I needed a word wrap function. It works pretty well, but trying to read it is frustrating. I'm specifically looking for readability improvements, but if there are some other tips you can give, including edge cases or PEP violations, they would also be appreciated.

class ui_util:
    def chunk_word(word, length):
        return [ word[i:i+length] for i in range(0, len(word), length) ]

    def word_wrap(str, width):
        def add_first_word():
            nonlocal word
            nonlocal wrapped_line
            nonlocal lines_final

            if (len(word) <= width):
                wrapped_line = word
            else:
                chunks = ui_util.chunk_word(word, width)
                for i in range(len(chunks) - 1):
                    lines_final.append(chunks[i])
                wrapped_line = chunks[-1]

        lines = str.splitlines()
        lines_final = []
        for line in lines:
            if (len(line) <= width):
                lines_final.append(line)
            else:
                words = line.split()
                wrapped_line = ""
                for word in words:
                    if (len(wrapped_line) == 0):
                        add_first_word()
                    elif (len(wrapped_line) + len(word) + 1 <= width):
                        wrapped_line += ' ' + word
                    else:
                        lines_final.append(wrapped_line)
                        add_first_word()
                lines_final.append(wrapped_line)
        return lines_final

Called like:

lines = ui_util.word_wrap("some test words 13_chars_word\r\nnew line\r\n12_char_word 13_chars_word", 12)
for i in range(len(lines)):
    print(lines[i])

Output:

some test
words
13_chars_wor
d
new line
12_char_word
13_chars_wor
d


texts: Very small start to MVC refactor in iOS app

texts:
I started to refactor my app to MVC today. I wasted a lot of time because of simple mistakes.

One was I kept trying to access the getter method inside of my custom getter method, which just causes and endless loop of gets.

Even when I figured it out, I repeated this mistake several times. I think it's safe to say I'll never use self.iVar inside of it's own getter method ever again.

The thing I sort of want advice on is not just whether I did an ok MVC refactor, but whether I approached things the right way.

One of the things that is really bugging me is my implementation of the phoneNumbers getter method in HALContact.

When I first created it, my nested for loops in my New View Controller Snippet would run forever and just keep adding the same phone number instead of moving on.

I finally just got frustrated and added the removeAllObjects method at the beginning of the phoneNumbers getter. As much as it works fine, I'm not sure if that's the way it should be.

And this is how the getter now looks and works fine:

- (NSArray *)phoneNumbers {

    // The difference is I remove all of the objects
    if (_phoneNumbers) {
        [_phoneNumbers removeAllObjects];
    }

    if (!_phoneNumbers) {
        //Create _phoneNumbers array
        _phoneNumbers = [[NSMutableArray alloc]init];
    }

    ABMultiValueRef *phoneNumberRef = ABRecordCopyValue(_contactRef, kABPersonPhoneProperty);

    NSString *phoneNumber = [[NSString alloc] init];

    // Make sure multi value ref exists
    if (phoneNumberRef) {
        CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumberRef);

        for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
            phoneNumber = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneNumberRef, i);
            CFStringRef label = ABMultiValueCopyLabelAtIndex(phoneNumberRef, i);
            if (label) {

            [_phoneNumbers addObject:phoneNumber];
                NSLog(@"phoneNumbers count in method: %d", _phoneNumbers.count);
            }
            CFRelease(label);
        }
        CFRelease(phoneNumberRef);
    }
    return _phoneNumbers;
}

As far as the general MVC refactor, I threw up all of my new and old files on Pastebin which I will link to in parentheses if you'd rather view them in separate tabs.

Here's a snippet of what the View Controller looks like after the refactor. It now uses 2 model classes I made to handle the address book and contacts data:

// Instantiate our address book instance
self.addressBook = [[HALAddressBook alloc]init];

// Instantiate our contact instance
self.currentContact = [[HALContact alloc]init];

//Ask for access to Address Book.
BOOL result = [self.addressBook requestAccess];

if (!result) {
    [self performSegueWithIdentifier:@"addFriendsToMediaCaptureSegue" sender:self];
}

if (result) {

    // Loop through all address book contacts
    for (int index = 0; index < self.addressBook.allContacts.count; index++) {

       // Create contactRef from current contact
        self.currentContact.contactRef = (__bridge ABRecordRef)(self.addressBook.allContacts[index]);

      // Loop through all of the current contact's phone numbers
        int index2;
        for (index2 = 0; index2 < self.currentContact.phoneNumbers.count; index2++) {
            if (self.currentContact.firstName) {
                // Add current contact's phone number to array
                [self.potentiaFriendsPhoneNumberArray addObject:self.currentContact.phoneNumbers[index2]];

                // Add current contact's first name to array
                [self.potentiaFriendsNotInParseFirstNamesArray addObject:self.currentContact.firstName];
            }
        }
    }
}

And here are the 2 model classes that I added. One for the address book and one for the contact:

1A. HALAddressBook header

1B. HALAddressBook implementation

2A. HALContact header

2B. HALContact implementation


texts: Is this a good approach for creating pages for multiple content typs with GatsbyJS?

texts:
I'm trying to create pages for multiple content types in Gatsby and I was wondering if this is the right approach:

My gatsby-node.js file:

const path = require(`path`)

const { createFilePath } = require("gatsby-source-filesystem")
exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  // Is this OK?
  if (
    node.internal.type === "Mdx" &&
    node.fileAbsolutePath.includes(`content/posts`)
  ) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: "slug",
      node,
      value: `/blog${value}`,
    })
  }
  if (
    node.internal.type === "Mdx" &&
    node.fileAbsolutePath.includes(`content/projects`)
  ) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: "slug",
      node,
      value: `/project${value}`,
    })
  }
}
exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage } = actions
  const blogPostTemplate = path.resolve(`./src/templates/template-blog-post.js`)
  const projectEntryTemplate = path.resolve(
    `./src/templates/template-project-entry.js`
  )
  const result = await graphql(`
    query {
      posts: allMdx(
        sort: { order: DESC, fields: [frontmatter___date, fields___slug] }
        limit: 10000
        filter: { fileAbsolutePath: { regex: "/content/posts/" } }
      ) {
        edges {
          node {
            id
            fields {
              slug
            }
            frontmatter {
              title
            }
          }
        }
      }
      projects: allMdx(
        sort: { order: DESC, fields: [frontmatter___date, fields___slug] }
        limit: 1000
        filter: { fileAbsolutePath: { regex: "/content/projects/" } }
      ) {
        edges {
          node {
            id
            fields {
              slug
            }
            frontmatter {
              title
            }
          }
        }
      }
    }
  `)
  if (result.errors) {
    reporter.panicOnBuild(
      '  ERROR: Loading "createPages" query.'
    )
  }
  const posts = result.data.posts.edges
  const projects = result.data.projects.edges
  posts.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: blogPostTemplate,
      context: { id: node.id },
    })
  })

  projects.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: projectEntryTemplate,
      context: { id: node.id },
    })
  })
}

My (redacted) gatsby-config.js file:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/content/posts/`,
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: `projects`,
        path: `${__dirname}/content/projects/`,
      },
    },
  ],
}

Although this works fine and I'm not getting any errors, I'm not sure using two if-statements in gatsby-node.js is the right approach to generating pages for multiple content types. I've searched online and I have not yet found a guide or 'best-practices' when it comes to handling multiple content types with GatsbyJS. Please share if you have!

Could you guys help me out? Am I on the right track or is there improvement to be found?

Cheers!


texts:
I've written a little calculator in C++ for complex numbers:

#include <iostream>
using namespace std;

class ComplexNumber {

    public:
        double real;
        double imaginary;

        void add(ComplexNumber a, ComplexNumber b) {

            //Just add real- and imaginary-parts
            double real = a.real + b.real;
            double imaginary = a.imaginary + b.imaginary;
            ComplexNumber c = ComplexNumber(real, imaginary);
            cout << "a + b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
        }

        void sub(ComplexNumber a, ComplexNumber b) {

            //Just subtract real- and imaginary-parts
            double real = a.real - b.real;
            double imaginary = a.imaginary - b.imaginary;
            ComplexNumber c = ComplexNumber(real, imaginary);
            cout << "a - b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
        }

        void multiply(ComplexNumber a, ComplexNumber b) {

            //Use binomial theorem to find formula to multiply complex numbers
            double real = a.real * b.real - a.imaginary * b.imaginary;
            double imaginary = a.imaginary * b.real + a.real * b.imaginary;
            ComplexNumber c = ComplexNumber(real, imaginary);
            cout << "a * b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
        }

        void divide(ComplexNumber a, ComplexNumber b) {

            //Again binomial theorem
            double real = (a.real * b.real + a.imaginary * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
            double imaginary = (a.imaginary * b.real - a.real * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
            ComplexNumber c = ComplexNumber(real, imaginary);
            cout << "a : b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
        }

    /*
     * Constructor to create complex numbers
     */
    ComplexNumber(double real, double imaginary) {
        this->real = real;
        this->imaginary = imaginary;
    }
};

int main() {

    /*
     * Variables for the real- and imaginary-parts of
     * two complex numbers
     */
    double realA;
    double imaginaryA;
    double realB;
    double imaginaryB;

    /*
     * User input
     */
    cout << "enter real(A), imag(A), real(B) and imag(B) >> ";
    cin >> realA >> imaginaryA >> realB >> imaginaryB;
    cout << endl;

    /*
     * Creation of two objects of the type "ComplexNumber"
     */
    ComplexNumber a = ComplexNumber(realA, imaginaryA);
    ComplexNumber b = ComplexNumber(realB, imaginaryB);

    /*
     * Calling the functions to add, subtract, multiply and
     * divide the two complex numbers.
     */
    a.add(a, b);
    a.sub(a, b);
    a.multiply(a, b);
    a.divide(a, b);
    return 0;
}

I would appreciate any suggestions to improve the code.

You can find my follow-up question here.


texts:
Context:

When sending message across the network, the sender has to convert the message from host byte order to network byte order and the receiver has to do the the reverse -  network order to host order.

There are multiple ways of going about it. One neat way to do is to convert the message to host byte
order as soon as it is received.

Eg:

struct Msg {
   uint32_t a;
   uint16_t b;
};

run_ntoh (Msg *m)
{
    m->a = ntohl(m->a);
    m->b = ntohs(m->b);
}

process (Msg *m)
{
   run_ntoh(m);
   further_process(m);
}

But there are cases where this will not work. Say, the message buffer is shared by multiple receivers.
We can always copy the message to local buffer and do it. But that is inefficient if the message is large.

The third option is to always access the fields of 'Msg' using ntohx function. But this is error prone.

a. The user might forget to use ntoh always  - it is not enforced.

b. Also user has to be very careful - use htonl or htons? What if the size of the varible is changed -
    nothing enforces the change of htonl instead of htons if the variable size changes from 16 to 32.

Here my idea is to enforce the use of ntoh, while making it easy for the user.

Code:

#include <cstdint>
#include <cstddef>
#include <type_traits>

//
// class to extract N number of bytes and form a number
// uint32_t value = ExtractValue<uint32_t>::get(buffer);
//
template <typename T, size_t val = sizeof(T)>
struct ExtractValue {
    static T get (uint8_t *p)
    {
        return (ExtractValue<T, val - 1>::get(p) << 8) |
                static_cast<T>(p[val - 1]);
    }
};

template <typename T>
struct ExtractValue<T, 0> {
    static T get (uint8_t *p)
    {
        return 0;
    }
};

// Get a field of the class T, in host byte order.
// The class T is wrapped in NetworkData class. The get() function
// takes the offset to the member as an argument, gets the address
// of field and extract the field
template <typename T>
struct NetworkData {

    using type = T;

    NetworkData (uint8_t *p) : _p(p) {}

    template<typename R, typename U = std::decay_t<R>,
             typename std::enable_if_t<!std::is_pointer<U>::value>* =  nullptr>
    U get (uintptr_t offset)
    {
        return ExtractValue<U>::get(_p + offset);
    }

    template<typename R, typename U = std::decay_t<R>,
             typename std::enable_if_t<std::is_pointer<U>::value>* = nullptr>
    U get (uintptr_t offset)
    {
        return (U)(_p + offset);
    }

private:
    uint8_t *_p;
};

// Macro to easily call the NetworkData::get()
#define GetNtoh(h, f)  \
    h.get<decltype(decltype(h)::type::f)>(offsetof(decltype(h)::type, f))

Usage:

struct Msg {
   uint32_t a;
   uint16_t b;
};

void process (uint8_t *p)
{
    NetworkData<Msg> h(p);

    auto a = GetNtoh(h, a);
    auto b = GetNtoh(h, b);
}

It is always better to use something like goolge protobuf to serialize/deserialize. But that is not possible when the sender is legacy code.


texts:
I wrote a function which takes in input a list of strings that is splitted by comma. Then each generated string is trimmed.

Example:

INPUT:    [[Cat, Dog, Snake]]
OUTPUT:   Cat Dog Snake

In particular, I'm interested in removing parenthesis and commas.
This is the code I wrote, but I think it is awful and not so efficient because I use so many String and LinkedList variables.

private List<String> splitListOfString(LinkedList<String> list)
{
String mylist = list.toString(); //is made by parenthesis, I do not want
mylist = mylist.substring(2);  //delete the first 2
mylist = mylist.substring(0, mylist.length() - 2); //delete the last 2
List<String> thelist = Arrays.asList(mylist.split(","));
List<String> thelist2 = new LinkedList<String>();
for (String string : thelist) {
    thelist2.add(string.trim());
}
    return thelist2;
}

The line of code involving the trim function is compulsory to avoid something like " string", that is undesirable. But I do not think that this is the best way to write this code.
How would you improve this?


texts: Pagination that doesn't rely on a database

texts:
I've created a pagination class in PHP. I've made it so it doesn't rely upon a database. Am I doing this correctly? is there anything you can suggest I improve?

<?php namespace Acme\Foo\Pagination;

class Pagination
{
    public $perPage;

    public $currentPage;

    public $data;

    public function __construct(Array $data)
    {
       $this->data = $data;
    }

    public function perPage($perPage = 10)
    {
        $this->perPage = $perPage;
    }

    public function setCurrentPage($currentPage)
    {
        $this->currentPage = $currentPage;
    }

    public function offset()
    {
        return ($this->currentPage - 1) * $this->perPage;
    }

    public function paginate()
    {
        $slice = array_slice($this->data, $this->offset(), $this->perPage);
        return $slice;
    }

    public function numPages()
    {
        return ceil( count( $this->data ) / $this->perPage );
    }
}

index.php:

// dummy data
$list = range(1,100);
$pagination = new Pagination($list);

$pagination->perPage(5);
$pagination->setCurrentPage($_GET['page']);
$items = $pagination->paginate();

foreach ($items as $row)
{
    echo $row . '
';
}

// page numbers

for($i = max(1, $pagination->currentPage - 2); $i <= min($pagination->currentPage + 2, $pagination->numPages()); $i++)
{
    echo '' . $i . '';
}


texts: Submitting the current webpage to a bookmarking site

texts:
I would like to hear your feedback on the link below that lets users add a link to a website. I read that javascript:void(0) is suggested instead of a # for the <a href="" attribute. Is this still the best practice?

Add Link


texts:
I wrote this small example piece of OOP being implemented in pure C. I wanted it to be reviewed for the following points:

Portability
Performance

And especially
Usability
"How does it look"

Implementation:

typedef char    XCFString;

struct XCFStringStatic {
    void *(*initWithCString)(const char *);
};

struct XCFStringClass {
    void (*release)(void);

    size_t      length;
    char        *value;
};

// Pointer to current class
XCFString **XCFStringCTX    = NULL;

// Release method
void XCFString__release(void)
{
    assert(XCFStringCTX != NULL);
    XCFString *ctx  = *XCFStringCTX;

    free(((char *)ctx) - sizeof(struct XCFStringClass));
}

// Init method
void *XCFString__initWithCString(const char *str)
{
    size_t str_len              = strlen(str);
    struct XCFStringClass *data = malloc(sizeof(* data) + str_len + 1);

    if (!data) return NULL;

    char *str_val               = ((char *)data) + sizeof(* data);

    memcpy(str_val, str, str_len + 1);

    data->length                = str_len;
    data->value                 = str_val;
    data->release               = XCFString__release;

    return data->value;
}

struct XCFStringStatic XCFStringStatic = {.initWithCString = XCFString__initWithCString};

#define priv_getMacroName1(_0, _1, macroName, ...)          macroName
#define getMacroName1(macroName, args...)                   priv_getMacroName1(_0, ##args, macroName ## _1, macroName ## _0)(args)

#define XCFString_0()       (XCFStringStatic)
#define XCFString_1(_var)   (XCFStringCTX=&(_var), ((struct XCFStringClass *)(((char *)_var) - sizeof(struct XCFStringClass))))
// Switch between XCFString_0 and XCFString_1, GNUC only
#define XCFString(args...)                                  getMacroName1(XCFString, ##args)

Test code for main.c

int main(int argc, const char **argv)
{
    // Pointer to our String class
    XCFString   *string     = NULL;

    // Initialize string with "Hallo Welt!"
    string = XCFString().initWithCString("Hallo Welt!");

    // Print it as if it were a normal string
    fprintf(stderr, "String        : %s\n",     string);
    fprintf(stderr, "Length        : %zu\n",    strlen(string));
    // Get the properties from the string
    fprintf(stderr, "Str.value     : %s\n",     XCFString(string)->value);
    fprintf(stderr, "Str.length    : %zu\n",    XCFString(string)->length);

    // Release the string
    XCFString(string)->release();
}


texts: Does this SQL code look okay to everyone? I'm new to coding

texts:
SELECT Title
FROM Film F, Award A
WHERE F.Film = a.FilmID
AND Award_Category = "Best Documentary"
AND Award_Ceremony = "Galway Film Fleadh"
AND F.Year = 2008;

SELECt Title,Year,Genre
FROM Film F, Director D
WHERE D.DirectorID = F.DirectorID
AND D.Forename = "Neil"
AND D.Surname = "Jordan";

SELECT A.Forename, A.Surname
FROM Actor A, Film F, Role R
WHERE A.ActorID = R.ActorID
AND F.Film.ID = R.FilmID
AND Part = "Harry Waters"
AND Year = "2008"
AND Made_In_Country = "Ireland"
AND F.Title = "In Bruges";

SELECT F.Title
FROM Director D,Film F, Role R,Actor A
WHERE D.DirectorId = F.DirectorID
AND F.FilmID = R.FilmID
AND A.ActorID = R.ActorID
AND D.Forename = "John"
AND D.Surname = "Forde"
AND A.Forename = "John"
AND A.Surname = "Wayne";

SELECT COUNT(Language)
FROM Film
WHERE Made_In_Country = "Ireland"
AND Langauge = "Irish"
AND Year >= 1995;

SELECT Title
FROM Film
WHERE Genre = "Western"
AND Title LIKE "%Riders%";

SELECT DISTINCT A.Forename, A.Surname
FROM Actor A, Role R
WHERE A.ActorID = R.ActorID
AND Part = "James Bond"

DELETE FROM Actor
WHERE Actor.Forename = "Steven"
AND Actor.Surname = "Spielberg";

INSERT INTO Director (Forename,Surname)
VALUES ("Steven", "Spielberg");

Assuming no actor has the same name.

SELECT A.Forename, A.Surname
FROM Actor, Award
WHERE A.ActorID = AW.ActorID
AND AW.Award_Category = "Best Actor"
AND Award_Ceremony = "Oscars"
GROUP BY A.FOrename, A.Surname
HAVING (SELECT COUNT(A.Forename,A.Surname)
FROM Actor A,Award AW
WHERE A.ActorID = AW.ActorID AND AW.Award_Category = "Best Actor"
AND Award_Ceremony = "Oscars"
GROUP BY A.Forename, A.Surname
HAVING COUNT(A.Forename, A.Surname) > 1);


texts: Mapping elements of nested list over values in a Python dict

texts:
Suppose there's a 3-level nested list, for example,

[[['<s>', '<s>', 'eu', 'rejects', 'german'], ['<s>', 'eu', 'rejects', 'german', 'call']],\
 [['eu', 'rejects', 'german', 'call', 'to'], ['rejects', 'german', 'call', 'to', 'boycott']]]

level 1: sentence level
level 2: context window level
level 3: word/token level

Task: I'd like to map each token to its corresponding index with a pre-defined Python dictionary (e.g, word2index['xx']=4).

Output example:

[[[2522, 2522, 475, 1620, 397], [2522, 475, 1620, 397, 439]],\
 [[475, 1620, 397, 439, 4], [1620, 397, 439, 4, 1443]]]

The following is what I've done,

def word2index(input, model):
    """ Map words to index
    """
    input2index = []
    for sent in input:
        sent2index = []
        for window in sent:
            window2index = []
            for elem in window:
                try:
                    index = model.vocab[elem].index
                    window2index.append(index)
                except KeyError:
                    unk = model.vocab['unk'].index
                    window2index.append(unk)
            sent2index.append(window2index)
        input2index.append(sent2index)
    return input2index

which involves lots of loops and creations of new list as intermediate containers. It'd be very easy to lose the track forgetting which container to append current data, especially when the nested list gets deeper.

Question: Would there be a more cleaner way to code such task?


texts: Ruby - Sending commands to multiple servers using Net::SSH

texts:
The idea

At my work, I'm tasked with retrieving logs for a list of online orders from a total of 12 servers. To do this, I SSH into them (with a jump host in between) one by one, run the script for every order, then parse the output. Overall, a very tedious process that I'm sure can be automated.

W -> J -> S

W = My Windows VM

J = Red Hat jump box

S = The Red Hat production servers

So the basic idea is the following:

Connect to every server by SSH
On every server, run the commands for all orders which are passed by command line
Associate each output with the order

Here is what I've come up with so far, and it is working on my home lab. But before I bring it in to work to propose it and try it on production servers, I want to know how the code can be cleaned up or done more efficiently.

The code

require 'net/ssh'
require 'io/console'
require 'pp'

ORDERS = ARGV.dup()
ARGV.clear()

SERVERS = [
    "prod1",
    "prod2",
    "prod3"
]

COMMAND = "aux_search.sh"

CONFIG = "C:/Users/myuser/.ssh/config"

RESULTS = ORDERS.each_with_object({}) { |k, v| v[k] = "" }

puts("Enter your username: ")
USERNAME = gets().chomp()
puts("Enter your password for accessing the servers: ")
SERVERPASSWORD = STDIN.noecho(&:gets).chomp()
puts("Enter your sudo password: ")
SUDOPASSWORD = STDIN.noecho(&:gets).chomp()

SESSIONS = []
SERVERS.each do |server|
    session = Net::SSH.start(server, USERNAME, :password => SERVERPASSWORD, :config => CONFIG,
        :verbose => :debug, :auth_methods => ["publickey", "password"], :verify_host_key => :accept_new)

    SESSIONS << session
end

SESSIONS.each do |ssh|
    ORDERS.each do |order|
        ssh.open_channel() do |channel|
            channel.on_data do |_, data|
                RESULTS[order].concat(data)
                if data.match(/\[sudo\]/)
                    channel.send_data("#{SUDOPASSWORD}\n")
                end
            end

            channel.request_pty() do |_, success|
                raise "Failed to request TTY for order #{order}" unless success
            end

            channel.exec("sudo ./#{COMMAND} #{order}") do |_, success|
                raise "Could not execute command #{COMMAND} #{order}" unless success
            end
        end
    end
    ssh.loop()
end

puts("===Results===")
pp(RESULTS)

My ssh config

Host jumpbox
    HostName 192.168.16.2
    User johrus2
    IdentityFile C:\Users\myuser\.ssh\id_rsa3
    Port 22

Host prod1
    HostName 192.168.16.3
    User johrus2
    IdentityFile C:\Users\myuser\.ssh\id_rsa3
    ProxyJump jumpbox
    Port 22

Host prod2
    HostName 192.168.16.4
    User johrus2
    IdentityFile C:\Users\myuser\.ssh\id_rsa3
    ProxyJump jumpbox
    Port 22

Host prod3
    HostName 192.168.16.5
    User johrus2
    IdentityFile C:\Users\myuser\.ssh\id_rsa3
    ProxyJump jumpbox
    Port 22

```


texts: Return true if a portion of one string can be rearranged to create the other string

texts:
function scramble(str1,str2) {
  let result;
  for(let i = 0; i < str2.length; i++){

    let found = str1.match(new RegExp(str2.charAt(i)));

    if(found === null){
      result = false;
      break;
    } else {
      str1 = str1.replace(found, "");
      result = true;
    }
  }

  return result;
}

The purpose of this function is to verify if the letters of the second string are contained in the first string and can be rescrambled to create the the word:

scramble('rkqodlw', 'world'); //true
scramble("scriptjavx", "javascript"); //false
scramble('katas', 'steak'); //false

The above is working but I am looking to improve the performance time to less than 12000ms for for any given string.


texts: Simple recursive transformation solution in Python

texts:
This simple Python code I wrote for a problem asked during an interview. The problem statement is:

  Given a tuple (a, b), transform this into (c, d) by applying any of the two below operations multiple time in any order you like:

  (a, b) -> (a+b, b)
  (a, b) -> (a, a+b)

  The program should take in a, b, c, and d. And tells us if it is possible to transform (a, b) to (c, d).

  Edit: a, b, c and d can be negative integers.

This recursive solution seems correct but recursion depth increases very fast for even slight increase in input size. I feel I am missing some easy optimization here. I would be glad for any kind of inputs be it style, algorithm choice, speed etc.

def intro():
  print "This program will check if transformation (a, b) -> (c, d) is possible by recursive application of any of the below rules:"
  print "1. (a, b) => (a+b, b) \n2. (a, b) => (a, a+b)\n"

def user_input():
  print "Enter space separated four integers a, b, c and d:\n"
  a, b, c, d = map(int, raw_input().split(' '))
  return a, b, c, d
  # print 'a = ' + a + ' b = ' + b + ' c = ' + c + ' d = ' + d

def solve(a, b, c, d):
  print '(a: {}, b: {})  (c: {}, d:{})'.format(a,b,c,d)
  if a == c and b == d:
    return True
  elif a > c or b > d:
    return False
  elif a == c and b != d:
    return solve(a, a+b, c, d)
  elif a !=c and b == d:
    return solve(a+b, b, c, d)
  else:
    return solve(a+b, b, c, d) or solve(a, a+b, c, d)

if __name__ == '__main__':
  intro()
  a, b, c, d = user_input()
  if solve(a, b, c, d):
    print "Transformation possible"
  else:
    print "Transformation not possible"


texts: Click-through rate calculator using jQuery

texts:
I created a calculator for CTR with jQuery.  The calculator is working just the way I want, but I'm quite new to jQuery and I wonder if I am using jQuery effectively.

The goal of the code is that if 2 values are entered and the button is clicked then the correct function is called and the output's background colour will change.

    CTR Calculator

    Number of Impressions:

    <input id="v1" type="text" style="width:10em;"/>

    Number of Clicks:

    <input id="v2" type="text" style="width:10em;"/>

    CTR:

    <input id="v3" type="text" style="width:10em;"/>

    <button id ="btn" type="button" class="btn btn-secondary">Calculate</button>

  $(document).ready(function(){
      $("#btn").on("click",function(event){
        if ($("#v1").val() === '' && $("#v2").val() === '' && $("#v3").val() === '') {
            $('#v1,#v2,#v3').css('background-color', 'transparent');
            alert("Please enter atleast 2 values!");
        } else if ($("#v1,#v2").val() === '' || $("#v1,#v3").val() === '' || $("#v2,#v3").val() === '') {
            $('#v1,#v2,#v3').css('background-color', 'transparent');
            alert("Please enter atleast 2 values!");
        } else if ($("#v1").val() === '') {
            var mathImp = (parseInt($('#v2').val()) / parseInt($('#v3').val())) * 100;
            $('#v1').val(mathImp);
            $('#v1').css('background-color', 'beige');
            $('#v2,#v3').css('background-color', 'transparent');
        }  else if ($("#v2").val() === '') {
            var mathClicks = (parseInt($('#v1').val()) * parseInt($('#v3').val())) / 100;
            $('#v2').val(mathClicks);
            $('#v2').css('background-color', 'beige');
            $('#v1,#v3').css('background-color', 'transparent');
        } else if ($("#v3").val() === '') {
            var mathCTR = (parseInt($('#v2').val()) / parseInt($('#v1').val())) * 100;
            $('#v3').val(mathCTR);
            $('#v3').css('background-color', 'beige');
            $('#v1,#v2').css('background-color', 'transparent');
        } else {
            alert("Please enter only 2 values!");
        }
     });
});


texts:
I have ext_scaffold (question.js). When I row click I get answers on this question, so

'rowselect': function(sm, row, rec) {
    store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
        url: '/answers/index_all_for_question_id/' + rec.data.id + '?format=ext_json',
        method: 'GET'}),
        reader: new Ext.data.JsonReader({
        root: 'answers',
        id: 'id',
        totalProperty: 'results'
      }, [
        {name: 'text', mapping: 'answer.text'},
        {name: 'email', mapping: 'answer.respondent.email'}
          ])
    });

    grid = Ext.getCmp('answers_grid');
    grid.reconfigure(store, new Ext.grid.ColumnModel([
                {id: 'text', header: "Answer &darr;", width: 500, sortable: true, dataIndex: 'text'},
                {id: 'email', header: "Email", width: 300, sortable: true, dataIndex: 'email'}
          ]));
    grid.store.load();

    scaffoldPanel.selectedRecordId = rec.data.id;
    scaffoldPanel.getFormPanel().getForm().loadRecord(rec);
}

and I have another admin file where grids (answer):

 var answers_datastore = new Ext.data.Store({
     autoLoad: true,
    proxy: new Ext.data.HttpProxy({
        url: '/answers/index_all_for_question_id/<%= @questions.first.id %>?format=ext_json',
        method: 'GET'}),
    reader: new Ext.data.JsonReader({
        root: 'answers',
        id: 'id',
        totalProperty: 'results'
      },[
      {name: 'text', mapping: 'answer.text'},
      {name: 'email', mapping: 'answer.respondent.email'}
      ])
    });

    var answersGrid = new Ext.grid.GridPanel({
    id: 'answers_grid',
    store: answers_datastore,
            frame: true,
        columns: [
          {id: 'text', header: "Answer &darr;", width: 500, sortable: true, dataIndex: 'text'},
          {id: 'email', header: "Email", width: 300, sortable: true, dataIndex: 'email'}
        ],
         listeners: {
             rowdblclick: function(answersGrid, rowI, event)   {
            Ext.MessageBox.show({
                title:            "Answer" ,
                   msg:             "A",
                closable:         true,
                   autowidth:        true
           });
             }
         },

        stripeRows: true,
        title:'Answers'
    });

How to avoid duplication?


texts:
<?php

define('AES_256_CBC', 'aes-256-cbc');

// both stored in a file on server
$encryption_key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));

$user_id = 1123;
$exp     = time() + (365 * 24 * 60 * 60);

$data = [
    "user_id" => $user_id,
    "exp"     => $exp,
];
$json = json_encode($data);

$token = openssl_encrypt($json, AES_256_CBC, $encryption_key, 0, $iv);
$base = base64_encode($token);
// at this point send the token to the client to use for further auth
$tokenDecoded = base64_decode($base);
$clear = openssl_decrypt($tokenDecoded, AES_256_CBC, $encryption_key, 0, $iv);
$sessionData = json_decode($clear);

?>

Everything occurs over an SSL HTTPS connection with signed certificate.

Is my implementation safe?


texts:
I've implemented two prime sieves in python 3 to find all prime numbers up to an upper limit n - n exlusive. The first one is rather naive, while the second one only considers odd numbers to begin with (some clever index-arithmetic is necessary).

Naive implementation:

def naive_sieve(n):
    if n < 3:
        return []

    sieve = [False, False, True] + [True, False] * (n // 2 - 1)

    for prime in range(3, int(n**0.5) + 1, 2):
        if sieve[prime]:
            for multiple in range(prime*prime, len(sieve), 2*prime):
                sieve[multiple] = False

    return [number for number, is_prime in enumerate(sieve) if is_prime]

I actually implemented the more advanced sieve twice. One time giving every little step a sub-function with name (to get the understanding right) and the second time without all these definitions (to minimize the number of
function calls).

More readable implementation

def easy_odd_sieve(n):
    if n < 3:
        return []

    def number_of_odd_nums_below(n):
        return n // 2

    def greatest_odd_number_below(n):
       return ceil(n) // 2 * 2 - 1

    def index_of_odd_number(n):
        return (n - 1) // 2

    def odd_number_from_index(i):
        return (2*i + 1)

    sieve = [0] + [1] * (number_of_odd_nums_below(n) - 1)

    for j in range(1, index_of_odd_number(greatest_odd_number_below(n ** 0.5)) + 1):
        if sieve[j]:
            for i in range(index_of_odd_number(odd_number_from_index(j) ** 2), len(sieve), odd_number_from_index(j)):
                sieve[i] = False

    return [2] + [odd_number_from_index(index) for index, is_prime in enumerate(sieve) if is_prime]

Final implementation:

def odd_sieve(n):
    if n < 3:
        return []

    sieve = [0] + [1] * (n //2 - 1)

    for j in range(1, ceil(n ** 0.5) // 2):
        if sieve[j]:
            for i in range((2*j)*(j + 1), len(sieve), 2*j + 1):
                sieve[i] = False

    return [2] + [2*index + 1 for index, is_prime in enumerate(sieve) if is_prime]

My questions regarding this code are:

How does my general python programming style look like?
Correctness. Is the code correct or did I overlook something?
(I've checked that all sieves return the same list for n in range(1, 1000))
Naming. Are the variable names clear to the reader? What would you change?


texts: Set openCV basic structures to zero in a unique way

texts:
For test cases I need a unique way to set any structure to zero. For openCV I wrote this:

  // Fill every basic structure of openCV with zero.
  template < typename Tp >
  void zero( cv::Point_<Tp>& p ) {
    p.x = p.y = 0;
  }
  template < typename Tp >
  void zero( cv::Point3_<Tp>& p ) {
    p.x = p.y = p.z = 0;
  }
  template < typename Tp >
  void zero( cv::Size_<Tp>& s ) {
    s.width = s.height = 0;
  }
  template < typename Tp >
  void zero( cv::Rect_<Tp>& r ) {
    r.x = r.y = r.width = r.height = 0;
  }
  inline void zero( cv::RotatedRect& r ) {
    zero( r.center );
    zero( r.size );
    r.angle = 0;
  }
  inline void zero( cv::TermCriteria& t ) {
    t.type = t.maxCount = 0;
    t.epsilon = 0.0;
  }
  template < typename Tp, int M, int N>
  void zero( cv::Matx<Tp, M, N>& m ) {
    m = 0;
  }
  // Vec<> and Scalar<> are derived from Matx<>
  inline void zero( cv::Range& r ) {
    r.start = r.end = 0;
  }
  inline void zero( cv::Mat& m ) {
    m = 0;
  }
  inline void zero( cv::SparseMat& sm ) {
    sm.clear();
  }
  template < typename Tp >
  void zero( cv::SparseMat_<Tp>& sm ) {
    sm.clear();
  }

Setting cv::Mat to zero by assigning a new zero filled Mat is reallocating. But looping over would be slow (now done by *= 0). Using memset( m.data, ... ) is only possible if m.isContinuous(). Any idea of being safe and fast? Is it possible to join some derived cases?

The template parameters _Tp has been replaced by Tp because starting with _, followed by uppercase letter is reserved. That is something the openCV authors do violate too (I copied it from the openCV core code).

Mat, Matx and derived Vec and Scalar can be set to zero by multiplying with zero. Internal this is a for() over all elements but without the realloc of the zeros() assignment.


texts:
I am writing Python code for a Tic Tac Toe game.  I need to write a function that takes in three inputs: board, x, and y.  Board being the current display of the board and then x and y being values of 0, 1, or 2.  The game is set up to ask the user for coordinates.

def CheckVictory(board, x, y):

    #check if previous move was on vertical line and caused a win
    if board[0][y] == ('X') and board[1][y] == ('X') and board [2][y] == ('X'):
        return True
    if board[0][y] == ('O') and board[1][y] == ('O') and board [2][y] == ('O'):
        return True

    #check if previous move was on horizontal line and caused a win
    if board[x][0] == ('X') and board[x][1] == ('X') and board [x][2] == ('X'):
        return True
    if board[x][0] == ('O') and board[x][1] == ('O') and board [x][2] == ('O'):
        return True

    #check if previous move was on the main diagonal and caused a win
    if board[0][0] == ('X') and board[1][1] == ('X') and board [2][2] == ('X'):
        return True
    if board[0][0] == ('O') and board[1][1] == ('O') and board [2][2] == ('O'):
        return True
    #check if previous move was on the secondary diagonal and caused a win
    if board[0][2] == ('X') and board[1][1] == ('X') and board [2][0] == ('X'):
        return True
    if board[0][2] == ('O') and board[1][1] == ('O') and board [2][0] == ('O'):
        return True

    return False
#end of CheckVictory function

The function is called in the game loop like so:

p_x, p_y = playerTurn(board)    #let player take turn
displayBoard(board)             #show board after move has been made
if CheckVictory(board, p_x, p_y):   #see if user has won
    print("CONGRATULATIONS, you win!")
    newGame(board)  #game over start new one
    continue

and it's similar for the computer turn.

I feel like there is a better way to write this function.  I feel like I should be using x and y more or there is a better way to check rather than writing all the possibilities. What's a better way to write this to make it short and concise?


texts:
Displaying Some Multiples
Write a program to calculate the multiples of a given number. Have the user enter a number, and then use a for loop to display all the multiples of that number from 1 to 12. It is not necessary to use a function.
You must use a for loop.
/*
 * Code by Clint <https://github.com/clieg>
 *
 *
 * Problem from: http://programmingbydoing.com/a/displaying-some-multiples.html
 */

import java.util.Scanner;

public class DisplayingSomeMultiples {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int number;

        System.out.print("Choose a number: ");
        number = input.nextInt();

        System.out.println();

        for (int i = 1; i <= 12; i++) {
            int mutiply = number * i;
            System.out.println(number + " x " + i + " = " + mutiply);
        }
    }
}


texts: Calling one method both dynamically and statically

texts:
I'm currently working on a PHP component: "Filesystem handler". I've run into a problem where I want to call one exact method in both dynamic and static ways.

I've ended up with this solution. Could you please give me a feedback ? I want to know, if there is a better or a simpler way to achieve the same result.

<?php

class File {

protected $file;

public function __construct($file) {
    $this->file = $file;
}

protected static function exists($arg) {
    var_dump($arg);
}

public function __call($method, $parameters = null) {
    if($method == 'exists') {
        return call_user_func_array(array($this, 'exists'), array(array($this->file)));
    }
}

public static function __callStatic($method, $parameters) {
    if($method == 'exists') {
        return call_user_func(__CLASS__.'::exists', $parameters);
    }
}

}

$file = new File('dynamic');
$file->exists();

File::exists('static');


texts:
I started with Python and Tkinter and am trying to make my first steps by creating a simple UI with a header, sidebar (currently just a label) and a few labels and entries.

Before I go on I want to ask you all if the way I do this is correct and a common one. Also if you see potential to make this better, please let me know!

import tkinter as tk
from tkinter import messagebox
import tkinter.ttk as ttk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        root.geometry('1280x768')
        root.configure(background='#0E2F47')

        root.grid_rowconfigure(20, weight=1)

        s = ttk.Style()
        s.theme_use('classic')
        s.configure('SOExample.TEntry', relief='flat')
        s.layout('SOExample.TEntry', [
            ('Entry.highlight', {
                'sticky': 'nswe',
                'children':
                    [('Entry.border', {
                        'border': '1',
                        'sticky': 'nswe',
                        'children':
                            [('Entry.padding', {
                                'sticky': 'nswe',
                                'children':
                                    [('Entry.textarea',
                                      {'sticky': 'nswe'})]
                            })]
                    })]
            })])

        # GUI elements
        header_img = tk.PhotoImage(file='Header.png')

        header_label = tk.Label(root, bg='#191E31', image=header_img)
        header_label.image = header_img
        header_label.grid(column=1, row=0, columnspan=20)

        sidebar_label = tk.Label(root, bg='#191E31', width=25)
        sidebar_label.grid(column=1, row=1, rowspan=20, sticky="nws")

        # Input Section
        adress_input_label = tk.Label(root, bg='#0E273B', fg='#CEDEEE', text="Adress", font=("Century Gothic", 12), anchor='w')
        adress_input_label.grid(column=2, columnspan=3, row=1, pady=25, sticky='new')

        adress_input_entry = ttk.Entry(root, style='SOExample.TEntry')
        adress_input_entry.grid(row=1, column=3, sticky='e')

        message_input_label = tk.Label(root, bg='#0E273B', fg='#CEDEEE', text="Message", font=("Century Gothic", 12), anchor='w')
        message_input_label.grid(column=2, columnspan=3, row=2, pady=25, sticky='new')

        message_input_entry = ttk.Entry(root, style='SOExample.TEntry')
        message_input_entry.grid(row=2, column=3, sticky='e')

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

if __name__ == "__main__":
    root = tk.Tk()

    MainApplication(root).grid(column=0, row=0)

    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop()


texts:
The question asked to find all the prime numbers within a particular range. The way I approached this was to loop through each of the numbers within the range and for each number check whether it's a prime. My method for checking prime is to start at 3 and loop till number/2 in hops of 2 (essentially excluding all the even numbers).

Can somebody take a look at the code an tell me how I might be able to better this snippet and what are some of the aspects that I am missing?

public class PrimeBetween{

public static void main(String[] args){
        printAllPrimes(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}

public static void printAllPrimes(int start,int end){
        for(int i = start;i <= end;i++){
                if(isPrime(i))
                        System.out.println("Print prime:"+i);
        }

}

private static boolean isPrime(int i){
        if(i%2 == 0 && i!=2)
                return false;
        else{
                if(i == 1) return false;
                for(int p=3;p<=i/2;p+=2){
                        if(i%p == 0)
                                return false;
                }
                return true;
        }

}

}


texts:
I've written a simple util-method in my spigot plugin to check if a message contains a valid minecraft colour code. A valid minecraft colour code consists of a & followed by a hex digit: 0 to f. Minecraft itself exchanges all & by a §, for reasons that would take too long to explain, it's not possible for the users to send messages to the server directly. Therefore & is generally used as a replacement.
I now have to check at some point, if the message the user sent to the server is coloured, which is the reason this method exists. Here are some quick examples, how it does work:
string value - return value

"Simple String" - false
"Smith&Wesson" - false
"&4This would be red." - true
"%aGreen &2Darker Green &0 Darkest Green" - true
"&& Omega &&" - false

Here's my code. It does what it's supposed to do, but for some reason it still seems unneccesary clunky to me. Any improvement is welcome :)
    public static boolean isMessageColoured(String message) {
        char[] arr = message.toCharArray();
        for (int i = 0; i < message.length() - 2; i++) {
            if (arr[i] == '&' && "0123456789abcdef".contains(Character.toString(arr[i + 1]))) {
                return true;
            }
        }
        return false;
    }


texts: Find all consecutive sequences in an ordered set

texts:
I have the following set. a = [1,2,3,4,5] and i want to find all of the following sequences of consecutive elements:

1,
1,2
1,2,3
1,2,3,4
1,2,3,4,5
2,
2,3,
2,3,4,
2,3,4,5
3,
3,4
3,4,5
4
4,5
5

This is the following code that I use and works correctly. My only problem is with the complexity of the algorithm O(n2). Is there a better approach that I can use to reduce the complexity?

    int main()
    {
        int a[5] = {1,2,3,4,5};
           vector<vector<int>> all;
            for(int i = 0; i < 5; i ++)
            {
                vector<int> g;
                g.push_back(a[i]);
                all.push_back(g);
               for(int j = i+1; j < 5; j++)
               {
                    g.push_back(a[j]);
                    all.push_back(g);
               }
               g.clear();
            }

            for(int i = 0; i < all.size();i++)
            {
               for(int j = 0; j < all[i].size();j++)
               {
                    cout << all[i][j] << "  ";
               }
               cout << endl;
            }

        return 0;
    }


texts: Java application for finding permutations efficiently

texts:
I am an eighth grader with a school project of creating and application in Java that returns the total permutations of two given numbers.  It needs to be light and efficient, for later deployment on a website.  I was wondering if there was any way I could improve the code so it would be more efficient.

class Factorials {
    public static void main(String[] args){
        int n = 8;
        long factorialN = n;
        for (int ForN = n; ForN <= n && ForN > 1; ForN--) {
            factorialN = factorialN * ForN;
        }
        factorialN = factorialN / n;
        System.out.println(factorialN);

        int r = 6;
        int rMinus1 = r - 1;
        long factorialR = rMinus1;
        for (int ForR = rMinus1; ForR <= rMinus1 && ForR > 1; ForR--) {
            factorialR = factorialR * ForR;
        }
        factorialR = factorialR / rMinus1;
        System.out.println(factorialR);

        int nMr = n - r;
        System.out.println(nMr);
        long factorialNmR = nMr;
        if (nMr == 2) {
            factorialNmR = 2;
        }
        else if (nMr <= 1){
            factorialNmR = 1;
        }
        else if (nMr > 2) {
            for (int FornMr = nMr; FornMr <= nMr && FornMr > 1; FornMr--) {
                factorialNmR = factorialNmR * FornMr;
            }
            factorialNmR = factorialNmR / nMr;
            System.out.println(factorialNmR);
        }

        long permutations = factorialN;
        System.out.println(permutations);
        permutations = permutations / factorialNmR;
        System.out.println(permutations);
    }
}


texts:
I'm posting two solutions for LeetCode's "Defanging an IP Address". If you'd like to review, please do. Thank you!
Problem
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"

Constraints:

The given address is a valid IPv4 address.

Code 1
#include <stdio.h>
#include <stdlib.h>

static const char* defangIPaddr(
    char* address
) {
    char* ipv4_memory = calloc(1, sizeof("###[.]###[.]###[.]###"));
    char* defanged = ipv4_memory;

    for (char* character = address; *character; character++) {
        if (*character == '.') {
            *ipv4_memory++ = '[';
            *ipv4_memory++ = '.';
            *ipv4_memory++ = ']';

        } else {
            *ipv4_memory++ = *character;
        }
    }

    return defanged;
}

int main() {

    printf ("%s \n", defangIPaddr("1.1.1.1"));
    printf ("%s \n", defangIPaddr("255.100.50.0"));

    return 0;
}

Code 2 without changing the input:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char* defangIPaddr(
    const char* address
) {
    char* cloned_address = NULL;
    cloned_address = strdup(address);

    char* ipv4_memory = calloc(1, sizeof("###[.]###[.]###[.]###"));
    char* defanged = ipv4_memory;

    for (char* character = cloned_address; *character; character++) {
        if (*character == '.') {
            *ipv4_memory++ = '[';
            *ipv4_memory++ = '.';
            *ipv4_memory++ = ']';

        } else {
            *ipv4_memory++ = *character;
        }
    }

    return defanged;
}

int main() {

    printf ("%s \n", defangIPaddr("1.1.1.1"));
    printf ("%s \n", defangIPaddr("255.100.50.0"));

    return 0;
}


texts: Sums of columns and diagonals of a matrix

texts:
I made a simple matrix program that prints some data..I want to know how to reduce amount of lines with some functions or whatever, because there is so much if-s,and for loops.

Tried to make functions but almost every for loop is different, so that did not work.

#include <stdio.h>
main()
{
    int i,j,m,n,sMain,sAnti,sCol,sMainUp,sMainDown,sAntiUp,sAntiDown;
    int arr[30][30];

    printf("What dimensions of matrix you want?(1 number) ");
    scanf("%d",&m);
    n = m;

    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            printf("Type elements: ");
            printf("Element[%d,%d]: ",i,j);
            scanf("%d",&arr[i][j]);
        }
    }
    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    sMain = 0;
    sAnti = 0;
    sMainUp = 0;
    sMainDown = 0;
    sAntiUp = 0;
    sAntiDown = 0;

    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            if(i == j){
                sMain += arr[i][j];
            }
            if((i + j) == (n - 1)){
                sAnti += arr[i][j];
            }
            if(i < j){
                sMainUp += arr[i][j];
            }
            if(i > j){
                sMainDown += arr[i][j];
            }
            if((i + j) < (n - 1)){
                sAntiUp += arr[i][j];
            }
            if((i + j) > (n - 1)){
                sAntiDown += arr[i][j];
            }
        }
    }
    sCol = 0;
    printf("Sum of what column you want? ");
    scanf("%d",&j);
    for(i = 0; i < m; i++){
        sCol += arr[i][j];
    }
    printf("Sum of main diagonal: %d.\n",sMain);
    printf("Sum of anti(counter) diagonal: %d.\n",sAnti);
    printf("Sum above main diagonal: %d.\n",sMainUp);
    printf("Sum under main diagonal: %d.\n",sMainDown);
    printf("Sum above anti diagonal: %d.\n",sAntiUp);
    printf("Sum under anti diagonal: %d.\n",sAntiDown);
    printf("Sum of %d. column is: %d.",j,sCol);

}


texts: Regular expression for application version

texts:
Only these formats are accepted.

1.1.1
1.1.1-r
1.1.1-b
1.1.1-r1
1.1.1-b1

I wrote this code. What don't I like in it? I used parentheses and now I have two groups. In fact, I don't need to do anything with groups. And there might be some bugs as well.

package com.sandbox;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
/**
 * @param args
 */
public static void main(String[] args) {
    checkVersion("10.22.5-r");
}

private static void checkVersion(String current) {
    String regex = "([1-9]\\d*)\\.(\\d+)\\.(\\d+)-[b|r](?:[1-9]\\d*)*";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcherCurrent = pattern.matcher(current);
    System.out.println("Matches: " + matcherCurrent.matches());
    System.out.println("The first digit: " + matcherCurrent.group(1));
    System.out.println("The second digit: " + matcherCurrent.group(2));
    System.out.println("The third digit: " + matcherCurrent.group(3));

    // Compare and decide whether an update is necessary
}

}

Thank you for the answers you give me. I'll vote up as soon as I have enough reputation.


texts: Reduce repetition in these Redux CRUD actions

texts:
My React application manages some entities. I'm using Redux (with redux-thunk) to manage the application state. I've created a RESTClient based on Axios:

export class RESTClient<E extends { id: number }> extends Client {
  protected path: string;
  public constructor(path: string, token?: string) {
    super(token);
    this.path = path;
  }

  public index() {
    return this.clientInstance.get<E[]>(this.path);
  }

  public create(entity: Omit<E, 'id'>) {
    return this.clientInstance.post<E>(this.path, entity);
  }

  public update(entity: E) {
    return this.clientInstance.put<E>(`${this.path}/${entity.id}`, entity);
  }

  public delete(entity: E) {
    return this.clientInstance.delete<E>(`${this.path}/${entity.id}`);
  }
}

This RESTClient is used by a Redux action generator:

export const createClientAction = <T extends Client>(
  type: new (token?: string) => T,
  action: (client: T, dispatch: Dispatch, getState: () => State) => void
) => {
  return async (dispatch: Dispatch, getState: () => State) => {
    const clientInstance = getState().session.isAuthenticated ? new type(getState().session.token) : new type();
    action(clientInstance, dispatch, getState);
  };
};

Now to create a delete action for the entity participant I create an action as follows:

import { createAction } from 'typesafe-actions';

const deleteParticipantSuccess = createAction('participant/DELETE', (participant: Participant) => participant)();

export const deleteParticipant = (participant: Participant) => {
  return createClientAction(ParticipantClient, (client, dispatch) => {
    client.delete(participant).then(() => {
      dispatch(deleteParticipantSuccess(participant));
      dispatch(
        addEvent({
          message: 'event.success.deleted',
          values: { entity: participant.email },
          type: EventType.SUCCESS
        })
      );
    });
  });
};

Obviously for error handling I need to add a few lines.

When I implement all CRUD-Actions with error handling I have per entity ~150 lines of code. What would you do with this, to DRY it up?

Would you write something which generates the CRUD actions?
Do you think I would benefit if I use sagas instead of redux-think?
Do you think I could simplify things if I implement a custom Redux middleware, especially regarding to the event dispatches?


texts:
Here is my final build of the Age Distance Calculator - Any feedback on the code would be great - This is my 2nd day of java programming and thought this was a good little project.

package dev.swift.atc;

import java.util.Scanner;

import java.util.concurrent.TimeUnit;

public class AgeCalc {

   private int personAge;
   private int age;
   private int d_age;
   private String name;
   static Scanner s = new Scanner(System.in);

   public static void main(String [] args) throws InterruptedException
   {
       AgeCalc ac = new AgeCalc();
       ac.getInputs();
       boolean result = ac.calculateAge();
       if (result == true) {
          ac.showResults();
          s.close();
       }
       else {
        ac.errorResults();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("Restarting Program");
        TimeUnit.SECONDS.sleep(2);
        ac.ageCalculateTwo();
       }
   }
   //The constructor
   public AgeCalc() throws InterruptedException {
       System.out.println("Welcome To Java Coded Age Differnce Calculator");
       TimeUnit.MILLISECONDS.sleep(100);
   }

   //Handle inputs
   public void getInputs() throws InterruptedException {
        System.out.println("Input Your Name Before We Start");
        this.name = s.nextLine();
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println("Input Your Age");
        this.age = s.nextInt();
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println("Your Age Is " + this.age + " Years Old.");
   }

   //Make the calculation
   public boolean calculateAge() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Now Input The Desired Age To Work Out The Distance To");
        this.d_age = s.nextInt();
        if (this.d_age < this.age){
            System.out.println("You Cannot Set The Target To Lower Then Your Current Age");
            return false;
        }
        else {
         this.personAge = this.d_age - this.age;
         return true;
        }
    }

   //Show the results
   public void showResults() throws InterruptedException {
       System.out.println("Working - Coded By Swift, Hope You Will Use This Program Again " + this.name);
       TimeUnit.SECONDS.sleep(3);
       System.out.println("You Will Be " + this.d_age + " In " + this.personAge +" Years");
       TimeUnit.SECONDS.sleep(3);
       System.out.println("Hope You Enjoyed The Program " + this.name);
       System.exit(0);
       System.out.println("Line Never Reached - Test");
   }
   public void errorResults() throws InterruptedException {
       System.out.println("You Have Entered An Error " + this.name);
   }
   public void ageCalculateTwo() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println("Now Input The Desired Age To Work Out The Distance To - Remember Not To Be Lower Than " + this.age);
        this.d_age = s.nextInt();
        if (this.d_age < this.age){
            System.out.println("You Have Already Been Told Not To Do This");
            TimeUnit.SECONDS.sleep(3);
            System.out.println("Program Shutting Down " + this.name + "Due To Multiple Errors You Have Caused ");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("Closed - Coded By Swift, Hope You Will Use This Program Again " + this.name);
            TimeUnit.SECONDS.sleep(2);
            System.exit(0);
            System.out.println("Line Never Reached - Test");
        }
        else {
         this.personAge = this.d_age - this.age;
         System.out.println("Working - Coded By Swift, Hope You Will Use This Program Again " + this.name);
         TimeUnit.SECONDS.sleep(3);
         System.out.println("You Will Be " + this.d_age + " In " + this.personAge +" Years");
         TimeUnit.SECONDS.sleep(3);
         System.out.println("Hope You Enjoyed The Program " + this.name);
         System.exit(0);
         System.out.println("Line Never Reached - Test");
        }
    }
   }


texts:
I'm working on writing a routing system for a PHP project. I'm trying to write it in a way that it can easily be expanded later on via plugins.
I have 2 ideas for how to go about doing it. I've already created working versions of both, now it's just down to which one people find easier to use.
1:
class GeneralRouter extends Router {

    public function RootRoute (Request $request, Response $response){
        $request->requiresGet();
        $response->html('home');
        $response->send();
    }

    public function PageRoute (Request $request, Response $response){
        $request->requiresGet();
        $response->html('Hi, looking at \"' . $request->parameters["page"]. '\"');
        $response->send();
    }

    public function routes (){
        return array(
            '/' => 'RootRoute',
            '/:page/' => 'PageRoute'
        );
    }
}

2:
class GeneralRouter extends Router {

    public function init (){
        $this->get('/', function(Request $req, Response $res){
            $response->html('
home
');
            $response->send();
        });

        $this->get('/:page/', function(Request $req, Response $res){
            $response->html('
Hi, looking at \"' . $req->parameters["page"]. '\"
');
            $response->send();
        });
    }
}

#1 is similar to the way I've seen other PHP projects do their routing classes (CraftCMS for example), however I really like the ExpressJS-like format of #2. Which would be easier for expansion and/or is the "correct" way of doing it?


texts:
I've written a solution to Euler 41:

  We shall say that an n-digit number is pandigital if it makes use of
  all the digits 1 to n exactly once. For example, 2143 is a 4-digit
  pandigital and is also prime.

  What is the largest n-digit pandigital prime that exists?

But it feels like I could compress the code down instead of having 30 lines of for loops. To briefly explain how it works:

I generate all pandigital numbers through the generate function which features 9 nested for loops which continue if their value is equal to a higher loop or if they would make a number longer than what is required. The generated numbers are then prime checked. This is a bruteforce method.

var time = new Date;
var buffer = [];
var greatest = 0;

function isPrime(number) {
var s = Math.sqrt(number);
for (var b = 2; b <= s; b++) {
    if (number % b === 0) {
        return false;
    }
}
return true;
}

function push(array) {
buffer.push(array.join(''));
}

function generate(length) {
var max = length;
for (var u = 1; u <= max; u++) {
    if (max === 1) {
        push([u]);
    }
    for (var i = 1; i <= max; i++) {
        if (i === u || max < 2) {
            continue;
        }
        if (max === 2) {
            push([u, i]);
        }
        for (var o = 1; o <= max; o++) {
            if (o === i || o === u || max < 3) {
                continue;
            }
            if (max === 3) {
                push([u, i, o]);
            }
            for (var p = 1; p <= max; p++) {
                if (p === i || p === o || p === u || max < 4) {
                    continue;
                }
                if (max === 4) {
                    push([u, i, o, p]);
                }
                for (var a = 1; a <= max; a++) {
                    if (a === i || a === o || a === p || a === u || max < 5) {
                        continue;
                    }
                    if (max === 5) {
                        push([u, i, o, p, a]);
                    }
                    for (var s = 1; s <= max; s++) {
                        if (s === a || s === p || s === o || s === i || s === u || max < 6) {
                            continue;
                        }
                        if (max === 6) {
                            push([u, i, o, p, a, s]);
                        }
                        for (var d = 1; d <= max; d++) {
                            if (d === s || d === a || d === p || d === o || d === i || d === u || max < 7) {
                                continue;
                            }
                            if (max === 7) {
                                push([u, i, o, p, a, s, d]);
                            }
                            for (var f = 1; f <= max; f++) {
                                if (f === d || f === s || f === a || f === p || f === o || f === i || f === u || max < 8) {
                                    continue;
                                }
                                if (max === 8) {
                                    push([u, i, o, p, a, s, d, f]);
                                }
                                for (var g = 1; g <= max; g++) {
                                    if (g === f || g === d || g === s || g === a || g === p || g === o || g === i || g === u || max < 9) {
                                        continue;
                                    }
                                    push([u, i, o, p, a, s, d, f, g]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
}

for (var i = 1; i <= 8; i++) {
generate(i);
}

for (var i = buffer.length - 1; i >= 0; i--) {
if (isPrime(buffer[i])) {
    greatest = buffer[i];
    break;
}
}

var time1 = new Date;
console.log(greatest, 'took:', time1 - time, 'ms');


texts:
I admit I'm sort of stuck on this. I couldn't think of a better way of representing the card value that will be used in a playing card game. How well thought out is the casting an enum value to an int? I might be wrong but it does not seem very OOP. Is there a different way I should be doing it instead?

void Main()
{
    Card testCard = new Card(CardSuit.Diamonds, (int)CardValue.Ace);
}

public enum CardSuit
{
    Spades,
    Hearts,
    Diamonds,
    Clubs
}

public enum CardValue
{
    Ace = 1,
    Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10,
    Jack = 11,
    Queen = 12,
    King = 13
}

public class Card
{
    public CardSuit CardSuit { get; private set; }
    public int CardValue { get; private set; }

    public Card(CardSuit cardSuit, int cardValue)
    {
        CardSuit = cardSuit;
        CardValue = cardValue;
    }
}


texts: Retrieve random element from array not contained in second array

texts:
I have a function, getUnusedName that returns a random name, but first checks if it's already used by any object within a second array.

Observing how many times the function is called across multiple runs shows a pretty wide variation as I would expect when using random. Is there a more efficient way of achieving this?

As well as a general code review, I'd also like to ask:

If possible, I'd like to avoid removing items from names, which is why I have chosen the random solution. Is this a bad choice? What are my alternatives?
Is there a cleaner way to check if a name is already in use? Using Array.filter then checking the resulting length seems a little verbose.

var names  = ['Steve', 'Adam', 'Phillip', 'Thomas', 'John', 'Joseph'];
var people = [];
var calls  = 0;

function getUnusedName() {
    calls++;

    var randomName = names[Math.floor(Math.random() * names.length)];

    if (people.filter(function (val) { return val.name === randomName; }).length === 0) {
        return randomName
    } else {
        return getUnusedName();
    }
}

for (var i = 0; i < names.length; i++) {
    var name = getUnusedName();

    people.push({
        name: name,
        age: (i * i) + 20,
    });
}

console.log('getUnusedName calls: ' + calls);
console.log(people);