texts:
At the end of the Day 1 Go Course slides (pdf) there is an exercise stated as follows (NOTE: the course in the linked presentation is considered obsolete. If you are looking to learn Go the suggested route is first via http://tour.golang.org):

  You all know what the Fibonacci series is. Write a package to implement it. There should be a function to get the next value. (You don't have structs yet; can you find a way to save state without globals?) But instead of addition, make the operation settable by a function provided by the user. Integers? Floats? Strings? Up to you.

How does the following solution rate with respect to its 'Go'-iness?

package fib

type BinOp func (uint64, uint64) uint64

func fib_intern(a, b uint64, op BinOp) uint64 {
    Fib = func(opnew BinOp) uint64 {
        return fib_intern(b, op(a,b), opnew)
    }
    return a
}

var Fib = func(op BinOp) uint64 {
    return fib_intern(0,1,op)
}

Which can then be called like:

package main

import (
    "./fib"
    "fmt"
)

func add(a, b uint64) uint64 {
    return a+b
}

func main() {
    for i := 0; i < 20; i++ {
        fmt.Println(fib.Fib(add))
    }
}


texts: Binary Search tree deletion optimization

texts:
I have just started implementing Binary Search tree on my own without using any tutorials online.
Please have a look and suggest how can I make code less cluttered and more faster. Right now I am using lots of if-else conditions and want to remove them as much as I can.

boolean deleteNode(int data, TreeNode node )
{
    if( data < node.key) deleteNode(data, node.left);
    else if( data > node.key) deleteNode(data, node.right);

    else {
        System.out.println("Value of node = " + node.key);
        //case 1 - Left and Right is null - Leaves
        if(node.left == null && node.right == null)
        {
            if(node == node.parent.left)node.parent.left =  null;
            else node.parent.right = null;
            System.out.println("Inside first if");
        }

        //case 2 - One child is null

        else if(node.left !=null && node.right ==null)

        {
            if(node == node.parent.left)node.parent.left = node.left;
            else node.parent.right = node.left;

        }
        else if(node.right !=null && node.left ==null)
        {
            if(node == node.parent.right)node.parent.right = node.right;
            else node.parent.left = node.right;
        }

        //case 3 - Delete node is an internal node

        else if(node.left !=null && node.right !=null)
        {
            TreeNode minNode = treeMin(node.right);

            if(minNode.parent == node)
            {
                if(node.parent == null)
                    {
                        node.key = minNode.key;
                        node.right = minNode.right;
                    }
                else{
                if(node == node.parent.left)
                    {
                        node.parent.left.key = minNode.key;
                        node.parent.right.right = minNode.right;

                    }
                if(node == node.parent.right)
                    {
                        node.parent.right.key = minNode.key;
                        node.parent.right.right = minNode.right;
                    }
                }
            }

            else
            {
                if(node == node.parent.left)
                {
                    node.parent.left.key = minNode.key;
                    node.left.right = minNode.right;

                }
                else if(node == node.parent.right)
                {

                    node.parent.right.key = minNode.key;
                    node.right.left = minNode.right;

                }
            }
        }

    }
    return true;

}


texts:
I have a text file with about a hundred code value pairs [$code, Value].

For example:

Sample file

$codeA
valueOfA
$codeB
valueofB
.
.
.

These values need to be initiated into textFields, radioButtons, checkBoxes, etc over "several panels" contained within a main Controller panel. I switch between panels through a simple card layout.

I read through the lines and use if/else statements to get values for the fields, which isn't efficient. I was wondering if there is a better approach, a more elegant approach maybe.

    /*
 * read File
 */
private void readFile() {
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.equals("$codeA")) {
                panel1.txtFieldA.setText(br.readLine()));
            } else if (line.equals("$codeB")) {
                panel2.txtFieldB.setText(br.readLine()));
            }
            //.....
            //.....
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


texts:
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it and it will have to last the whole day. He creates a list of what he wants to bring for the trip but the total weight of all items is too much. He then decides to add columns to his initial list detailing their weights and a numerical value representing how important the item is for the trip.

I decided to solve the knapsack problem by a greedy algorithm. I am not sure of the need of the Item class, maybe another data structure is better?

from __future__ import division

class Item:
    def __init__(self, weight, value):
        self.weight = weight
        self.value = value
        self.convenience = value / weight

    def __repr__(self):
        return "Item({}, {})".format(self.weight, self.value)

class Knapsack:
    def __init__(self, capience, items_inside=[]):
        self.capience = capience
        self.items_inside = items_inside

    def current_weight(self):
        return sum(item.weight for item in self.items_inside)

    def is_full(self):
        return self.current_weight() == self.capience

    def can_incorporate(self, item):
        return self.current_weight() + item.weight <= self.capience

    def fill(self, items):
        while not self.is_full():
            self.items_inside.append(
                max((item for item in items if self.can_incorporate(item)),
                key= lambda item: item.convenience))

    def __repr__(self):
        return "Knapsack({}, {})".format(self.capience, self.items_inside)

def main():
    bag = Knapsack(54)
    bag.fill([
        Item(12, 8),
        Item(20, 13),
        Item(4, 2),
        Item(1, 0.1)])
    print(bag)

if __name__ == "__main__":
    main()


texts:
This is a followup to:

Pointer class/handle

Please review this pointer class.

template<typename T>
class Ptr {
public:
    Ptr(T* t, int s = 1) {
        sz = s;
        p = new T[sz];
        for (int i = 0; i < sz; ++i) {
            p[i] = t[i];
        }
    }

    Ptr(const Ptr& t) {
        sz = t.sz;
        p = new T[sz];
        T* x = t.get();
        for (int i = 0; i < sz; ++i) {
            p[i] = x[i];
        }
    }

    Ptr& operator=(const Ptr& t) {
        Ptr copy{t};
        std::swap(copy.sz, sz);
        std::swap(copy.p, p);
        return *this;
    }

    Ptr(Ptr &&t) :p{t.p}, sz{t.sz} {
        t.p = nullptr;
        t.sz = 0;
    }

    Ptr& operator=(Ptr &&t) {
        std::swap(t.p,p);
        std::swap(t.sz,sz);
        return *this;
    }

    T& operator*() {
        check_range();
        return *p;
    }

    T& operator[](int i) {
        check_range(i);
        return p[i];
    }

    T* get() const {
        return p;
    }

    void operator+=(int i) {
        check_range(index+i);
        index += i;
        p+= i;
    }

    void operator-=(int i) {
        check_range(index-i);
        index -= i;
        p -= i;
    }

    Ptr operator+(int i) {
        Ptr old{*this};
        old+=i;
        return old;
    }

    Ptr operator-(int i) {
        Ptr old{*this};
        old-= i;
        return old;
    }

    Ptr& operator++() {
        operator+=(1);
        return *this;
    }

    Ptr operator++(int) {
        Ptr<T> old{p};
        operator++();
        return old;
    }

    Ptr& operator--() {
        operator-=(1);
        return *this;
    }

    Ptr operator--(int) {
        Ptr<T> old{p};
        operator--();
        return old;
    }

    ~Ptr() {
        delete[] p;
    }

private:
    T* p;
    int sz;
    int index = 0;

    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
    }

    void check_range() {
        if (p == nullptr) {
            throw std::out_of_range("null pointer");
        }
    }

};


texts:
This is a program to return the sum of pairwise Hamming Distance of the binary string representation of a vector of integers. Please let me know how I can make this better?

int Solution::hammingDistance(const vector<int> &A) {
    vector<string> binrep;
    int N=A.size();
    int i,j, rem, n;
    for(i=0;i<N;i++){
        n=A[i];
        string bin;
        if (n == 0){
            bin.push_back((char)('0'));
            binrep.push_back(bin);
            continue;
        }
        while (n > 0) {
        rem = n % 2;
        bin.push_back((char)('0' + rem));
        n /= 2;
        }
        binrep.push_back(bin);
    }
    int ans=0;
    for(i=0;i<N;i++){
        for(j=i+1;j<N;j++){
            int k = 0, count = 0;
            while (binrep[i][k] != '\0' && binrep[j][k] !='\0')
            {
                if (binrep[i][k] != binrep[j][k])
                    count++;
                k++;
            }
            if(binrep[i][k] == '\0' && binrep[j][k]!='\0'){
                while (binrep[j][k] !='\0'){
                    if(binrep[j][k]=='1')
                        count++;
                    k++;
                }
            }
            else if (binrep[i][k] != '\0' && binrep[j][k]=='\0'){
                while (binrep[i][k] !='\0'){
                    if(binrep[i][k]=='1')
                        count++;
                    k++;
                }
            }
            ans+=count*2;
            ans=ans%1000000007;
        }
    }
    return(ans);
}


texts: Methods to create C# dictionaries, with static keys/values, in fluent notation

texts:
I created these little utility methods to build fluent C# dictionaries. The value declarations shall be quick to write and easy to comprehend when somebody views the code. Usage conditions are as follows:

many keys point to the same values
group keys pointing to one value. Declare value only once for better visual comprehension.
only relatively few values (usually 10 to 20, rarely up to 100)
main application purpose: replace switch-case blocks in legacy code

The keys/values can also be added otherwise, such as from all constants or Resource content, and can be of any type useful to be declared in code.

In addition, I created an extension convenience method: simply .ToDictionary(), instead of constructor lambdas kv => kv.Key, kv => kv.Value

Is this good, or are there any problems or better ideas? What about performance when used frequently, compared to switch-case?

Usage/test:

class Program
{
    public const string RoadVehicles = "RoadVehicles";
    public const string RailVehicles = "RailVehicles";
    public const string Watercraft = "Watercraft";
    public const string Aircraft = "Aircraft";

    public static readonly IReadOnlyDictionary<string, string> GroupsForVehicles =
        FluentDictionaries.KeysToValue(
            RoadVehicles, "Car", "Truck", "Tractor", "Motorcycle")
        .KeysToValue(
            RailVehicles, "Locomotive", "Railcar", "Powercar", "Handcar")
        .KeysToValue(
            Watercraft, "Ship", "Sailboat", "Rowboat", "Submarine")
        .KeysToValue(
            Aircraft, "Jetplane", "Propellerplane", "Helicopter", "Glider", "Balloon")
        .ToDictionary();

    static void Main(string[] args)
    {
        foreach (var key in GroupsForVehicles.Keys.OrderBy(key => key))
        {
            Console.WriteLine(key + ": " + GroupsForVehicles[key]);
        }
        Console.ReadLine();
    }
}

The fluent methods:

public static class FluentDictionaries
{
    public static IEnumerable<KeyValuePair<TKey, TValue>> KeysToValue<TKey, TValue>(TValue value, params TKey[] keys)
    {
        return keys.Select(key =>
            new KeyValuePair<TKey, TValue>(key, value));
    }

    public static IEnumerable<KeyValuePair<TKey, TValue>> KeysToValue<TKey, TValue>(
        this IEnumerable<KeyValuePair<TKey, TValue>> previous, TValue value, params TKey[] keys)
    {
        return previous.Concat(keys.Select(key =>
            new KeyValuePair<TKey, TValue>(key, value)));
    }

    public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
    {
        return keyValuePairs.ToDictionary(kv => kv.Key, kv => kv.Value);
    }
}

Test output of the program above:

Balloon: Aircraft

Car: RoadVehicles

Glider: Aircraft

Handcar: RailVehicles

Helicopter: Aircraft

Jetplane: Aircraft

Locomotive: RailVehicles

Motorcycle: RoadVehicles

Powercar: RailVehicles

Propellerplane: Aircraft

Railcar: RailVehicles

Rowboat: Watercraft

Sailboat: Watercraft

Ship: Watercraft

Submarine: Watercraft

Tractor: RoadVehicles

Truck: RoadVehicles


texts:
I was thinking about how I was going to use some enums I made, how I was going to make sure they had valid values and how to call the class which would contain the necessary extensions methods. And then I thought: why not wrap the enum in a struct. I wrote up a little example code and it looks like this (ignore the fact that it's a very common day enum, I needed something as an example):

public struct Day
{
    private enum DayE
    {
        Monday = 1,
        Tuesday,
        Wednesday,
        Thursday,
        Friday
    }

    private readonly DayE value;

    public static Day Monday { get { return new Day( DayE.Monday ); } }
    public static Day Tuesday { get { return new Day( DayE.Tuesday ); } }
    public static Day Wednesday { get { return new Day( DayE.Wednesday ); } }
    public static Day Thursday { get { return new Day( DayE.Thursday ); } }
    public static Day Friday { get { return new Day( DayE.Friday ); } }

    private Day( DayE value )
    {
        this.value = value;
    }

    public override string ToString()
    {
        switch( value )
        {
            case DayE.Monday:
                return "mo";
            case DayE.Tuesday:
                return "tu";
            case DayE.Wednesday:
                return "we";
            case DayE.Thursday:
                return "th";
            case DayE.Friday:
                return "fr";
            default:
                throw new InvalidOperationException( "Can't convert 0 value" );
        }
    }
}

Some advantages of this approach I could think of:

Allows you to limit the possible values, only the ones you construct using the private constructor can be made. (Of course, the 0 value can always be constructed using default(Day) or new Day().) This means you only have to test if the value is not 0 to make sure it's valid. If 0 is a valid value, you don't have to test for validity.
No need for an helper class for the extension methods, you can just put them in the struct. Also, you can override the ToString method, as can be seen in the example.
In a similar fashion, static methods are now possible.
I think it should be equally fast to just using the enum, since the compiler will probably take away most of the wrapper. Unless, of course, you add functionality, like validity checks, to methods.

Disadvantages:

Need to create public static properties for all enum values. Although this does allow you to create extra values from combinations of other values, that you don't want to put in the enum itself (useful for tweaking the ToString behavior of a enum with Flags attribute).
Need to define methods for all common enum functionality (for each wrapper you make), like HasFlag and ==, !=, & and | operators. However, this gives you control over which of these methods/operators are available and it allows for validity checks inside them. It's possible to create one or more VS code snippets for this.
Visual Studio's auto complete will be a little less happy with this. With enums it usually immediately auto selects the enum type name when you type e.g. Day x =. With this you'll first have to (partially) type that.
To use this in a switch statement, you need to make the internal value and enum public, because structs don't work in a switch.

What do you think of this construction? Can you name any more disadvantages? Would you recommend me not to use this?

Edit: found a new disadvantage, see last point above.


texts: Ask the user random questions from a multiple-choice test

texts:
I'm quite new to programming and was hoping you wouldn't mind taking a look at my code and giving some points as to how I could clean it up.

Assignment guidelines:

  Create a program that reads multiple choice questions from 1 file and
  gives 10 random questions to the user. Do Not uses classes.

Example of how the questions are stored in the text document I created

Question (end of line)
Option1 (end of line)
Option2 (end of line)
Option3 (end of line)
Option4 (end of line)
Answer (end of line)
(intentionally left blank)
Question2...Question20 (rinse and repeat for remaining questions)

Code I used:

#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>

using namespace std;

struct questionFormat
{
    string question;
    string answersA;
    string answersB;
    string answersC;
    string answersD;
    string answerSheet;
    string space;
};

int main ()
{
    questionFormat q;
    string questions [20];
    string answersA [20];
    string answersB [20];
    string answersC [20];
    string answersD [20];
    string answerSheet [20];
    string space[20];
    int userAnswer [10];
    int testQuestions [10] = {99,99,99,99,99,99,99,99,99,99};
    int counter = 0, num = 0, userCorrect =0, correctAnswer = 0;
    fstream infile("testQuestions.txt", ios::in);
    srand(time(NULL));

    do
    {
        getline (infile, q.question);
        questions[counter] = q.question;

        getline (infile, q.answersA);
        answersA[counter] = q.answersA;

        getline (infile, q.answersB);
        answersB[counter] = q.answersB;

        getline (infile, q.answersC);
        answersC[counter] = q.answersC;

        getline (infile, q.answersD);
        answersD[counter] = q.answersD;

        getline (infile, q.answerSheet);
        answerSheet[counter] = q.answerSheet;

        getline (infile, q.space);
        space[counter] = q.space;

        counter++;
    } while (counter < 20);

    cout << "Welcome to my fantastic test.\nYou will randomly be given 10/20 questions." << endl;

    counter = 0;

    while (counter < 10)
    {
        num = rand()%20;
        cout << "Current random number: " << num << endl;
        cout << "Counter is: " << counter << endl;
        if (bool exists = find(begin(testQuestions), end(testQuestions), num) != end(testQuestions))
        {
            continue;
        }
        else
        {
            testQuestions[counter] = num;
            cout << "\nQuestion # " << counter +1 << endl;
            cout << questions [num] << endl;
            cout << answersA [num] << endl;
            cout << answersB [num] << endl;
            cout << answersC [num] << endl;
            cout << answersD [num] << endl;
            cin >> userAnswer[counter];

            correctAnswer = stoi(answerSheet[num]);
            if (userAnswer[counter] == correctAnswer)
            {
                userCorrect++;
            }
            counter++;
        }
    }
    cout << "You got a total of " << userCorrect << " out of 10 correct" << endl;

    return 0;
}


texts: Best way to identify a computer in LAN C#

texts:
I have a web application to manage computers. Every registered computer is locally querying the latest information and updates the database with it in a 10 minute cycle.

But the computer is only allowed to update its information and nothing else. Currently I'm identifying the computer like this:

I get its hostname from the "remote_addr" variable

string senderHostname = (Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName).Split('.')[0];

Then I compare the hostname of the sender computer with the hostname of the computer which should be updated.

if (senderHostname.Equals(targetHostname, StringComparison.InvariantCultureIgnoreCase)) {
 // allowed
}
else {
 // forbidden
}

If they are the same, then I'm allowing the update, otherwise not.

I know that this code is very very ugly and I would be interested in a best practice to do this.

All the code:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        clientMachineName = (Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName).Split('.')[0];
    }
    catch (Exception)
    {
        clientMachineName = "n/a";
    }

    if (!String.IsNullOrEmpty(Request.QueryString["status"]) && !String.IsNullOrEmpty(Request.QueryString["value"]))
    {
        String macAddress = Request.QueryString["status"];
        String statusCode = Request.QueryString["value"];

        if (clientMachineName.Equals(getHostName(macAddress), StringComparison.InvariantCultureIgnoreCase))
        {
            ComputerDbCommunicator communicator = new ComputerDbCommunicator();
            communicator.insertIntoComputerDb("UPDATE [Computer] SET [statuscode] = " + statusCode + " WHERE [macaddress] = '" + macAddress + "'");

            communicator.closeConnections();
            communicator = null;

            Response.Clear();
            Response.ClearHeaders();
            Response.AddHeader("Content-Type", "text/plain");
            Response.Write(statusCode);
            Response.Flush();
            Response.End();
        }
        else
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.AddHeader("Content-Type", "text/plain");
            Response.Write("Operation not allowed");
            Response.Flush();
            Response.End();
        }
    }
    else if (!String.IsNullOrEmpty(Request.QueryString["status"]))
    {
        String macAddress = Request.QueryString["status"];
        String statusCode = null;
        ComputerDbCommunicator communicator = new ComputerDbCommunicator();
        SqlDataReader dr = communicator.queryComputerDb("SELECT [statuscode] FROM [Computer] WHERE [macaddress] = '" + macAddress + "'");
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                statusCode = dr[0].ToString();
            }
            dr.Close();

            Response.Clear();
            Response.ClearHeaders();
            Response.AddHeader("Content-Type", "text/plain");
            Response.Write(statusCode);
            Response.Flush();
            Response.End();

            communicator.closeConnections();
            communicator = null;
        }
    }
}

protected String getHostName(String macAddress)
{
    String hostName = null;
    ComputerDbCommunicator communicator = new ComputerDbCommunicator();
    SqlDataReader dr = communicator.queryComputerDb("SELECT [hostname] FROM [Computer] WHERE [macaddress] = '" + macAddress + "'");
    while (dr.Read())
    {
        hostName = dr[0].ToString();
    }
    dr.Close();

    communicator.closeConnections();
    communicator = null;

    return hostName;
}


texts: Script to check for failed logins and then trawl users' .bash_history for keywords

texts:
I have created a script to check for failed logins and then trawl User .bash_history for keywords. There is also processing on the .bash_history files to convert epoch to human-readable timestamps.
I've run my script through shellcheck.net and the only real thing that it's complaining about are my For loops. It's saying they should be while loops instead, and I'm struggling to convert them.

Here's the script in its entirety:

#! /bin/bash
#

printf "\n"
echo -e "\e[93m*** Failed Login Checker ***\e[0m"
sleep 2
grep -E 'Failed password|invalid' /var/log/secure* | grep "sshd\[" | uniq
read -r -p "Press [Enter] key to continue..."

printf "\n"
echo -e "\e[93m*** BASH History Checker - script initiated ***\e[0m"
sleep 2

HOLDINGDIR=/root/check_history

if [ ! -d $HOLDINGDIR ];
then
        mkdir $HOLDINGDIR
fi

for i in $( find /home -name .bash_history -type f );
do
        cp "$i" $HOLDINGDIR/$( ls -la "$i" | awk '{print$3}' )_history
done

echo -e "\e[93mAll BASH History files copied - now processing date format...\e[0m"

for k in $( find $HOLDINGDIR -name '*_history' -type f );
do
        echo "Processing file: " "$k"
        sed -i -E 's/^#([0-9]+).*$/date -d @\1/e' "$k"
        chmod 755 "$k"
done

printf "\n"
echo -e "\e[93mAll BASH History files timestamps converted\e[0m"

printf "\n"
read -r -e -p "Enter search term: " -i "sudo su" search
echo "You typed: " "$search"
sleep 3
printf "\n"

for m in $( find $HOLDINGDIR -name '*_history' -type f );
do
        printf "\n"
        FILENAME=$m
        echo "-----------------------------------------------------------"
        echo "History file for: " "$FILENAME" | awk -F/ '{print$4}'
        echo "-----------------------------------------------------------"
        grep -F -B1 -i "$search" "$m"
        read -r -p "Press [Enter] key for next file..."
done


texts:
This is one of the longest programs I have made with methods and I think I must be doing this rather inefficiently. Any comments to improve would be appreciated.

package numberwords2;
import java.awt.Component;
import javax.swing.JOptionPane;
public class NumberWords2
{
    static String rawInput;
    static String output = "";
    static int hold;

    private static Component frame;

    public static void main(String[] args)
    {

        rawInput = JOptionPane.showInputDialog("Enter a number between 0 and 9999.");
        int input = Integer.parseInt(rawInput);

        if(input == 0)
        {
            output += "Zero";
        }
        else if(input < 10)
        {
            output += ones(0);
        }
        else if(input < 20)
        {
            output += teens(0);
        }
        else if(input < 100)
        {
            output += tens(0);
            output += ones(1);
        }
        else if(input < 1000)
        {
            output += hundreds(0);
            int temp = Integer.parseInt(rawInput.substring(1,3));
            if(temp > 10 && temp < 20)
            {
                output += teens(2);
            }
            else
            {
                output += tens(1);
                output += ones(2);
            }

        }
        else if(input < 10000)
        {
            output += thousands(0);
            output += hundreds(1);
            int temp = Integer.parseInt(rawInput.substring(2,4));
            if(temp > 10 && temp < 20)
            {
                output += teens(3);
            }
            else
            {
                output += tens(2);
                output += ones(3);
            }

        }

        JOptionPane.showMessageDialog(frame, rawInput + " is" + output + ".");
        output = "";
        main(args);
    }

    public static String teens(int hold)
    {
        String[] teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
            "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nighteen"};
        int x = Character.getNumericValue(rawInput.charAt(hold));
        int y = 0;
        for(int i = 0; i < 10; i++)
        {
            if(i == x)
            {
                y = i;
                break;
            }
        }
        return " " + teens[y];
    }

    private static String tens(int hold)
    {
        String[] tens = {"", "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
        int x = Character.getNumericValue(rawInput.charAt(hold));
        int y = 0;
        for(int i = 0; i < 10; i++)
        {
            if(i == x)
            {
                y = i;
            }
        }
        return  " " + tens[y];
    }

    private static String ones(int hold)
    {
        String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
        int x = Character.getNumericValue(rawInput.charAt(hold));
        int y = 0;
        for(int i = 1; i < 10; i++)
        {
            if(i == x)
            {
                y = i;
                break;
            }
        }
        return " " + ones[y];
    }

    private static String hundreds(int hold)
    {
        return ones(hold) + " Hundred";
    }

    private static String thousands(int hold)
    {
        return ones(hold) + " Thousand";
    }
}


texts:
The goal of the code is to

initialize a Dialog with settings

make sure the object is reusable

Setup the options to reuse the code

I'm not quite sure if this is overkill, or I am going about this problem in the entirely wrong way. Any input would be appreciated.

var myDialog = myDialog || (function() {

  var options = {
    title: 'Attention',
    msg: 'Message Here',
    focusOn: ''
  }

    function show(opts) {

      options = $.extend({}, options, opts);

      $('<p>' + options.msg + '</p>').dialog({
        title: options.title,
        modal: true,
        draggable: false,
        show: {
          effect: "fade",
          duration: 500
        },
        hide: {
          effect: "fade",
          duration: 200
        },
        buttons: {
          'Close': function() {
            $(this).dialog("close");
          }
        },
        close: function() {
          if (options.focusOn.length !== 0) {
            $(options.focusOn).focus()
          }
          $(this).dialog("destroy");
        }
      });
    }

    function updateOptions(opts) {
      options = $.extend({}, options, opts);
    }

  return {
    fire: show,
    options: updateOptions
  };

}());

myDialog.fire({
  msg: 'Hello there',
  focusOn: '#test'
});


texts: How to make Print() method memory & CPU efficient?

texts:
Problem Statement
You are receiving n objects in a random order, and you need to print them to stdout correctly ordered by sequence number.
The sequence numbers start from 0 (zero) and you have to wait until you get a complete, unbroken sequence batch of j objects before you output them.
You have to process all objects without loss. The program should exit once it completes outputting the first 50000 objects Batch size j = 100
The object is defined as such:
    {
    "id" : "object_id", // object ID (string)
    "seq" : 0, // object sequence number (int64, 0-49999)
    "data" : "" // []bytes
    }

Example Output Statement
    Step                Input Value                Output State j = 1                  Output state j = 3
    0                       6
    1                       0                           0
    2                       4                           0
    3                       2                           0
    4                       1                           0,1,2                               0,1,2
    5                       3                           0,1,2,3,4                           0,1,2
    6                       9                           0,1,2,3,4                           0,1,2
    7                       5                           0,1,2,3,4,5,6                       0,1,2,3,4,5

Solution
func (receiver *Receiver) Print(seqNumber uint64, batchSize uint64, outputFile io.Writer) (error, bool) {

    fmt.Fprintf(outputFile, "[ ")
    if seqNumber >= receiver.outputSequence.length {
        receiver.outputSequence.bufferSizeIncrease(seqNumber)
    }
    receiver.outputSequence.sequence[seqNumber] = true

    printedCount := uint64(0) // check for MAX_OBJECTS_TO_PRINT
    var nthBatchStartingIndex uint64
    MaxObjectsToPrint := config.GetMaxPrintSize()
Loop:
    for nthBatchStartingIndex < receiver.outputSequence.length { // check unbroken sequence
        var assessIndex = nthBatchStartingIndex
        for j := assessIndex; j < nthBatchStartingIndex+batchSize; j++ { // Assess nth batch
            if j >= receiver.outputSequence.length { //index out of range - edge case
                break Loop
            }
            if receiver.outputSequence.sequence[j] == false {
                break Loop
            }
        }

        count, printThresholdReached := receiver.printAssessedBatchIndexes(assessIndex, printedCount, batchSize, MaxObjectsToPrint, outputFile)
        if printThresholdReached { // print sequence threshold reached MAX_OBJECTS_TO_PRINT
            fmt.Fprintf(outputFile, " ]  ")
            fmt.Fprintf(outputFile, " ----for input value %d\n", seqNumber)
            return nil, false
        }
        printedCount += count
        if printedCount >= MaxObjectsToPrint { // print sequence threshold reached MAX_OBJECTS_TO_PRINT
            fmt.Fprintf(outputFile, " ]  ")
            fmt.Fprintf(outputFile, " ----for input value %d\n", seqNumber)
            receiver.Log.Printf("****MaxObjectsToPrint threshold(%d) reached \n", MaxObjectsToPrint)
            return nil, false
        }
        nthBatchStartingIndex = assessIndex + batchSize // next batch
    }
    fmt.Fprintf(outputFile, " ]  ")
    fmt.Fprintf(outputFile, " ----for input value %d\n", seqNumber)
    return nil, true
}

Here is the complete solution, written for this problem.

Print() is the method that does heavy lifting in this code, with varying size of memory & heavy CPU usage:

How to make receiver.outputSequence memory effective by using datastructure other than array? because newBufferSize := 2 * seqNumber is doubling memory...

How to make Print method have effective CPU usage? On some goroutine


texts: Making the parsing of a String to an Int32 robust (valid, positive, not 0 validation)

texts:
I've a static method which parses a String (from the App.config) to a Int32. I need to have a valid (since the parsing would fail of course^^), positive and not zero integer. I've done it like this:

    public static int uiScale ()
    {

        int retint = 0;

        try
        {

            retint = Int32.Parse(ConfigurationManager.AppSettings.Get("UiScale"));

        }
        catch (FormatException) {}
        catch (OverflowException){}

        return retint != 0 ? Math.Abs(retint) : 1;

    }

This feels (don't ask me why) a little bit smelly I've to admit. Is this the best way to achieve this?


texts:
I was doing a few basic Java recursion problems to refresh my memory with recursion (honestly never had to use it in a long, LONG, time), along with using it as a useful way to prepare for any possible interviews for entry level positions. I came upon this problem on codingbat.com:

  Given a non-negative int n, compute recursively (no loops) the count
  of the occurrences of 8 as a digit, except that an 8 with another 8
  immediately to its left counts double, so 8818 yields 4. Note that mod
  (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/)
  by 10 removes the rightmost digit (126 / 10 is 12).

  count8(8) → 1
  count8(818) → 2
  count8(8818) → 4

My solution, which was all correct for all the test cases they had is as follows:

public int count8(int n) {
  if(n == 0) {
    return 0;
  } else {

    int count = (n % 10 == 8)? 1: 0;

    //This is testing for adjacent 8s.
    if(count == 1) {
      int tempN = n;
      tempN = tempN / 10;
      count = (tempN % 10 == 8) ? 2 : 1;
    }

    n = n/10;
    return count + count8(n);
  }
}

I was wondering if anyone could critique this solution, and let me know if this is the best approach, or if there is a better way. I am not a big fan of the if(count == 1) that I created, but that was the only way I could think of to test the presence of an 8 to the left of the current one.


texts:
I'm currently in the process of creating a online work schedule for internal use. For this, the client needs to show the days of a single week.

I pass a week number and a year.
From that I get the first day of that week, by using strtotime() passing an argument in the format [year]-W[weekno]-[dayofweek]. Example: strtotime('2011-48W-1');

With that function I create my table as mentioned earlier:

            <?php for($i = 1; $i <= 7; $i++): ?>

            <?php echo $dage[$i] . " ". date("j/m", strtotime($year.'-W'.$week.'-'.$i)); ?>

            <?php endfor; ?>

            <?php for($i = 1; $i <= 7; $i++): ?>

            <td<?php if($i == 7) { echo ' class="last"'; } ?>>

                <?php

                $day = date("Y-m-d", strtotime($year.'-W'.$week.'-'.$i));

                if(isset($entries[$day])):

                foreach($entries[$day] as $entry):

                ?>

                <div class="workEntry" title="<?php echo $entry->note; ?>">

                        <?php echo date("H:i", strtotime($entry->workStart)); ?>

                        <?php if($entry->workStart != "0000-00-00 00:00:00") { echo " - ".date("H:i", strtotime($entry->workEnd)); } ?>

                    <?php if($entry->userId == 0): ?>

                    Unspecifed

                    <?php else: ?>

                    <?php echo $entry->name; ?>, <?php echo $entry->pgroup; ?>

                    <?php endif; ?>

                <?php endforeach;

                endif; ?>

            <?php endfor; ?>

Well, it works, but I'm pretty sure that I'm reinventing the wheel, and doing a pretty bad job at it too. I'd like to know what you think and to hear any suggestions.


texts: Functional interface hierarchy in Java 8

texts:
I just created the following code and am wondering whether it is logically correct (all other feedback is of course also welcome):

public interface HandView extends View<Hand> {
    void onCardAdded(final Card card);

    void onCardPlayed(final int cardIndex);

    void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);

    public static HandView merge(final HandView... handViews) {
        return new HandView() {
            @Override
            public void onCardAdded(final Card card) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardAdded(card));
            }

            @Override
            public void onCardPlayed(final int cardIndex) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardPlayed(cardIndex));
            }

            @Override
            public void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) {
                Arrays.stream(handViews).forEach(handView -> handView.onCardsSwapped(cardIndexOne, cardIndexTwo));
            }
        };
    }

    @FunctionalInterface
    public static interface OnCardAddedListener extends HandView, Consumer<Card> {
        @Override
        default void accept(final Card card) {
            onCardAdded(card);
        }

        @Override
        void onCardAdded(final Card card);

        @Override
        default void onCardPlayed(final int cardIndex) { }

        @Override
        default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
    }

    @FunctionalInterface
    public static interface OnCardPlayedListener extends HandView, IntConsumer {
        @Override
        default void accept(final int cardIndex) {
            onCardPlayed(cardIndex);
        }

        @Override
        default void onCardAdded(final Card card) { }

        @Override
        void onCardPlayed(final int cardIndex);

        @Override
        default void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo) { }
    }

    @FunctionalInterface
    public static interface OnCardsSwappedListener extends HandView {
        @Override
        default void onCardAdded(final Card card) { }

        @Override
        default void onCardPlayed(final int cardIndex) { }

        @Override
        void onCardsSwapped(final int cardIndexOne, final int cardIndexTwo);
    }
}

And then I used it like this in the following integration test (so you can see the usage):

@Test
public void testRemoveCallbackNotTriggeredAfterRemoval() {
    Hand hand = new Hand(5);
    AtomicInteger counter = new AtomicInteger(0);
    HandView.OnCardAddedListener handView = card -> counter.incrementAndGet();
    hand.addViewCallback(handView);
    HandView.OnCardAddedListener handView2 = card -> counter.incrementAndGet();
    hand.addViewCallback(handView2);

    hand.add(new MonsterCard("Test", 7, 7, MonsterModus.HEALING));
    assertEquals(2, counter.get());

    hand.removeViewCallback(handView2);
    hand.add(new MonsterCard("Test Test", 5, 5, MonsterModus.HEALING));
    assertEquals(3, counter.get());

    hand.removeViewCallback(handView);
    hand.add(new MonsterCard("Test Test Test", 3, 3, MonsterModus.HEALING));
    assertEquals(3, counter.get());
}

Where Hand.addViewCallback expects an argument of type HandView.

It seems to be working, the only thing I am left off wondering is:

Is it not normal to have HandView extends OnCardAddedListener, OnCardPlayerListener, OnCardsSwappedListener?

The caveat then is that I don't think methods accepting an HandView now, would accept those sub-interfaces then.


texts: Adjusting integer based on multiple elements in int array

texts:
I'm working with the following code which adjusts an int based on multiple elements of an integer array. I am wondering if there's a cleaner, easier-to-read construct for this:

int Blue = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments

if (Adjustments[0] == 255)
    Blue = 128;
else if (Adjustments[0] == 0)
    Blue = 0;

if (Adjustments[1] == 255)
    Blue += 64;
else if (Adjustments[1] == 0)
    Blue += 0;

if (Adjustments[2] == 255)
    Blue += 32;
else if (Adjustments[2] == 0)
    Blue += 0;

if (Adjustments[3] == 255)
    Blue += 16;
else if (Adjustments[3] == 0)
    Blue += 0;

if (Adjustments[4] == 255)
    Blue += 8;
else if (Adjustments[4] == 0)
    Blue += 0;

if (Adjustments[5] == 255)
    Blue += 4;
else if (Adjustments[5] == 0)
    Blue += 0;

if (Adjustments[6] == 255)
    Blue += 2;
else if (Adjustments[6] == 0)
    Blue += 0;

if (Adjustments[7] == 255)
    Blue += 1;
else if (Adjustments[7] == 0)
    Blue += 0;

Any suggestions?

Edit

Here is the revised version based on suggestions provided:

Blue = 0;
Green = 0;
Red = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments

int[] AdjustmentStops = new[] { 128, 64, 32, 16, 8, 4, 2, 1 };
for (int i = 0; i < 8; i++)
{
    Blue += Adjustments[i] == 255 ? AdjustmentStops[i] : 0;
    Green += Adjustments[i + 8] == 255 ? AdjustmentStops[i] : 0;
    Red += Adjustments[i + 12] == 255 ? AdjustmentStops[i] : 0;
}


texts: jQuery security and efficiency simple calculation code

texts:
//AMOUNT CALCULATOR
            var totalAmount = 0;
            var serviceAmount = 0;

jQuery('.select-service').click(function(){
    var serviceAmount = parseInt(jQuery(this).parent().html().replace(/\D/g,''));
    if(jQuery(this).is('.selected')){
        jQuery(this).removeClass('selected');
        totalAmount -= serviceAmount;
        jQuery('#total-amount').html(totalAmount);
    }else{
        jQuery(this).addClass('selected');
        totalAmount += serviceAmount;
        jQuery('#total-amount').fadeIn('slow').html(totalAmount);
    }
});
//AMOUNT CALCULATOR

is this code efficient and secure? I am PHP dont know if it is required or not to judge.. Please any Help/feed back would be awesome! really trying to better my coding..


texts: Generating random and secure CSRF tokens

texts:
I googled around for secure random number generation and random string generation, combining them with some user data.

Is this good or am I totally off-base?  I don't know much about cryptography but I do not see many alternatives, other than some bad code that gets copied around a lot with mt_rand and uniqid.

//csrf tokens
    public function csrf_token($regen = false)
    {
        if($regen === true) {
            //we need to give the user a token
            if(isset($_SESSION["__csrf_token"])) {
                unset($_SESSION["__csrf_token"]);
            }
            $max = mt_rand(0, mt_getrandmax());
            $rand_num = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
            $rand_string = "";
            for($i=0; $i < 11; $i++) {
                $x = mt_rand(0, 2);
                switch($x) {
                    case 0: $rand_string.= chr(mt_rand(97,122));break;
                    case 1: $rand_string.= chr(mt_rand(65,90));break;
                    case 2: $rand_string.= chr(mt_rand(48,57));break;
                }
            }

            $_SESSION["__csrf_token"] = hash('whirlpool', $rand_num . $this->username . $rand_string . $this->hash_pw);
            $this->csrf_token = $_SESSION["__csrf_token"];
            return $this->csrf_token;
        }else{
            //the user already has a token
            return $this->csrf_token;
        }
    }


texts: Setting a common background image on a dozen screens

texts:
Is there something as "they have too little in common to use a superclass"?

In my case, doing iOS programming, in a project, every screen has the same background. So I created a superclass which only has:

.h

@property (nonatomic) IBOutlet UIImageView *backgroundImageView;

.m

- (void)viewDidLoad {
    [super viewDidLoad];

    UIImage *backgroundImage = ...;
    [self.backgroundImageView setImage:backgroundImage];
}

Is this too little to use a superclass for?

If I didn't add it here, I'd have about 10 view controllers where I would have to do this. (Obviously code duplication).


texts:
This code achieves the effect, but is it a resource friendly way of doing it?

Just to clarify: target div.fixMe and fix it to the top of the window when the user scrolls past its natural position. (I do realise there are plugins to achieve this result, but I wanted to build it myself)

Is this the best way to achieve the desired result? Is it a good idea that the whole function triggers whenever the user scrolls, or should I be splitting up code?

(function() {
var fixedElement = $('.fixMe').offset(),
    scrolled = $(window).scroll(function() {
        var winScrolled = $(this).scrollTop();
        if(winScrolled > fixedElement.top - 10) {
            $('.fixMe').css({'position': 'fixed','top' : '10px'})
        }
        else {
            $('.fixMe').css({'position': 'static'})
        }
    });
})()

Any feedback/criticism is welcome. I should probably get/set the width of div.fixMe to avoid display issues.


texts:
I need to write a function that, when given an input (string, float, or int), returns that input as a reduced partial fraction, and it needs to accept a wide array of inputs:

1.5 =>  "1 1/2"
5/2 => "2 1/2"
"1/3" => "1/3"
5 => "5"
"6 1/3" => "6 1/3"
0 => "0"

I've written this function using the Rational class, but was wondering if there were a better, more elegant solution:

def format_partial_fraction(fraction)
  if fraction.include? "/" # to handle "6 1/3" => "6 1/3" (or maybe I'll just trust user input in this case)
    fraction = fraction.split(" ").inject{|sum,x| sum.to_r + x.to_r }
  end

  rational = fraction.to_r
  if rational == 0
    return "0"
  elsif rational < 1 # e.g. "1/3"
    rational.to_s
  else # e.g. "3 1/2" or just "3"
    rational.to_i.to_s + ( rational%1 == 0 ? "" : " " + (rational%1).to_s)
  end
end

Ruby 2.0.0, Rails 3.2.13


texts:
I have n Objects,
Each Object has a Set of "nested" "Neighboring Objects".
I need to check if there are duplicates between the "Neighboring Objects" Sets (there are no duplicates inside a single Set of "Neighboring Objects", but there might be between Sets).

At the end I need a new List of shared "Neighboring Objects"

In order to qualify, an Object must be present in every "Neighboring Set"

public List<Object> getOverlapingNeighbors(Object... d) {

    Objects.requireNonNull(d);

    List<Object> overlapingNeighbores = new ArrayList<Object>();

    Set<Object> neighbores = d[0].getNeighboringObjects(); // returns the "Neighboring Objects" Set

    for (Object candidate : neighbores) {

        boolean flag1 = true;

        for (int i = 1; i < d.length; i++) {

            boolean flag2 = false;

            for (Object other : d[i].getNeighboringObjects()) {
                if (candidate.equals(other)) {
                    flag2 = true;
                    break;
                }
            }

            if (!flag2) {
                flag1 = false;
                break;
            }

        }

        if (flag1) {
            overlapingNeighbores.add(candidate);
        }

    }

    return overlapingNeighbores;
}

I don't feel comfortable with this approach...
I was hoping some one smarter has implemented a way of doing this better


texts: Generate next combination in lexicographic order

texts:
C++'s standard library has a std::next_permutation algorithm but no next_combination. The reason behind this absence is, I guess, that one of the easiest and fastest way to generate combinations one at a time is to rely on the permutations of a vector of boolean values, which is then used as a sieve to retain the elements in the combination. The drawback is that you need to maintain some state to compute the next permutation.

Here's a try at a STL style next_combination state-less algorithm. The range [begin, end) contains the whole set of elements, and [begin, begin+k) the current combination of k elements. The next combination is generated in place.

I'd be grateful for advice and improvement suggestions.

NB1: the algorithm depends on two invariants: [begin, begin+k] is sorted, and [begin+k, end) is sorted also.

NB2: I've tried to rely on existing STL algorithms as much as possible.

#include <algorithm>
#include <functional>

template <typename Iterator>
Iterator find_next_increase_position(Iterator begin, Iterator combination_end, Iterator end);

template <typename Iterator>
bool next_combination(Iterator begin, Iterator end, unsigned k) {
    const auto combination_end = begin+k;
    const auto next_move = find_next_increase_position(begin, combination_end, end);
    if (next_move == end) return false;
    const auto previous_value = *next_move;
    std::inplace_merge(next_move, combination_end, end);
    const auto next_rotation =
        std::rotate(next_move, std::upper_bound(next_move, end, previous_value), end);
    std::rotate(combination_end, next_rotation, end);
    return true;
}

template <typename Iterator>
Iterator find_next_increase_position(Iterator begin, Iterator combination_end, Iterator end) {
    auto pos = std::upper_bound(std::reverse_iterator(combination_end),
                                    std::reverse_iterator(begin),
                                    *--end,
                                    std::greater<typename Iterator::value_type>());
    if (pos.base() == begin)
        return ++end;
    return --pos.base();
}

An example:

#include <vector>

int main() {
    std::vector<int> test{1,2,3,4,5};
    while (next_combination(test.begin(), test.end(), 3)) {
        for (auto i : test) std::cout << i;
        std::cout << std::endl;
    }
}

With output:

12435
12534
13425
13524
14523
23415
23514
24513
34512

Edit: added #includes and example


texts: Testing a service that makes database calls, without a database

texts:
I'm working on a new service, for the past year I haven't needed to write tests from scratch. I've either been bug fixing, or adding features that require modification of tests, but not writing everything from scratch.
I need to make sure I'm doing things right. The unit tests below test a service that queries a database for data.

The *Proc files use Springs @Repository annotation, and each one calls a different stored procedure in the database. For these tests I'm mocking everything. Have I done it correctly? Is there anything I have overlooked? Anything I've possibly missed? The tests all pass when I run them in my IDE or with maven. In this particular instance those method calls simply return the object(s) retrieved from the database, so there isn't any actual business logic in there apart from calling the get() method from the proc objects that I'm mocking.
Have I done things the correct way?

    @RunWith(MockitoJUnitRunner.class)
    @SpringBootTest
    public class FusServiceImplTest {

        @Mock
        private GetFileInfoByIdProc getFileInfobyIdProc;
        @Mock
        private GetFileInfoProc getFileInfoProc;
        @Mock
        private GetFileInfoByFileNameProc getFileInfoByFileNameProc;
        @Mock
        FileInfoVO voMock;
        @Mock
        FileInfoVO voMock2;

        @InjectMocks
        private FusServiceImpl service;

        @Test
        public void whenGetFileById_thenReturnFile(){
            final Long ID = 99999L;

            when(getFileInfobyIdProc.get(ID)).thenReturn(voMock);

    FileInfoVO voResult = service.getFile(ID);

        assertThat(voResult.getFileName())
                .isEqualTo(voMock.getFileName());

    }

    @Test
    public void whenGetFileByName_thenReturnFile(){
        final String NAME = "test.file";

        when(getFileInfoByFileNameProc.get(NAME)).thenReturn(voMock);

        FileInfoVO voResult = service.getFile(NAME);

        assertThat(voResult.getFileName())
                .isEqualTo(voMock.getFileName());

    }

    @Test
    public void whenGetAllFiles_thenReturnAllFiles(){

        List<FileInfoVO> list = new ArrayList<>();
        list.add(voMock);
        list.add(voMock2);

        when(getFileInfoProc.get()).thenReturn(list);

        List<FileInfoVO> voListResult = service.getAllFiles();

        assertThat(voListResult.size())
                .isEqualTo(list.size());

    }

}


texts:
I try to create compare script using awk and another command and running successful.
But I think the script I create it's to long.
Is there anyone can shorten my script below ?
After plan A shorten the code than, plan B is :
 1. I want eliminated a lot temp file (.txt), only need `lengkap.txt`
 2. Put command in variable if can

It's my pleasure if anyone can help me
Below is the code that I create based searching and trying.
#!/bin/bash

### Path Folder who will be compare ###
path1=/home/rio/apps1
path2=/home/rio/apps2

### Find all filename and convert to MD5 ###
find $path1 -type f | xargs md5sum > checksums.md5
find $path2 -type f | xargs md5sum > checksums2.md5

### Compare to find different folder ###
awk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums.md5 checksums2.md5 > hasil1.txt
awk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums2.md5 checksums.md5 > hasil2.txt

### Merge result of compare ###
awk '{print $0}' hasil1.txt hasil2.txt > perbedaan.txt

### Filter Just Filename Difference ###
cat perbedaan.txt | awk '{print $2}' > hasilperbedaan.txt

### File about result compare (just filename) ###
cekhasil=/home/rio/hasilperbedaan.txt

### Check if File result compare empty or not ###
if [ -s "$cekhasil" ]
then
   echo " file exists and is not empty "
    ### Find All filename and date, after that put as we want ###
    find $path1 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate1.txt
    find $path2 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate2.txt

    ### Compare to get the date of filename ###
    awk 'A[$1]++' hasilperbedaan.txt filedate1.txt > pre_hasil1.txt
    awk 'A[$1]++' hasilperbedaan.txt filedate2.txt > pre_hasil2.txt
    ### Merge result of compare with date ###
    awk '{print $0}' pre_hasil1.txt pre_hasil2.txt > lengkap.txt
else
   echo " file does not exist, or is empty "
fi


texts:
dataListOne and dataListTwo will be full of BO objects (around 4000 - 5000).

Lets say dataListOne comes with objects with business keys: "one,two,three,one"
and dataListTwo has: "three,four,five".

At the end I must have:

insertList: "one,two"
updateList: "three"
deactivateList: "four,five"

There may be 2 BO's with same business key but different properties but I do not care about that.. So once I process a BO which has a businessKey "one" in dataListOne, if there comes another, I will not care about it..

What kind of approach should I take?

/*
Base Business Objects are considered to be same if they have the same businessKey !
 */
public class DataDiffContainer<BO extends BaseBusinessObject> {

    private List<BO> insertList = new ArrayList<BO>();
    private List<BO> updateList = new ArrayList<BO>();
    private List<BO> deactivateList = new ArrayList<BO>();

    private Set<String> handledString = new HashSet<String>();

    public void performDiff(List<BO> dataListOne, List<BO> dataListTwo) {
        for (BO dataOne : dataListOne) {
            if (handledString.contains(dataOne.getBusinessKey())) {
                // See the comment above class declaration
                continue;
            }
            boolean found = false;
            for (BO dataTwo : dataListTwo) {
                if (dataTwo.equals(dataOne)) {
                    updateList.add(dataOne);
                    dataListTwo.remove(dataTwo);
                    // we already know what to do with this object,
                    // so we may as well remove from the List that we need to check..
                    found = true;
                    break;
                }
            }
            if (!found) {
                insertList.add(dataOne);
            }
            handledString.add(dataOne.getBusinessKey());
        }

        // What is remaining in dataListTwo data should be dectivated:
        for (BO bo : dataListTwo) {
            if (bo.isActive())
                deactivateList.add(bo);
        }
    }
}


texts: Harmonic partial sum calculator with multithreading

texts:
I wrote a program which computes the harmonic partial sum to N terms with multithreading capability. I've been working on this to sharpen my C++ skills for the upcoming semester. Just wondering if there's anything that doesn't follow the C++ standard and/or glaringly wrong. Also wondering if I can make any further optimizations.

Basically I have my program set up to only use threads if the input is divisible by 4, since I am using 4 threads due to my quad core CPU. I want this to be more flexible but I haven't thought of a better solution yet. If anyone has a suggestions, that'd be appreciated.

#include <iostream>
#include <cstdio>
#include <thread>
#include <ctime>
#include <cassert>

using namespace std;

const int NUM_THREADS = 4;

// H(N) is defined to be the harmonic partial sum to N terms.
// calculateHarmonic(): function given to threads to compute H(N).
// unsigned long start: starting point for the loop; different for each thread.
// unsigned long N: amount of terms to compute; different for each thread; divided evenly by # of threads.
// double *sum: pointer to a double which holds a thread's individual sum for H(N).
void calculateHarmonic(long long start, long long N, double *sum)
{
    for(; start <= N; start++)
    {
        *sum += 1.0/start;
    }
}

void executeWithThreads(long long N)
{
    thread t[NUM_THREADS];  // using four threads
    double sum[NUM_THREADS] = {0.0};    // array of each sum calculated by each thread
    double finalSum = 0.0;
    clock_t start = clock();

    // Assign threads their task.
    for(int i = 0; i < NUM_THREADS; i++)
    {
        // thread([name of function], [starting point], [N], [address of individual element in sum array])
        t[i] = thread(calculateHarmonic, (((N/4)*i)+1), ((N/4)*(i+1)), &(sum[i]));
    }

    // Join threads to terminate and sum up all individual sums into finalSum.
    for(int i = 0; i < NUM_THREADS; i++)
    {
        t[i].join();
        finalSum += sum[i];
    }

    clock_t end = clock();
    printf("Harmonic sum of %lld is %1.18lf\n", N, finalSum);
    printf("Calculation took %1.18lf seconds.\n", (((double)(end-start)/CLOCKS_PER_SEC))/NUM_THREADS);
}

void executeNoThreads(long long N)
{
    double sum = 0.0;
    clock_t start = clock();
    for(int i = 1; i <= N; i++)
    {
        sum += 1.0/i;
    }
    clock_t end = clock();
    printf("Harmonic sum of %lld is %1.18lf\n", N, sum);
    printf("Calculation took %1.18lf seconds.\n", (((double)(end-start)/CLOCKS_PER_SEC))/NUM_THREADS);
}

int main()
{
    long long N;

    cout << "Enter the amount of terms to calculate the Harmonic sum to: ";
    cin >> N;
    assert(N > 0 && "N must be a nonzero positive integer.");
    cout << endl;

    if(N > NUM_THREADS && N % 4 == 0)
    {
        cout << "Calculating with threads..." << endl;
        executeWithThreads(N);
    }
    else if(N > NUM_THREADS && N % 4 != 0)
    {
        cout << "Calculating without threads..." << endl;
        executeNoThreads(N);
    }
    else
    {
        cout << "Calculating without threads due to small N..." << endl;
        executeNoThreads(N);
    }

    return 0;
}

Compiled with:

g++ -std=c++11 -pthread -Ofast harm_sum.cpp -o harm.out ; ./harm.out


texts: Select top 2 employees based on Grade and Alphabetical Order

texts:
Given a list of Employees ( name and grade). Output the names of the top 2 employees selected for a task(sorted based on grade and then alphabetically).

I am using a maxHeap and override the compareTo method of the Employee class
to define the sorting order while initializing the heap .I would like to know if there is a more efficient way(space/time).

The Code:

//Employee class
class Employee implements Comparable<Employee>{
    String name;
    int grade;

    public Employee (String name,int grade){
        this.name = name;
        this.grade = grade;
    }

    @Override
    public int compareTo(Employee e) {
        if(this.grade == e.grade) {
            // if the grades are the same then alphabetical priority
            return e.name.compareTo(this.name);
        }

        if(this.grade < e.grade) return -1;
            return 1;
        }
    }

Class to build max heap and print out two names

class EmployeePicker {
    public static void main(String[] args) {

        PriorityQueue<Employee> employeeHeap = new PriorityQueue<>(5,Collections.reverseOrder());

        // add 5 employees
        employeeHeap.add(new Employee("Adam", 5));
        employeeHeap.add(new Employee("Annie",7));
        employeeHeap.add(new Employee("Amit", 5));
        employeeHeap.add(new Employee("Carl", 5));
        employeeHeap.add(new Employee("Tom", 4));

        // print first two names
        System.out.println(employeeHeap.poll().name);
        System.out.println(employeeHeap.poll().name);
    }
}


texts: Event sourcing using functional programming

texts:
Is this a satisfactory implementation of event sourcing using functional programming?

module Account

(*Types*)
type EventAggregate<'Aggregate> = { Event:Event; Aggregate:'Aggregate }

and Command =
    | Login      of EventAggregate<Account>
    | Deposit    of EventAggregate<Account>
    | Withdrawal of EventAggregate<Account>

and Event =
    | LoggedIn  of Login
    | Deposited of decimal
    | Withdrew  of decimal

and AccountId = AccountId of string
and FirstName = FirstName of string
and LastName =  LastName  of string

and Login =   { UserId:string; Password:string }
and Account = {
    AccountId: AccountId
    FirstName: FirstName
    LastName:  LastName }

(*Functions*)
let appendTo (repo:Map<Event,_>) (plan:EventAggregate<'a>) =
    repo.Add (plan.Event , plan.Aggregate)

let getAccount login = {
    AccountId= AccountId "myAccountId"
    FirstName= FirstName "Scott"
    LastName= LastName   "Nimrod" }

let interpret cmd repo = cmd |> function
    | Login   v
    | Deposit v -> appendTo repo v
    | _         -> repo

(*Client*)
let login = { UserId= "MyUserId"; Password= "MyPassword" }
let account = getAccount login

let loginPlan =    { Event=     LoggedIn login
                     Aggregate= account        }

let depositPlan =  { Event=     Deposited 100m
                     Aggregate= account        }

let store =  (Login loginPlan , Map.empty)
             ||> interpret
              |> interpret (Deposit depositPlan)


texts: Is there any memory leak for the implementation of array of char arrays

texts:
Basically, I declared a char array to hold a maximum size of 100 char arrays.

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

int add_to_urls(char **urls, char *url) {
    for (int i = 0; i < 100; i++) {
        if (urls[i] == NULL) {
            urls[i] = malloc(sizeof(strlen(url) + 1));
            strcpy(urls[i], url);
            break;
        } else {
            //make sure we don't add same site twice
            if (strcmp(urls[i], url) == 0) {
                printf("%s already in list\n", urls[i]);
            }
        }
    }
    return 0;
}

void free_urls(char **urls) {
    for (int i = 0; i < 100; i++) {
        if (urls[i] != NULL) {
            free(urls[i]);
        } else break;
    }
}

int main() {
    char *urls[100] = {NULL};

    char *url = "www.youtube.com";
    add_to_urls(urls, url);

    url = "www.reddit.com";
    add_to_urls(urls, url);

    url = "www.reddit.com";
    add_to_urls(urls, url);

    printf("URL: %s\n", urls[0]);
    printf("URL: %s\n", urls[1]);

    free_urls(urls);

    return 0;
}

I'm not sure if there's any conventions of making such an array container, as I am learning how to use c. The priority is to check if there's any memory leak, what I did is iteratively release the urls[i] and urls itself will be automatically handled (I suspect).

The second thing is about improvements, what do you think might be inappropriate causing any potential troubles?


texts: Ensuring that attributes referenced by a mixin are present in the children class

texts:
I have implemented the below _get_schema method to ensure that schema attribute is always present on the Todos instance, and can therefore be used in the mixin.
Is it OK to do it like this? As far as I know, mixins usually do not implement constructors.
Is there a better way to make sure that someone did not forget to explicitly set the schema attribute in the Todos class, especially that this attribute is also not inherited from View?
class Mixin:
    def __init__(self):
        self._get_schema()
        super().__init__()

    def _get_schema(self):
        if not hasattr(self, 'schema'):
            msg = f'No "schema" attribute provided in {self.__class__.__name__} class'
            raise Exception(msg)

class View:
    def __init__(self):
        print('view constructor')

class Todos(SchemaMixin, MethodView):
    schema = 'todo schema'

todos = Todos()


texts:
I wrote a Perl script that implements the algorithm described in this
article to generate terrain height maps.  The idea is to raise a random hill \$i\$ of size \$r_i\$ centered at point \$(x_i, y_i)\$, such that the height at point \$(x, y)\$ is

$$ z = r_i^2 - ((x - x_1)^2 + (y - y_1)^2) $$

The resulting terrain is the sum of many such hills, with some normalization and flattening.

The output of this program is a bunch of inserts into the database and a png. The only problem with it is that it has really bad performance.

#!/usr/bin/perl
# mapgen.pl
# Henry J Schmale
# August 16, 2015
# Generates a height map

use strict;
use warnings;
use DBI;
use Image::Magick;
use constant {
    MAX_X   =>  2000,
    MAX_Y   =>  2000,
    MAX_R   =>  1075,
    MIN_R   =>  100,
    NUM_HILLS => 250
};

my @heightmap;

makemap();

sub makemap {
    #init heightmap to 0
    for(my $i = 0 ; $i < MAX_Y; $i++){
        my @arr;
        for(my $j = 0; $j < MAX_X; $j++){
            $arr[$j] = 0;
        }
        $heightmap[$i] = \@arr;
    }

    # Start adding hills
    for(my $i = 0; $i < NUM_HILLS; $i++){
        makehill(int(rand(MAX_X)), int(rand(MAX_Y)), int(rand(MAX_R) + MIN_R));
    }
    # normallize
    my $maxvalue = 0;
    for(my $x = 0; $x < MAX_X; $x++){
        for(my $y = 0; $y < MAX_Y; $y++){
            if($heightmap[$x][$y] > $maxvalue){
                $maxvalue = $heightmap[$x][$y];
            }
        }
    }
    for(my $x = 0; $x < MAX_X; $x++){
        for(my $y = 0; $y < MAX_Y; $y++){
            $heightmap[$x][$y] /= $maxvalue;
        }
    }
    # Flatten
    for(my $x = 0; $x < MAX_X; $x++){
        for(my $y = 0; $y < MAX_Y; $y++){
            $heightmap[$x][$y] *= $heightmap[$x][$y];
            $heightmap[$x][$y] *= $heightmap[$x][$y];
            $heightmap[$x][$y] *= $heightmap[$x][$y];
        }
    }
    # Dump to file
    dumpToImg();
    dumpToDb();
}

sub makehill {
    my ($x1, $y1, $r) = @_;
    my $z;
    for(my $x = $x1 - $r; $x < ($x1 + $r); $x++){
        for(my $y = $y1 - $r; $y < ($y1 + $r); $y++){
            my $dx = $x - $x1;
            my $dy = $y - $y1;
            $z = ($r * $r) - (($dx * $dx) + ($dy * $dy));
            if($z > 0 and $x > 0 and $y > 0){
                $heightmap[$x][$y] += $z;
            }
        }
    }
}

sub dumpToDb {
    my $dbh = DBI->connect("dbi:SQLite:dbname=server.sqlite",'','')
            or die DBI::errstr;
    my $sth = $dbh->prepare("INSERT INTO map_heights(lat_pt, long_pt, z_pt)".
                            "VALUES(?, ?, ?)");
    for(my $x = 0; $x < MAX_X; $x++){
        for(my $y = 0; $y < MAX_Y; $y++){
            $sth->execute($x, $y, $heightmap[$x][$y]);
        }
    }
    $dbh->disconnect();
}

sub dumpToImg {
    my $im = Image::Magick->new;
    my $junk = MAX_X.'x'.MAX_Y;
    print $junk."\n";
    $im->Set(size => $junk);
    $im->ReadImage('canvas:white');
    warn "$im" if "$im";
    for(my $x = 0; $x < MAX_X; $x++){
        for(my $y = 0; $y < MAX_Y; $y++){
            my $z = $heightmap[$x][$y];
            my @pixel = ($z, $z, $z);
            $im->SetPixel(x=>$x, y=>$y, color=>\@pixel);
        }
    }
    my $x = $im->Write('heightmap.png');
    warn "$x" if "$x";
}


texts: Analyzing distances between clusters of orders

texts:
I wrote the Python class below, which does what I want it to do, but the data structure is a mess. Was wondering if there was a better structure I could use to get the same results but with better readable code.

Idea here is we retrieve a dataset from SQL(constructor), cluster the dataset into distinct keys(constructor), iterate through the keys and isolate the matching criteria in the dataset(organizer), pass those data chunks to map_loc_to_lat_long which will find all possible combinations of rows in the chunk and find the straight line distance between all the combination Lat Longs.

class OrderProximityModel:
    def __init__(self, date):
        self.date = str(date)
        self.order_data = OrderProxDao().Load_Order_Lat_Long_Date_Zone_Data(self.date)
        self.distinct = set([str(row.Requirements) + ' ' + str(row.Route_Date) for row in self.order_data])

    def organizer(self):
        container = []
        for date_zone in self.distinct:
            latlng = list(filter(lambda x: str(x.Requirements) + ' ' + str(x.Route_Date) == date_zone, self.order_data))
            for i in self.map_loc_to_lat_long(latlng):
                container.append((i[0][0][0], i[0][0][1], i[0][0][2], i[0][0][4], i[0][0][5], i[0][0][6]))
        InsertHelpers(container).chunk_maker(100)
        return True

    def map_loc_to_lat_long(self, grouped_zone):
        converted = {}
        for row in grouped_zone:
            converted[row.LocationKey] = [row.Latitude, row.Longitude, row.DA, row.Route_Date, row.Requirements, row.DA]
        grouped_combos = self.combo_creator(converted.keys())
        return map(lambda combo: ([converted[combo[0]][2:] + [combo[0]] + [combo[1]] +
                                  [StraightLineDistance().dist_cal(converted[combo[0]][0],
                                                                   converted[combo[0]][1],
                                                                   converted[combo[1]][0],
                                                                   converted[combo[1]][1])]],
                                  ), grouped_combos)

    @staticmethod
    def combo_creator(inputs):
        out = []
        for index, value in enumerate(inputs):
            for nex_value in inputs[index + 1:]:
                out.append((value, nex_value))
        return out


texts: Automated batch and python skeleton script file creation

texts:
The code below uses a single command line 'filename' argument to create a batch and python skeleton script file in the cwd. The python file is then automatically opened in IDLE for convenience.

As a beginner making a significant amount of python files for worked educational examples this could save me 15 minutes per day.

Example usage for the below code which is named "make.py":

Cd in command line to the desired wd
Input script name("make") and the desired name of the files to be created minus any filename extension(in this case "test") as the single argument

Batch file created("test.bat"):

@py.exe C:\Users\Dave\Desktop\2016Coding\AutomateBoring\18-GUIAutomation\test.py %*
@pause

Python file("test.py") created in cwd and which is opened automatically in IDLE:

#! python3

#

import logging

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - " +\
            "%(levelname)s - %(message)s")

def main():
    pass

if __name__ == "__main__":
    main()

Code:

#! python3

# Takes a command line filename and creates a batch file and .py file
# named "filename" in the cwd. The python file contains a basic script
# framework. In additon, the python file will be automatically opened.

import argparse
import os
import subprocess

def handle_input():
    """Parses user commandline input"""

    parser = argparse.ArgumentParser()
    parser.add_argument("filename", type=str,
                        help="The name of the files to create minus any" +\
                        "extensions.")
    args = parser.parse_args()
    return args.filename

def make_batch(filename: str, cwd: str):
    """Makes a batch file name "filename" in "cwd"""

    filepath = os.path.join(cwd, filename + ".bat")
    with open(filepath, "w") as f:
        f.write("@py.exe " + os.path.join(cwd, filename + ".py ") +
                "%*\n@pause")
    print("\nCreated batch file: {}".format(filepath))

def make_py(filepath: str):
    """Makes a .py file in cwd written with a basic skelton script"""

    # *****I realize it's a simpler task to copy a template from a .
    # py file created for the purpose and write that to the new .py*****

    shebang = "#! python3\n\n"
    comment = "#\n\n"
    imports = "import logging\n\n"
    logging = "logging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - " \
              "\" +\\\n\t\t    \"%(levelname)s - %(message)s\")\n\n"
    functions = "def main():\n\tpass\n\n"
    main = "if __name__ == \"__main__\":\n\tmain()"

    with open(filepath, "w") as f:
        f.write(shebang + comment + imports + logging + functions + main)
    print("Created .py file: {}".format(filepath))

def open_py_idle(filename: str):
    """Opens a .py file in IDLE using subprocess"""

    idle_path = r"C:\Users\Dave\AppData\Local\Programs\Python\Python35" +\
                r"-32\Lib\idlelib\idle.bat"
    subprocess.run([idle_path, filename], shell=True)

def main():
    """Creates .bat and .py file in cwd. Auto opens .py file"""

    filename = handle_input()
    cwd = os.getcwd()
    python_file = os.path.join(cwd, filename + ".py")

    # ensure an existing python file is not overwritten
    if not os.path.exists(python_file):
        # make .bat file named "filename" in cwd
        make_batch(filename, cwd)
        # make .py file
        make_py(python_file)
        # open .py file in idle
        open_py_idle(python_file)
    else:
        print("\n.py file already exists: {}".format(python_file))

    print("\n*****Done*****\n")

if __name__ == "__main__":
    main()


texts:
So I noticed Chrome has quirky behaviour when it encounters script tags whose src is a base64 value. I decided to write a quick jQuery method that is supposed to work around it:

jQuery.extend({

    /**
     * Takes a script decodes the base64 src, puts it into the body of the script tag,
     * then puts it in whatever parent specified.
     *
     * @requires https://plugins.jquery.com/base64/
     *
     * @param  {Object} script The script tag that should be manipulated
     * @param  {Object} parent The parent element to append the final script tag to.
     *
     * @return {Object}        The script tag in question
     */
    importBase64Script : function ( script, parent ) {

        // Check for base64 library
        if ( typeof $.base64 === 'undefined' )
            throw 'No $.base64 found!';

        // Sanitize our script var
        // Normalize our script object
        script = ( script instanceof jQuery ? script : $(script) );

        // Check if it is a script tag
        if ( script[0].tagName !== "SCRIPT" )
            throw "Not a script tag";

        // Set default parent value
        parent = parent || $('head');
        // Normalize our parent var
        parent = ( parent instanceof jQuery ? parent : $(parent) );

        // We're gonna extract the base64 value
        var re        = /data:[a-z]+\/[a-z]+;base64,([0-9a-zA-Z\=\+]+)/,
        base64Content = script.prop('src').match(re)[1],
        scriptContent = $.base64.decode( base64Content );

        // Drop the decoded javascript into the contents of the script tag
        script.html( scriptContent );
        // Clear src value
        script.prop('src','');

        // Append it to the parent
        parent.append(script);

        return script;

    }
});

I tested a few of the conditions on JsPerf to see which is better performance wise. Granted, I didn't do a full sweep on every browser.

Any suggestions that anybody could make?


texts:
I created a quick function to convert n bytes into binary for my student.
She is not on that level yet, but I think it would be best for her if my demonstrative functions aren't trash.
void binary (void* p, size_t nBytes)
{
    int iBit    = 0;
    int iByte   = 0;

    putchar('[');

    for(iByte = 0; iByte < nBytes; iByte++)
    {
        for(iBit = 0; iBit < CHAR_BIT; iBit++)
        {
            int bit = ((unsigned char* )p)[iByte] >> iBit;

            putchar((bit & 1) ? '1':'0');
        }

        if(iByte < nBytes-1)
        {
            printf("]\t[");
        }
    }

    printf("]\n");
}

it goes with a macro for easier use: #define BINARY(x) binary(&x, sizeof x)
and the obvious disadvantage that it expects a variable and not cannot work with literals.

And yes, endianness is explained to her.


texts: Cracking the Coding Interview - 4.1 Graph Traversal

texts:
I'm working through the classic Cracking the Coding Interview book. I'm trying to solve the following graph problem:

  4.1) Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

I've written a solution in JavaScript and found it was a lot less complicated than the book's solution. Am I missing something? Why does the solution use a Visiting state? Can't we just use Visited instead?

function RouteBetweenNodes( node1, node2 ) {

    const q = new Queue()
    q.add( node1 )

    while ( !q.isEmpty() ) {
        const node = q.remove()
        if ( node === node2 ) {
            return true
        }
        node.visited = true
        node.children.forEach( child => !child.visited && q.add( child ) )
    }

    return false

}

Here is an implementation of a Queue for completeness:

class QueueNode {

    constructor( data ) {
        this.data = data
        this.next = null
    }

}

class Queue {

    constructor() {
        this.first = null
        this.last = null
    }

    add( item ) {
        const newNode = new QueueNode( item )
        if ( this.last ) {
            this.last.next = newNode
        } else {
            this.first = newNode
        }
        this.last = newNode
    }

    remove() {
        if ( this.first ) {
            const data = this.first.data
            this.first = this.first.next
            if ( this.first == null ) {
                this.last == null
            }
            return data
        }
        throw Error( 'empty queue' )
    }

    peek() {
        if ( this.first ) {
            return this.first.data
        }
        throw Error( 'empty queue' )
    }

    isEmpty() {
        return this.first === null
    }

}

Here is the book's solution.


texts: Implementing `concat` using `foldTree` on Rose Tree

texts:
I attempted (incorrectly) to implement foldTree here.

Recently, I updated it per Petr's help:

treeFold :: (b -> [b] -> b) -> (a -> b) -> Tree a -> b
treeFold f g tree = f (g (rootLabel tree)) (map (treeFold f g) (subForest tree))

I implemented toList:

toList :: Tree a -> [a]
toList = treeFold (\x y -> x ++ (foldr (++) [] y)) (\x -> [x])

Test

ghci> stringTree
Node {rootLabel = "foo",
      subForest =
                [Node {rootLabel = "bar", subForest = []},
                 Node {rootLabel = "bippy", subForest = []},
                 Node {rootLForest = []}]}

ghci> toList stringTree
["foo","bar","bippy","baz"]

I'm not sure if it's idiomatic to include the foldr call. Nor am I sure if I like the usage of ++.

Please review this code.


texts:
I'm quite new to Go and I feel like this code could be smaller and cleaner.

I would love any suggestions and/or hints about mistakes and conventional go things!

func getBookTitle(client *http.Client) {
    rsp, err := client.Get(bookSite)
    if err != nil {
        panic(err)
    }
    html, _ := ioutil.ReadAll(rsp.Body)

    //Get div with title
    regTitle := regexp.MustCompile("(
)[\n+\\s]*(
)[a-zA-Z–\\-\n\\s:]*(
)[\n+\\sdd]*(
)")
    //remove linebreaks regex
    regFormatTitle := regexp.MustCompile("[\r\n]*")
    //apply regex
    title := regFormatTitle.ReplaceAllString(string(regTitle.Find(html)),"")
    //Remove remove html tags and remove whitespaces
    title =  strings.TrimSpace(title[strings.Index(title,"
")+len("
"):strings.Index(title,"
")])

    fmt.Printf("Book title:%s\n",title)

    rsp.Body.Close()
}


texts: Adding a replica of some DOM elements on click

texts:
I have the following code which inserts a new element of the same type over and over again to the parent element. I am new to JavaScript so was wondering if there was a better way of doing this. I apologise for the variable names, I'll get around to changing those later, just allows me to see the flow better. I'm trying to write this in pure js.

//Add a new lobby element
document.getElementById("addLobby").addEventListener("click", function(e) {
  var layer1 = document.createElement("div");
  layer1.setAttribute("class","col-wd-12 col-md-6 col-sm-4");
  var layer2 = document.createElement("div");
  layer2.setAttribute("class","col lobby");
  var layer3 = document.createElement("div");
  layer3.setAttribute("class","col lobby-infoPanel");
  var layer3v2 = document.createElement("div");
  layer3v2.setAttribute("class","overlay lobby-overlay");
  var layer3v2v1 = document.createElement("a");
  layer3v2v1.setAttribute("href","#");
  var l3v2v1v1 = document.createElement("span");
  l3v2v1v1.setAttribute("class", "overlay-options lobby-overlay-options");
  var layer4 = document.createElement("div");
  layer4.setAttribute("class","col lobby-info-count");
  var layer4v2 = document.createElement("div");
  layer4v2.setAttribute("class","col lobby-info-count lobby-info-users");

  var l3v2v1v1Text = document.createTextNode("+");
  var l4text = document.createTextNode("5/5");
  var l4v2text = document.createTextNode("@User1");

  layer4v2.appendChild(l4v2text);
  layer4.appendChild(l4text);
  layer3.appendChild(layer4);
  layer3.appendChild(layer4v2);
  l3v2v1v1.appendChild(l3v2v1v1Text);
  layer3v2v1.appendChild(l3v2v1v1);
  layer3v2.appendChild(layer3v2v1);
  layer2.appendChild(layer3);
  layer2.appendChild(layer3v2);
  layer1.appendChild(layer2);

  var lastNode = document.getElementById("addLobby").parentElement;
  lastNode.parentElement.insertBefore(layer1, lastNode);
});


texts: Assembling and traversing a graph, given a list of items and parent pointers

texts:
I've written a function which takes input such as this:

lines: [
    { id: 1, name: "1" },
    { id: 2, name: "2" },
    { id: 9, superIds: [1, 2], name: "Shared…" },
    { id: 3, superIds: [2], name: "2.1" },
    { id: 4, superIds: [2], name: "2.2" },
    { id: 5, superIds: [3], name: "2.1.1" },
    { id: 6, superIds: [5], name: "2.1.1.1" },
    { id: 7, superIds: [4], name: "2.2.1" },
    { id: 8, superIds: [2], name: "2.3" },
    { id: 10, superIds: [9], name: "Shared.1" },
    { id: 11, superIds: [8], name: "2.3.1" }
]

And transforms it to output such as this:

1
 Shared…
   Shared.1
2
 Shared… (ref)
 2.1
   2.1.1
     2.1.1.1
 2.2
   2.2.1
 2.3
   2.3.1

The way that's done is this.

*recurse(superId, instanceSuperIds, level) {
    for (const line of lines) { // `lines` is the input above
        const index = (line.superIds || [undefined]).indexOf(superId);
        const instanceSuperId = instanceSuperIds[line.id];
        if (index !== -1) {
            if (instanceSuperId ? superId === instanceSuperId : index === 0) {
                yield { /*...*/line, level, isInstance: true };
                yield *recurse(line.id, instanceSuperIds, level + 1);
            } else {
                yield { /*...*/line, level, isInstance: false };
            }

        }
    }
}

const instanceSuperIds = [];
instanceSuperIds[9] = 1;

console.time();
for (const line of this.recurse(undefined, instanceSuperIds, 0)) {
    console.debug(Array(line.level * 2).join(" "), line.line.name + (!line.isInstance && " (ref)" || ""));
}

console.timeEnd();

Right now this is 132 loop iterations. Of course this number won't get any smaller as the number of lines grows.

Is there an obvious optimalization I am missing? (This feels like basic CS will have answers, but I don't have basic CS.)


texts: Pointers to polymorphic classes saved in vector that reference data in a list as source

texts:
I have a list called data with strings in it. I have a class String that derives from class Item. A class Scene to which I can add Items that are put in a vector. Scene has a print function to show the current Items.

If I change an element in the data list it also changes what it prints in the Scene.print().

When I remove an item from a Scene with function del it also removes the element in data (list).

Is this a good way to do it am I missing something? The code is actually for a game where I want to add items with coordinates in a scene. Each item has its own function to draw itself etc. and when I remove an item from the scene the data it relates to should be removed too.

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

using namespace std;

list<string> data;

class Item {
public:
    Item() {
    }

    virtual void print() = 0;
};

class String : public Item {
public:
    String(string &s) {
        _s = &s;
    }

    virtual void print() override {
        cout << *_s << endl;
    }

    string  *_s;

    string ret() {
        return *_s;
    }
};

class Scene {
public:
    void add(shared_ptr<Item> item) {
        _items.push_back(item);
    }

    void del(int n) {
        shared_ptr<Item> pa = _items[n];
        shared_ptr<String>pb = dynamic_pointer_cast<String>(pa);

        if (pb) {
            data.remove(pb->ret());
        }

        _items.erase(_items.begin()+n);
    }

    void print() {
        for(int i = 0; i < _items.size(); i++) {
            _items[i]->print();
        }
    }

    vector<shared_ptr<Item>> _items;
};

void print (list<string> l) {
    for (std::list<string>::iterator it = l.begin(); it != l.end(); ++it) {
        cout << "data: " << *it << endl;
    }
}

int main() {
    Scene s;

    data.push_back("first");
    data.push_back("seconed");
    data.push_back("third");
    data.push_back("fourth");

    std::list<std::string>::iterator it = data.begin();

    for (std::list<string>::iterator it = data.begin(); it != data.end(); ++it) {
        s.add(make_shared<String>(*it));
    }

    s.print();

    *it++;
    *it = "$$$";

    s.print();

    print(data);

    s.del(1);
    s.del(1);

    s.print();
    print(data);

    return 0;
}
```


texts: Function to count rows in a database query result

texts:
I have written this function that surprisingly works. (I didn't really know what I was doing; just a little experiment.) It is supposed to count rows selected by a PDO query.

Is it well written? It works, but I am just asking, as it is my first more-complex function.

function countRows($sql, $parameters){
            require("include/db.php");

            $result = $db->prepare($sql);
            foreach ($parameters as $key => $parameter) {
                    $result->bindParam($key, $parameter);
            }

            $result->execute();
            $number_of_rows = $result->fetchColumn();

            return $number_of_rows;

            }


texts:
I'm currently working with Web Audio for creating a simple synth like project in the browser and implementing controls for the Oscillators via jQuery/jQueryUI:

var wF = {
    0: "sine",
    1: "square",
    2: "sawtooth",
    3: "triangle"
};
$(function () {
    $("#osc1_wave").slider({
        min: 0,
        max: 3,
        value: 0,
        step: 1,
        slide: function (event, ui) {
            $("#cur_wave_osc1").val(wF[ui.value]); <--------
            osc1.type.value = $("#cur_wave_osc1").val(); <------------
        }
    });
    //initial waveform.//
    $("#cur_wave_osc1").val("Sine");
});

jsFiddle


texts:
I have two modules, Notification which basically contains SignalR hubs and CoreSetup which contains core setup logic in it.

I have a class in CoreSetup module which keeps track of employee location . I want SignalR hubs to be notified and those locations to be on MAP when new data are inserted through Web API.
I don't want CoreSetup module to have dependency on SignalR module.
This is what I have done currently.

[Route("api/salesman-location")]
[ApiController]
public class SalesmanLocationController : BaseController
{
    private readonly SalesmanLocationService _salesmanLocationService;
    private readonly IHubContext<ChatHub> _hubContext;

    public SalesmanLocationController(SalesmanLocationService salesmanLocationService,IHubContext<ChatHub> hubContext)
    {
        _salesmanLocationService = salesmanLocationService;
        _hubContext = hubContext;
    }

    [Route("save")]
    [HttpPost]
    public IActionResult save([FromBody]List<SalesmanLocationDto> datas)
    {
        try
        {
            _hubContext.Clients.All.SendAsync("SalesManLocationfromHub", datas);
            _salesmanLocationService.save(datas);
            return Ok();
        }
        catch (CustomException ex)
        {
            return ApiResponse.getErrorResponseJson(ex.Message);
        }
        catch (Exception ex)
        {
            return ApiResponse.getErrorResponseJson("Failed to save data.");
        }
    }
}

It works pretty well but I have some logic inside save() method of SalesmanLocationService . It would be great if hub can subscribe to save() method of SalesmanLocationService without  SalesmanLocationService knowing anything about Hub.Under some condition, I should not broadcast data through hub.

This is how my interface of SalesmanLocationService looks like:

 public interface SalesmanLocationService
    {
        void save(List<SalesmanLocationDto> datas);
    }

This is the actual implementation of SalesmanLocationService

 public class SalesmanLocationServiceImpl : SalesmanLocationService
    {
        public SalesmanLocationServiceImpl()
        {
        }

        public void save(List<SalesmanLocationDto> datas)
        {
           foreach (var data in datas)
           {
            save(data);
           }
        }

        private void save(SalesmanLocationDto data)
        {
           if(someCondition){
             //broadcast to hub
           }
        }
    }


texts: All-purposes AJAX handler made with PHP and .htaccess that speaks JSON - Part 2

texts:
Earlier, I've posted a question about a file used to handle AJAX requests.

I've followed some of the advices given and made some changes on the code itself.

You can go on "All-purposes AJAX handler made with PHP and .htaccess that speaks JSON" to read more information about it's working.

This is simply a follow-up, and I will only present here the PHP code:

<?php
    define( 'ROOT', $_SERVER['DOCUMENT_ROOT'] ); //define the root beforehand

    //if the cookie isn't set or the session failed or you aren't an admin or your level is inferior to 2
    if( !isset( $_COOKIE[session_name()] ) || !@session_start() || !isset($_SESSION['admin']) || $_SESSION['admin']['level']<2 )
    {
        //you aren't allowed here
        header( 'HTTP/1.1 403 Forbidden' );
        echo '{"error":403}';
    }
    //if the file exists and the name has the proper format (to avoid stuff like ../../../../../killall$\.php)
    else if( @is_file($file = ROOT.'/ajax/'.preg_replace('@^/([a-z_]+)\.php@', '$1', $_SERVER['ORIG_PATH_INFO']).'.php') )
    {
        ob_start(); //avoid 'leaked' non-JSON garbage
        session_start();

        //database file, returns the result of mysqli_connection()
        if( $link = include ROOT.'/bd/bd.php' )
        {
            //returns a massive array with the translations
            $text = include ROOT.'/lang/'.$_SESSION['admin']['lang'].'.php';

            //the included files return an array or nothing (requiring the (array) there)
            $out = (array)include $file;
        }
        else
        {
            //indicates which error was it (in this case, a communication error)
            $out = array('error' => true, 'type' => 'link');
        }

        if( isset($_REQUEST['debug']) && $_SESSION['admin']['level']>=5)
        {
            //debug informations sent when the parameter ?debug is added
            //only allowed for administrators with level higher than 5
            $out['__debug'] = array(
                'mysql' => array(
                    'n' => mysqli_errno( $link ),
                    'desc' => mysqli_error( $link )
                ),
                '$_POST' => print_r( $_POST, true ),
                '$_SERVER' => print_r( $_SERVER, true ),
                '$_SESSION' => print_r( $_SESSION, true ),
                'last_error' => error_get_last(),

                'output' => ob_get_contents()
            );
        }

        ob_end_clean(); //clears the errors

        //outputs the JSON code to the browser
        echo json_encode( $out );
    }
    else
    {
        //if none of the conditions was met, send the error 404
        header( 'HTTP/1.1 404 Not Found' );
        echo '{"error":404}';
    }

Since the code looks a little more difference, I've made a new question instead of an edit in the older one.

Considering the new code, What else can I change?

What else can I improve?


texts: Split data from single CSV file into several CSV files by column value

texts:
Okay...so I have been self teaching for about seven months, this past week someone in accounting at work said that it'd be nice if she could get reports split up....so I made that my first program because I couldn't ever come up with something useful to try to make...all that said, I got it finished last night, and it does what I was expecting it to do so far, but I'm sure there are things that have a better way of being done.

I wanted to get it finished without help first, but now I'd like someone to take a look and tell me what I could have done better, or if there is a better way to go about getting the same results....

What this is doing is: it opens a CSV file (the file I've been practicing with has 27K lines of data) and it loops through, creating a separate file for each billing number, using the billing number as the filename, and writing the header as the first line.  Each instance is overwriting the file if it is already created, this is an area I'm sure I could have done better. After that, it loops through the data again, appending each line of data into the correct file.

import os
import csv

#currentdirpath = os.getcwd()
#filename = 'argos.csv'
#file_path = os.path.join(os.getcwd(), filename) #filepath to open

def get_file_path(filename):
    ''' - This gets the full path...file and terminal need  to be in
same directory - '''
    file_path = os.path.join(os.getcwd(), filename)
    return file_path

pathOfFile = get_file_path('argos.csv')
''' - Below opens and reads the csv file,
    then going to try to loop and write the rows out in files sorted
by Billing Number - '''
with open(pathOfFile, 'rU') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader)
    for row in reader:
        new_file_name = row[5][:5] + '.csv'
    ''' Create file named by billing number, and print the header to
each file '''
        fb = open(new_file_name, 'w+')
        fb.write(str(header) + '\n')
        #fb.close()
with open(pathOfFile, 'rU') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        new_file_name = row[5][:5] + '.csv'
        ab = open(new_file_name, 'a')
        ab.write(str(row) + '\n')

I've left a few of the things in there that I had at one point, but commented out...just thought it might give you a better idea of what I was thinking...any advice is appreciated!


texts: Lowest Common Multiple of 1 to n in Ruby

texts:
Project Euler problem 5 asks:

  What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

I'm learning Ruby by going through Project Euler problems, and though I got the following code right (as in the answer given by it), I'm not sure if I'm doing things quite the "Ruby way". Hence, I wanted the community's opinion of my code to better understand alternatives to my code (using the same algorithm please!), so that I don't become used to writing "C++ using Ruby!"

def prime? x
  (2..x-1).each { |y| return false if x % y == 0 }
  true
end

def primes_upto n
   p = Array.new
   (2..n-1).each {|x| p.push(x) if prime? x}
   return p
end

upto = 20 # The upper limit of the LCM range
primes = primes_upto upto
range  = Array.new(upto) {|i| i + 1}
lcm = 1
primes.each do |i|
flag = true
while flag and range.length > 0
  range.each do |x|
    if x % i == 0
      flag = true
      break
    else
      flag = false
    end
  end
  if flag
    lcm *= i
    range.map! {|y| y % i == 0? y/i : y}
  end
  range.delete(1)
  range.compact!
end
end
print "\nLCM of 1..", upto, " = ", lcm

In particular, I would like to take advantage of ruby's built-in operators on Array, to reduce the size of the code, as well as make it less of an if-then, while structure that I've seen in C++ programs.

The algorithm I've used can be found here (if its not obvious from the code!)