texts: Write one string to a socket within 10 seconds or another string if the time is out

texts:
I have implemented a method which will send one data to the server if it (Raspberry Pi Pin Input HIGH, in this case) occurs within 10 seconds. If this doesn't happen within 10 seconds then I should send some other data.

This implementation works for me, but I think that there should be another better implementation.

ScheduledExecutorService timeoutScheduler = Executors.newScheduledThreadPool(1);

ScheduledFuture<?> timeoutHandler = timeoutScheduler.schedule(() -> {
    try {
        socketConnection.writeData("String that should be sent if time is out");
        turnstileClosed.removeAllListeners();
        timeoutScheduler.shutdownNow();
    } catch (IOException e) {
        e.printStackTrace();
    }
}, 10_000, TimeUnit.MILLISECONDS);

turnstileClosed.addListener((GpioPinListenerDigital) event -> {
    try {
        if (event.getState() == PinState.HIGH) {
            socketConnection.writeData("String that should be sent within 10 seconds");
            timeoutHandler.cancel(true);
            timeoutScheduler.shutdownNow();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
});

timeoutScheduler.awaitTermination(10_000, TimeUnit.MILLISECONDS);
turnstileClosed.removeAllListeners();


texts: PHP OOP registration with User class and singleton Database class

texts:
I created registration system with PHP. I have User class that will handle all the input and insert the user input into database, and i created Database class with Singleton pattern that will connect to database. After user submited his data, new User object is created.

This is my Database class with singleton patter:

class Database {
    private static $instance = null;
    private $conn;

    private function __construct() {
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
        $this->conn = new PDO($dsn, DB_USER, DB_PASS);
    }
    private function __clone() {
        return false;
    }
    private function __wakeup() {
        return false;
    }
    public static function getInstance() {
        if(!self::$instance) {
            self::$instance = new Database();
        }
        return self::$instance;
    }
    public function getConnection() {
        return $this->conn;
    }
}

And this is my User class:

class User {

    public $errors = array();
    protected $username;
    protected $pw1;
    protected $pw2;
    protected $mail;
    private $db;
    private $conn;

    public function __construct() {
        $this->db = Database::getInstance();
        $this->conn = $this->db->getConnection();
    }
    }

I didn't copied rest of the User class code, because my question is: Is this a good way to create singleton pattern for db connection, and a good way to use it in other classes?
I'm fairly new to PHP, and i understand good amount of writing the PHP code, but what i lack is practical knowledge, what are common practices and how to structure the code.


texts: Elegant way to replace substring in a regex with optional groups in Python?

texts:
Given a string taken from the following set:

strings = [
    "The sky is blue and I like it",
    "The tree is green and I love it",
    "A lemon is yellow"
]

I would like to constuct a function which replaces subject, color and optional verb from this string with others values.

All strings match a certain regex pattern as follow:

regex = r"(?:The|A) (?P<subject>\w+) is (?P<color>\w+)(?: and I (?P<verb>\w+) it)?"

The expected output of such function would look like this:

repl("The sea is blue", "moon", "white", "hate")
# => "The moon is white"

Here is the solution I come with (I can't use .replace() because there is edge cases if the string contains the subject twice for example):

def repl(sentence, subject, color, verb):
    m = re.match(regex, sentence)
    s = sentence
    new_string = s[:m.start("subject")] + subject + s[m.end("subject"):m.start("color")] + color
    if m.group("verb") is None:
        new_string += s[m.end("color"):]
    else:
        new_string += s[m.end("color"):m.start("verb")] + verb + s[m.end("verb"):]
    return new_string

Do you think there is a more straightforward way to implement this?


texts: Checking a one-dimensional numpy array in a multidimensional array without a loop


texts:
I am doing exercise 1-13 of K&R. The problem is to print a histogram of the lengths of words in the input. This is the easier problem, printing the histogram with horizontal bars. This is what I came up with. Is there a better way to do this? Are there any bugs?
#include <stdio.h>

#define MAXLEN 10

int main(){
    int c,length;
    int hist[MAXLEN+1];

    length=0;
    for(int i=0;i<MAXLEN+1;i++) hist[i]=0;

    while((c=getchar())!=EOF){
        if((c==' ' || c=='\t' || c=='\n') && length){
            if(length>MAXLEN)
                hist[MAXLEN]++;
            else
                hist[length-1]++;
            length=0;
        }
        else if(c!=' ' && c!='\t' && c!='\n')
            length++;
    }
    //to deal with situations in which input doesn't end in a space or newline or tab
    if(length>MAXLEN)
        hist[MAXLEN]++;
    else if(length)
        hist[length-1]++;

    //printing the histogram horizontally
    putchar('\n');
    for(int i=0;i<MAXLEN;i++){
        printf("%3d|",i+1);
        for(int j=0;j<hist[i];j++) putchar('x');
        putchar('\n');
    }
    printf(">%d|",MAXLEN);
    for(int i=0;i<hist[MAXLEN];i++) putchar('x');
    putchar('\n');
}


texts:
This is a Bash script that runs commands which builds code using the parameters given.
Code
The task:
I have multiple instances of websites which need to be build individually using individual yarn commands and then copied out of a build folder and placed into their own individual folder. I found this very repetitive and so I wanted to solve the problem using a script. I thought about using Python but I ended up using Bash.
Pseudocode:
Inputs: folder where the code is built, folder where the output code is stored, list of languages to run yarn build on.
For each language in input:
   Go to project/build
   Run "yarn build_language"
   Delete output/language folder
   Copy project/build to output/language folder

Here is my Bash implementation:
#!/bin/bash

# PROC Build and Copy:
#     Args:
#         1) Build directory
#         2) Output directory path (general)
#         3) List of language names

#     For each lang in list of language names:
#         Run appropriate build command
#         Delete output directory
#         Copy build directory to output directory/lang

if (( $# < 3 )); then
    echo "Please use at least 3 parameters"
    exit 2
fi

array=("$@")

readonly build_path=$1
readonly output_path=$2
languages=("${array[@]:2}")

build_command="yarn build_"

for lang in "${languages[@]}"
do
    cd "$build_path" || exit
    eval "${build_command}${lang}"
    cd ~- || exit
    output=${output_path}${lang}
    rm -rf "$output"
    mkdir -p "$output"
    cp -r "$build_path" "$output"
done

Sample usage: ./build_all.sh my_project/build/. environments/ python lua
Discussion
I found a style guide on Github and tried to follow it but this is my first Bash script so I am not sure if I followed a good style. I am a Python developer and I fear I may have written a Python-script in Bash. I am also not sure if Bash is the best way to implement this type of script. I wanted to make this re-usable by pulling the directories out into parameters, but I decided not to have the yarn command as a parameter as I thought it could be confusing having lots of parameters. Are my assumptions justified, or do they make the code confusing?


texts:
I noticed there's some code on StackOverflow that is, to put it mildly, suboptimal. I'm posting here to see if we can provide a better solution.

Here's a proposal for fixing it.

The approach is to provide a small utility class with static methods, so it can be used just like Math.method(...).

The standard deviation implements this formula, which applies to a sample.

The median function is taken from this answer, which is based on the reasonable assumption that the array can be sorted in memory.

import java.util.Arrays;

public class Statistics {

    static public double getMean(double[] nums) {
        double total = 0;
        for (double value : nums) {
            total += value;
        }
        return total / nums.length;
    }

    // sample version
    static public double getVariance(double[] nums) {
        if (nums.length <= 1) {
            return 0;
        }

        double sum = 0;
        double mean = getMean(nums);

        for (double value : nums) {
            sum += Math.pow(value - mean, 2);
        }

        return sum / (nums.length - 1); // notice the -1
    }

    // sample version
    static public double getStdDev(double[] nums) {
        return Math.sqrt(getVariance(nums));
    }

    static public double getMedian(double[] nums) {
        Arrays.sort(nums);

        if (nums.length % 2 == 0) {
            return ((double) nums[nums.length / 2] + (double) nums[nums.length / 2 - 1]) / 2;
        } else {
            return (double) nums[nums.length / 2];
        }
    }
}

Is there something you would add?

Assuming this works well, it only works for double (and float) arrays.

It does not work for int arrays, nor does it work for Container classes, although all it would require to get it to work would be a copy-paste and some minimal changes.

Could Java 8 lambdas help make the code more generic and reduce the need for copy-paste?

Feel free to comment.


texts: Pulling a subset of elements from a Dictionary

texts:
I have a function that returns a set of values from a Dictionary.
I don't currently want to allow it to throw KeyNotFoundException, so I'm filtering the keys out before I try to select the values.

I have a feeling this can be done in a more straightforward fashion, but I'm not sure where to go with it.

// this.resources is a Dictionary<string, Resource>

public IEnumerable<Resource> GetResources(IEnumerable<string> resourceNames)
{
    HashSet<string> hs = new HashSet<string>(resourceNames);

    hs.IntersectWith(this.resources.Keys);

    List<Resource> resources = new List<Resource>();

    foreach(string resourceName in hs)
    {
        resources.Add(this.resources[resourceName]);
    }

    return resources;
}


texts:
I have implemented a Producer-Consumer by Semaphore implementation.
I am looking forward to for your code review comments.
Thanks.
package ProducerConsumer.Semaphore;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreMain {

    public static void main(String args[]){

        List<Integer> arrayList = new LinkedList<>();
        int capacity = 50;

        Semaphore semaphoreProducer = new Semaphore(1);
        Semaphore semaphoreConsumer = new Semaphore(0);

        Producer producer = new Producer(arrayList, capacity, semaphoreProducer, semaphoreConsumer);
        Consumer consumer = new Consumer(arrayList, capacity, semaphoreProducer, semaphoreConsumer);

        Thread t1 = new Thread(producer);
        Thread t2 = new Thread(consumer);

        ExecutorService es = Executors.newFixedThreadPool(2);
        es.submit(t1);
        es.submit(t2);

        es.shutdown();

    }
}

Producer.java
package ProducerConsumer.Semaphore;

import java.util.List;
import java.util.concurrent.Semaphore;

public class Producer implements Runnable {

    List<Integer> linkedList;
    Semaphore semaphoreProducer;
    Semaphore semaphoreConsumer;
    int capacity;

    public Producer(List linkedList, int capacity, Semaphore semaphoreProducer, Semaphore semaphoreConsumer){
        this.linkedList = linkedList;
        this.capacity = capacity;
        this.semaphoreProducer = semaphoreProducer;
        this.semaphoreConsumer = semaphoreConsumer;
    }

    @Override
    public void run() {

        for (int i=0;i<50;i++){

                    try {
                        semaphoreProducer.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    linkedList.add(i);
                    System.out.println("Added" + i);
                    semaphoreConsumer.release();

        }

    }
}

Consumer.java
package ProducerConsumer.Semaphore;

import java.util.List;
import java.util.concurrent.Semaphore;

public class Consumer implements Runnable{

    List<Integer> linkedList;
    Semaphore semaphoreProducer;
    Semaphore semaphoreConsumer;

    public Consumer(List linkedList, int capacity, Semaphore semaphoreProducer, Semaphore semaphoreConsumer){
        this.linkedList = linkedList;
        this.semaphoreProducer = semaphoreProducer;
        this.semaphoreConsumer = semaphoreConsumer;
    }

    @Override
    public void run() {

        while(true){

                    try {
                        semaphoreConsumer.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("removed :" + linkedList.remove(0));
                    semaphoreProducer.release();

        }

    }
}


texts: User needs to type in the password to send an email

texts:
User has three attempts (locks you out for 10 seconds if you fail) to log in to send an email. Afterwards, you need to insert your username and password to send your message to someone of your will.

Any improvements that I can make?

import smtplib
import time

def send_mail() :
    try :
        content = input("Type in your content :")
        mail = smtplib.SMTP('smtp.gmail.com', 587)
        mail.ehlo()
        mail.starttls()

        username = input("Username :")
        password = input("Password :")
        mail.login(username,password)
        receiver = input("Receiver : ")
        mail.sendmail(username, receiver, content)
        mail.close()

    except smtplib.SMTPException :
        print("Error. Mail was not sent.")
    else :
        print("Success. Mail sent.")

if __name__ == '__main__' :
    password = "password123"
    num_of_tries = 3
    input_password = input("Enter password")

    '3 attempts before locking you out for 10 seconds.'
    while password != input_password :
        num_of_tries -= 1
        if num_of_tries == 0 :
            print("Try again in 10 seconds")
            time.sleep(10)
            num_of_tries = 3

        input_password = input(str(num_of_tries) + " Attempts Remaining. Password : ")

    if password == input_password :
        print("Success.")
        send_mail()


texts: Unique compile time (constexpr) type ID without RTTI

texts:
I am making a library where I need to generate a unique ID for a type where the ID must be known at compile time. I first relied on the address of a template function, but it proved itself unreliable both with MSVC and Clang on windows.

Then I came up with the address of a static data member inside a template class.

I want to support most use cases as possible here's what comes to my mind:

Eager optimizations that would merge the definition of static variables or inline functions
DLL and shared libraries
Link time optimizations

My tests were successful, but it wasn't an exotic setup with multiple level dlopen or stuff like that. I'm not an expert with the kind of use case I want to support so it's hard to tell if I can ensure my claims are okay.

My design work by declaring a static data member of type T* inside a template class, then taking its address as the value of the ID.

namespace detail {

/**
 * Template class that hold the declaration of the id.
 *
 * We use the pointer of this id as type id.
 */
template<typename T>
struct type_id_ptr {
    // Having a static data member will ensure (I hope) that it has only one address for the whole program.
    // Furthermore, the static data member having different types will ensure (I hope) it won't get optimized.
    static const T* const id;
};

/**
 * Definition of the id.
 */
template<typename T>
const T* const type_id_ptr<T>::id = nullptr;

} // namespace detail

/**
 * The type of a type id.
 */
using type_id_t = const void*;

/**
 * The function that returns the type id.
 *
 * It uses the pointer to the static data member of a class template to achieve this.
 * Altough the value is not predictible, it's stable (I hope).
 */
template <typename T>
constexpr auto type_id() noexcept -> type_id_t {
    return &detail::type_id_ptr<T>::id;
}

It there any caveats to be aware with this design?

Here's some usage of this and motivation for this code:

constexpr auto id_of_int_type = type_id_t{type_id<int>()};
constexpr auto id_of_float_type = type_id_t{type_id<float>()};

static_assert(id_of_int_type != id_of_float_type);

This can be compiled with -fno-rtti.

Also, it can fully be used at compile time. Here's the equivalent with RTTI:

constexpr auto test = typeid(int); // won't compile

This code won't compile since typeid cannot be used at compile time. Also, disabling RTTI also disables static RTTI.

The code is useful because it can be used in data structure or to be couple with compile time type erasure.

std::map<type_id_t, void*> anything;

// sorry for raw new
anything[type_id<std::string>()] = new std::string{"hello"};

// compile time example
static auto static_int = int{};
static auto static_double = double{};

// type_id as the keys in a compile time map
constexpr auto anything_compiletime = frozen::unordered_map<type_id_t, void*, 2>{
    {type_id<int>(), &static_int},
    {type_id<double>(), &static_double}
};


texts: Show all full/partial search matches in the first worksheet from other worksheets

texts:
Search and display all instances of a full/partial match in the first worksheet from all the other worksheets in the workbook after running a macro to clear formatting of previous search results.

I have data in over 1000 cells in one workbook, spread over 10 worksheets that I am able to search through using a button.

If I use find and replace the data is found within seconds, but using the button it takes a little longer. The idea is that it is much more user friendly and reports the results into one of the worksheets and the next time you click the search button it removes the search results and all formatting.

Can someone please tell me if there is anything I can do to speed it up?

The workbook contains several worksheets with data and each worksheet has different headers. Within the search page, I would like to include the headers at the top of each list of results and then insert a blank row between the search results of each sheet on the search page but I'm not sure how this should be implemented?

Sub Set_Search()
Call Reset1
 '   Object variables
Dim wks As Excel.Worksheet
Dim rCell As Excel.Range
Dim fFirst As String
 '   {i} will act as our counter
Dim i As Long
 '   Use an input box to type in the search criteria
Dim MyVal As String
MyVal = InputBox("Enter the full name of an individual, department, organisation or area that you wish to contact.", "Contact Search", "")
 '   if we don't have anything entered, then exit the procedure
If MyVal = "" Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'       Add a heading to the sheet with the specified search value
With Cells(1, 1)
.Value = "Found '" & MyVal & "' in the following cells:" & vbCrLf & "(click below to view the original data)"
.EntireColumn.AutoFit
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
    With Selection.Font
         .Name = "Arial"
         .FontStyle = "Regular"
         .Size = 10
    End With
i = 2
 '       Begin looping:
 '       We are checking all the Worksheets in the Workbook
For Each wks In ActiveWorkbook.Worksheets
     If wks.Name <> "Search" Then
     '       We are checking all cells, we don't need the SpecialCells method
     '       the Find method is fast enough
        With wks.Range("A:G")
         '           Using the find method is faster:
         '           Here we are checking column "A:G" that only have {myVal} partially
            Set rCell = .Find(MyVal, , , xlPart, xlByColumns, xlNext, False)
         '           If something is found, then we keep going
            If Not rCell Is Nothing Then
             '               Store the first address
                fFirst = rCell.Address
                Do
                 '                   Link to each cell with an occurence of {MyVal}
                    rCell.Hyperlinks.Add Cells(i, 1), "", "'" & wks.Name & "'!" & rCell.Address
                    wks.Range("A" & rCell.Row & ":I" & rCell.Row).Copy Destination:=Cells(i, 2)
                    Set rCell = .FindNext(rCell)
                    i = i + 1 'Increment our counter
                Loop While Not rCell Is Nothing And rCell.Address <> fFirst
            End If
        End With
     End If
Next wks
 '   Explicitly clear memory
Set rCell = Nothing
 '   If no matches were found, let the user know
If i = 2 Then
    MsgBox "No results containing your search term were found." & vbCrLf & "" & vbCrLf & "Your search for '" & MyVal & "' did not match any exising data." & vbCrLf & "" & vbCrLf & "These contact details will be added if you send an email to me.", 64, "Contact Search"
    Cells(1, 1).Value = ""
End If
 '   Reset application settings
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub


texts:
I am trying to create something that is very reusable here so that I can use it in other sites for other pages etc.

This code is for a simple photo gallery,

I took the code from here, but I changed it a bit and would like to add more functionality to it eventually, though.

PhotoGallery.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PhotoGallery.ascx.cs" Inherits="PhotoGallery" %>

Before and After Pictures

                <asp:Repeater ID="Repeater1" runat="server">
                    <ItemTemplate>
                        <img class="thumbnails" src='<%#Eval("ImageUrl") %>' alt='<%#Eval("ImageUrl") %>' />
                    </ItemTemplate>
                </asp:Repeater>

PhotoGallery.ascx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PhotoGallery : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateImages();
        }
    }

    public string FolderPath {get;set;}

    private void PopulateImages()
    {
        List<Image> myImages = new List<Image>();
        DirectoryInfo DI = new DirectoryInfo(Server.MapPath(FolderPath));
        foreach (var file in DI.GetFiles())
        {
            myImages.Add(new Image { ImageUrl = FolderPath + file.Name });
        }
        Repeater1.DataSource = myImages;
        Repeater1.DataBind();
    }
}


texts: Pandoc filter to allow embedding arbitary HTML in latex documents

texts:
I wrote a Pandoc filter that allows me to embed arbitrary HTML snippets in LaTeX documents, which are then printed out as-is when the document is converted to HTML. It is slightly more generic than it needs to be right now, in case I want to embed other types of things in the future.

It can be used like:

\begin{verbatim}
    %%% html
    <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe>
\end{verbatim}

In particular, I think the chain of >>= in convertCode could be improved some how, possibly using Applicatives. runReader basically does nothing except rearrange its arguments and call a thing.

import Data.Char ( isSpace )
import Data.List ( dropWhileEnd )
import Data.Maybe ( fromMaybe )

import Text.Pandoc.JSON ( Block(CodeBlock, RawBlock), Format(Format), toJSONFilter )

main = toJSONFilter convertCodeBlocks

type Reader = String -> Maybe [Block]

convertCodeBlocks :: Block -> [Block]
convertCodeBlocks b = case b of
    (CodeBlock _ code) -> fromMaybe [b] $ convertCode code
    _                  -> [b]

-- Given a string of code, try to convert it into something nicer
convertCode :: String -> Maybe [Block]
convertCode code =
    codeBlockType codeHead >>= codeBlockReader >>= runReader codeTail
  where (codeHead, codeTail) = splitWhen (== '\n') $ strip code

-- Get the reader name from the magic header
codeBlockType :: String -> Maybe String
codeBlockType line = if percent == "%%% "
    then Just $ strip typeName
    else Nothing
  where (percent, typeName) = splitAt 4 $ strip line

-- All the known readers and their name from the magic header
codeBlockReader :: String -> Maybe Reader
codeBlockReader "html" = Just rawHtml
codeBlockReader _      = Nothing

-- Make a raw HTML block from some string
rawHtml html = Just [RawBlock (Format "html") html]

-- A mostly useless function, only here because I can't make Applicatives work
runReader :: String -> Reader -> Maybe [Block]
runReader code reader = reader code

-- Strip whitespace from the start and end of a string
strip = dropWhileEnd isSpace . dropWhile isSpace

-- Split an array at a predicate, returning (before, after)
splitWhen :: (a -> Bool) -> [a] -> ([a], [a])
splitWhen pred [] = ([], [])
splitWhen pred (x:xs) = if pred x
    then ([], xs)
    else let (before, after) = splitWhen pred xs in (x:before, after)

I initially implemented something for this as a modification to Pandoc itself (See this PR on Github), but the maintainer suggested a filter instead.


texts: Encoding variable-length quanties for MIDI

texts:
I was reading about the MIDI spec and I challenged myself to implement a function to convert an int32 to a variable length quantity uint32.

I didn't look it up or anything so there might be a way more efficient or tricky way to get the same result, but as far as doing what I set out to accomplish the following code works.

I'm interested to know if anyone can significantly simplify or improve the algorithm that does the conversion, public static uint CalculateEncodedQuantity(int q).

I included the whole thing in case anyone wanted to paste it in to VS.

Specification:

Tests:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace VariableLengthRepresentation.Test
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreEqual(0u, new VariableLengthQuantity(0).EncodedQuantity);
            Assert.AreEqual(0x40u, new VariableLengthQuantity(0x40).EncodedQuantity);
            Assert.AreEqual(0x7fu, new VariableLengthQuantity(0x7f).EncodedQuantity);

            //  input:           1000 0000
            // output: 1000 0001 0000 0000
            Assert.AreEqual(0x8100u, new VariableLengthQuantity(0x80).EncodedQuantity);

            //  input: 0010 0000 0000 0000
            // output: 1100 0000 0000 0000
            Assert.AreEqual(0xc000u, new VariableLengthQuantity(0x2000).EncodedQuantity);

            Assert.AreEqual(0xff7fu, new VariableLengthQuantity(0x3fff).EncodedQuantity);
            Assert.AreEqual(0x818000u, new VariableLengthQuantity(0x4000).EncodedQuantity);
            Assert.AreEqual(0xc08000u, new VariableLengthQuantity(0x100000).EncodedQuantity);
            Assert.AreEqual(0xffff7fu, new VariableLengthQuantity(0x1fffff).EncodedQuantity);
            Assert.AreEqual(0x81808000u, new VariableLengthQuantity(0x200000).EncodedQuantity);
            Assert.AreEqual(0xc0808000u, new VariableLengthQuantity(0x8000000).EncodedQuantity);
            Assert.AreEqual(0xffffff7fu, new VariableLengthQuantity(0xfffffff).EncodedQuantity);
        }
    }
}

Implementation:

using System;

namespace VariableLengthRepresentation
{
    public struct VariableLengthQuantity
    {
        public VariableLengthQuantity(int quantity)
        {
            Quantity = quantity;
            EncodedQuantity = CalculateEncodedQuantity(quantity);
        }

        public static uint CalculateEncodedQuantity(int q)
        {
            if (q > 0x0fffffff)
            {
                throw new Exception("Variable length quantity cannot exceed 0x0fffffff.");
            }

            uint n = (uint)q;

            if (n < 128)
                return n;

            var result = new byte[4];

            for (int i = 3; i >= 0; i--)
            {
                result[i] = (byte)(n & 0x7f);

                if(i < 3)
                    result[i] |= 0x80;

                n >>= 7;

                if (n < 1)
                    break;
            }

            if(BitConverter.IsLittleEndian)
                Array.Reverse(result);

            return BitConverter.ToUInt32(result, 0);
        }

        public int Quantity { get; private set; }
        public uint EncodedQuantity { get; private set; }
    }
}


texts:
So I have a grid with data and above that grid 2 comboboxes, the grid will be filled with data based on the selected values from the comboboxes. This works but can you do it way easier like I did?

if (_InitialDataGridPersonList != null)
{
    if (GetSelectedComboBoxPersonStateText() == "-" && GetSelectedComboBoxPersonLanguageText() != "-")
    {
        var dataGridPersonQuery = _InitialDataGridPersonList
            .Where(w => w.Language.Equals(GetSelectedComboBoxPersonLanguageText()));

        foreach (var person in dataGridPersonQuery)
        {
            _DataGridPersonList.Add(person);
        }
    }
    else if (GetSelectedComboBoxPersonStateText() != "-" && GetSelectedComboBoxPersonLanguageText() == "-")
    {
        var dataGridPersonQuery = _InitialDataGridPersonList
            .Where(w => (w.PersonState.Equals(GetSelectedComboBoxPersonStateText())));

        foreach (var person in dataGridPersonQuery)
        {
            _DataGridPersonList.Add(person);
        }
    }
    else if (GetSelectedComboBoxPersonStateText() == "-" && GetSelectedComboBoxPersonLanguageText() == "-")
    {
        foreach (var person in _InitialDataGridPersonList)
        {
            _DataGridPersonList.Add(person);
        }
    }
    else if (GetSelectedComboBoxPersonStateText() != "-" && GetSelectedComboBoxPersonLanguageText() != "-")
    {
        var dataGridPersonQuery = _InitialDataGridPersonList
            .Where(w => (w.PersonState.Equals(GetSelectedComboBoxPersonStateText()))
                    && (w.Language.Equals(GetSelectedComboBoxPersonLanguageText())));

        foreach (var person in dataGridPersonQuery)
        {
            _DataGridPersonList.Add(person);
        }
    }

Imagine there are like 10 comboboxes. So what I'm asking is, if there is a easier way with less code?

PS. I'm using MVVM so no code behind.


texts:
I have a dataframe with several columns. One of them is an user ID column, in this column, I have several ids that can be repeated several times.

What I want to do is remove the first ID, for instance:

1,2,3,4,3,4,2,1,3,4,6,7,7

I would like to have an output like this:

3,4,2,1,3,4,7

Where is what I have done:

#find first duplicated of the each user
dup <- duplicated(results$user)

#create other data frame, every time vector is TRUE add the row to new dataframe
results1 <- NULL

for(i in 1:length(results$user)){
    if (dup[i] == TRUE) {
        rbind(results1, results[i,]) -> results1
    }
 }

Since I'm more used to think in Python, I have a feeling this is a very ugly solution for R. I would like to have some feedback, as well as some pointers on how to improve this piece of code.


texts: Bare minimum neural network, random weight update etc

texts:
I'm trying to understand that how a simple neural network works. The program below (that I wrote to test my understanding) aims to train a network that will eventually be able to distinguish whether given elements of input are bigger than 0.5 or not.

Its input size is 4 and output size is 2. It generates its own dataset contains 100 amount of bigger than 0.5 and 100 amount of smaller than 0.5 lists.

It generates a random hidden layer/neuron (hidden_current) at first and calculates the total error of the dataset. Then, in an endless loop it regenerates a brand new random hidden layer/neuron (hidden_new) and calculates the total error with this new hidden layer/neuron. If new error is smaller than previous one then that means this hidden layer/neuron is better. So it updates the current one.

But this network is unable reduce the error below 0.60 even after 200,000 epochs. Obviously there is something wrong with my code but I couldn't understand what is the issue...

from itertools import repeat
import random
import numpy as np
import sys
import time

INPUT_SIZE = 4
OUTPUT_SIZE = 2
PRECISION = 1

def generate_list_bigger():
    generated_list = []
    for i in repeat(None, INPUT_SIZE):
        generated_list.append(round(random.uniform(0.6, 1.0), PRECISION))
    return generated_list

def generate_list_smaller():
    generated_list = []
    for i in repeat(None, INPUT_SIZE):
        generated_list.append(round(random.uniform(0.0, 0.4), PRECISION))
    return generated_list

dataset = []
for i in repeat(None, 100):
    dataset.append([ generate_list_bigger(), [1.0, 0.0] ])
for i in repeat(None, 100):
    dataset.append([ generate_list_smaller(), [0.0, 1.0] ])

error_current = 0
hidden_current = np.around(np.random.rand(INPUT_SIZE,OUTPUT_SIZE), decimals=1)
for data in dataset:
    output = np.dot( np.array(data[0]), hidden_current) / 2
    error_current += np.linalg.norm(output-np.array(data[1]))
error_current = error_current / len(dataset)

counter = 0
while True:
    counter += 1
    print str(counter) + "\r",
    sys.stdout.flush()

    error_new = 0
    hidden_new = np.around(np.random.rand(INPUT_SIZE,OUTPUT_SIZE), decimals=1)
    for data in dataset:
        output = np.dot( np.array(data[0]), hidden_new) / 2
        error_new += np.linalg.norm(output-np.array(data[1]))
    error_new = error_new / len(dataset)

    if (error_new - error_current) < 0:
        hidden_current = hidden_new
        error_current = error_new
        print error_current


texts:
I needed several classes with methods performing network requests which should be executed asynchronously (with callbacks). To get rid of repetition, I added a mixin and a helper class:

module Asyncable
  def async(&callback)
    AsyncHelper.new(self, &callback)
  end
end

class AsyncHelper
  attr_reader :base, :callback, :errback

  def initialize(base, &callback)
    @base = base
    @callback = callback
    @errback = nil
  end

  def onerror!(&errback)
    @errback = errback
    self
  end

  def method_missing(sym, *args)
    method = @base.method(sym)
    Thread.new do
      begin
        res = method.call(*args)
      rescue => e
        if @errback.nil?
          raise
        else
          @errback.call(e)
        end
      else
        unless @callback.nil?
          @callback.call(res)
        end
        res
      end
    end
  end
end

Now all methods in classes can be implemented as synchronous, and then used in these ways:

# assuming base is an instance of a class including Asyncable
# sequential execution of a method:
value = base.method(params)
f(value) # process the value

# same method executed asynchronously, without callback:
thread = base.async.method(params)
# ... other operations while the method is executed in the background ...
value = thread.value # blocks until completed and raises errors, if any
f(value)

# same method executed asynchronously, with callback:
thread = base.async { |value| f(value) }.method(params)
# ... other operations while the method is executed in the background ...
thread.join # blocks until completed and raises errors, if any

# using errback to handle errors:
thread = base.async { |value| f(value) }.onerror! { |e| puts e }.method(params)
# ... other operations while the method is executed in the background ...
thread.join # only blocks, no errors raised here

This works perfectly for me, but I am a bit concerned by the fact that such an approach isn't widely used (I haven't seen it anywhere), while the use-case for it may be common enough. Is it a good way to approach the task, and how can be improved?


texts:
I was practicing divide-two-integers question from leetcode

Question: Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Question Link: https://leetcode.com/problems/divide-two-integers/

For this I wrote the following algorithm but clearly it isn't optimized with my time complexity coming out to be about  8248 ms. Can someone please help me in optimizing the code?

 /**
 * @param {number} dividend
 * @param {number} divisor
 * @return {number}
 */
/**
     * @param {number} dividend
     * @param {number} divisor
     * @return {number}
     */
var divide = function(dividend, divisor) {
   let negativeFlag = false
   let quiotentHolder = 0
   if (divisor === 0 || dividend === 0) return 0;
   if (dividend === -2147483648 && divisor === -1) return 2147483647;
  else if (dividend < 0 && divisor < 0) {
      dividend = -dividend
      divisor = -divisor
  } else if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
        negativeFlag = true
        divisor < 0 ? divisor = -divisor :dividend = -dividend
    }
    while (divisor <= dividend) {
        dividend = dividend - divisor
        quiotentHolder += 1
    }
    if (negativeFlag) return -quiotentHolder
    else return quiotentHolder
}


texts: Hiding and repositioning some elements for some WordPress posts

texts:
I have to gather a few posts (a Wordpress site) and I need to hide some elements and move some others. There are 2 simple ways to do this, which one of these is better if there is a better one and why?

/* 1 */
var $postCollection = $("#post-3993, #post-4278, #post-4272, #post-4270, #post-4275, #post-3989, #post-4280, #post-4274, #post-4271, #post-4276, #post-3929, #post-4285, #post-4282, #post-4279, #post-4284");
$postCollection.find( $(".flexslider-last-photo")).css("display", "none");
$postCollection.find( $("#carousel-constructora .flex-next") ).css("top", "92%");
$postCollection.find( $("#carousel-constructora .flex-prev") ).css("top", "92%");

/* 2 */
function hidePostElements(posts){
  $(posts).find( $(".flexslider-last-photo")).css("display", "none");
  $(posts).find( $("#carousel-constructora .flex-next") ).css("top", "92%");
  $(posts).find( $("#carousel-constructora .flex-prev") ).css("top", "92%");
}

hidePostElements( $("#post-3993, #post-4278, #post-4272, #post-4270, #post-4275, #post-3989, #post-4280, #post-4274, #post-4271, #post-4276, #post-3929, #post-4285, #post-4282, #post-4279, #post-4284") );


texts: Mapping uint to value within min/max set

texts:
I have a method that transforms any input uint into a [min,max] set. I am looking for improvements on the function, specifically to get rid of the input == uint.MaxValue case.

public static uint NumberInRange(uint input, uint min, uint max)
{
    decimal divider = uint.MaxValue / (decimal)max;
    if (input == uint.MaxValue)
        return (uint)max;

    var i = (uint)(Math.Floor(input / divider) + min);
    return i;
}

Let me know if you see any ways to improve this function, or if you think that there is any subtle bug within it.

I am basically just looking into a way to map a bigger set [0,uint.MaxValue] into a smaller set [min,map].

Let's say the inputs are:

NumberInRange(0, 10, 100) - I should get 10

NumberInRange(uint.MaxValue, 10, 100) - I should get 100

For any number in between, I want them to be mapped "equally" between members of the set.

Let's say I put in a number that gives value between 0 and 1:

for (input / (uint.MaxValue/max)))

All 0.xxxx values should map to min (instead of getting min for numbers between 0 and 0.5, and min+1 for 0.5-1.5, etc) in order to see equal distribution in mapping (hence Math.Floor).

I think the function does it's job pretty well.  I was just looking to see if I can eliminate that if (input == uint.MaxValue) case since it's a weird edge case (for which result is max+1). This is also one thing that can be nitpicked from math standpoint - all members of the set will get mapped from n elements, while the last member will get mapped from n+1 elements (because of this special if case).


texts:
I have a process where I take several .lst flatfiles, apply filters and reformat the data, then append the results to a single file. I loop through every file in a subdirectory, applying the reformatting, then I append it to a file called Myoutput. I also strip out some rows of the dataframe and write this to a different .lst called Myoutput2.

My code:

fileNames = next(os.walk('subdirectory'))[2]

for filename in fileNames:
    headers = ['My', 'list', 'of', 'headers']
    columns = [0,2,3,4]
    filePath = r'subdirectory\\' + filename

    df = pd.read_csv(filePath, sep='\t', names=headers, usecols=columns)

    #My reformatting code...

    with open('output/Myoutput_{}_{}_{}.lst'.format(year,month,day), 'a') as f:
        df.to_csv(f, header=False, index=False, sep='\t')

    df = df.loc[df['Type']!='UNKNOWN'] #removes UNKNOWN types for paragon

    paragonCount += len(df)
    with open('output/Myoutput2_{}_{}_{}.lst'.format(year,month,day), 'a') as f:
        df.to_csv(f, header=False, index=False, sep='\t')

    os.remove('download/'+filename)

This process has worked so far but I now have to change it so that the two output files are ordered by a datetime field in the files. All the datetime values in the field are on the same day. The input files are not chunked by datetime, so it wouldn't be enough to just change the order I load the files.

I appended this code to the end:

df = pd.read_csv('output/Myoutput_{}_{}_{}.lst'.format(year,month,day),header=None,sep='\t')
df = df.sort_values(by=1)

df.to_csv('output/Myoutput_{}_{}_{}_ordered.lst'.format(year,month,day),index=None,headers=None)

df = pd.read_csv('output/Myoutput2_{}_{}_{}.lst'.format(year,month,day),header=None,sep='\t')
df = df.sort_values(by=1)

df.to_csv('output/Myoutput2_{}_{}_{}_ordered.lst'.format(year,month,day),index=None,headers=None)

The output files tend to be around 1.5GB, so this doubles the runtime of my script, and it feels inefficient re-loading the data into memory. Is there any way to speed this up, perhaps have the loop appending the results based on their datetime field instead of on the end of the file?


texts:
Given graph/network of nodes without any loops/circuits.
I'm trying to find the center: the node from which I can reach all other nodes the fastest.
Imagine if I want to spread the word about something and the information traveling from one node to the next takes 1.
My solution removes nodes from the graph that have only one connection.
To keep track of the amount of connections a node has I use a Counter.
This process repeats till there are only nodes with one connection left.
These nodes can be seen as "center" nodes of the graph.
from collections import Counter

def get_center(graph):
    c = Counter()

    for v in graph.values():
        c.update(v)

    while c.most_common(1)[0][1] > 1:
        for k, v in list(c.items()):
            if v == 1:
                tmp = graph[k][0]
                graph.pop(k)
                c.pop(k)
                c[tmp] -= 1
                graph[tmp].remove(k)

    return list(c.keys())

if __name__ == '__main__':
    graph = {'a': ['b'],
             'b': ['a', 'c'],
             'c': ['b', 'd', 'e'],
             'd': ['c'],
             'e': ['c', 'f'],
             'f': ['e']}
    print(get_center(graph))

Is there a more efficient way to tackle this problem? Either in my implementation or a completely different approach...
Update
to clarify what the above code actually tries to do:

In the blue example we choose node b as center of start spreading the word and need 3 steps till all nodes are aware of the message. In the yellow example we choose node c as center of start spreading the word and need only 2 steps till all nodes are informed. The algorithm should find the node that minimises the steps needed to inform the whole network. The graphs fed to the algorithm are undirected and have no disconnected parts.


texts: Best way to pass a 2d array to functions which size is unknown at compile time in pure C

texts:
I've been wondering for some time what the best way to pass a 2d array to functions is. I know that arrays, passed to functions, decay into pointers, so int arr[25] would become int *arr inside a function. The problem is with 2d arrays, int arr[5][5] would not become int **arr. Instead I've been taught to pass it like this: int (*arr)[5]. The problem with that is that the final square brackets need to have a size parameter inside and it needs to be known at compile time.

I've looked around and found this answer which, I believe, has the best solution. The idea is to pass the 2 dimensions separately and the location of the data. So, the function's signature would be like this:

void print(void *arr, size_t rows, size_t cols);

Then, we create a temporary array, which we can use conventionally, like this:

int (*temp)[cols] = (int (*)[cols]) arr;

I wrote some code to test this and it works.

#include <stdio.h>

void fill(void * arr, size_t rows, size_t cols, int val);
void print(void * arr, size_t rows, size_t cols);

int main(void) {
  size_t iArr = 5, jArr = 3;
  int arr[iArr][jArr];
  fill(arr, iArr, jArr, 0x45);
  print(arr, iArr, jArr);
  return 0;
}

void fill(void * arr, size_t rows, size_t cols, int val)
{
  int (*temp)[cols] = (int (*)[cols])arr;
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      temp[i][j] = val;
    }
  }
  arr = temp;
}

void print(void * arr, size_t rows, size_t cols)
{
  int (*temp)[cols] = (int (*)[cols])arr;
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      printf("%3d ", temp[i][j]);
    }
    putchar('\n');
  }
}

This can also be tested here. I'm curious whether this will work always without errors. I tested it with all kinds of sizes and, again, no problem there. Can this be improved further? Could there be any edge cases where this breaks (checks for valid arguments or making sure the size passed doesn't exceed the stack size are omitted here, as that's not the point of this question).


texts: Backend application to bookmark GitHub repository

texts:
The backend part has the following purposes.

An endpoint that takes a search term and returns a list of repositories.
An endpoint that allows bookmarking a repository by its id.
An endpoint to get all bookmarked repositories
An endpoint to remove a bookmark.

I have written the code for the application using NodeJS and Express. The application is working well. I would like to have a code review for code quality and suggestions for improvements.

const express = require('express');
const timeout = require('express-timeout-handler');
const cors = require('cors');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());

let options = {
    timeout: 3000,
    onTimeout: function(req, res) {
      res.status(503).send('Service unavailable. Please retry.');
    },
    onDelayedResponse: function(req, method, args, requestTime) {
      console.log(`Attempted to call ${method} after timeout`);
    },
    disable: ['write', 'setHeaders', 'send', 'json', 'end']
  };

app.use(timeout.handler(options));

app.listen(port, () => console.log(`Server Listening on port ${port}`));

const listrepositoriesRoutes = require('./routes/repositories.route');
const bookmarksRoutes = require('./routes/bookmarks.route');
const authentication = require('./basic_auth/auth');
app.use('/userauth', authentication);
app.use('/listallrepos', listrepositoriesRoutes);
app.use('/bookmarks', bookmarksRoutes);


texts: What is better to use for mapping value to Map of functions: tail recursion or foreach?

texts:
I want to map functions from my functions library (Map called as chain) to input string str. Also that functions (Twitter.removeRT, ...) are regex which replace substrings in input str. I think it is better to save that regex-functions in Map like in my example.

So, the code:

Tail recursion variant

  def filterTwitter2 (str: String): String = {

    @scala.annotation.tailrec
    def recFilter(str: String, chain: Map[String, (String) => String]): String = {
      chain.headOption match {
        case Some(v) =>
          val filteredString = v._2(str)
          recFilter(filteredString, chain.tail)
        case None => str
      }
    }

    val chain = Map[String,(String) => String](
      "f1"-> Twitter.removeRT,
      "f2"-> Twitter.removeNickName,
      "f3"-> Twitter.removeURL,
      "f6"-> Emoticons.removePunctRepetitions,
      "f7"-> Emoticons.removeHorizontalEmoticons,
      "f9"-> Emoticons.normalizeEmoticons,
      "f10"-> Beautify.removeCharRepetitions,
      "f12"-> Beautify.removeNSpaces
    )

    recFilter(str, chain)
  }

foreach variant

  def filterTwitter (str: String): String = {
    var tmp = str
    val chain = Map[String,(String) => String](
      "f1"-> Twitter.removeRT,
      "f2"-> Twitter.removeNickName,
      "f3"-> Twitter.removeURL,
      "f6"-> Emoticons.removePunctRepetitions,
      "f7"-> Emoticons.removeHorizontalEmoticons,
      "f9"-> Emoticons.normalizeEmoticons,
      "f10"-> Beautify.removeCharRepetitions,
      "f12"-> Beautify.removeNSpaces
    )
    chain.foreach {
      case (name, func) => tmp = func(tmp)
    }
    tmp
  }

So, the questions:

Is it normal to save functions in map? What can be better for it?
What better: tail recursion variant or variant with foreach?
Maybe there is any better solution for that problem?


texts: Implementing a queue using a linked-list

texts:
In my intro CS class we're reviewing data structures. I'm currently working on implementing a queue using a linked list (FIFO) in C. I'd appreciate a review of the implementation as well as of my understanding of how a queue should work

// This program is implementation of queue data structure
// via linked list (FIFO)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
    int number;
    struct node *next;
} node;

node *enqueue(int element, node *temp);
node *dequeue(int n, node *temp);
void display(node *temp);
void destroy_queue(node *temp);

int main()
{
    node *queue = NULL;

    // add some elements to queue
    for (int i = 0; i < 5; i++)
    {
        queue = enqueue((i + 1), queue);
    }

    // display queue
    display(queue);

    // dequeue 2 elements from queue
    printf("Removing two elements from queue...\n");
    queue = dequeue(2, queue);

    //display queue
    display(queue);

    // free memory
    destroy_queue(queue);

}

node *enqueue(int element, node *temp)
{
    node *newElement = malloc(sizeof(node));
    node *head = temp;
    if (newElement == NULL)
    {
        fprintf(stderr, "No memory for the new queue element");
        return temp;
    }

    newElement->number = element;
    newElement->next = NULL;

    if (head == NULL)
    {
        return newElement;
    }
    else
    {
        while ((temp->next) != NULL)
        {
            temp = temp->next;
        }
        temp->next = newElement;
    }
    return head;
}

node *dequeue(int n, node *temp)
{
    node *aux;
    for (int i = 0; i < n; i++)
    {
        if (!temp)
        {
            fprintf(stderr,"No elements to remove!");
            return temp;
        }
        aux = temp->next;
        free(temp);
        temp = aux;
    }
    return temp;
}

void display(node *temp)
{
    while (temp)
    {
        printf("Elements in queue are: %i\n", temp->number);
        temp = temp->next;
    }
}

void destroy_queue(node *temp)
{
    node *aux = temp;
    while (temp)
    {
        aux = temp->next;
        free(temp);
        temp = aux;
    }
}


texts: Creating idiomatic and efficient method to stream large JSON file

texts:
The purpose of the code is to efficiently stream JSON items from a large file.
I am wondering if this is efficient and decently idiomatic. Not sure how I could eliminate the while loop either.

module Seq =
    let inline tryMove (e:IEnumerator<'T>) =
        try
            let moved = e.MoveNext()
            if moved then
                Some <| Choice1Of2 e.Current
            else
                e.Dispose()
                None
        with ex ->
            Some <| Choice2Of2 ex
    let catch (items:_ seq) =
        use e = items.GetEnumerator()
        e
        |> Seq.unfold(
            tryMove
            >> function
            | Some (Choice1Of2 item) -> Some(Choice1Of2 item,e)
            | Some (Choice2Of2 ex) -> Some(Choice2Of2 ex, e)
            | None -> None
        )

module SuperSerial =
    let deserialize<'T>(x):'T =
        JsonConvert.DeserializeObject<'T>(x)

    let streamJson<'T> sr =
        let serializer = JsonSerializer()
        seq{
            use r = new JsonTextReader(sr)
            while r.Read() do
                if r.TokenType = JsonToken.StartObject then
                    yield serializer.Deserialize<'T>(r)
        }
    let streamString<'T> x =
        seq{
            use s = new StringReader(x)
            yield! streamJson(s)
        }
    let streamJsonFile<'T> target =
        seq{
            use s = File.Open(target,FileMode.Open)
            use sr = new StreamReader(s)
            yield! streamJson(sr)
        }


texts:
Please help me improve my code. Note that it runs just fine. Especially with the way I use SFML, I need lots of guidance since I've just started learning how to use this library. I'm still learning C++ as well.

main.cpp

#include <SFML/Graphics.hpp>
#include "counter.hpp"

std::string day(int num) { return (num!=1)? "s":""; } //the 's' in the word day(s) in the text displayed

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,300), "New Year Counter");
    window.setVerticalSyncEnabled(true);
    window.setPosition(sf::Vector2i(sf::VideoMode::getDesktopMode().width/2 -400, sf::VideoMode::getDesktopMode().height/2 -150)); //put window in the middle of the screen

    sf::Font font;
    font.loadFromFile("Beyond Wonderland.ttf");
    sf::Text text;
    text.setFont(font);
    text.setCharacterSize(80);
    text.setFillColor(sf::Color::White);
    text.move(25, 10);

    sf::Text counter = text; //initialize with the same attributes as text so that I won't have to write everything again.

    while(window.isOpen())
    {
        sf::Event event;
        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
                window.close();
        }

        TimeToNewYear year;
        window.clear(sf::Color::Black);
        text.setString("Until New Year "+year.get_newYear()+"\n"+year.get_daysLeft()+" day"+day(std::stoi(year.get_daysLeft()))+" left\n\t\tand");
        window.draw(text);
        counter.setString(year.get_counter());
        counter.setCharacterSize(120);
        counter.setPosition(360, 140);
        window.draw(counter);
        window.display();
    }
}

counter.hpp

#ifndef COUNTER_HPP
#define COUNTER_HPP
#include <string>
#include <ctime>

class TimeToNewYear
{
private:
    time_t m_nowTime = time(0);
    time_t m_tmny; //for mktime (time new year)
    tm *m_locTime = localtime(&m_nowTime);
    tm m_newYear {};
    int m_timeLeft;
    int m_daysLeft;
    std::string m_counter;

    void addNum(int num) //to display single digits with a 0 ex: 03
    {
        if(num<=9)
            m_counter += "0";
        m_counter += std::to_string(num);
    }
public:
    TimeToNewYear()
    {
        m_newYear.tm_mday =1;
        m_newYear.tm_year = 1+ m_locTime->tm_year; //set m_newYear
        m_tmny = mktime(&m_newYear);
        m_timeLeft = difftime(m_tmny, m_nowTime);
        //calculate days left
        m_daysLeft = m_timeLeft/(24*3600);
        m_timeLeft %= 24*3600;
    }

    std::string get_daysLeft() const { return std::to_string(m_daysLeft); }
    std::string get_newYear()  const { return std::to_string(m_newYear.tm_year +1900); } //tm_year is the years from 1900
    std::string get_counter()
    {
        addNum(m_timeLeft/3600);
        m_counter += ":";
        m_timeLeft %= 3600;
        addNum(m_timeLeft/60);
        m_counter += ":";
        addNum(m_timeLeft%60);
        return m_counter;
    }
};

#endif


texts:
Inspired by Don Stewart's article on Scripting with Haskell I tried a rewrite of a shell-script I did the other day. I was really astonished how easily it worked but as a whole it is about double the size of my shell script and some things feel a bit "clumsy".

myReadTile and getCurlIP have IO-return type, which seems a bit "unhaskellish"
extractIp and extractFromFile seem a bit unelegant especially the maybe parts and the trivial case "" to prevent last from throwing an error.

To run my code the packages curl network-info had to be installed - the rest was already there (Debian haskell-platform 2012.2.0.0, ghc-7.4.1)

What my code does:
I want to log the IP-address my provider gives me - and when it changes; as I have a dynamic IP.  With this information I can ssh from other devices to my home PC, and I know how long the periods are in which my IP doesn't change.

Code

import System.IO         (readFile, appendFile)
import System.Exit       (exitSuccess)
import System.Directory  (doesFileExist, getHomeDirectory)
import Data.Maybe        (listToMaybe, fromMaybe)
import Data.Time         (getZonedTime)
import Network.BSD       (getHostName)
import Network.Curl      (curlGetString, URLString, CurlOption(CurlTimeout))
import Network.Curl.Code (CurlCode(CurlOK))
import Network.Info      (getNetworkInterfaces, NetworkInterface, name, ipv4)

localFilePath :: FilePath
localFilePath = "/Dropbox/iplog.log"

dyndns :: URLString
dyndns = "http://checkip.dyndns.org"

main :: IO ()
main = do
    home <- getHomeDirectory
    let iplogFilePath = home ++ localFilePath
    iplogS <- myReadFile iplogFilePath
    curlS <- getCurlIP dyndns
    let oldIP     = extractFromFile iplogS
        currentIP = extractIp curlS
    if oldIP /= currentIP
      then do
        date <- fmap show getZonedTime
        host <- getHostName
        localIP <- fmap getLocalIP getNetworkInterfaces
        let content = unwords [currentIP, date, host, localIP, "\n"]
        appendFile iplogFilePath content
      else
        exitSuccess

extractFromFile :: String -> String
extractFromFile "" = ""
extractFromFile s = (fromMaybe [] . listToMaybe . words . last . lines) s

extractIp :: String -> String
extractIp "" = ""
extractIp s = (takeWhile (/='<') . last . words) s

myReadFile :: FilePath -> IO String
myReadFile fp = do
    iplogExists <- doesFileExist fp
    if iplogExists
      then
          readFile fp
      else do
          print "File does not exist - and will be created"
          print ("at: ~" ++ localFilePath)
          return ""

getCurlIP :: URLString -> IO String
getCurlIP url = do
    (curlState, curlString) <- curlGetString url [CurlTimeout 60]
    if curlState == CurlOK
      then
          return curlString
      else do
          print "No external IP found"
          return "0.0.0.0"

getLocalIP :: [NetworkInterface] -> String
getLocalIP = show . ipv4 . head . filter (\x -> name x == "eth0")


texts: Find intersection of two arrays without duplicates

texts:
A = [9, 1, 4, 2, 5] k unique integers
  B = [3, 1, 8, 7, 6, 5] n unique integers
  Intersection => [1, 5]

Find an algorithm that uses \$O(1)\$ space (the space used by the return variable is not considered) and runs as fast as possible to find the intersection of the arrays.

private static List<Integer> getIntersectionO1Space(List<Integer> a, List<Integer> b)
{

    List<Integer> intersection = new ArrayList<Integer>();
    mergeSort(a); //Time O(k log k), space O(1)

    for (Integer n : b) //O(n log k)
    {
        int r = Collections.binarySearch(a, n); //O(log k)
        if (r > -1)
            intersection.add(n);
    }
    return intersection;
}

So the total time complexity is \$O(\max(k,n) \log k)\$.

But my solution doesn't utilize the property that "no duplicate elements in the array". I wonder whether there is an algorithm that uses the property and runs faster.


texts: This piece of ABAP code should run through multiple tables and run a COUNT in all of them.

texts:
The code runs through multiple tables to perform a count for a given ID. the ID is given by the user and then the program would look through all of the tables to check how many records each table has, that also has that ID. This is then returned to the user in an ALV with the table ID, the table Name and the number of records.

The program is run an pretty large sized tables and takes about 4 minutes to finish. Since I am fairly new with ABAP and OpenSQL I was wondering how this query could be improved to boost performance. I tried first checking if the ID exists in the table with SELECT SINGLE, and if it exists launch the count but that only made it slower with about a minute.

LOOP AT lt_where_used_data_of_coll ASSIGNING <fs_curr_tab>.

  SELECT ddtext AS table_description
  FROM dd02t
  INTO <fs_curr_tab>-table_description
  WHERE tabname = <fs_curr_tab>-table_id AND ddlanguage = 'EN'.
  ENDSELECT.

  lv_curr_table_name = <fs_curr_tab>-table_id.

        SELECT COUNT(*) AS nr_of_records
        FROM (lv_curr_table_name)
        INTO <fs_curr_tab>-nr_of_records
        WHERE id = p_c_id.
ENDLOOP.

The internal table in the program that is being filled already has the ID's of the tables to search through. The first SELECT inside the loop gets the name of the table corresponding with the ID. The second SELECT statement goes through all those tables and counts the number of records that contain the ID given by the user.

How can this statement be improved to run faster?


texts: Port Availability Scanner, written in Java (9)

texts:
For purpose of practice and experience, I was working on a "Port Availability Scanner" written in Java. So far it's working but it's really slow. Especially on relatively large quantities of ports (1000+).

It's quite faster scanning localhost then my external IP (If it actually scans externally correctly).

As an additional note for if it really matters:
I am using Java 9.

Code:

package test;

import java.io.IOException;
import java.net.Socket;
import java.util.Arrays;

public class Test {

    private static final Test instance = new Test("157.97.56.42", 80, 443, 21, 22, 25, 8080);
    private static String ip;
    private int[] ports = new int[1_000_000];

    private Test(String ip, int start, int end) {
        Test.ip = ip;

        ports: {
            int c = 0;

            for (int i = start; i < end; i++) {
                ports[c++] = i;
            }

            ports = Arrays.copyOfRange(ports, 0, c + 1);
        }
    }

    private Test(String ip, int... ports) {
        Test.ip = ip;
        this.ports = ports;
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(instance::check);
        thread.start();
        long end = System.currentTimeMillis();

        System.out.println("Took: " + (end - start) + "ms.");
    }

    public void check() {
        if(ports.length > 1) {
            for (int port : ports) {
                System.out.println("Available " + port + ": " + Test.isAvailable(port));
            }
        } else if(ports.length == 1) {
            System.out.println("Available " + ports[0] + ": " + Test.isAvailable(ports[0]));
        } else {
            throw new IllegalStateException();
        }
    }

    private static boolean isAvailable(int port) {
        Socket socket = null;

        try {
            socket = new Socket(ip, port);
            return false;
        } catch (IOException e) {
            return true;
        } finally {
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException ignored) { }
            }
        }
    }
}

Please can you review my code, especially performance-wise?

Edit:
Would it be possible by using NIO or any other form of MultiThreading the sake of speed?


texts:
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

We should return its max depth, which is 3.

Note:

The depth of the tree is at most 1000.
The total number of nodes is at most 5000.

Here is my code, and also 1 test as an example
Please comment about space and time complexity, I also made a recursive answer but I tend to think about BFS in an iterative way while using queue, and DFS in recursive way, although you can use a stack for it as well.
so I a real interview I would probably go with BFS with a queue.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace TreeQuestions
{
    // Definition for a Node.
    public class Node
    {
        public int val;
        public IList<Node> children;

        public Node()
        {
        }

        public Node(int _val, IList<Node> _children)
        {
            val = _val;
            children = _children;
        }
    }

    /// <summary>
    /// https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
    /// </summary>
    [TestClass]
    public class MaximumDepthOfN_aryTree
    {
        public int MaxDepth(Node root)
        {

            if (root == null)
            {
                return 0;
            }

            int maxDepth = 0;
            Queue<Node> queue = new Queue<Node>();
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                maxDepth++;
                var queueSize = queue.Count;
                for (int i = 0; i < queueSize; i++)
                {

                    var current = queue.Dequeue();
                    if (current.children != null)
                    {
                        foreach (var child in current.children)
                        {
                            queue.Enqueue(child);
                        }
                    }
                }
            }

            return maxDepth;
        }

        [TestMethod]
        public void MaximumDepthOfN_aryTreeTest()
        {
            List<Node> node3 = new List<Node>();
            node3.Add(new Node(5, null));
            node3.Add(new Node(6, null));

            List<Node> node1 = new List<Node>();
            node1.Add(new Node(3, node3));
            node1.Add(new Node(2, null));
            node1.Add(new Node(4, null));

            Node root = new Node(1, node1);
            int result = MaxDepth(root);
            Assert.AreEqual(3, result);
        }
    }
}


texts: Uploading and downloading files with FTP

texts:
I'm learning Python and decided to rewrite my FTP tool from Perl to Python. The program is able to up/download files, change the directory and list the files of the current directory.

Is there anything I can improve?

#!/usr/bin/python

import time
import sys
import os
from ftplib import FTP
import getpass

def menue():
    print "1) Verzeichnisse auflisten"
    print "2) Verzeichnis wechseln"
    print "3) Datei hochladen"
    print "4) Datei runterladen"
    print "9) Programm beenden"
    choice = raw_input("Was wollen Sie tun? ")
    return choice

def connect(counter):
    user = raw_input("User: ")
    password = getpass.getpass()
    ftp = FTP('xxxxxx')
    ftp.login(user, password)
    counter += 1
    return ftp, counter

def list_dir( ftp ):
    ftp.retrlines('LIST')

def chd_dir( ftp ):
    change_choice = raw_input("In welches Verzeichnis moechten Sie wechseln? ")
    if change_choice not in ftp.nlst():
        print "Das angegebene Verzeichnis existiert nicht!"
    else:
        ftp.cwd(change_choice)

def upl_file( ftp ):
    file_upl = raw_input("Bitte geben Sie den Dateinamen an: ")
    curr_dir = os.curdir
    if file_upl not in os.listdir(curr_dir):
        print "Die angegebene Datei existiert nicht!"
    else:
        ftp.storbinary('STOR ' +file_upl, open(file_upl, 'rb'))

def dwl_file( ftp ):
    file_dwl = raw_input("Bitte geben Sie den Dateinamen an: ")
    if file_dwl not in ftp.nlst():
        print "Die angegebene Datei existiert nicht!"
    else:
        ftp.retrbinary('RETR ' +file_dwl, open(file_dwl, 'wb').write)

counter = 0
while True:
    choice = menue()
    if choice == "9":
        print "Programm wird beendet..."
        time.sleep(1)
        sys.exit()
    if counter == 0:
        ftp, counter = connect(counter)
    if choice == "1":
        list_dir(ftp)
    elif choice == "2":
        chd_dir(ftp)
    elif choice == "3":
        upl_file(ftp)
    elif choice == "4":
        dwl_file(ftp)
    else:
        print "Falsche Eingabe!"

Python version 2.6.


texts: Mocking pathlib.Path I/O methods in a maintainable way which tests functionality not implementation

texts:
I have a function that constructs a path based on a function of inputs and creates the parent directory.

When writing a unit test for this function, I want to mock the I/O part of the function, namely the .exists() and .mkdir() methods of the pathlib.Path objects.  However, since both are not called until the path has been constructed, I find myself reconstructing the implementation using a long chain of return_value.__truediv__ accesses, such as below:

import pathlib
import unittest.mock
import datetime

def get(base, timestamp, channel):
    base = pathlib.Path(base)
    path = base / "tofu" / timestamp.strftime("%Y%m%d") / f"{channel:>02d}" / "quinoa.txt"
    if path.exists():
        print(path, "exists")
    else:
        path.parent.mkdir(exist_ok=True, parents=True)
    return path

@unittest.mock.patch("pathlib.Path", autospec=True)
def test_get(pP):
    pP.return_value.__truediv__.return_value.__truediv__.return_value.\
                    __truediv__.return_value.__truediv__.return_value.\
                    exists.return_value = False
    get("quorn", datetime.datetime.now(), 42)
    pP.return_value.__truediv__.return_value.__truediv__.return_value.\
                    __truediv__.return_value.__truediv__.return_value.\
                    parent.mkdir.assert_called_once()

This test passes, but I have several concerns:

It is testing implementation rather than functionality.  If I were to rewrite the second line in get to read path = base / timestamp.strftime("tofu%Y%m%d") / f{channel:>02d} / "quinoa.txt", the functionality would be identical, but the test would fail as I wouldn't be mocking the right value anymore.
It is hard to read and easy to miscount the depth of __truediv__.return_value chain.

Apart from moving the I/O out of get, can I mock this in another way, that does not share those limitations?  Or does the difficulty of writing a good test (with mock) telling me my function is too complex, despite it's small size?


texts:
I am trying to implement a stack with Java:

public class Stack<E> {

    Node top = null;

    public void push(E data) {
        Node node = new Node(data);
        if (null != top) {
            node.next = top;
        }
        top = node;
    }

    public E pop() {
        if (null == top) {
            throw new IllegalStateException("Stack is empty");
        } else {
            E data = top.data;
            top = top.next;
            return data;
        }
    }

    public E peek() {
        if (null == top) {
            throw new IllegalStateException("Stack is empty");
        } else {
            E data = top.data;
            return data;
        }
    }

    public void print() {
        if (null == top) {
            throw new IllegalStateException("Stack is empty");
        } else {
            Node node = top;
            while(null != node) {
                System.out.println(node.data);
                node = node.next;
            }
        }
    }

    private class Node {

        Node next;
        E data;

        Node(E data) {
            this.data = data;
        }

    }
}

I am looking for feedback for the implementation. Also, I wanted to know if the pop() implementation can cause a memory leak?


texts:
I call these text updates "Feeds". A Feed object has some basic attributes like its content string, how many lives it has and its priority in the queue. I haven't made a unittest for this one, but below I have added a small test function for the purpose of posting this question. I use this to update statusbar in GUI applications.

import threading
import queue
import time

LOW_PRIORITY = 0
MEDIUM_PRIORITY = 1
HIGH_PRIORITY = 2

class Feed(object):
    def __init__(self, msg, life=1, priority=LOW_PRIORITY):
        self.msg = msg
        self.life = life
        self.priority = LOW_PRIORITY if life == -1 else priority

    def hit(self):
        if self.life > 0:
            self.life -= 1
        elif not self.life:
            raise ValueError("Feed {} is already dead.".format(self))

    def __bool__(self):
        return True if self.life else False

    def __lt__(self, obj):
        if self.priority > obj.priority:
            return True
        return False

class FeedThread(threading.Thread):
    def __init__(self, globevent, handler, updateinterval=3):
        super(FeedThread, self).__init__()

        self.globevent = globevent
        self.handler = handler
        self.updateinterval = updateinterval
        self.feedqueue = queue.PriorityQueue()

    def PushFeed(self, feed):
        self.feedqueue.put(feed)

    def run(self):
        while not self.globevent.is_set():
            try:
                feed = self.feedqueue.get(block=True, timeout=1)
                if feed:
                    self.handler(feed.msg)
                    feed.hit()
                    self.PushFeed(feed)
                    time.sleep(self.updateinterval)
            except queue.Empty:
                pass

def test_feed():
    newstime = threading.Event()
    def bullettin(news):
        print("\r{:^79}".format(news), end="")
    scroll = FeedThread(newstime, bullettin)
    scroll.start()
    sports_feed = Feed("Barclays Premier League - Man Utd V Tottenham - 12:45",
                        life=2, priority=MEDIUM_PRIORITY)
    weather_feed = Feed("London - Cloudy, High 26C. Winds EDE at 15 to 30 km/h",
                        life=-1)
    entertainment_feed = Feed("Upcoming movie - Pixels (2015)",
                            life=2)
    for feed in (sports_feed, weather_feed, entertainment_feed):
        scroll.PushFeed(feed)
    time.sleep(15)
    breaking_feed = Feed("BREAKING NEWS - Cats love lasers - pew pew pew!",
                        priority=HIGH_PRIORITY)
    scroll.PushFeed(breaking_feed)
    time.sleep(15)
    newstime.set()

if __name__ == "__main__":
    test_feed()


texts:
I have been working on translating some code from C to C# but since I haven't been coding in C / C++ for many years now plus I do not want to resort to the unsafe keyword. I have made an attempt and would like some verification & optimisation suggestions.

Here is the code in C/C++.

#ifdef __cplusplus /* C++ cannot assign void* from malloc to *data */
#define APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
  if (!((*size) & ((*size) - 1))) {\
    /*double alloc size if it's a power of two*/\
    void** data_void = reinterpret_cast<void**>(data);\
    *data_void = (*size) == 0 ? malloc(sizeof(**data))\
                              : realloc((*data), (*size) * 2 * sizeof(**data));\
  }\
  (*data)[(*size)] = (value);\
  (*size)++;\
}
#else /* C gives problems with strict-aliasing rules for (void**) cast */
#define APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\
  if (!((*size) & ((*size) - 1))) {\
    /*double alloc size if it's a power of two*/\
    (*data) = (*size) == 0 ? malloc(sizeof(**data))\
                           : realloc((*data), (*size) * 2 * sizeof(**data));\
  }\
  (*data)[(*size)] = (value);\
  (*size)++;\
}
#endif

Here is the code in C#:

public static T[] AppendData<T>(T value, T[] data, ref uint size)
{
    if ((size & (size - 1)) != 0)
    {
        /* Double alloc size if it's a power of two */
        var tsize = size == 0 ? data.Length : size*2*data.Length;
        var tdata = new T[tsize];
        Array.Copy(data, tdata, data.Length);
        tdata[size] = value;
        data = tdata;
    }
    else
    {
        data[size] = value;
    }

    size++;
    return data;
}

One more thing to note is that performance is paramount for this code as the overall algorithm it fits in to is quite slow.


texts:
First of all, I'd want to represent, in my application, two different users (admin and client) which can access to two different classes, through two different graphic interfaces...

My idea is to represent faithfully what is in the e/r and I'd want to generalize shared information (like nick, pw, email) using an interface and represent specific information into the two sub-classes

To store information, I use a database and a piece of the e/r is:

Now, in my code, I've implemented it in this way:

Utente entity  - represented using Interface:

package users;

/**
 * Interface which represent a general user (both admin either client)
 *
 * @author Federico Cuozzo
 *
 */
public interface User {
    public String getNick();
    public String getPw();
    public String getEmail();
}

Admin entity  - represented using Class with Override:

package users;

import global.Globals;
import java.util.ArrayList;

/**
 * Represents the admin user instance and his all information.
 *
 * @author Federico Cuozzo
 *
 */
public class Admin implements User {
    private String nick;
    private String pw;
    private String email;
    private ArrayList<Integer> authorizations = new ArrayList<Integer>();   // List of authorizations rwx in integer (r-- 4, rwx 7)

    public Admin(String aNick, String aPw, String anEmail) {
        this.nick = aNick;
        this.pw = aPw;
        this.email = anEmail;
        this.authorizations.add((int) Globals.r.nextInt((7-4) + 1) + 4);
        this.authorizations.add((int) Globals.r.nextInt((7-4) + 1) + 4);
        this.authorizations.add((int) Globals.r.nextInt((7-4) + 1) + 4);
    }

    // Accessor methods for private fields
    @Override
    public String getNick() { return this.nick; }
    @Override
    public String getPw() { return this.pw; }
    @Override
    public String getEmail() { return this.email; }
    public ArrayList<Integer> getAuthorizations() { return this.authorizations; }
}

Client entity  - represented using Class with Override:

package users;

/**
 * Represents the client user instance and his all information.
 *
 * @author Federico Cuozzo
 *
 */
public class Client implements User {
    private String nick;
    private String pw;
    private String name;
    private String surname;
    private String email;
    private String street;
    private String city;
    private String cap;
    private String phoneNumber;

    public Client(String aNick, String aPw, String anEmail, String aName, String aSurname, String aStreet, String aCity, String aCap, String aPhoneNumber) {
        this.nick = aNick;
        this.pw = aPw;
        this.name = aName;
        this.surname = aSurname;
        this.email = anEmail;
        this.street = aStreet;
        this.city = aCity;
        this.cap = aCap;
        this.phoneNumber = aPhoneNumber;
    }

    // Accessor methods for private fields
    @Override
    public String getNick() { return this.nick; }
    @Override
    public String getPw() { return this.pw; }
    @Override
    public String getEmail() { return this.email; }
    public String getName() { return this.name; }
    public String getSurname() { return this.surname; }
    public String getStreet() { return this.street; }
    public String getCity() { return this.city; }
    public String getCap() { return this.cap; }
    public String getPhoneNumber() { return this.phoneNumber; }
}

Is this correct? Using an interface to represent main class and two concrete classes to represent sub-classes...


texts:
Working on below problem, looking for advice on code style, functional bug and time complexity improvements.

Also looking for advice in,

If array is not sorted, any solutions available for O(n^2) time complexity?
In my loop, I always search from exclude_index + 1 to reduce duplicate, is it a safe start boundary?

Problem,

Given a sorted array and a target number, tell whether there are three numbers in the array which add up to the target number. (Time complexity should be O(n^2))

Source code,

def two_sum(numbers, start, end, target, exclude_index):
    while start < end:
        if start == exclude_index:
            start += 1
        elif end == exclude_index:
            end -= 1
        elif numbers[start] + numbers[end] > target:
            end -= 1
        elif numbers[start] + numbers[end] == target:
            print numbers[start], numbers[end], numbers[exclude_index]
            start += 1
            end -= 1
            while start < end and (numbers[start] == numbers[start - 1] or start == exclude_index):
                start += 1
            while start < end and (numbers[end] == numbers[end + 1] or end == exclude_index):
                end -= 1
        else:
            start += 1
def three_sum(numbers, target):
    for exclude_index in range(len(numbers)):
        if exclude_index > 0 and numbers[exclude_index] == numbers[exclude_index - 1]:
            continue
        two_sum(numbers, exclude_index + 1, len(numbers) - 1, target - numbers[exclude_index], exclude_index)

if __name__ == "__main__":
    numbers = [1, 3, 4, 6, 7, 8, 9, 9, 10, 12]
    three_sum(numbers, 15)


texts:
I have recently started working on a server software in Java and wanted to add a configuration option to the program.  I have gone through a few revisions of this class because I never liked what I came up with.  I finally made something that I'm somewhat happy about and it works better than past versions.  I'm just curious if anything can be done better or if this class should be rewritten again in a different?

FYI: some methods are not done yet. I'm not worried about those methods, I'm asking about what is there so far.

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

public class Config
{
public static final String SERVER_NAME = "serverName";
public static final String MOTD = "motd";
public static final String SERVER_PORT = "serverPort";

private static final File file = new File("config.yaml");
private Map<String, Object> config = new HashMap<String, Object>();

private DumperOptions yamlOptions = new DumperOptions();
private Yaml yaml;

private void setDefaults()
{
    config.clear();

    config.put(SERVER_NAME,     "Server");
    config.put(MOTD,            "Welcome to the server!");
    config.put(SERVER_PORT,     21020);
}

public void generate()
{
    setDefaults();
    save();
}

public void load()
{
        //To-do
}

public void save()
{
    //To-do
}

public Object getObject(String key)
{
    return config.get(key);
}

public String getString(String key)
{
    return (String) getObject(key);
}

public int getInt(String key)
{
    return (int) getObject(key);
}

public double getDouble(String key)
{
    return (double) getObject(key);
}
}

Example of usage:

Config.getInt(Config.SERVER_PORT);


texts: Finding number of possible arrangements of books on a shelf with a Monte-Carlo approach

texts:
The Problem
I am trying to determine numerically how many possible ways a number of books can be arranged on a shelf. Specifically, there are x3 categories "physics", "sci-fi", and "travel". Each contains N_phys, N_scifi, and N_travel numbers of books respectively. Within their category, the books can be placed in any order, but they must stay within their respective category (i.e all the physics books together). The categories can then be arranged in any order (i.e I could have all the sci-fi books first, followed by travel, followed by physics, for example).

My Attempt
I have decided to label each book and its category by integers, with "physics" = 1, "sci-fi" = 2, and "travel" = 3. The shelf is then a 2D array. So for example, a whole shelf could look like the following:
[3   2   1   4   1   2   2   1   3;   % Book ID
 1   1   1   1   3   3   2   2   2]  % Categrory label

where the the first 4 books are physics (because the second row is 1), followed by 2 travel books, and finally 3 sci-fi books, like this:

This problem can be solved easily and exactly as a permutation, and the result is N_phys ! x N_scifi ! x N_travel ! x 3 !. For N_phys = 4, N_scifi = 3, and N_travel = 2, the result is 1728 possible arrangements.
I have written a "brute-force" numerical attempt, shown below in Matlab, which seems to give the correct result:
N_phys = 4;   % Number of physics books
N_scifi = 3;  % Number of sci-fi books
N_travel = 2; % Number of travel books

books_physics = [1:N_phys;...
                 ones(1,N_phys)]; % Collection of physics books

books_scifi = [1:N_scifi;...
               2*ones(1,N_scifi)]; % Collection of sci-fi books

books_travel = [1:N_travel;...
                3*ones(1,N_travel)];  % Collection of travel books

num_samples = 10000; % Number of random shelves to generate
unique_shelves = zeros(num_samples*2,N_phys+N_scifi+N_travel); % Preallocate

unique_shelves(1:2,:) = [books_physics books_scifi books_travel];
num_unique_shelves = 1;

% Generate "num_samples" permutations of shelves randomly
for sample_num = 1:num_samples

books_physics_shuffled = books_physics( :, randperm(N_phys) ); % Shuffle physics books
books_scifi_shuffled = books_scifi( :, randperm(N_scifi) );    % Shuffle sci-fi books
books_travel_shuffled = books_travel( :, randperm(N_travel) ); % Shuffle travel books

category_order = randperm(3,3); % Choose order of categories, e.g. sci-fi/phsycis/travel  = [2 1 3]

shelf = [];

% Arrange the categories in a random order
for k = 1:3
    if category_order(k) == 1
        shelf = [shelf books_physics_shuffled];
    elseif category_order(k) == 2
        shelf = [shelf books_scifi_shuffled];
    elseif category_order(k) == 3
        shelf = [shelf books_travel_shuffled];
    end
end

% Iterate over discovered shelves, and see if we have found a new unique one
shelf_exists = 0;
for k = 1:num_unique_shelves
    if shelf == unique_shelves( (2*k-1):(2*k),:)
        shelf_exists = 1; % Shelf was previously discovered
        break
    end
end

if ~shelf_exists % New shelf was found
    unique_shelves( (2*num_unique_shelves+1):(2*num_unique_shelves+2),:) = shelf; % Add shelf to existing ones
    num_unique_shelves = num_unique_shelves + 1;
end

end

disp(['Number of unique shelves found = ',num2str(num_unique_shelves)])
disp(['Expected = ', num2str(factorial(N_phys)*factorial(N_scifi)*factorial(N_travel)*factorial(3) )])

As can be seen, I am basically randomly generating a shelf, and then checking if it has been previously found. If it has, I add it to the list.
I am looking for feedback on the way this is implemented, and how it can be improved to make it more concise and efficient. Is there a better data structure for storing such "unique_shelves", instead of the 2D array of integers as above? My code also doesn't scale easily for more categories, since they are hardcoded.
Tips or alternative examples would be great! Thanks.


texts: Three PHP database queries to manage accounts

texts:
I have a database connection PHP file which has a lot of queries to the database. Here are 3 of the functions that I am using:

public function deleteAccount($token)
{
    $sql1 =
        "DELETE FROM $this->table_user
         WHERE $this->key_token = ?;";

    $stmt1 = $this->connection->prepare($sql1);
    $stmt1->bind_param("s", $token);
    $stmt1->execute();
    $result = $stmt1->affected_rows;
    $stmt1->close();
    return ($result >= 1);
}

public function getAccountDetails($token)
{
    $sql1 =
        "SELECT $this->key_name, $this->key_username, $this->key_email
         FROM $this->table_user
         WHERE $this->key_token = ?;";
    $stmt1 = $this->connection->prepare($sql1);
    $stmt1->bind_param("s", $token);
    $stmt1->execute();
    $stmt1->bind_result($name, $username, $email);
    $stmt1->fetch();
    $stmt1->close();
    return
        array(
            "name" => $name,
            "username" => $username,
            "email" => $email
        );
}

public function resetPassword($password, $hash, $email)
{
    $sql1 =
        "UPDATE $this->table_user
         SET $this->key_hash = ?
         WHERE $this->key_email = ? AND $this->key_passwordhash = ?;";

    $stmt1 = $this->connection->prepare($sql1);
    $passhash = password_hash($password, $this->algorithm);
    $stmt1->bind_param("sss", $passhash, $email, $hash);
    $stmt1->execute();
    $result = ($stmt1->affected_rows == 1);
    $stmt1->close();
    return $result;
}

To me this seems like a lot of code duplication and I find myself doing a lot of copying and pasting which is a big sign that it is very duplicated but I am struggling to see how I can refactor this code so that for every sql query I perform it does not require so many lines of code.


texts: Locate a number in an array with a special ordering

texts:
Below are two examples of arrays (with a special ordering with odd numbers on one side, and even number on the other side) I have, with some given len:

9  7  5  3  1  2  4  6  8

11  9  7  5  3  1  2  4  6  8  10

For some value z, I want to find the column the value is in. MATLAB code I wrote:

if z == 1
   column = ceil(len/2);
elseif logical(mod(z,2))
   column = ceil(len/2) - (z-1)/2;
else
   column = ceil(len/2) + z/2;
end

Does this above locate the correct column?


texts: Maximum product of 3 integers in an int array using Python - follow up

texts:
This is a follow up to Maximum product of 3 integers in an int array using Python

Changes to the code include renamed variables for improved readability and I added more test cases.

import unittest

def highest_product(list_of_ints):
    max_seen = [float("-inf"), float("-inf"), float("-inf")]
    min_seen = [float("inf"), float("inf")]

    for x in list_of_ints:
        if x >= max_seen[0]:
            max_seen[0], max_seen[1], max_seen[2] = x, max_seen[0], max_seen[1]
        elif x >= max_seen[1]:
            max_seen[1], max_seen[2] = x, max_seen[1]
        elif x > max_seen[2]:
            max_seen[2] = x
        if x <= min_seen[0]:
            min_seen[0], min_seen[1] = x, min_seen[0]
        elif x < min_seen[1]:
            min_seen[1] = x

    max_product_candidate_one = min_seen[0] * min_seen[1] * max_seen[0]
    max_product_candidate_two = max_seen[0] * max_seen[1] * max_seen[2]

    return max(max_product_candidate_one, max_product_candidate_two)

class TestHighestProduct(unittest.TestCase):
    def test_highest_product(self):
        self.assertEqual(highest_product([6, -1, -1, -2, 0]), 12)
        self.assertEqual(highest_product([-6, -1, -1, -2]), -2)
        self.assertEqual(highest_product([0, 0, 0]), 0)
        self.assertEqual(highest_product([0, 0, -2]), 0)

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


texts:
In this class I made a webscraper for a cryptocurrency website to get the name and the price of each currency. There are maybe API's that I can also use, but I thought it is better to gain some knowledge doing it with scraping.

import requests
from bs4 import BeautifulSoup
import json

class Coins:

    def __init__(self):
        self.url = "https://www.coinbase.com/price"
        self.new_list = []

    # Check if I get a 200 status code and if so, create instance from bs4
    def get_response(self):
        self.response = requests.get(self.url)

        if self.response:
            print("Access granted")
            self.soup = BeautifulSoup(self.response.text, 'lxml')
        else:
            print("Error")

    # Select the class and get the data
    def get_data(self):
        info = self.soup.find_all(class_="Header__StyledHeader-sc-1q6y56a-0 hZxUBM TextElement__Spacer-sc-18l8wi5-0 hpeTzd")
        # Here, I only want to get the name and the price of the crypto, I don't want to get other information and thats why I am using the modulo operator.
        for x,e in enumerate(info):
            if x % 3 == 2:
                # print("I dont need this information")
                pass
            else:
                self.new_list.append(e.text)

        return self.new_list

    # From the information that I got and appended into a list, make a dict
    def make_dict(self):
        self.my_dict = {self.new_list[x]:self.new_list[x + 1] for x in range(0, len(self.new_list), 2)}
        return self.my_dict

    # Save the data into a json file
    def save_data(self):
        with open('data.json','w') as output:
            json.dump(self.my_dict, output, indent=2)

if __name__ == '__main__':
    test = Coins()
    test.get_response()
    test.get_data()
    test.make_dict()
    test.save_data()

One of my concern is: I try to access variables inside a method, is using self a good idea? For example in the method save_data(). I wanted to pass the function get_data() in json.dump() but it didn't work out. So I changed in make_dict() the variable to self.my_dict to access it in the method save_data() and it worked out, but is it a good practice or not at all?

This is my first time actually working with classes. I appreciate any feedback to improve myself.


texts: Arduino Create and send data to Serial Port (Software Serial function)

texts:
I have this code written and functioning that will write out the chars in cmd to a serial port for an input of two int values. As the majority of the byte values fed are constant, I created the following code that only requires receiving the values that change frequently.

void Create_Message(int Address, int Data)
{
  //Local Vars
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc & 0xFF;
  byte CrcLo = crc >> 8;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */
  //Send Data
  unsigned char cmd[8]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo};
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  lcd.setCursor(0, 1);
  for (int i=0; i< 8; i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
    /*//Serial.print(cmd[i]); //echo back (debug)
    if (i>1)
    {
    lcd.print(cmd[i]);
    lcd.print(" ");
    }*/
   }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

unsigned int CRC(byte AdDa[], int Size )
{
  unsigned int crc16 = 0xFFFF;
  int pos = 0;
  int i = 0;
  /*Write CRC*/
  for (pos = 0; pos < Size; pos++)
  {
    crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc
    for (i = 8; i != 0; i--) // Loop over each bit
    {
      if ((crc16 & 0x0001) != 0)        // If the LSB is set
      {
        crc16 >>= 1;                    // Shift right and XOR 0xA001
        crc16 ^= 0xA001;
      }
      else                            // Else LSB is not set
      crc16 >>= 1;                    // Just shift right
    }
  }
  /*Note, this number has low and high bytes swapped,
  so use it accordingly (or swap bytes)*/
  return crc16;
}

I'm pretty new to writing code, but want to try and make this as efficient as possible. Any pointers as to how I could better optimize this function would be greatly appreciated.


texts:
I'm doing some toy problems in a variety of languages and wanted to do the following in Racket Lisp.

Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
0, 1, 3, 50, 75

Lower: 0
Upper: 99
Expected Output:
["2", "4->49", "51->74", "76->99"]

As you can see on the linked page I had to take two whacks at it but eventually came up with the following. How does it look? Is it idiomatic? Could I have done certain things far better?
(define (missing-ranges nums lower upper)
  (in-generator
   (define (yield-missing-range current num)
     (yield (if (eq? num (add1 current))
                (~a current)
                (~a current "->" (sub1 num)))))
   (let recur ([remaining-nums nums]
               [current lower])
     (match remaining-nums
       [(cons num rest-nums) (if (< current num)
                                 (begin
                                   (yield-missing-range current num)
                                   (recur rest-nums num))
                                 (recur rest-nums (add1 current)))]
       ['() (cond [(<= current upper)
                   (yield-missing-range current (add1 upper))])]))))