texts:
I have some code in Go that is attempting to compare two images and determine how different they are. The method is fairly crude, but it is fast enough. Basically it just compares both images pixel by pixel and for each pixel it determines how different they are by comparing the RGBA values separately and using the absolute value of the difference (summed across the 4 channels) as the difference value for the current pixel. It sums together all these difference values and uses that number as the final result (that is then printed).

Does anyone have any comment on how this can be improved? Specifically for accuracy, as I mentioned, performance is "good enough" for now, though I'm not opposed to comments on efficiency as well.

package main

import (
    "os"
    "log"
    "image"
    "image/color"
    "math"
    "fmt"

    _ "image/png"
)

func main () {
    // open the target file
    target_file, err := os.Open("/home/gregg/workspace/Fueled/imagefilters/www/test_images/nashville.png")
    if (err != nil) {
        log.Fatal(err)
    }
    defer target_file.Close()

    // open the source file
    source_file, err := os.Open("/home/gregg/workspace/Fueled/imagefilters/www/test_images/out.png")
    if (err != nil) {
        log.Fatal(err)
    }
    defer source_file.Close()

    // decode the target file
    target, _, err := image.Decode(target_file)
    if (err != nil) {
        log.Fatal(err)
    }

    // decode the source file
    source, _, err := image.Decode(source_file)
    if (err != nil) {
        log.Fatal(err)
    }

    // check to make sure Bounds match
    target_bounds := target.Bounds()
    source_bounds := source.Bounds()
    if (!boundsMatch(target_bounds, source_bounds)) {
        log.Fatal("Image sizes don't match!")
    }

    var diff int64
    for y := target_bounds.Min.Y; y < target_bounds.Max.Y; y++ {
        for x := target_bounds.Min.X; x < target_bounds.Max.X; x++ {
            diff += compareColor(target.At(x, y), source.At(x, y))
        }
    }
    fmt.Printf("%d\n", diff)
}

func compareColor(a, b color.Color) (diff int64) {
    r1, g1, b1, a1 := a.RGBA()
    r2, g2, b2, a2 := b.RGBA()

    diff += int64(math.Abs(float64(r1-r2)))
    diff += int64(math.Abs(float64(g1-g2)))
    diff += int64(math.Abs(float64(b1-b2)))
    diff += int64(math.Abs(float64(a1-a2)))
    return diff
}

func boundsMatch(a, b image.Rectangle) bool {
    return a.Min.X == b.Min.X && a.Min.Y == b.Min.Y && a.Max.X == b.Max.X && a.Max.Y == b.Max.Y
}


texts: Drawing a circle with text in it using CSS

texts:
I'm trying to draw a circle and put text in the circle.  It'll be part of a UI I'm working on.  I have it working and it looks the way I want, but I think there must be a better way to do it.  Mainly, I don't like all the hard coded numbers and lining up everything by hand.  What I'd love is a version that could easily scale to any size without having to change a lot of the top and left properties of all the text.  Any ideas on how to improve this?

Fiddle

div.arcs {
    border: 50px solid red;
    display: inline-block;
    min-width: 14em;
    min-height: 14em;
    max-height: 14em;
    max-width: 14em;
    border-radius: 50%;
    border-top-color: rgb(109, 176, 65);
    border-bottom-color: rgb(167, 167, 167);
    border-left-color: rgb(255, 199, 45);
    border-right-color: rgb(104, 162, 219);
    box-shadow: 0 0 20px 5px #a0a0a0;
}

div.arcs > div {
    font-family: Calibri;
    font-size: 20pt;
    text-align: center;
    text-shadow: 1px 1px 3px #000000;
    color: #e0e0e0;
    position: relative;
    width: 8.45em;
    height: 1.5em;
    line-height: 1.35em;
}

div.arcs > div:hover {
    text-decoration: underline;
    cursor: pointer;
}

div.arcs > div.top {
    top: -1.55em;
}

div.arcs > div.left {
    transform: rotate(270deg);
    transform-origin: right top 0;
    left: -10em;
    top: -1.5em;
}

div.arcs > div.right {
    transform: rotate(90deg);
    transform-origin: left top 0;
    left: 10em;
    top: -3.1em;
}

div.arcs > div.bottom {
    top: 3.7em
}

Text 1

Text 4

Text 2

Text 3


texts:
I've written a bash script that backs up databases and uploads the backups to an S3 bucket. I have the bucket configured to delete backups that are older than 90 days.

Is there anything that can be improved in this script?

#!/usr/bin/env bash

# Backup MySQL databases to S3

# Follow the installation instructions listed on the user guid doc:
# http://docs.aws.amazon.com/cli/latest/userguide/installing.html

# Note backups will be deleted after 90 days. This is setup in the management tab:
# https://s3.console.aws.amazon.com/s3/buckets/backups.databases/?tab=management

# DB details
DB_USER=""
DB_PASSWORD=""
DB_HOST=""
DB_IGNORED=(Database mysql information_schema performance_schema cond_instances)

# S3 details
S3_BUCKET=backups.databases
S3_FOLDER=backups/databases

# Temp storage location
TMP_DIR=/tmp

# Check if dependencies exist
dependencies=(aws mysql mysqldump tar rm echo)
for dependency in "${dependencies[@]}"
do
    if [[ $(command -v "$dependency") = "" ]]
    then
        # Tell the user that the dependency is not installed, then exit the script
        $(which echo) "Dependency $dependency isn't installed. Install this dependency to continue."
        exit 0
    fi
done

DB_DATABASES=($($(which echo) "show databases;" | $(which mysql) -h ${DB_HOST} -p${DB_PASSWORD} -u ${DB_USER} 2> /dev/null))

# Filename for the backups
time=$($(which date) +%b-%d-%y-%H%M)
filename="backup-$time.tar.gz"

for database in "${DB_DATABASES[@]}"
do
    # Skip ignored databases
    if [[ "${DB_IGNORED[@]}" =~ "$database" ]]
    then
        continue
    fi

    # Dump database SQL schema to an SQL file stored in the temp directory
    $(which echo) "Backing up $database..."
    $(which mysqldump) -h ${DB_HOST} -u ${DB_USER} -p${DB_PASSWORD} ${database} > "$TMP_DIR/$database.sql" 2> /dev/null
    $(which tar) -cpzf "$TMP_DIR/$database-$filename" "$TMP_DIR/$database.sql" 2> /dev/null

    # Upload the exported SQL file to S3
    $(which echo) "Uploading to S3..."
    $(which aws) s3 cp "$TMP_DIR/$database-$filename" "s3://$S3_BUCKET/$S3_FOLDER/$database-$filename"
    $(which echo) "Database $database uploaded to S3"

    # Remove the temporary files
    $(which echo) "Cleaning up..."
    $(which rm) -f "$TMP_DIR/$database-$filename"
    $(which rm) -f "$TMP_DIR/$database.sql"
done

I had to add 2> /dev/null  to the end of the mysql and mysqldump commands due to a warning message showing.

  Warning: Using a password on the command line interface can be
  insecure.

Is there a better way of handling this?

Any feedback would be greatly appreciated.


texts:
This code has a method that I call for in main.

I am given a list with temperatures.  What I need to do is to write out the biggest absolute difference of 2 neighbour numbers.  For example, if I have {1, 3, 4, 10, 7, 4}, the result is 6 (between 4 and 10) and also all other pairs that have the same difference.

I have this code written down but I feel it looks kind of clumsy. I'd be very grateful for any suggestions and improvements.

public class DN4 {
    static void najvecjaZaporednaRazlika(double stevila[]){
        double maxRaz = 0;
        double[] tStevil = new double[0];
        for (int i = 0; i < stevila.length - 1; i++){
            double a = stevila[i];
            double b = stevila[i+1];
            double absRaz = a - b;
            if (absRaz < 0){
                absRaz = -1 * absRaz;
            }
            if (absRaz == maxRaz){
                double tStevilStara[] = tStevil;
                tStevil = new double[tStevilStara.length+2];
                tStevil[tStevil.length - 2] = a;
                tStevil[tStevil.length - 1] = b;
                for (int t = 0; t < tStevilStara.length; t++){
                    tStevil[t] = tStevilStara[t];
                }
            }
            else if (absRaz > maxRaz){
                maxRaz = absRaz;
                tStevil = new double[2];
                tStevil[0] = a;
                tStevil[1] = b;
            }
        }
        System.out.printf("Najvecja razlika: %.2f\n",maxRaz);
        System.out.printf("Pari,ki dosezejo maksimalno razliko: ");
        for (int i = 0; i < tStevil.length - 1; i = i+2){
            if (i == 0){
                System.out.printf("(%.2f, %.2f)",tStevil[i],tStevil[i+1]);
            }
            else{
                System.out.printf(", (%.2f, %.2f)",tStevil[i],tStevil[i+1]);
            }
        }
        System.out.println();
    }

    public static void main (String args[]){
        double kredarica2011[] = {-7.8, -6.5, -5.7, -1.3, 1.7,  5,
                               5.6,  9.2,  7.1,  0.5, 0.3, -6.3};
        najvecjaZaporednaRazlika(kredarica2011);
    }
}


texts: Streaming objects from JDBC query through Jackson and Ktor

texts:
I am attempting to improve performance for an endpoint that may return a lot of data. I am retrieving the data from a database using JDBC, and constructing an object representation of the data. These objects are then serialised as JSON using Ktor's content negotiation (relying on Jackson).
The improvement that I am attempting, is to construct the objects from the ResultSet in one coroutine, sending them in an UNLIMITED channel, and in another coroutine, serialise each object into JSON, and stream the response data as each object is serialised.
Something doesn't feel right about my approach though. I suspect there should be a way to stream objects directly to the content negotiation, and have it serialise them into a JSON array, rather than the approach I have here, but I'm failing to see it.
I'm also curious if cleaner solutions are also possible with kotlinx.serialisation, but I think that may currently not be the case, do to this: https://github.com/Kotlin/kotlinx.serialization/issues/204
Here's my code so far:
fun Application.module() {

    install(DefaultHeaders)
    install(CORS) {
        anyHost()
        methods.add(HttpMethod.Patch)
    }

    // Even though the endpoint I am asking about is streamed, and I serialise the objects by
    // hand, this is still used for other endpoints that only need to return one JSON object.
    install(ContentNegotiation) {
        jackson {
            MessageMapper.setupMapper(this)
        }
    }

    // There's more code here, but I don't think it is relevant
}

fun Route.DataRetrievalAPI() {
   get<Paths.getData> { params ->
       experimentalStreamingEndpoint(this, params)
   }
}

suspend fun experimentalGetDataEndpoint(context: PipelineContext<Unit, ApplicationCall>, params: dataRequestParams) {
    context.call.respond(object : OutgoingContent.WriteChannelContent() {
        override val contentType = ContentType.Application.Json
        override suspend fun writeTo(channel: ByteWriteChannel) = coroutineScope {
            val dataChannel = Channel<Data>(Channel.UNLIMITED)

            launch {
                getConnection().use {
                    loadData(
                        connection = it,
                        channel = dataChannel
                    )
                }

            }

            var firstValueDone: Boolean = false
            channel.writeStringUtf8("[")
            for (value: Data in dataChannel) {
                if (!firstValueDone) {
                    firstValueDone = true
                } else {
                    channel.writeStringUtf8(",")
                }
                //messageMapper is a Jackson ObjectMapper
                channel.writeStringUtf8(messageMapper.writeValueAsString(value))
            }
            channel.writeStringUtf8("]")
        }
    })

}

// Snippet from loadData(connection: java.sql.Connection, channel: Channel<Data>)
        preparedStatement.executeQuery().use {
            while(it.next()) {
                //Just example data, real data is more complex
                val item = Data(it.getString("column_name"))
                channel.send(item)
            }
            channel.close()
        }


texts: Return specific variable of Enum, determined by variable with the same name of another Enum?

texts:
I wonder if there is any way to write the followig in a few lines instead of using all cases. Both CategoryType and AnimalSpecies are Enums.

private AnimalSpecies GetAnimalSpeciesBasedOnCategoryType(CategoryType categoryType)
{
    switch (categoryType)
    {
        case CategoryType.Reptile :
            return AnimalSpecies.Reptile;

        case CategoryType.Bird:
            return AnimalSpecies.Bird;
        case CategoryType.Mammal:
            return AnimalSpecies.Mammal;
        case CategoryType.Insect:
            return AnimalSpecies.Insect;
        case CategoryType.Marine:
            return AnimalSpecies.Marine;

        default:
            MessageBox.Show("Category doesn't exist.Something wrong in programming code");
            return AnimalSpecies.Marine;
    }
}


texts:
This is something I wrote as a reply to a deleted "Rock/paper/scissors [updated]" question. Since I can't post it as an answer (and the line-by-line analysis is gone as well), it might be nice to get a code review.

"""A game of rock/paper/scissors."""

import random

SIGNS = ("rock", "paper", "scissors")
VERBS = ("crushes", "covers", "cut")
YES = ("yes", "y")

class Counter(object):
    """Keep track of game session scores."""

    def __init__(self):
        self.rounds = 0
        self.losses = 0
        self.wins = 0
        self.draws = 0
        self.rounds_total = 0
        self.losses_total = 0
        self.wins_total = 0
        self.draws_total = 0

    def increment(self, state):
        """Increment losses, wins, draws.

        Args:
            state: "losses", "wins", or "draws".

        Raises:
            ValueError: If input is invalid.
        """
        if state not in ["losses", "wins", "draws"]:
            raise ValueError("Acceptable input: losses, wins, or draws.")
        for attr in (state, "%s_total" % state, "rounds", "rounds_total"):
            setattr(self, attr, getattr(self, attr) + 1)

    def flush(self):
        """Restart the current game counters, keep the total counters."""
        self.rounds = 0
        self.losses = 0
        self.wins = 0
        self.draws = 0

    def print_results(self):
        print "Games played: ", self.rounds
        print "Games won: ", self.wins
        print "Games lost: ", self.losses
        print "Games drawn: ", self.draws
        print "Total played: ", self.rounds_total
        print "Total won: ", self.wins_total
        print "Total lost: ", self.losses_total
        print "Total drawn: ", self.draws_total

class Sign(object):
    """A rock/paper/scissors sign."""

    def __init__(self, sign):
        global SIGNS

        if sign not in SIGNS:
            raise ValueError("Allowed signs are: %s." % SIGNS.join(", "))
        self.sign = sign

    def __eq__(self, other):
        try:
            if self.sign == other.sign:
                return True
        except AttributeError:
            pass
        return False

    def __gt__(self, other):
        if (self.sign == "rock" and other.sign == "scissors" or
            self.sign == "scissors" and other.sign == "paper" or
            self.sign == "paper" and other.sign == "rock"):
            return True
        return False

    def __lt__(self, other):
        return not self.__gt__(other)

def main(max_rounds=5):
    global SIGNS
    global VERBS
    global YES

    counter = Counter()
    while True:
        if counter.rounds == max_rounds:
            counter.print_results()
            again = raw_input("Play/again? (Y/n) ").lower()
            if again in YES:
                counter.flush()
            else:
                print "Bye!"
                break
        while True:
            player_sign = raw_input("Rock/paper/scissors? ").lower()
            if player_sign not in SIGNS:
                print "Only following words are valid: %s." % SIGNS.join(" ,")
                continue
            break
        player = Sign(player_sign)
        computer = Sign(random.choice(SIGNS))
        if player > computer:
            counter.increment("wins")
            verb = VERBS[SIGNS.index(player.sign)]
            print "Player wins: %s %s %s." % (player.sign, verb, computer.sign)
        elif player == computer:
            counter.increment("draws")
            print "It's a draw! Both played %s." % player.sign
        else:
            counter.increment("losses")
            verb = VERBS[SIGNS.index(computer.sign)]
            print "Player lost: %s %s %s." % (computer.sign, verb, player.sign)

if __name__ == "__main__":
    main(max_rounds=5)


texts: Is there more efficient way of processing my XML file in PHP?

texts:
The page is assigning $gid to the url paramater gid. It then reads an XML file that looks like this:

<games>
 <game>
  <name>name 1</name>
  <appID>1234</appID>
 </game>
 <game>
  <name>name 2</name>
  <appID>5678</appID>
 </game>
</games>

The code I am using works correctly but takes a second to load because there are so many <game> elements on the list. Is there are more efficient way to go about foreach? Here is the code:

$gid = (int) $_GET['gid'];
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
$games = $gamespage->games;

foreach ($games->game as $game) {
  if ($gid == $game->appID) {
    $appid = $game->appID;
    $gamename = $game->name;
  }
}

echo $gid, "
";
echo $appid, "
";
echo $gamename;


texts:
I am generating SQL statements (of MySQL format) and writing into a file to create 10,000 tables. Each table contains 5 columns with 1.5 million rows of data in each column. I generated these data by using regex and faker module. So, I have a loop of 10,000 (one for each create table statement) and within this loop, I have another loop of 1.5 million (to insert rows of data into each table created).

The code is running properly but is extremely slow. Is there any way to make this run considerably faster?

import rstr
import random
from faker import Faker
import time

fake = Faker()

name = ['Name', 'Person_Name', 'Customer_Name', 'Employee_Name', 'Contact_Name', 'CustName', 'EmpName']
ssn = ['SSN', 'Social_Security_Number', 'National_Identification_Number', 'NID', 'US_SSN', 'Social_Number', 'Social_Security_No', 'Social_Security_Num', 'Customer_Social_Security Number', 'Employee_Social_Security_Number']
address = ['Address', 'Customer_Location_Details', 'Employee_Address_Details', 'Address_Det.', 'Add_Line_1', 'Add_Line_2', 'Address_Line_1', 'Address_Line_2']
dob = ['DOB', 'Date_Of_Birth', 'Birth_Date', 'V_VLD_BRTH_DT', 'DAY_OF_BRTH', 'DT_OF_BIRTH']
phone = ['Phone_Number', 'Contact_Number', 'Office_Phone', 'Residential_phone', 'Contact_Phone']

ssn1='(?!000|.+0{4})(?:\d{9})'
ssn2='(?!000|.+0{4})(\d{3}-\d{2}-\d{4})'
sList=[ssn1,ssn2]

db1='^(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19)\d\d$'
db2='^(19)\d\d$[.](0[1-9]|1[012])[.](0[1-9]|[12][0-9]|3[01])'
db3='^(19)\d\d$[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])'
db4='^(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-](19)\d\d$'
db5='^(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.]\d\d$'
dbList=[db1,db2, db3, db4, db5]

p1='1[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p2='[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p3='001[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p4='[(][\d]{3}[)][ ]?[\d]{3}-[\d]{4}'
p5='\+1[2-9][0-8][0-9][2-9][0-9]{2}[0-9]{4}'
p6='(\d{3}\d{3}\d{4})'
p7='[2-9][0-8][0-9][-][2-9][0-9]{2}[-][0-9]{4}'
pList=[p1, p2, p3, p4, p5, p6, p7]

tables=10001
rows=1500001

with open("D:\Output.sql", "a") as text_file:
    count = 0

    for i in range(1,tables):
        a=[]
        b=[]
        j=str(i)
        x=f'Tab_{i}'

        #a.append(random.choice(name)+'_'+j)
        #a.append(random.choice(ssn)+'_'+j)
        #a.append(random.choice(address)+'_'+j)
        #a.append(random.choice(dob)+'_'+j)
        #a.append(random.choice(phone)+'_'+j)
        a.extend(f'{random.choice(n)}_{j}' for n in (name, ssn, address, dob, phone))

        text_file.write(f"create table Python_test.{x}({a[0]} VARCHAR(255),{a[1]} VARCHAR(255),{a[2]} VARCHAR(255),{a[3]} VARCHAR(255),{a[4]} VARCHAR(255));\n")

        start = time.time()
        for j in range(1,rows):
            text_file.write(f"insert into {x}({a[0]},{a[1]},{a[2]},{a[3]},{a[4]}) values ('{fake.name()}','{rstr.xeger(random.choice(sList))}','{fake.address()}','{rstr.xeger(random.choice(dbList))}','{rstr.xeger(random.choice(pList))}');\n")

        print(time.time() - start)
        text_file.write('\n')
        count+=1
        print(count)


texts:
I'm doing a code-challenge problem:

Captain Kaban: National Treasure is a popular football simulation game which can be played on most smartphones. In this game, you put up a team of 11 players and then compete in either story mode or multi-player mode. As you might already know, a football match is played by 11 players, which consists of one goalkeeper and ten outfield players.

Each outfield player's capability is measured with scores in 3 areas: Attack (dribble, shoot, pass), Defense (tackle, block, intercept), and Physical (speed, power, technique). For example, a player with A:4103 D:2837 P:3410 is a typical attacker player (forward position) as his Attack (4103) is higher than his Defense (2837) and Physical (3410). On the other hand, a player with A:1546, D:5209, P:2708 is a typical defensive player as his Defense is much higher than his Attack and Physical. A goalkeeper has a different measurement (Saving and Physical), but it's not our concern in this problem.

A team strength is simply the sum of all the main outfield player's capability-scores. Note that the team strength score does not consider the team's balance, e.g., a team of 10 players where each player has A:8000, D:1000, P:1000 is stronger than a team where each player has A:3000, D:3000, P:3000; the first team's team strength is 100,000 (10 * (8000 + 1000 + 1000)) while the second one is 90,000 (10 * (3000 + 3000 + 3000)).

Let say you are given a team with ten main outfield players and N reserve players. If you are allowed to substitute at most 1 main outfield player (with a reserve player), what is the maximum team strength you can obtain?

Input

Input begins with an integer: T (1 ≤ T ≤ 20) denoting the number of cases.

Each case contains the following input block: Each case begins with an integer: N (1 ≤ N ≤ 10) denoting the number of reserve players. The next 10 lines each contains three integers: Ai Di Pi (100 ≤ Ai, Di, Pi ≤ 20,000) representing the Attack, Defense, and Physical score for the ith main player. The next N lines each contains three integers: Aj Dj Pj (100 ≤ Aj, Dj, Pj ≤ 20,000) representing the Attack, Defense, and Physical score for the jth reserve player.

Output

For each case, output in a line "Case #X: Y" where X is the case number (starts from 1) and Y is the output for the respective case.

#include <iostream>

using namespace std;

int main () {
    const int totalOriginalPlayer {10};
    int testCases {};
    cin >> testCases;

    for (int i = 1; i <= testCases; i++) {
        int reserve {}, total {}, lowest {500000}, highest {};
        int attack {}, defense {}, physical {};
        cin >> reserve;

        int reservePlayers [reserve];
        int powerReservePlayers [reserve];

        int powerOriginalPlayers [totalOriginalPlayer];

        // Get power of all original players, calculate sum and find the minimum
        for (int i = 0; i < totalOriginalPlayer; i++) {
            cin >> attack >> defense >> physical;
            powerOriginalPlayers[i] = attack + defense + physical;
            total += powerOriginalPlayers[i];

            if (powerOriginalPlayers[i] < lowest) {
                lowest = powerOriginalPlayers[i];
            }
        }

       // Get power of all reserve players and find the maximum power
       for (int j = 0; j < reserve; j++) {
            cin >> attack >> defense >> physical;
            powerReservePlayers[j] = attack + defense + physical;

            if (powerReservePlayers[j] > highest) {
                highest = powerReservePlayers[j];
            }
       }

       // Subtract total with lowest and add highest
       if (lowest < highest) {
            total = total - lowest + highest;
       } else if (lowest >= highest) {
            total = total;
       }

       // Print out total
       cout << "Case #" << i << ": "<< total << endl;
    }
}


texts:
Intention

I intend to replace my own Bash script executing the following commands indefinitely in favor of this C++ compiled code, the reason being that the Bash script seemed very CPU ineffective.

It's not that I would think this solution is effective, nor perfect, but better than the one written in Bash for there is a great overhead over time.

The two commands are very simple:

/usr/bin/numlockx on
sleep 1

Environment

Linux Mint 18 with Cinnamon desktop environment.

Purpose

As I don't have a Num Lock indicator on my laptop, I want to ensure the Num Lock is always turned on.

xmodmap

I have tried using this utility, but it literally, excuse my wording, crippled my key mappings, which I have set up from inside Cinnamon DE.

Current C++ code

#include <cstdlib>  // in order to use system function
#include <unistd.h> // in order to use sleep  function

int main()
{

do {

    system("/usr/bin/numlockx on");

    sleep(1);

} while (true);

return 0;

}

This is compiled with g++ 5.x as follows:

g++ numlock-always-on.c -o "numlock-always-on"


texts:
This is a school project that I am turning in late. The prof suggested that i somehow prove myself by improving upon the basic code. This is really tough to do for someone who is just starting to learn to code.

Is there something I can do to:

add onto the code (have it do or ask something different)?
make it even more simple than it probably already is (unlikely)?
though it's counter intuitive, make it more complicated by adding a function or something similar?

I have really looked at this and now that I've actually coded it, I don't know how to improve it.

print("This program computes a cable bill")
account = input("Enter account number: ")
cust_type = input("Enter customer type: R (Residental) or B (Business): ")

def residential():
 premium_channels = int(input("Enter number of premium channels used: "))
 processing_fee = 4.50
 basic_service_fee = 20.50
 premium_channel_fee = 7.50
 amount = processing_fee + basic_service_fee + (premium_channels * premium_channel_fee)
 return (amount)

def business():
 basic_connections = int(input("Enter number of basic service connections: "))
 premium_channels = int(input("Enter number of premium channels used: "))
 processing_fee = 15.0
 basic_service_fee = 75.0
 preimum_channel_fee = 50.0
 if (basic_connections <= 10):
     amount = processing_fee + basic_service_fee + (premium_channels * preimum_channel_fee)
 else:
     amount = processing_fee + basic_service_fee + ((basic_connections - 10) * 5) + (premium_channels *
preimum_channel_fee)
 return (amount)

if (cust_type == "R"):
    bill_amount = residential()
else:
    bill_amount = business()

print("Account number: ", account)
print("Amount due: ", bill_amount)


texts:
What I want is getting all names (first, middle, last) of the users along with each of their total hours of work which will be calculated by the SQL statement: CAST(SUM(timediff(dateTimeOut,dateTimeIn) as time).

I was able to achieve this with two queries, but somehow, I feel that this is inefficient (?):

$sql = "SELECT id, firstName, middleName, lastName FROM users_info";
$result = $pdo->query($sql);

$rows = array();

while($row = $result->fetch()){
     $time = $pdo->query(
                "SELECT CAST(SUM(timediff(dateTimeOut, dateTimeIn))
                 as time) as totalHoursWorked
                 FROM users_time WHERE user_id = {$row['id']}"
            )->fetch();

     $row['totalHoursWorked'] = $time['totalHoursWorked'];
     $rows[] = $row;

}

echo json_encode($rows);

I'll use the json data for a DataTable.

users_info table
+----+-----------+------------+----------+
| id | firstName | middleName | lastName |
+----+-----------+------------+----------+
|  1 | Isabelle  | Luna       | Ibarra   |
|  2 | George    | Boston     | Everett  |
|  3 | Skyler    | Land       | Cohen    |
+----+-----------+------------+----------+

users_time table:
+---------+---------+---------------------+--------------------+
| time_id | user_id |     dateTimeIn      |    dateTimeOut     |
+---------+---------+---------------------+--------------------+
|       1 |       1 | 2019-06-14 00:00:00 | 2019-06-16 09:00:0 |
|       2 |       1 | 2019-06-15 00:00:00 | 2019-06-16 08:00:0 |
|       3 |       2 | 2019-06-14 00:00:00 | 2019-06-16 09:30:0 |
|       4 |       2 | 2019-06-15 00:00:00 | 2019-06-16 08:30:0 |
|       5 |       3 | 2019-06-16 00:00:00 | 2019-06-16 09:00:0 |
+---------+---------+---------------------+--------------------+

db-fiddle link : https://www.db-fiddle.com/f/vpozKbVoXxPoGzcsBkLL36/0


texts: Refreshing customer list periodically in the background

texts:
I have a method RefreshCustomersInternal that refreshes customer data from a server and returns a Task. Since this process is very costly, I want to prevent this method from being called too many times in a short time or prevent the process from running if there's another refresh process running already. So a wrapper method RefreshCustomers is written for this purpose:

private Task _refreshTask;
private readonly object _refreshLock = new object();
private DateTime _lastRefreshTime = DateTime.MinValue;
private static readonly TimeSpan MinimumRefreshInterval = TimeSpan.FromSeconds(5);

private Task RefreshCustomers()
{
    lock (_refreshLock)
    {
        // If there is already a refresh task, just return this one.
        if (_refreshTask != null)
            return _refreshTask;

        // Check if the time between this refresh request and the previous one is too close.
        var intervalFromLastRefresh = DateTime.Now - _lastRefreshTime;
        if (intervalFromLastRefresh < MinimumRefreshInterval)
        {
            // If this refresh request is too close to the previous one,
            // make this request wait until the minimum refresh interval is passed,
            // then perform the refresh.
            var waitTaskSource = new TaskCompletionSource<bool>();
            _refreshTask = waitTaskSource.Task.ContinueWith(_=>RefreshCustomersInternal()).Unwrap();

            // Force the wait in a background thread to ensure a non-blocking UI experience.
            ThreadPool.QueueUserWorkItem(_ =>
            {
                Thread.Sleep(MinimumRefreshInterval - intervalFromLastRefresh);
                waitTaskSource.SetResult(true);
            });
        }
        else
            // If this refresh request is far enough from the last one,
            // just perform the normal refresh.
            _refreshTask = RefreshCustomersInternal();

        // When the refresh process is done, always clear the refresh task reference
        // and update the refresh timestamp.
        return _refreshTask = _refreshTask.ContinueWith(task =>
        {
            lock (_refreshLock)
            {
                _refreshTask = null;
                _lastRefreshTime = DateTime.Now;
            }
        });
    }
}

In a previous version of this method, instead of using the ThreadPool, it was simply just calling the Thread.Sleep method in a new Task:

if (intervalFromLastRefresh < MinimumRefreshInterval)
    _refreshTask = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(MinimumRefreshInterval - internvalFromLastRefresh);
        return RefreshCustomersInternal();
    }).Unwrap();

Since there is no guarantee that Task.Factory.StartNew will never start the new task on the UI thread, I updated it to use the ThreadPool to force the wait into a background thread.

The method seems working from some basic tests, but I wonder if there is any better way for the part where I had to use the ThreadPool.QueueUserWorkItem to force the wait in a background thread?

BTW, the code runs in .NET 4.0 hence the lack of all the neat async and await statements.


texts: Update extremities losses when selected type changes

texts:
The following code works, but is it a good idea to call another method in a setter?

public TypeSignalDTO SelectedTypeSignal
{
    get { return _selectedTypeSignal; }
    set
    {
        _selectedTypeSignal = value;
        RaisePropertyChanged(() => SelectedTypeSignal);
        UpdateExtremitiesLosses(); //This really bugs me.
    }
}

public void UpdateExtremitiesLosses()
{
    if (_completeLink.Any() && SelectedTypeSignal != null)
    {
        try
        {
            _lossService.SetLinkLosses(SelectedTypeSignal.Id_TSI, _completeLink);
            ShowLossColumn = true;
            TotalLoss = _completeLink.Last().LossAtCurrentPoint;
        }
        catch (ServiceException ex)
        {
            ShowLossColumn = false;
            TotalLoss = 0;
            _dialogService.ShowErrorMessage(ex.Message);
        }
        finally
        {
            Extremities = _completeLink.ToViewModel().ToList();
        }

    }
}

As you can see the setter calls another method: UpdateExtremitiesLosses which in turn changes other properties on the view model ShowLossColumn, Extremities and TotalLoss.

I know that properties are actually functions, but changing another property when calling a setter seems like an unintended side effect to me.

Being a beginner with WPF this really seems wrong to me. I would like to know if it is a better idea to subscribe to the ChangeEvent and call the method there, or just call the method in the setter.


texts: Linked list node implementation with maximum code reuse

texts:
Currently as an exercise to practicing SOLID principles and basic data structures, I am trying to implement linked list type structures with as much code reuse as possible. Currently, I have:

package structures.linked;

public class SingleNode<T> {

    private T data;
    private SingleNode<T> next;

    public SingleNode(T data, SingleNode<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public SingleNode<T> getNext() {
        return next;
    }

    public void setNext(SingleNode<T> next) {
        this.next = next;
    }

}

and...

package structures.linked;

public class DoubleNode<T> extends SingleNode<T> {

    private DoubleNode<T> prev;

    public DoubleNode(T data, DoubleNode<T> next, DoubleNode<T> prev) {
        super(data, next);
        this.prev = prev;
    }

    public DoubleNode<T> getPrev() {
        return prev;
    }

    public void setPrev(DoubleNode<T> prev) {
        this.prev = prev;
    }

    public DoubleNode<T> getNext() {
        return (DoubleNode<T>) super.getNext();
    }

    public void setNext(DoubleNode<T> next) {
        super.setNext(next);
    }
}

It seems to me that getNext() inside of DoubleNode<T> is a violation of Liskov's substitution principle. Is this the case? Is there a better way to implement this while still reusing the code in SingleNode<T> and without breaking SOLID principles?


texts: Parsing a string as fast as possible that is using comma delimiters

texts:
I have made a simple static parser for a bigger program. This parser takes a string that has comma deliminators and I need to separate the strings in to a vector for handling in a different section of the code.

I would like this to run as fast as possible so the rest of the program isn't tied up separating strings. I also need this parser to be robust, so I can't set how many columns it should have or anything like that.

For the life of me however, I can't seem to figure out how I can make this any less of a O notation. Right now it is O(N) because of the for loop, if there is something in the string. So worse case, the function is O(N). Is there any way to speed it up? I made this, because I have some special cases where if something has nothing between the commas IE ",," then it still needs to make a spot in the vector so the ",," can be placed in a CSV. Also if we need the parser to ignore a comma between quotes it can do that by setting a bool value.

The main problem, or what I would like to see is, is there a way to reduce the complexity of the function to less than \$O(N)\$?

//pass in a string and a vector and if quotes should be used or not and what     char should be used for delimation.
void Strtov::parse(vector<string>& inboundVector, const string& stringToBeParsed, bool quotesUsed, const char& charToSepBy)
{
    string temporary = "";
    //vector<string> retVal;
    bool quoteTriggered = false;
    //if we get an empty string do nothing.
    if (stringToBeParsed.size() > 0) {
        //if the string has something in it then go ahead down the list.
        for (size_t i = 0; i < stringToBeParsed.size(); i++) {

            if (stringToBeParsed[i] == '\"' && quotesUsed) {
                //if they are true, then mark them false, if they are false then mark them true
                quoteTriggered = quoteTriggered ? false : true;
                if (quoteTriggered) {
                    temporary.push_back(stringToBeParsed[i]);
                }
                else {
                    //place quote in to the temporary string and store it.
                    temporary.push_back(stringToBeParsed[i]);
                }
            }
            //place comma if the string is in a quote.
            else if (stringToBeParsed[i] == charToSepBy && quoteTriggered) {
                temporary.push_back(stringToBeParsed[i]); //<-push the comma on to the string because quotes are being used.
            }
            else if (stringToBeParsed[i] == charToSepBy && !quoteTriggered) {
                inboundVector.push_back(temporary);
                temporary = "";
            }
            else if (stringToBeParsed[i] != charToSepBy)
            {
                temporary.push_back(stringToBeParsed[i]);
            }

        }
        if (stringToBeParsed[stringToBeParsed.size() - 1] == charToSepBy) {
            inboundVector.push_back(string()); //if the last character is a comma then push an empty string on the end.
        }
        else if (!temporary.empty())
        {
            inboundVector.push_back(temporary);
        }
     }

  }

Is there any way to improve this code? Obviously I'm the only one working on it, so forgive me if the names seem a bit rough. I'm not the most original in naming things, but I do try and make them descriptive enough for the average person to see what is going on.


texts: Fraction or percentage regular expression

texts:
I'm learning regular expression as part of my Java course. Now I know sometimes the best use of regex is to not use regex at all. But since I have to use it for this course and learn it, I figure I might as well learn it properly.

I am matching (##/##) or (##) where # is a number 0-9. All white space is ignored (except for in between the digits ##). In context, I'm matching a fraction (10/20) or a percentage (50).

For example (  ##   / ##    ) and (   ## ) are valid. (# #/#  #) and (#  #) are not.

Code / Explanation:

(?:[(])(?:[ ]*)?([\d][\d])(?:[ ]*)?(?:[\/])?(?:[ ]*)?([\d][\d])?(?:[ ]*)?(?:[)])

(?:[(])          Beginning parathensis (
(?:[ ]*)?        All white space
([\d][\d])       Two digits for the first number ##
(?:[ ]*)?        All white space
(?:[\/])?        Forward slash /
(?:[ ]*)?        All white space
([\d][\d])?      Two digits for the second number ##
(?:[ ]*)?        All white space
(?:[)])          Closing parathensis )

Try it online

Example usage in Java:

String regex = "(?:[(])(?:[ ]*)?([\\d][\\d])(?:[ ]*)?(?:[\\/])?(?:[ ]*)?([\\d][\\d])?(?:[ ]*)?(?:[)])";
String test = "(20/50)";

if (test.matches(regex)) { // true
    System.out.println("Valid.");
else {
    System.out.println("Invalid.");
}

Everything is setup using non-capture groups, except for the two digits. This is so I can reference the capture groups in my code (and simply check if group 2 is null before trying to use it, indicating (##) not (##/##)).

This is basically my first time writing regex from complete scratch. Some questions are:

Should I be wrapping everything in [ ] even when they can be left out? i.e. (?: *) instead of (?:[ ]*).
Is my use of non-capture groups the right way to do things (feels verbose to me)?

Generally, what can I improve on?


texts: build a string based on user's input python

texts:
I need to write a function to build a string based on user input.
when user provide one type group of input: "tab" and link variable the string should be tab_link: xxxx.
when user provide one type group of input: "subtab" and link variable the string should be subtab_link: subtabxxxxx.

the logic is pretty much like following function. but do I have better way to do it then using if, else? because lets say if I have multiple group, does it mean I need to have more if, elif, elif to identify different group input and match the string?

subtab = {'subtab1': 1, 'subtab2': 2, 'subtab3': 3}
_dir = {'tab': 'tab_link:{}', 'subtab': 'subtab_link:{}'}

def func(**kwargs):
    if kwargs['_type'] == 'tab':
        print(_dir[kwargs['_type']].format(kwargs['_link']))
    else:
        print(_dir[kwargs['_type']].format(subtab[kwargs['_link']]))

func(_type='tab', _link='a')
func(_type='tab', _link='b')
func(_type='subtab', _link='subtab1')
func(_type='subtab', _link='subtab2')

#expect
tab_link:a
tab_link:b
subtab_link:1
subtab_link:2


texts:
The code I have works. I was just curious if there was an easier way to write the function.

Note: It is referenced inside of an object so you may need to change the $this variables.

public function workTime() {

    $startDate = new DateTime($this->start_date);
    $startPretty = date("F Y", strtotime($this->start_date));
    $endDate = new DateTime($this->end_date);
    $endPretty = date("F Y", strtotime($this->end_date));
    $current = $this->current; // boolean true/false

    if($current) // currently works at this job
    {
        $endDate = new DateTime(); // current date/time
        $endPretty = 'Present';
    }

    $diff = $endDate->diff($startDate);

    if($diff->y = 0)
    {
        if($diff->m > 1)
        {
            $string = $diff->m . ' months';
        }
        else
        {
            $string = '1 month';
        }
    }
    elseif ($diff->y = 1)
    {
        if($diff->m > 1)
        {
            $string = '1 year ' . $diff->m . ' months';
        }
        else
        {
            $string = '1 year 1 month';
        }
    }
    else
    {
        if($diff->m > 1)
        {
            $string = $diff->y . ' years ' . $diff->m . ' months';
        }
        else
        {
            $string = $diff->y . ' years 1 month';
        }
    }
    $output = $startPretty . ' - ' . $endPretty . ' ( ' . $string . ' )';
    return $output;

}

Here is some sample data:

$this->start_date = '2013-05-01';
$this->end_date = '2014-12-01';

or you can make $this->end_date = null; and $current = true;

It currently outputs:

  May 2013 - Present ( 1 year 7 months )

which is what it should do. I'm just curious if this could be done cleaner/simpler.


texts: Count the status messages in a column VBA

texts:
Can someone review my code and provide feedback. For context in column A will be a status message of "OK" or "NOK" and this little function just counts the number of times this appear so I can update a label in another procedure. Not too sure if this is the most efficient way of doing this because looping will create delay going row by row if the data set is very large as in the main procedure this function will be called to update the label is in a loop so depending on the size of the data it can be small or very large and will trigger this function for each row.
Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String
Dim OK As Long
Dim NOK As Long
Dim i As Long
Dim uploadMsg As String

If StartRow = 0 And EndRow = 0 Then Exit Function
With WS
    For i = StartRow To EndRow
        If .Range("A" & i).value = "OK" Then
            OK = OK + 1
        Else
            If .Range("A" & i).value <> vbNullString Then
                NOK = NOK + 1
            End If
        End If
    Next i
End With

If OK < 2 Then
    uploadMsg = OK & " OK row, "
Else
    uploadMsg = OK & " OK rows, "
End If

If NOK < 2 Then
    uploadMsg = uploadMsg & NOK & " NOK row"
Else
    uploadMsg = uploadMsg & NOK & " NOK rows"
End If
If strMsg <> vbNullString Then
    UploadStatus = strMsg & " " & uploadMsg
Else
    UploadStatus = uploadMsg
End If
End Function


texts: Walking and comparing contents of binary trees

texts:
I've written a solution for http://tour.golang.org/concurrency/8, which asks for a Walk() function to traverse a randomly generated binary tree, and a Same() function to check if two trees have the same values.

Is this solution is the most efficient? (I think that the Same function is not the most efficient solution, but I don't know how to make it better.)

package main

import "code.google.com/p/go-tour/tree"
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t == nil {
        return
    }
    Walk(t.Left, ch)
    ch <- t.Value
    Walk(t.Right, ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    c1 := make(chan int)
    c2 := make(chan int)
    go Walk(t1,c1)
    go Walk(t2,c2)
    for z:=0;z<10;z++ {
        if <-c1 != <-c2 {
            return false
        }
    }
    return true
}

func main() {
    ch := make(chan int)
    go Walk(tree.New(1), ch)
    for z:= 0; z<10; z++ {
        fmt.Println(<-ch)
    }
    fmt.Println(Same(tree.New(1), tree.New(1)) == true)
    fmt.Println(Same(tree.New(1), tree.New(2)) == false)
}


texts: Targeting specific elements with CSS only

texts:
This code below works as needed, but I am not sure if there is a more elegant way with pure CSS. I have a table with two columns, and 4+ rows. I'll actually upload a picture.  It's the first table in grey that I am messing with.

I want to select all the TDs--except for the first TD, because that first one has been changed to vertical text--and give them a 100% width and text align center. Any thoughts?

.greyBG tr:nth-of-type(1) ~ tr > td {
    width: 100%;
    text-align: center;
}

And the HTML:

               Landscape

               Lorum Ipsum

                Lorum Ipsum

                 Lorum Ipsum

                  Lorum Ipsum


texts: Handling parsing failure in Scala without exceptions

texts:
I have a Scala (Play!) application that must get and parse some data in JSON from an external service. I want to be able to gently handle failure in the response format, but it is becoming messy. What I am doing right now is, for instance,

def columnsFor(json: JsValue): Option[Map[String, String]] =
  try {
    val cols = (json \ "responseBody" \ "columns") match {
      case JsArray(xs) => xs map { col =>
        ((col \ "leafid").as[String], (col \ "name").as[String])
      }
      case _ => throw new Exception("Response unparsable")
    }
    Some(cols.toMap)
  }
  catch {
    case e: Exception => None
  }

That is, I go parsing optimistically and throw an exception whenever I find something that does not match my expected format (the methods as[String] also raise exceptions when they do not find strings). Then I recover from the exception and give back a None.

This approach is working and allows me to go from a potentially broken textual response to some type-safe data.

The problem is that having all these try..catch blocks looks ugly and messy. In theory it would be nicer to use optional types during all parsing steps. But then all my data structures become messy, as at each level you must have Options. When the data is deeply nested, I do not know how to handle failure at all levels. Moreover, I do not want to return something like an Option[Map[Option[String], Option[String]], but just an Option[Map[String, String]].

Is there some better/more idiomatic way to handle failures during parsing?

EDIT

I try to make the question more clear. Say I am expecting a response like

{
    "foo": [1, 2, 3],
    "bar": [2, 5]
}

I want to be able to parse it; taking failure into account I want to get something of type Option[Map[String, List[Int]]]. Now the problem is that parsing errors can appear at any level. Maybe I get a map with string keys, but its values are not lists. Or maybe the values are lists, but the content of the lists are strings instead of ints. And so on.

Whenever I want to parse a value, say as a string, I can choose between x.as[String] and x.asOpt[String]. The former will throw an exception when dealing with wrong input, while the latter returns a Option[String]. Similarly, when dealing with an array, I can do pattern matching like

x match {
  case JsArray(xs) => // continue parsing
  case _ => // deal with failure
}

I can deal with failure returning None or with an exception.

If I choose to use exceptions all along, then I can just wrap everything inside a try..catch and be sure to have handled all failures. Otherwise, my problem is that at any level, I have to put an option. So I have to

get something with an awful type like Option[Map[Option[String], Option[List[Option[Int]]]]]
find some way to flatten this all the way down to turn into the more manageable Option[Map[String, List[Int]]]

Of course, thing become even worse as soon as the JSON gets more nested.


texts:
Since my last tattoo resulted in a syntax error I was thinking of getting it peer reviewed this time around, are there any errors or quirks with this recursive Blum Blum Shub implementation that I have made?

f(_, _, 0) -> [];
f(M, S, N) -> R=S*S rem M, [R|f(M, R, N-1)].

% M - The modulo number
% S - The seed
% N - The number of pseudo random numbers to generate

Some simple tests:

zero_test() -> [] = f(5, 9, 0).
some_test() -> [9,81,82,36,42] = f(11*19, 3, 5).
static_test() -> [0,0,0,0,0,0,0,0,0,0] = f(1,1,10).


texts:
I've made the following to draw a series of zooming in images of a fractal.

using Distributed, FileIO, ImageCore, Images, ImageView

@everywhere function mandel_pow(z::Complex, p::Number)
    c = z
    maxiter::UInt8 = 255
    for n = 1:maxiter
        if abs2(z) > 4
            return n-1
        end
        z = z^p + c
    end
    return maxiter
end

@everywhere function mandel(z)
    mandel_pow(z, 2)
end

@everywhere function julia_pow(z::Complex, c::Complex, p::Number)
    maxiter::UInt8 = 255
    for n = 1:maxiter
        if abs2(z) > 4
            return n-1
        end
        z = z^p + c
    end
    return maxiter
end

@everywhere function julia(z)
    julia(z, 2)
end

function gen_frame(min_coord::Complex,
                       max_coord::Complex, res, fn)
    x_res, y_res = res
    arr = @distributed hcat for i in range(real(min_coord), real(max_coord), length=x_res)
        col = Vector{UInt8}(undef, y_res)
        for j in enumerate(range(imag(max_coord), imag(min_coord), length=y_res))
            col[j[1]] = fn(i+j[2]*im)
        end
        col
    end
    fetch(arr)
end

function zoom_in(image, zoom, scale)
    y_res, x_res = size(image)
    zoom = zoom/2
    xmin = 1+round(Int, x_res*(.5-zoom))
    xmax = round(Int, x_res*(.5+zoom))
    ymin = 1+round(Int, y_res*(.5-zoom))
    ymax = round(Int, y_res*(.5+zoom))
    v = @view image[ymin:ymax, xmin:xmax]
    imresize(v, div.(size(image), scale))
end

function draw_zoom(center, half_size, fps, seconds, fn)
    res = (1920,1080)
    scale = 2

    for t in 0:seconds
        print(t)
        zoom = scale^convert(Float64, -t)
        base = normedview(gen_frame(center - half_size*zoom,
                                    center + half_size*zoom,
                                    res.*scale, fn));
        println(size(base))
        for i in 0:fps
            zoom = scale^(-i/fps)
            save("mandel" * lpad(string(i+fps*t),4,'0') * ".jpg", zoom_in(base, zoom, scale))
        end
        println(" done.")
    end
end

c = -0.5-0im
half_size = 1.5+1im
draw_zoom(c, half_size, 1, 1, mandel)

It can draw 10 seconds of frames at 30fps in about a minute using all cores of my computer.
I'm specifically looking for ways to improve the way gen_frame is parallelized, and ideally make the saving zoomed in strings happen while the next computation is being done.


texts: Insertion Sort and Selection Sort Implementation

texts:
I wanted to practice using templates since I have no experience with them, so I implemented these sorting algorithms.

Selection Sort:

template<typename Container>
void selectionSort(Container& numbers)
{
    for (auto iter = std::begin(numbers), iterEnd = std::end(numbers); iter != iterEnd; ++iter)
    {
        auto minNum = minIndex(numbers, iter, iterEnd);

        std::swap(*iter, *minNum);
    }
}

template<typename Container, typename Iter>
Iter minIndex(const Container& numbers, Iter start, Iter end)
{
    Iter minIdx = start;
    auto minNum = *start;

    while (++start != end)
    {
        if (*start < minNum)
        {
            minNum = *start;
            minIdx = start;
        }
    }
    return minIdx;
}

Insertion Sort:

template<typename Container>
void insertionSort(Container& numbers)
{
    for (auto iter = std::begin(numbers) + 1, iterEnd = std::end(numbers); iter != iterEnd; ++iter)
    {
        if (*iter < *(iter-1))
        {
            resort(numbers, iter);
        }
    }
}
template<typename Container, typename Iter>
void resort(Container& numbers, Iter containerIter)
{
    auto temp = *containerIter;

    while (containerIter != std::begin(numbers) && temp < *(containerIter-1))
    {
        *containerIter = *(containerIter - 1);
        --containerIter;
    }

    *containerIter = temp;
}


texts:
I wrote a Python method to convert an object and a subset of its attributes into a JSON string with a given field as the key.

There's a lot of string concatenation, and I'm not too sure what the best way to do that in Python is.

I'm also wondering if attr.replace('"','\"') is sufficient to sanitize input.

def to_json_with_key(nodes, key, fields, insertIndex=False):
    i=0
    s="{"
    for node in nodes:
        s += '"%s":{' % getattr(node,key)
        attrs=[]
        for field in fields:
            attr = getattr(node,field)
            if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long):
                attrs.insert(0, '"%s":"%s"' % (field, attr.replace('"','\"') ))
            else:
                attrs.insert(0, '"%s":%s' % (field, attr ))

        if (insertIndex):
            s+='index:%d,' % i
            i=i+1

        s+=','.join(attrs) + "},"
    s = s.rstrip(",") + "}"
    return s

Sample input:

to_json_with_key(myObj, "title", fields=["length","time_offset"], insertIndex=True)

Sample output:

{"Introduction_to_Lists":{index:0,"length":128,"time_offset":0,
 "Pass_by_Reference":{index:1,"length":84,"time_offset":128}}


texts: Erlang handling errors in concurrent programs

texts:
I have two tasks:

  Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, restart it

Here is the code that I built:

proc() ->
    receive
        p -> exit("I need to die")
    end.

start_and_monitor(0) ->
    spawn_monitor(proc()),
    receive
        {'DOWN',_,process,_,_} -> spawn_monitor(proc())
    end;
start_and_monitor(Int) ->

    spawn_monitor(proc()),
    start_and_monitor(Int - 1).

  Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, kill all the worker processes and restart them all.

Here I thought that instead of monitoring all of the process I could link all the small processes and monitor a major process that is linked to all of them. Here is the code:

start_and_monitor_but_kill(Int) ->
{Pid,Ref} = spawn_monitor(start_monitor_kill(Int)),
receive
    {'DOWN', Ref, process, _, _} -> start_and_monitor_but_kill(Int)
end.

start_monitor_kill(0) ->
    spawn_link(proc());
start_monitor_kill(Int) ->
    spawn_link(proc()),
    start_monitor_kill(Int-1).

Is there any way that I can improve my code? Am I using all the erlang primitives correctly ? Any criticism is highly appreciated.

Also I am very curious if I used the primitives correctly. For example I used the monitor process without giving a ref. Is this acceptable in this case?


texts: Reading Excel (93-97) sheet with more than 65536 rows using cfspreadsheet

texts:
I have a process that reads multiple sheets from an Excel file, then inserts the data into a database table. However, I am experiencing some memory issues when one of the sheets contains more than 65536 rows and am looking for ideas on how to improve the code.

In summary, I am using cfspreadsheet to "read" an uploaded Excel file. (In most cases, the file contains a single sheet. However, in some cases it is more than 2 sheets.) The process always reads the first sheet ie "Details" . If more than 65533 rows are found, it then reads the second sheet too i.e. "Details_1". Finally, I use a QoQ and UNION ALL to create a combined query. Once read, the data is inserted into a database table.

Can anyone offer suggestions for improving the process to make it less memory intensive?

<cffunction name="putExcel" access="remote" returnFormat="plain" output="true">
    <cfargument name="xclfile" required="no" type="string" default="0">

    <cfset ins =insertUserLog("#Session.user_name#","#Session.user_code#","putExcel function called for  Upload","","")>

    <cftry>
        <cfset fileEXCL = "#ExpandPath('../folder')#/#arguments.xclfile#" />

        <!---when there e 2 Sheets --->
        <!---get info from  sheet1 as a "query1"--->
        <cfspreadsheet action="read" src="#fileEXCL#" sheet="1" query="Query1" headerrow="1" />
         <!--- recordcount for "sheet1" as "count1"--->
        <cfset count1 =#Query1.recordcount#>
        <!--- case when excel has more than 65533 rows
            ;THIS IMPLIES THAT THERE 2 SHEETS)--->
        <cfif count1 gt 65533>
         <!--- take info from  sheet 2 as a "query2" and count as "count2"--->
            <cfspreadsheet action="read" src="#fileEXCL#" sheet="2" query="Query2" headerrow="1"  />

            <cfset count2 =#Query2.recordcount#>
            <!---club both query's using QoQ and call it "excelQuery"--->
            <cfquery dbtype="query" name="excelQuery">
                SELECT * FROM Query1
                UNION ALL
                SELECT * FROM Query2
            </cfquery>
            <!---total record count for "sheet1" & "sheet2"--->
            <cfset rowCount =#excelQuery.recordcount#>
        <cfelse>
            <!---this case there is just 1 query "Query1" ;rename it "excelQuery"--->
            <cfquery dbtype="query" name="excelQuery">
                SELECT * FROM Query1
            </cfquery>
            <!--- recordcount for "sheet1"--->
            <cfset rowCount =#excelQuery.recordcount#>
        </cfif>

        <cflog file="Collections" application="yes"  text="#Session.user_info.uname# logged in. Data  file #fileEXCL# read. Recordcount:#rowCount#" type="Information">

        <cfset ins =insertUserLog("#Session.user_name#","#Session.user_code#","file #fileEXCL# read. ","Recordcount:#rowCount#","")>

        <cfcatch type="any" >
            <cflog file="Collections" application="yes" text="Error in reading Data  file #fileEXCL#." type="Error">
            <cfset ins =insertUserLog("#Session.user_name#","#Session.user_code#","error file","failed","#cfcatch.Message#")>
            <cfreturn 1>
        </cfcatch>
    </cftry>

    ... etc...


texts: Flash Memory block write counting & thresholding

texts:
I am trying to solve this question:

  In a block storage system, new data is written in blocks. We are going
  to represent the flash memory as one sequential array. We have a list
  of block writes coming in the form of arrays of size 2: writes[i] =
  [first_block_written, last_block_written].

  Each block has a rewrite limit. If rewrites on a block reach a certain
  specified threshold we should run a special diagnostic.

  Given blockCount (an integer representing the total number of blocks),
  writes (the list of block-write arrays of size 2), and threshold, your
  task is to return the list of disjoint block segments, each consisting
  of blocks that have reached the rewrite threshold. The list of block
  segments should be sorted in increasing order by their left ends.

  Example

  For blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]], and threshold
  = 2, the output should be blockStorageRewrites(blockCount, writes, threshold) = [[2, 5]].

  After the first write, the blocks 0, 1, 2, 3 and 4 were written in
  once
  After the second write, the blocks 0, 1, 2 and 5 were written in
  once, and the blocks 3 and 4 reached the rewrite threshold;
  After the final write, the blocks 2 and 5 reached the rewrite threshold as well,
  so the blocks that should be diagnosed are 2, 3, 4 and 5. Blocks 2, 3,
  4 and 5 form one consequent segment [2, 5]. For blockCount = 10,
  writes = [[0, 4], [3, 5], [2, 6]], and threshold = 3, the output
  should be blockStorageRewrites(blockCount, writes, threshold) = [[3,
  4]];

  For blockCount = 10, writes = [[3, 4], [0, 1], [6, 6]], and threshold
  = 1, the output should be blockStorageRewrites(blockCount, writes, threshold) = [[0, 1], [3, 4], [6, 6]].

I have come up with a correct naive solution here but it's too slow to pass the test cases:

def blockStorageRewrites(blockCount, writes, threshold):
    a = defaultdict(int)
    for (l, r) in writes:
        for i in range(l, r+1):
            a[i] += 1

    start = None
    res = []
    for i in range(0, blockCount+1):
        if a[i] >=threshold:
            if start is None:
                start = i
        elif a[i] < threshold and start is not None:
            res.append([start, i-1])
            start = None
    return res

How do I optimize it to run faster?


texts:
In researching the new .NET Async and Await keywords in .NET 4.5, I created a simple example showing how to update a progress bar and a label while an async function is running. I also included how to cancel the process while it is taking place.

To use the code below, create a Windows form and include two buttons:

Button1 = start button
Button2 = stop button

Also add a progress bar called ProgressBar1 and a label called Label1.

A few things to note:

The functions use ASYNC and AWAIT "all the way down" from the initial button click to the final VB function that supports asynchronous support;
Note the use of the cancellationtokensource to signal that we want to cancel things;
The final asynchronous VB function we use is WebClient.DownloadStringTaskAsync(). This is arbitrary, and is used for example purposes only.

Please let me know if you have any questions or problems with this code.

' Simple progress bar example with cancellation and label updating
' Using the ASYNC and AWAIT keywords available through .Net 4.5

' Helpful sources include:
' - http://msdn.microsoft.com/en-us/library/hh191443.aspx
' - http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx

Imports System.Net
Imports System.Threading

Public Class Form1

    Dim test As WebClient = New WebClient ' This is specific to the type of async function we're doing. Yours may be different.
    Dim myToken As CancellationTokenSource ' This is used to notify the async function that we want to cancel it.
    Dim myProgress As Progress(Of Integer) ' We use this as the vehicle for reporting progress back to our GUI thread

    Dim Counter As Integer = 0 ' This is a variable that we use to track our progress (specific to this example)

    Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ProgressBar1.Value = 0
        Counter = 0
        myToken = New CancellationTokenSource
        Await startProgressBar(myToken) ' Note that the signature of our startprogressbar method includes the cancellationtokensource
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If Not myToken Is Nothing Then
            myToken.Cancel() ' We tell our token to cancel
        End If
    End Sub

    Public Async Function startProgressBar(ct As CancellationTokenSource) As Task

        Dim progressTarget As Action(Of Integer) ' We have to create an event handler for the function we use to report progress
        progressTarget = AddressOf ReportProgress ' We assign the handler to our specific function (see below)
        myProgress = New Progress(Of Integer)(progressTarget) ' When we initialize our progress reporter, we pass our handler to it

        For I = 0 To 9

            If ct.IsCancellationRequested = True Then
                Exit For ' We then break out of the loop
            End If

            Dim myString As String = Await RetrieveString(myProgress) ' We don't do anything with this string, just so we can run our async function

        Next

    End Function

    Public Async Function RetrieveString(ByVal myProgress As IProgress(Of Integer)) As Task(Of String)

        Dim myString As String = ""

        If Not myProgress Is Nothing Then 'If we have a valid progress object, report our progress using it
            Counter = Counter + 10
            myProgress.Report(Counter)
        End If

        myString = Await test.DownloadStringTaskAsync("http://www.cnn.com") ' This is a throwaway function - just something that uses async
        Return myString ' We are really not doing anything with the results of this function, just returning it

    End Function

    Private Sub ReportProgress(ByVal myInt As Integer)
        Label1.Text = "Step Number: " & myInt.ToString
        ProgressBar1.Value = myInt
    End Sub

End Class


texts:
I'm just playing about with Go, and am trying to solve some project euler problems to get used to it.

I've created a generator function for Pythagorean triples, using a channel which returns a set of 3 integers for the sides, like so (HCF implements Euclid's algorithm for finding greatest common divisor or highest common factor in this part of the world):

package main
import "fmt"

func HCF(a, b int) int {
    if a % b == 0 {
        return b
    } else {
        return HCF(b, a%b)
    }
}

func PythagTriple() chan [3]int {

    ch := make(chan [3]int)

    go func() {
        for m := 2; ; m++ {
            for n := m%2 + 1; n < m; n += 2 {
                if HCF(m, n) == 1 {
                    var triple [3]int
                    triple[0] = m*m - n*n
                    triple[1] = 2 * m * n
                    triple[2] = m*m + n*n
                    ch <- triple
                }
            }
        }
    }()

    return ch
}

func main() {

    ch := PythagTriple()
    for i := 0; i < 10; i++ {
        fmt.Println(<- ch)
    }
}

Questions:

Do I need to do anything with the channel, or will it close and clean up when it goes out of scope?
Is there a better way of creating a quick array than how I've done it?
Is this idiomatic Go, or am I barking up the wrong tree entirely?  I've just started and am not sure if I'm doing it right!

Don't worry too much about efficiency of the algorithm; I'm not too concerned about speed at this point.


texts: Remotely collect server data using Net::OpenSSH Perl

texts:
I am newbie in Perl programming and currently trying to use Net::OpenSSH module in my code, my new code as below which the task is to run multiple command in remote server,

Code as below::

foreach $s (@servers) {
my $ssh = Net::OpenSSH->new("$username\@$s", timeout=>30);
$ssh->error and die "Unable to connect: " . $ssh->error;
print "Connected to $s\n";

my $fh = $ssh->capture("df -k /home/ | tail -1") or die "Unable to run command\n";
my @df_arr = split(/\s+/, $fh);
print "$s:  Disk space /home/ = $df_arr[3] \n";

my $fh1 = $ssh->capture("svmon -G -O unit=GB | grep memory") or die "Unable to run command\n";
my @sv_arr = split(/\s+/, $fh1);
print "$s:  Free memory = $sv_arr[3] \n\n";

close $fh;
undef $ssh;
}

This code is not so nice since I plan to simplify and reduce a line as many as possible.

Does there are any techniques or methods that I can use to simplify this code?


texts:
I wrote a simple extension to convert a number into a hours and minutes string in the ##:## format. This seems like a good way to do it, but let me know what you think.

Number.prototype.display_hours_minutes = function () {
  var remainder = this % 1;
  var remainderTime = new Date(remainder * 3600 * 1000);
  return ('0' + Math.floor(this)).slice(-2) + ':' + ( '0' + remainderTime.getMinutes()).slice(-2);
};

So this turns something like 53.34 into "53:20"


texts:
I'm starting C as my first language and am just under halfway done the book I'm using. However, I commonly hear about 'bad' programmers and 'bad' code whenever I encounter any sort of programming related discussion on the internet.

I've done some examples that do work as they should but, I want to make sure that when I eventually am able to contribute to projects on GitHub, etc. that I'm not screwing everything up and writing unmaintainable code.

Do these examples follow common best practices? I did have comments but took them out as the code should be easy enough to understand and it's the actual code I'm wondering about.

/*make a box*/
#include <stdio.h>
int main(void)
{
    int i = 0;
    int long length = 0;
    int long width = 0;
    printf("Enter Box dimensions (LxW):");
    scanf("%ld %ld", &length, &width);
    for(i = 0; i <= width; i++)
    {
        printf("*");
    }
    for(i = 0; i <= length; i++)
    {
        printf("\n*");
        for(int a = 0; a <= (width-2); a++)
        {
            printf(" ");
        }
        printf("*");
    }
    printf("\n");
    for(i = 0; i <= width; i++)
    {
        printf("*");
    }
    return 0;
}


texts:
Calling execv(3) (and similar functions) in C++ can be
problematic. execv expects an array of const pointers to
non-const char, and string literals are inherently const, so you have
to jump through hoops to convert your literals to non-const char arrays.
And of course in C++ you normally want to use vectors and strings
instead of arrays.

Not finding any standard functions to handle this, I wrote two wrapper
functions to make things easy. They seem to work correctly, in the ways
I thought to test, but I’m fairly new to C++; more experienced
developers may see any number of pitfalls I’ve missed.

My first version just used argv[0] as the path. Then I checked and
found good reasons for path != argv[0] in some cases, so I
overloaded it; one version is more general and one simplifies the call.

#include <cerrno>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>

#include <unistd.h>

int execv_cpp(const std::string &path,
              const std::vector<std::string> &argv);
int execv_cpp(const std::vector<std::string> &argv);

int main()
{
    // Test some failure modes.

    execv_cpp({});
    perror("execv() 1 failed");

    execv_cpp("/bin/ls", {});
    perror("execv() 2 failed");

    execv_cpp({"/foo/bar/baz"});
    perror("execv() 3 failed");

    execv_cpp({"/etc/passwd"});
    perror("execv() 4 failed");

    // Test valid calls.

    if (fork() == 0) {
        execv_cpp({"/bin/ls", "-lart"});
        perror("forked execv() unexpectedly failed");
        return 0;
    }

    usleep(50000);
    execv_cpp("/bin/ls", {"ls", "-lh"});
    perror("final execv() unexpectedly failed");

    return 0;
}

int execv_cpp(const std::string &path,
              const std::vector<std::string> &argv)
{
    /* Convert arguments to C-style and call execv. If it returns
     * (fails), clean up and pass return value to caller. */

    if (argv.size() == 0) {
        errno = EINVAL;
        return -1;
    }

    std::vector<char *> vec_cp;
    vec_cp.reserve(argv.size() + 1);
    for (auto s : argv)
        vec_cp.push_back(strdup(s.c_str()));
    vec_cp.push_back(NULL);

    int retval = execv(path.c_str(), vec_cp.data());

    int save_errno = errno;
    for (auto p : vec_cp)
        free(p);
    errno = save_errno;
    return retval;
}

int execv_cpp(const std::vector<std::string> &argv)
{
    /* Overloaded. Use first element as path for simpler call. */

    if (argv.size() == 0) {
        errno = EINVAL;
        return -1;
    }

    return execv_cpp(argv[0], argv);
}


texts:
Over the last few days I created this Pig Latin Translator just for fun. I would really appreciate it if anybody could give suggestions of how to improve the code and make the program more efficient.

Here is the GitHub link for the project.

For anybody who doesn't know the Pig Latin, feel free to look at the README, which explains what Pig Latin is, and the rules of the language. The code is in PigLatin.java.

    /*  -------------------- Program Information --------------------
    Name Of Program: PigLatin.java
    Date of Creation: 7/3/2018
    Name of Author(s): Agnik Banerjee
    Version of Java: 1.8.0_171
    Created with: IntelliJ IDEA 2017.3.5 Community Edition
    -------------------- Program Information --------------------  */

import java.util.Scanner;

public class PigLatin {

    private static Scanner scan = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.print("Enter one or more words that you would like to translate to Pig Latin: ");
        final String userInput = scan.nextLine();
        scan.close();

        String[] word = userInput.split(" "); // Splits the string into an array of words
        String output = "";

        for (int i = 0; i < word.length; i++) {
            String pigLatinWord = translateWord(word[i]); // Translates each word individually
            output += pigLatinWord + " "; // Joins the translated word back into the output
        }

        System.out.println("Original Word(s): " + userInput);
        System.out.println("Translation: " + output + "\n");
    }

    public static String translateWord(String word) {
        String lowerCaseWord = word.toLowerCase();
        int pos = -1; // Position of first vowel
        char ch;

        // This for loop finds the index of the first vowel in the word
        for (int i = 0; i < lowerCaseWord.length(); i++) {
            ch = lowerCaseWord.charAt(i);

            if (isVowel(ch)) {
                pos = i;
                break;
            }
        }

        if (pos == 0) {
            // Translating word if the first character is a vowel (Rule 3)
            return lowerCaseWord + "yay"; // Adding "yay" to the end of string (can also be "way" or just "ay")
        } else {
            // Translating word if the first character(s) are consonants (Rule 1 and 2)
            String a = lowerCaseWord.substring(pos); // Extracting all characters in the word beginning from the 1st vowel
            String b = lowerCaseWord.substring(0, pos); // Extracting all characters located before the first vowel
            return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
        }
    }

    // This method checks if the character passed is a vowel (the letter "y" is counted as a vowel in this context)
    public static Boolean isVowel(char ch) {
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
            return true;
        }
        return false;
    }
}


texts:
(function ($) {

    "use strict";

    $(document).ready(function () {

        $('.bookinginput').on('change', function(){

            var adults = $('#t_adults_qty').val(),
                    child =  $('#t_children_qty').val(),
                    pickup = $('#pick_up_list').val(),
                    priceBase = priceBooking.adult * adults,
                    priceChild = priceBooking.child * child;

            var price = priceBase + priceChild

            $('#price_total').val(price);
        })

    });
}(jQuery));

I will explain my code a bit, basically it is a small mathematical calculation based on the value of the inputs.

I have a json with the variable priceBooking, which has two values (Adult and Child), and I have several inputs with the numbers of the (adults and children).

I simply calculate the number of (Adults for the Adult price) the same with the children.

and the result I put it in the value of another hidden input (#price_total)

I would like to simplify this code or improve it. I want to be able to work with variables globally and not have to duplicate code.

Any suggestions?


texts: Directly initialize variable from std::istream

texts:
For some time it has been bothering me that there is apparently no way to directly initialize variables from input streams (something like int i << std::cin;)

My solution is this:

#include <iostream>
#include <iomanip>
#include <string>

template<class T>
T get(std::istream& in){
    T tmp;
    in >> tmp;
    return tmp;
}

template<class T,class A, class... ARGS>
T get(std::istream& in, A& arg, ARGS&... args){
    in >> arg;
    return get<T>(in, args...);
}

int main() {
    int i = get<int>(std::cin);
    std::cout << i << std::endl;

    std::string s = get<std::string>(std::cin , std::setw(5));
    std::cout << s << std::endl;
}

I'd like to know if

I can improve something on the design
There are serious performance implications
There are corner cases where this will not work or even worse produce silent errors.
I've overlooked any standard functions/classes that already implement that functionality.


texts: Determine hour in other countries with generated random time

texts:
I hope the title is clear. The objective is as following:

  There are 4 clocks in a hotel in London. One is showing the time for
  London. The others for New York, Tokyo and Hong Kong.

  Generate a random time for the clock in London, with that result,
  determine the hour for New York(+5), Tokyo(-9) and Hong Kong(-8). Then
  show the results.

This is not homework, this is practice. Is this a good way? Or can i generate a random timespan? All input will be appreciated!

Random generator = new Random();

DateTime london = DateTime.Now;

DateTime timeInLondon = london.AddMinutes(generator.Next());

DateTime timeInNewYork = timeInLondon.AddHours(5);
DateTime timeInTokyo = timeInLondon.AddHours(-9);
DateTime timeInHongKong = timeInLondon.AddHours(-8);

Console.WriteLine("London: " +london.ToShortTimeString() +"\n" +"New York: " +timeInNewYork.ToShortTimeString() + "\n" +"Tokyo: " +timeInTokyo.ToShortTimeString() + "\n" +"Hong Kong: " +timeInHongKong.ToShortTimeString());


texts: Is there a better version for verbosing the output of the euclidean method?

texts:
Here is my implementation of the Euclidean Algorithm. My question is how to make it more "professional". It's working right, but isn't this too newbie?

public class Euklideszi {

    public int Euklideszi(int a, int b, boolean lepesrolLepesre) {
        int r = a % b;
        if (a < b) {
            r = a;
            a = b;
            b = r;
        }
        if (a % b == 0) {
            if (lepesrolLepesre) {
                System.out.println("A legnagyobb közös osztó: " + b);
            }
            return b;
        } else {
            while (r != 0) {
                r = a % b;
                if (lepesrolLepesre) {
                    System.out.println(a + "=" + a / b + "*" + b + "+" + r);
                }
                a = b;
                b = r;
            }
            if (lepesrolLepesre) {
                System.out.println("A legnagyobb közös osztó: " + a);
            }
            return a;
        }

    }

 }


texts: Counts instances for each category for many Matlab files

texts:
This is for machine learning.  I have 5 matlab files: AWA, REM, S1, S2, SWS.
Each one has 2 arrays: x and y. y are the labels. I want to know the number of instances for each category in each file:

I load the matlab file

I convert from f8 to int32

If I do not use ravel, bincount will not work

I count the instances for each category in the file
I repeat these 4 steps 5 times (as there are 5 files). Is there a way to do it better?

Then I just join all the vectors in one array to send them to PANDAS.

#AWA
awa_y=sio.loadmat('/home/AWA_FeaturesAll.mat')['y']
awa_y=awa_y.astype('int') #from f8 to int32
awa=np.ravel(awa_y) #needed in order to use np.bincount()
AWA=np.bincount(awa)

#Rem
rem_y=sio.loadmat('/home/Rem_FeaturesAll.mat')['y']
rem_y=rem_y.astype('int')
rem=np.ravel(rem_y)
REM=np.bincount(rem)

#S1
s1_y=sio.loadmat('/home/S1_FeaturesAll.mat')['y']
s1_y=s1_y.astype('int')
s1=np.ravel(s1_y)
S1=np.bincount(s1)

#S2
s2_y=sio.loadmat('/home/S2_FeaturesAll.mat')['y']
s2_y=s2_y.astype('int')
s2=np.ravel(s2_y)
S2=np.bincount(s2)

#SWS
sws_y=sio.loadmat('/home/SWS_FeaturesAll.mat')['y']
sws_y=sws_y.astype('int')
sws=np.ravel(sws_y)
SWS=np.bincount(sws)

#Joining the 5 vectors
table= (np.vstack((AWA, REM, S1, S2, SWS))).T
TABLE = np.delete(table, (0), axis=0)
print(TABLE)


texts:
I'm trying to learn learning javascript and jQuery plugin standards, and after some googling and testing I've come up with this pattern:

;(function(window, document, $, undefined){
  var plugin = function(element){
    var instance = this,
        somePrivateFunc = function(){
          console.log(instance.options);
        };

    this.options = $(element).data();
    this.publicFunc = function(){
     somePrivateFunc();
    };
  }

  $.fn.myplugin = function(){
    return this.each(function(){
      if(!$(this).data('_myplugin')){
        var myplugin = new plugin(this);
        myplugin.publicFunc();
        $(this).data('_myplugin', myplugin);
      }
    });
  }

}(window, document, jQuery));

Example

http://jsfiddle.net/4NAXb/

Is this OK? Do you have any suggestions on improving it? Thanks!


texts:
I need my code to be reviewed if there is any mistake in my code, as I am wondering of getting 14 perplexity rate, is it correct?
import os, nltk
import requests
import io #codecs
from nltk.util import pad_sequence
from nltk.util import bigrams
from nltk.util import ngrams
from nltk.util import everygrams
from nltk.lm.preprocessing import pad_both_ends
from nltk.lm.preprocessing import flatten
from nltk import word_tokenize, sent_tokenize, bigrams,trigrams
import os
import requests
import io #codecs
import pandas as pd
if os.path.isfile('file.txt'):
    with io.open('file.txt', encoding='utf8') as fin:
        text = fin.read()
else:
    print('file not found')

words = text.split()
print('Number of words in text file :', len(words))

# Train on 80% f the corpus and test on the rest
split = int(80*len(text)/100)
train = text[:split]
test = text[split:]

train_word =  nltk.word_tokenize(train)
print('Number of words in text file :', len(train_word))

test_word = nltk.word_tokenize(test)
print('Number of words in text file :', len(test_word))

from nltk.lm.preprocessing import padded_everygram_pipeline
from nltk.lm import MLE,Laplace
from nltk.lm import Vocabulary

n = 2
train_data, padded_vocab = padded_everygram_pipeline(n, train_word)
model = Laplace(1)
model.fit(train_data, padded_vocab)

test_data, _ = padded_everygram_pipeline(n, test_word)
s = 0
for i, test in enumerate(test_data):
    p = model.perplexity(test)
    s += p

print ("Perplexity: {0}".format(s/(i+1)))


texts: Converting and enriching an array of data

texts:
The method below converts an array of TheatreListData objects to an array of TheatreListDataWrapper. It also loads additional attributes such as patientIdentifierNumber and requestText to enrich the converted data.

This method is called by many EJBs, and so I'm especially looking for ways to improve performance.

/**
* Converts TheatreListDatas into TheatreListDataWrappers. This also
* loads the attributes that has to be generated from client such as
* patientIdentifierNumber, requestText
*
* @param theatreListData
* @return TheatreListDataWrapper[]
*/
public TheatreListDataWrapper[] wrapData(TheatreListData[] theatreListData){

    TheatreListDataWrapper[] wrapperList = wrapDataWithoutRequestData(theatreListData);

    if (wrapperList != null && wrapperList.length > 0)
    {
      Set<String> requestIds = new HashSet<String>();

      for (TheatreListData listData : theatreListData)
      {

        // Collect request id for each List Data into a set
        String requestId = listData.getCarePlan().requestId;
        //Should check for '-1' here to avoid calls to fetch invalid requests.
        //'-1' could have been saved with registrations with 'None' requests.
        if (requestId != null && requestId.trim().length() > 0 && !requestId.equals("-1"))
        {
          //Since adding to a set no duplicates are possible.
          requestIds.add(requestId);
        }
      }

      //Load request Id, request Text map using the collected request ids.
      Map<String, String> requestMap = Collections.emptyMap();
      if (!requestIds.isEmpty())
      {
        requestMap = getRequestDelegator().getRequestPresentationStringsByIds(new ArrayList<String>(requestIds));
      }

      //Create wrappers & fill with loaded data.
      for (int i = 0; i < theatreListData.length; i++)
      {
        TheatreListDataWrapper wrapper = wrapperList[i];

        TheatreListData listData = theatreListData[i];
        String requestId = listData.getCarePlan().requestId;
        if (requestId != null && requestId.trim().length() > 0)
        {
          wrapper.requestText = requestMap.get(requestId) != null ? requestMap.get(requestId) : "";
        }

        wrapperList[i] = wrapper;
      }

    }
    return wrapperList;

  }


texts:
I'm learning to set up systemd file-transfer & related services (samba, ftp, http..). So far it's all LAN or WLAN.
The configuration file for most these services is under /etc/<bin>.conf (like smbd.conf or vsftpd.conf). Because systemd services running on port < 1000 have to be run as root. (systemd --user won't work.)
The idea is that the users connect to a directory, anonymous users only have read privileges, local users read and write. (I am guessing anonymous won't be treated as local user, but this still needs testing). Also from the manpages anonymous_enable

Controls whether anonymous logins are permitted or not. If enabled, both the usernames ftp and anonymous are recognised as anonymous logins.

Communication is TLS encrypted just to avoid people sniffing in the LAN.
# GENERAL

listen_ipv6=YES
# accept connections from IPv6 and IPv4 clients.

write_enable=YES
# enable any form of FTP write command.
# choose no for FTP read-only sites.

connect_from_port_20=YES

# LOGS

xferlog_enable=YES
# Activate logging of uploads/downloads.

xferlog_file=/home/minsky/logs/ftp/vsftpd.log

# TIMEOUTS

idle_session_timeout=600 #10 min
data_connection_timeout=30

# SECURITY (encrypt connections)
# Certificate and private file generated with openssl.

rsa_cert_file=/etc/pki/tls/certs/ftp_cert.crt
rsa_private_key_file=/etc/pki/tls/certs/FTP.key

ssl_enable=YES
allow_anon_ssl=YES
ssl_tlsv1=YES
ssl_ciphers=HIGH
require_ssl_reuse=NO

# Anonymous user (ftp)
ftp_username=anonymous
# cat /etc/passwd: anonymous:x:996:996:ftp anonymous:/home/anonymous:/bin/bash
anonymous_enable=YES
# user:ftp or anonymous
anon_upload_enable=YES
# upload files.
no_anon_password=YES
#no password
anon_root=/home/minsky/public
#switch to

anon_mkdir_write_enable=NO
anon_other_write_enable=NO

# Local users (will need pwd unless is user "anonymous")

local_enable=YES
# Allow local users to log in.

local_root=/home/minsky/
# switch to dir

# Special user (requested by vsftpd config file)
nopriv_user=unprivileged # cat /etc/passwd: unprivileged:x:997:997:FTP unprivileged acc:/home/unprivileged:/sbin/nologin

# Customization
#secure_chroot_dir=/var/run/vsftpd/empty #necessary
ftpd_banner=Welcome to Raspberry Pi FTP service.
#

I think one problem here could be that the user could move off the /public directory, though I'm still to test this.
Any recommendations or questions about the configuration file or the process are really welcome.


texts:
Please feel free to be as harsh as possible.

Implementation file:

#include "Stack.h"
#include <iostream>
using namespace std;

// Initializes an empty Stack.
Stack::Stack() {
    this->head = new node();
    this->num_elements = 0;

    // set default values for head
    this->head->next = 0;
    this->head->value = 0;
}

// Cleans up memory before the Stack's destruction.
Stack::~Stack() {
    while (this->head->next != 0) {
        pop();
    }
    delete this->head;
}

// Pushes value onto the top of the stack.
void Stack::push(int value) {
    node* newTopNode = new node();
    newTopNode->value = value;

    // currentTopNode may be null if stack is empty
    node* currentTopNode = this->head->next;

    this->head->next = newTopNode;
    newTopNode->next = currentTopNode;

    this->num_elements++;
}

// Pops the top-most value off the stack and returns its value.
int Stack::pop() {
    if (this->head->next == NULL) {
        cout << "\nIllegal State Exception: You cannot pop an empty stack." << endl;
        return 0;
    } else {
        node* topNodeToRemove = this->head->next;

        // save the value of the node before deleting it
        int topNodeValue = topNodeToRemove->value;

        this->head->next = this->head->next->next;

        delete topNodeToRemove;
        this->num_elements--;

        return topNodeValue;
    }
}

// Returns the value at the top of the stack.  Works similarly to pop(), but
// retains the internal structure of the stack.  That is, it does not remove
// the top-most element.
int Stack::getTopElement() const {
    if (this->head->next == NULL) {
        cout << "\nIllegal State Exception: You cannot get the top element of an empty stack." << endl;
        return 0;
    } else {
        return this->head->next->value;
    }
}

// Returns the number of elements currently in the stack.
int Stack::size() const {
    return this->num_elements;
}

Header file:

#ifndef STACK_H_
#define STACK_H_

class Stack {
public:
    Stack();
    ~Stack();
    void push(int);
    int pop();
    int getTopElement() const;
    int size() const;

private:
    struct node {
        int value;
        node* next;
    };

    node* head;
    int num_elements;
};

#endif // STACK_H_


texts: Tarjan's strongly connected components algorithm

texts:
Can anyone suggest to me how I can make this "nicer"? If you can see any glaring details that I could change to speed things up too, that would be great -- though it's not priority.

public class Tarjans {

    private static class Node {
        // -1, -1, our node is unvisited
        // by default.
        public int index = -1, lowLink = -1;
        public String name;

        public Node(String name) {
            this.name = name;
        }

        public String toString() {
            return name;
        }
    }

    // graph representation
    HashMap<String, Node> nodes = new HashMap<>();
    HashMap<String, ArrayList<Node>> graph = new HashMap<>();

    private int index = 0;

    // for a DFS, basically
    private ArrayDeque<Node> visited = new ArrayDeque<>();
    private HashSet<String> stack = new HashSet<>();

    // stores our strongly connected componts
    // from the algorithm pass
    private HashSet<HashSet<Node>> scc = new HashSet<>();

    public HashSet<HashSet<Node>> tarjan() {
        for (Node n : nodes.values()) {
            if (n != null && n.index == -1) {
                strongConnect(n);
            }
        }
        return scc;
    }

    private void strongConnect(Node node) {
        node.index = index;
        node.lowLink = index;
        index += 1;

        visited.push(node);
        stack.add(node.name);

        ArrayList<Node> neighbours = graph.get(node.name);
        if (neighbours != null) {
            neighbours.forEach(n -> {
                if (n.index == -1) {
                    strongConnect(n);
                    node.lowLink = Math.min(node.lowLink, n.lowLink);
                }
                else if (stack.contains(n.name)) {
                    node.lowLink = Math.min(node.lowLink, n.index);
                }
            });
        }

        if (node.lowLink == node.index) {
            HashSet<Node> cycle = new HashSet<>();
            while (true) {
                Node p = visited.pop();
                stack.remove(p.name);
                cycle.add(p);

                if (p == node) {
                    break;
                }
            }
            if (cycle.size() > 1) {
                scc.add(cycle);
            }
        }
    }

    private void foo() {
        nodes.put("bs", new Node("bs"));
        nodes.put("a", new Node("a"));
        nodes.put("b", new Node("b"));
        nodes.put("c", new Node("c"));

        graph.put("bs", new ArrayList<>(Arrays.asList(nodes.get("a"))));
        graph.put("a", new ArrayList<>(Arrays.asList(nodes.get("b"))));
        graph.put("b", new ArrayList<>(Arrays.asList(nodes.get("c"))));
        graph.put("c", new ArrayList<>(Arrays.asList(nodes.get("a"))));

        HashSet<HashSet<Node>> cycles = tarjan();
        for (HashSet<Node> cycle : cycles) {
            System.out.println("[" + cycle.stream().map(Node::toString).collect(Collectors.joining(",")) + "]");
        }
    }

    public static void main(String[] args) {
        new Tarjans().foo();
    }

}


texts: Generation of all numbers of arbitrary length and base

texts:
quux (['0'..9'] ++ ['A'..F']) 2 generates hexademical numbers of length 2 (with leading zeros), but it's obviously possible to generate any base and any length.

quux digits length = iterate foo return !! length $ [] where
    foo bb aa = map (: aa) digits >>= bb

Can this code be simplified, while retaining the idea of iterating in list monad?


texts: Abstracting async hooks out from components

texts:
A component displays a list of values and I'm trying to hide everything about how those values are gotten, essentially divorcing concerns about state away from the component itself so that in the future any changes to which API data is fetched from, what store is used, etc won't effect the component.
First, is this a good idea at all or should mount/unmount actions be handled directly in the component?
Second, if it is a good approach, how is my implementation? I'm feeling comfortable in JS but am not an expert
ContentList.js:
import React from 'react'

import './ContentList.css'

import { ContentCardContainer } from '../ContentCard/ContentCard'
import { getPostSummaries } from '../../Utils/ContentAPI'

import { Grid } from '@material-ui/core'

export function ContentListContainer(props) {
  const posts = getPostSummaries()

  return <ContentList posts={posts} />
}

function ContentList(props) {
  return  (
    <div className='content-list'>
      <Grid container >
        {props.posts.map((post, id) =>
          <Grid item xs={12} sm={12} lg={6}>
            <ContentCardContainer
              key={id}
              id={id}
              title={post.title}
              summary={post.summary}
              link={'post/' + post.title}
            />
          </Grid>
        )}
      </Grid>
    </div>
  )
}

ContentApi.js:
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { setContent, setSummaries } from '../Store/Actions'
import axios from 'axios'

const apiRoot = '/api'

export const getPostByID = (id) => {
    const dispatch = useDispatch()

    useEffect(() => {
      axios.get(apiRoot+'/post', {params: {id}})
        .then(resp => dispatch(setContent(resp.data.content)))
        .catch(() => dispatch(setContent('')))

        return () => dispatch(setContent(''))
    }, [])

    return useSelector(state => state.content)
}

export const getPostSummaries = () => {
  const dispatch = useDispatch()

  useEffect(() => {
    axios.get(apiRoot+'/post-summaries')
      .then(resp => dispatch(setSummaries(resp.data.posts)))
      .catch(() => dispatch(setSummaries([])) )
  }, [])

  return useSelector(state => state.summaries)
}


texts:
Project Euler Problem 76 asks:

  How many different ways can one hundred be written as a sum of at least two positive integers?

My code is correct but just works slowly.

import time
start = time.perf_counter()

def con(H):
    J = []
    Q = []
    W = []
    for i in H:
        for j in range(len(i)-1):
            Cop = i[::]
            y = i[j]+i[j+1]
            del Cop[j:j+2]
            Cop.insert(j,y)
            J.append(Cop)
    for i in J:
        y =(sorted("".join(str(j) for j in i)))
        Q.append("".join(y))
    T = list(set(Q))
    for i in T:
        y = [int(j) for j in i]
        W.append(y)
    return W

num = 5
K = [[1 for i in range(num)]]
count = 0
for i in range(len(K[0])-2):
    K = con(K)
    print(K)
    count = count + len(K)
print(count+1)
end = time.perf_counter()
print(end-start,"second")

Here what this code does. For example, let us say num = 4. Then it creates an array of

[[1,1,1,1]]. Then it sums the consecutive numbers so our result becomes (from line 9-14)

[[2,1,1],[1,2,1],[1,1,2]] Since they are all same my code (from line 15-18) makes them just one function and returns ["112"] and then from 18-21 turns ["112"] to [[1,1,2]] and then I do this whole process again for the [[1,1,2]] and then I count the number of these arrays (from 25-29). The problem is its fast up to num = 20-30 but then it really slows down. Is there a way to increase the speed of my code or should I try a different algorithm?