texts: Calculating the total of each column and display in footer of gridview in DataTable

texts:
I've used this code to get the sum of the values of each column and display in footer. Here, the advantage is that I don't have to look for the column name, just get the count of total number of rows and columns and then iterate over each row and column.

Please suggest how I can make this code more efficient or if there is any way to make this code block more effective.

#region column sum and show in footer
//loop all the rows in the datatable
int[] RowTotals = new int[dt_.Columns.Count];
foreach (DataRow row in dt_.Rows)
{
    if(dt_.Rows.IndexOf(row) !=0)
    {
        //loop all the columns in the row
        for (int i = 1; i < dt_.Columns.Count; i++)
        {
            //add the values for each cell to the total

            RowTotals[i] += Convert.ToInt32(row[dt_.Columns[i].ColumnName]);
        }
    }

}

//loop all the columns again to set the values in the footer

for (int i = 1; i < dt_.Columns.Count; i++)
{

    GridView1.FooterRow.Cells[i].Text = string.Format("{0:N2}", RowTotals[i]);
}
///////
#endregion


texts: Calculating the results of bit operations

texts:
I have a simple program that calculates and outputs the results of all the bit operators. I'm planning to send it to my friend and to explain some stuff about them to him. Before I do that, I want to know if I can make any improvements to my program.

internal class Program
{
    private static int a;
    private static int b;
    private static byte byteOperation;
    private static short int16Operation;
    private static int int32Operation;
    private static long int64Operation;

    private static void Main()
    {
        while (true)
        {
            bool numberA = int.TryParse(Console.ReadLine(), out a);
            bool numberB = int.TryParse(Console.ReadLine(), out b);
            if (!numberA || !numberB) Console.WriteLine("Input can be only numbers !");
            else
            {
                Console.WriteLine();
                byteOperation = (byte) (a & b);
                int16Operation = (short) (a & b);
                int32Operation = a & b;
                int64Operation = a & b;
                WriteLine("Binary AND", "&");

                byteOperation = (byte) (a | b);
                int16Operation = (short) (a | b);
                int32Operation = a | b;
                int64Operation = a | b;
                WriteLine("Binary OR", "|");

                byteOperation = (byte) (a ^ b);
                int16Operation = (short) (a ^ b);
                int32Operation = a ^ b;
                int64Operation = a ^ b;
                WriteLine("Binary XOR Operator", "^");

                byteOperation = (byte) (a << b);
                int16Operation = (short) (a << b);
                int32Operation = a << b;
                int64Operation = a << b;
                WriteLine("Binary Left Shift", "<<");

                byteOperation = (byte) (a >> b);
                int16Operation = (short) (a >> b);
                int32Operation = a >> b;
                int64Operation = a >> b;
                WriteLine("Binary Right Shift", ">>");

                byteOperation = (byte) (a << b | a >> 8 - b);
                int16Operation = (short) (a << b | a >> 16 - b);
                int32Operation = a << b | a >> 32 - b;
                int64Operation = a << b | a >> 64 - b;
                WriteLine("Circular Shift", "<< | >>", "<<", "|", ">>");
            }
        }
    }

    private static void WriteLine(string text, string ch)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(text + " : " + ch);
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Byte : {0} " + ch + " {1} = {2}", a, b, byteOperation);
        Console.WriteLine("Int16 : {0} " + ch + " {1} = {2}", a, b, int16Operation);
        Console.WriteLine("Int32 : {0} " + ch + " {1} = {2}", a, b, int32Operation);
        Console.WriteLine("Int64 : {0} " + ch + " {1} = {2}", a, b, int64Operation);
        Console.WriteLine();
    }

    private static void WriteLine(string text, string chFull, string ch1, string ch2, string ch3)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(text + " : " + chFull);
        Console.WriteLine();
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Byte : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 8 - {1}" + " = {2}", a, b, byteOperation);
        Console.WriteLine("Int16 : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 16 - {1}" + " = {2}", a, b, int16Operation);
        Console.WriteLine("Int32 : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 32 - {1}" + " = {2}", a, b, int32Operation);
        Console.WriteLine("Int64 : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 64 - {1}" + " = {2}", a, b, int32Operation);
        Console.WriteLine();
    }
}


texts:
I want to throttle asynchronous actions at a specific maximum rate of n actions per t period, and have pending actions wait until there is a free slot (rather than drop them). I want to receive the outcome When an action completes or fails.  I also want the option of cancelling an action.  The order of actions is unimportant, though I have been considering if a priority queue would be worth the trouble.

For example, if your maxActions was 2 and your maxPeriod 1 second, if 3 actions each taking 500 ms were queued simultaneously then the first two would run immediately and complete in 500ms but the 3rd would have to wait a whole second before starting, rather than starting at 500ms.

What I've come up with so far is based around two semaphores, one to control the number of actions active at any one time, and one to control the number of actions throughout the max period.  I release separately, because it is possible that a request may take longer than the given period.

Are there any logical errors to this approach (e.g., could a semaphore potentially never be released)? Is there a completely different approach that would be better?

public class Throttle
{
    private readonly TimeSpan _maxPeriod;
    private readonly System.Threading.SemaphoreSlim _throttleActions, _throttlePeriods;

    public Throttle(int maxActions, TimeSpan maxPeriod)
    {
        _throttleActions = new System.Threading.SemaphoreSlim(maxActions, maxActions);
        _throttlePeriods = new System.Threading.SemaphoreSlim(maxActions, maxActions);
        _maxPeriod = maxPeriod;
    }

    public Task<T> Queue<T>(Func<T> action, System.Threading.CancellationToken cancel)
    {
        return _throttleActions.WaitAsync(cancel).ContinueWith<T>(t =>
        {
            try
            {
                _throttlePeriods.Wait(cancel);

                // Release after period
                // - Allow bursts up to maxActions requests at once
                // - Do not allow more than maxActions requests per period
                Task.Delay(_maxPeriod).ContinueWith((tt) =>
                {
                    _throttlePeriods.Release(1);
                });

                return action();
            }
            finally
            {
                _throttleActions.Release(1);
            }
        });
    }
}


texts: Inserting into Group_roles table for all rows in Group table

texts:
I have five groups in Group table as Group1, Group2, Group3, Group4, Group5 and whenever a new role added into Role table I have to make an entry into GROUP_ROLES table as below:

declare @gid1 int, @gid2 int,@gid3 int,@gid4 int,@gid5 int,@rid int
select @gid1 = id from Group where name = 'Group1'
select @gid2 = id from Group where name = 'Group2'
select @gid3 = id from Group where name = 'Group3'
select @gid4 = id from Group where name = 'Group4'
select @gid5 = id from Group where name = 'Group5'
select @rid = id from ROLE where name = 'newRole'

if @gid1 is not null and not exists(select * from GROUP_ROLES where group_id = @gid1 and roles_id = @rid)
begin
insert into GROUP_ROLES(group_id, roles_id) values (@gid1, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid2, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid3, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid4, @rid)
insert into GROUP_ROLES(group_id, roles_id) values (@gid5, @rid)
end

Right now I kinda have a redundant script. Is there a way to simplify the script?


texts: Cropping faces from images in a directory

texts:
I am using the below code for cropping faces from images in a directory

import cv2
import glob
import os

def facechop(image,imgname):
    facedata = "haarcascade_frontalface_default.xml"
    cascade = cv2.CascadeClassifier(facedata)

    img = cv2.imread(image)

    minisize = (img.shape[1],img.shape[0])
    miniframe = cv2.resize(img, minisize)

    faces = cascade.detectMultiScale(miniframe)

    for f in faces:
        x, y, w, h = [ v for v in f ]
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,255,255))

        sub_face = img[y:y+h, x:x+w]
        face_file_name = "faces/" + imgname + "_" + str(y) + ".jpg"
        cv2.imwrite(face_file_name, sub_face)

    # cv2.imshow(image, img)
    # cv2.waitKey(0)
    cv2.destroyAllWindows()

    return

# if __name__  '__main__':
path = "images"
images = glob.glob(path + "/*")
for imgpath in images[0:]:
    imagename = os.path.basename(imgpath)
    imgname = os.path.splitext(imagename)[0]
    facechop(imgpath, imgname)
    print(imgname,"exported")

# while(True):
#     key = cv2.waitKey(20)
#     if key in [27, ord('Q'), ord('q')]:
#         break

The code is too slow and sometimes even hangs the system. Please help improve.


texts:
The function hash_blog is inspired by "how git stores its objects". It is supposed to take a String, append a header to it, compute the SHA1 of it, then compress it and write it to a file. The first two characters of SHA1 is a directory name, and the rest of the characters are the file name.

Since I am learning the language, I am looking for general review. Is my code idiomatic Java code? Are there parts where I could make the code better?

package yas;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.DeflaterOutputStream;
// import java.util.zip.Inflater;

public class Yas {

    public static void main(String[] args) {
        try {
            hash_blob("yasar arabaci");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     * @throws NoSuchAlgorithmException
     */
    public static String hash_blob(String content) throws NoSuchAlgorithmException {

        String hash_string; // hold sha1 hash
        String input = "blob " + content.length() + '\0' + content;

        // Step 1 is to compute sha1
        MessageDigest mDigest = MessageDigest.getInstance("SHA1");
        byte[] result = mDigest.digest(input.getBytes());
        { // to create namespace for StringBuilder
            // This code block was borrowed from internet ;)
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.length; i++) {
                sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
            }
            hash_string = sb.toString();
        }
        System.out.println("hash string is " + hash_string);
        // Step 3 is to write to a file

        File dest_file;
        {
            File yas_dir = new File(System.getProperty("user.dir"), ".yas");
            File object_dir = new File(yas_dir, "objects");
            File dest_dir = new File(object_dir, hash_string.substring(0, 2));
            dest_dir.mkdirs();
            dest_file = new File(dest_dir, hash_string.substring(2));
            System.out.println("dest file = " + dest_file);
        }
        try {
            if (!dest_file.exists()) {
                dest_file.createNewFile();
            }
            try (OutputStream out = new DeflaterOutputStream(new FileOutputStream(dest_file))) {
                out.write(input.getBytes());
            }

        } catch (IOException e) {
            e.printStackTrace();;
        }
        return "Dummy Return";

    }
}


texts: Making a function which can be called with an object literal

texts:
I am working on a code snippet to make a function which can be called with an object literal.

Problem area: If I do not need to track the product value, then a check has been placed for undefined. But do I really need to make check for each and every value if it's not there in the object literal?

trackProduct = function (args) {

      if(args.label == undefined) {
        value.push([args.category, args.action, args.value]);
      } else if(args.value == undefined){
        value.push([args.category, args.action, args.label]);
      } else {
        value.push([args.category, args.action, args.label, args.value]);
      }
};

I'm calling this function via below object literal. I have not passed the value parameter.

trackProduct({
    category: elemcategory,
    action: elemaction,
    label: elemlabel
});

Do we need to check for undefined for all three parameters? Any suggestions on how to improve this code?


texts:
My professor wants me to do this:

  Write a number of interchangeable counters using the Counter interface below:

public interface Counter {
/** Current value of this counter. */
int value();
/** Increment this counter. */
void up();
/** Decrement this counter. */
void down();
}

I need comments on my work so far.  Do you think it's sufficient?  How do I work on the ResetableCounter?  I'm very new to Java and it's been a long time since I've done C++.

Develop the following:

  An interface ResetableCounter that supports the message void reset() in addition to those of Counter.

Here's what I did:

public interface ResetableCounter {
void reset();
int value();
void up();
void down();
}

  An implementation of ResetableCounter called BasicCounter that starts at the value 0 and counts up and down by +1 and -1 respectively.

Here's what I did:

public class BasicCounter implements ResetableCounter
    {
      int counterVariable = 0;
    public static void main(String[] args)
    {
        BasicCounter cnt = new BasicCounter();
        cnt.up();
        cnt.down();
        System.out.printf("The value is %d", cnt.counterVariable);
    }

    public void reset() {
        this.counterVariable = 0;
    }

    public int value() {
        return this.counterVariable;
    }

    public void up() {
        ++this.counterVariable;
    }

    public void down() {
        --this.counterVariable;
    }
    }

  An implementation of ResetableCounter called SquareCounter that starts at the value 2, counts up by squaring its current value, and counts down by taking the square root of its current value (always rounding up, i.e. 1.7 is rounded to 2, just like 1.2 is rounded to 2).

Here's what I did:

public class SquareCounter implements ResetableCounter {
int counterVariable = 2;
public static void main(String[] args) {
    SquareCounter cnt = new SquareCounter();
    cnt.up();
    cnt.down();
    double d = Math.ceil(cnt.counterVariable);
    System.out.printf("The value is %f", d);
}

public void reset() {
    this.counterVariable = 0;
}

public int value() {
    return this.counterVariable;
}

public void up() {
    Math.pow(this.counterVariable, 2);
}

public void down() {
    Math.sqrt(this.counterVariable);
}
 }

  An implementation of ResetableCounter called FlexibleCounter that allows clients to specify a start value as well as an additive increment (used for counting up) when a counter is created. For example new FlexibleCounter(-10, 3) would yield a counter with the current value -10; after a call to up() its value would be -7.

public class FlexibleCounter implements ResetableCounter
{
public static void main(String[] args)
{
    int start = Integer.parseInt(args[0]);
    int step = Integer.parseInt(args[1]);
    start.up();
    System.out.printf("The value is %d", count);
}

public void reset() {
    this.count = 0;
}

public int value() {
    return this.count;
}

public void up() {
    this.count = args[0] + args[1];
}

public void down() {
    --this.count;
}
}

  All of your implementations should be resetable, and each should contain a main method that tests whether the implementation works as expected using assert as we did in lecture (this is a simple approach to unit testing which we'll talk about more later).


texts: Is there a more optimal way to approach some of these bitwise functions?

texts:
I completed some bit manipulation exercises out of a textbook recently and have grasped onto some of the core ideas behind manipulating bits firmly. My main concern with making this post is for optimizations to my current code. I get the hunch that there are some functions that I could approach better. Do you have any recommendations for the following code?

#include <stdio.h>
#include "funcs.h"

// basically sizeof(int) using bit manipulation
unsigned int int_size(){
    int size = 0;
    for(unsigned int i = ~00u; i > 0; i >>= 1, size++);
    return size;
}

// get a bit at a specific nth index
// index starts with 0 on the most significant bit
unsigned int bit_get(unsigned int data, unsigned int n){
    return (data >> (int_size() - n - 1)) & 1;
}

// set a bit at a specific nth index
// index starts with 0 on the most significant bit
unsigned int bit_set(unsigned int data, unsigned int n){
    return data | (1 << (int_size() - n - 1));
}

// gets the bit width of the data (<32)
unsigned int bit_width(unsigned int data){
    int width = int_size();
    for(; width > 0; width--)
        if((data & (1 << width)) != 0)
            break;
    return width + 1;
}

// print the data contained in an unsigned int
void print_data(unsigned int data){
    printf("%016X = ",data);
    for(int i = 0; i < int_size(); i++)
        printf("%X",bit_get(data,i));
    putchar('\n');
}

// search for pattern in source (where pattern is n wide)
unsigned int bitpat_search(unsigned int source, unsigned int pattern,
        unsigned int n){
    int right = int_size() - n;
    unsigned int mask = 0;
    for(int i = 0; i < n; i++)
        mask |= 1 << i;
    for(int i = 0; i < right; i++)
        if(((source & (mask << (right - i))) >> (right - i) ^ pattern) == 0)
            return i - bit_width(source);
    return -1;
}

// extract {count} bits from data starting at {start}
unsigned int bitpat_get(unsigned int data, int start, int count){
    if(start < 0 || count < 0 || int_size() <= start || int_size() <= count || bit_width(data) != count)
        return -1;
    unsigned int mask = 1;
    for(int i = 0; i < count; i++)
        mask |= 1 << i;
    mask <<= int_size() - start - count;
    return (data & mask) >> (int_size() - start - count);
}

// set {count} bits (basically width of {replace}) in {*data} starting at {start}
void bitpat_set(unsigned int *data, unsigned int replace, int start, int count){
    if(start < 0 || count < 0 || int_size() <= start || int_size() <= count || bit_width(replace) != count)
        return;
    unsigned int mask = 1;
    for(int i = 0; i < count; i++)
        mask |= 1 << i;
    *data = ((*data | (mask << (int_size() - start - count))) & ~(mask << (int_size() - start - count))) | (replace << (int_size() - start - count));
}


texts:
I am learning circular / cyclic buffer using this link. Here is the code that I have written so far:

#include <iostream>
#include <memory>
#include <cstddef>

class CircularBuffer
{
    std::unique_ptr<int[]> u_ptr;
    std::size_t head;
    std::size_t tail;
    const std::size_t capacity;
    bool full_v;
public:
    CircularBuffer(std::size_t);
    void reset();
    bool full() const;
    bool empty() const;
    std::size_t size() const;
    void write(int);
    int read();
};

// Constructor
// Set the capacity via initializer list because it is const
CircularBuffer::CircularBuffer(std::size_t space):capacity{space}
{
    u_ptr = std::unique_ptr<int[]>(new int[space]);
    head = 0;
    tail = 0;
    full_v = false;
}

// Reset the Buffer
void CircularBuffer::reset()
{
    head = 0;
    tail = 0;
    full_v = false;
    u_ptr[head] = int{};
}

// Check if buffer is full
bool CircularBuffer::full() const
{
    return full_v;
}

// Check if buffer is empty
bool CircularBuffer::empty() const
{
    return (!full_v && head == tail);
}

// Return the size of the buffer
std::size_t CircularBuffer::size() const
{
    if(full_v)
    {
        return capacity;
    }
    if(head >= tail)
    {
        return head - tail;
    }
    else
    {
        return capacity - (tail - head);
    }
}

// Write values into the buffer
void CircularBuffer::write(int data)
{
    u_ptr[head] = data;
    head = (head + 1) % capacity;
    if(full_v)
    {
        tail = (tail + 1) % capacity;
    }
    full_v = (head == tail);
}

// Read from buffer
int CircularBuffer::read()
{
    if(this -> empty())
    {
        return int{};
    }
    int ret_val = u_ptr[tail];
    full_v = false;
    tail = (tail + 1) % capacity;
    return ret_val;
}

int main()
{
    CircularBuffer cb{10};
    std::cout << "Empty: " << cb.empty() << "\n";
    for(int i = 0; i < 10; i++)
    {
        cb.write(i);
    }
    std::cout << "Full: " << cb.full() << "\n";
    std::cout << "Read: " << cb.read() << "\n";
    std::cout << "Full: " << cb.full() << "\n";
    std::cout << "Empty: " << cb.empty() << "\n";
    std::cout << "Size: " << cb.size() << "\n";
    cb.write(35);
    std::cout << "Size: " << cb.size() << "\n";
    std::cout << "Read: " << cb.read() << "\n";
    std::cout << "Size: " << cb.size() << "\n";
    cb.reset();
    std::cout << "Size: " << cb.size() << "\n";
    return 0;
}

Is the implementation correct? What are the shortcomings that can be fixed?
I see that the original reference uses a mutex object and uses lock. Is such an approach used with all data structures? If not, is there a reason why that has been used here?


texts:
Am teaching myself about sorting techniques and trying my hand at a quicksort implementation. I found a lot of examples based on recursion but didn't want to go that route in a language that doesn't support tail-call optimization.

public static class ListExtensions
{
    public static void InsertionSort<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer) {
        var left = startIndex;
        var right = 0;
        var temp = default(T);

        while (left < endIndex) {
            right = left;
            temp = values[++left];

            while ((right >= startIndex) && (0 < comparer.Compare(values[right], temp))) {
                values[(right + 1)] = values[right--];
            }

            values[(right + 1)] = temp;
        }
    }
    public static void InsertionSort<T>(this IList<T> values, IComparer<T> comparer) {
        InsertionSort(values, 0, (values.Count - 1), comparer);
    }
    public static void InsertionSort<T>(this IList<T> values) {
        InsertionSort(values, Comparer<T>.Default);
    }
    public static void QuickSort<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
        var range = (startIndex, endIndex);
        var stack = new Stack<(int, int)>();

        do {
            startIndex = range.startIndex;
            endIndex = range.endIndex;

            if ((endIndex - startIndex + 1) < 31) {
                values.InsertionSort(startIndex, endIndex, comparer);

                continue;
            }

            var pivot = values.SampleMedian(startIndex, endIndex, comparer, randomNumberGenerator);
            var left = startIndex;
            var right = endIndex;

            while (left <= right) {
                while (0 > comparer.Compare(values[left], pivot)) { left++; }
                while (0 > comparer.Compare(pivot, values[right])) { right--; }

                if (left <= right) {
                    values.Swap(left++, right--);
                }
            }

            if (startIndex < right) {
                stack.Push((startIndex, right));
            }

            if (left < endIndex) {
                stack.Push((left, endIndex));
            }
        }
        while (stack.TryPop(out range));
    }
    public static void QuickSort<T>(this IList<T> values, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
        QuickSort(values, 0, (values.Count - 1), comparer, randomNumberGenerator);
    }
    public static void QuickSort<T>(this IList<T> values) {
        QuickSort(values, Comparer<T>.Default, FastRandom.Default);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static T SampleMedian<T>(this IList<T> values, int startIndex, int endIndex, IComparer<T> comparer, IRandomNumberGenerator randomNumberGenerator) {
        var left = randomNumberGenerator.NextInt32(startIndex, endIndex);
        var middle = randomNumberGenerator.NextInt32(startIndex, endIndex);
        var right = randomNumberGenerator.NextInt32(startIndex, endIndex);

        if (0 > comparer.Compare(values[right], values[left])) {
            Swap(values, right, left);
        }

        if (0 > comparer.Compare(values[middle], values[left])) {
            Swap(values, middle, left);
        }

        if (0 > comparer.Compare(values[right], values[middle])) {
            Swap(values, right, middle);
        }

        return values[middle];
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static void Swap<T>(this IList<T> values, int xIndex, int yIndex) {
        var temp = values[xIndex];

        values[xIndex] = values[yIndex];
        values[yIndex] = temp;
    }
}


texts: Project Euler #645 -- speed up Monte-Carlo simulation in Python

texts:
I am trying to solve Q645. While the logic used for my code seems to be appropriate, the code itself is way too slow for the large number required in this question. May I ask for suggestion(s) to improve my code's performance?
The question is as in the link: https://projecteuler.net/problem=645
My Python code is as follow:
def Exp(D):
    day_list = [0]*D
    num_emperor = 0
    while all((d == 1 for d in day_list)) == False:
        #the birthday of the emperors are independent and uniformly distributed throughout the D days of the year
        bday = np.random.randint(0,D)
        day_list[bday] = 1
        num_emperor+=1
        #indices of d in day_list where d == 0
        zero_ind = (i for i,v in enumerate(day_list) if v == 0)
        for ind in zero_ind:
            try:
                if day_list[ind-1] and day_list[ind+1] == 1:
                    day_list[ind] = 1
            except IndexError:
                if ind == 0:
                    if day_list[-1] and day_list[1] == 1:
                        day_list[0] = 1
                elif ind == len(day_list)-1:
                    if day_list[len(day_list)-2] and day_list[0] == 1:
                        day_list[len(day_list)-1] = 1
    return num_emperor

def my_mean(values):
    n = 0
    summ = 0.0
    for value in values:
        summ += value
        n += 1
    return summ/n

def monte_carlo(iters, D):
    iter = 0
    n_emperor = 0
    while iter < iters:
        n_emperor = Exp(D)
        yield n_emperor
        iter += 1

avg_n_emperor = my_mean(monte_carlo(iters,D))
print(avg_n_emperor)

And my logic is as follow:
For the day_list inside the Exp(D) function, where D is the number of days in a year, zeros mean no holiday, and ones mean holiday. Initially the day_list is all zeros since there is no holiday to begin with.
The rules of defining a random day (d) as a holiday is as follow:

At the beginning of the reign of the current Emperor, his birthday is declared a holiday from that year onwards.

If both the day before and after a day d are holidays, then d also becomes a holiday.

I then subsequently implement the rules stated for the question, to gradually add holidays (ones) into the day_list. After num_emperor number of emperors, all the days (d) in day_list will become 1, i.e. all days will become holiday. This is the point to quit the while_loop in Exp(D) function and count the number of emperors required. To get the average number of emperors required for all the days to become holidays (avg_n_emperor), I then apply the monte-carlo method.
For my current code, the time takes is as follow:
avg_n_emperor = my_mean(monte_carlo(iters=100000,D=5)) #6-7 seconds

avg_n_emperor = my_mean(monte_carlo(iters=1000000,D=5)) #about 62 seconds

in which the time takes increase approx. linearly with the iters.
However,
avg_n_emperor = my_mean(monte_carlo(iters=1000,D=365)) #about 68 seconds

already takes about 68 seconds, and the question is asking for D=10000. Not to mention that the iters required for the answer to be accurate within 4 digits after the decimal points (as required by the question) would be much larger than 1000000 too...
Any suggestion(s) to speed up my code would be appreciated! :)


texts: Asynchronous connect() with one function call, using C++11 lambdas and Boost.Asio

texts:
I've wanted to write a C++11 class for making IPv4 TCP connections and figured that it probably could be done with just one static function using some shared_ptr and lambda "magic". The following code seems to work - but I'm not entirely sure that it's safe and completely bug-free:

void Client::connect(boost::asio::io_service& io_service,
                     const std::string& address,
                     const std::string& port,
                     const Callbacks& callbacks)
{
  using namespace boost::asio::ip;

  std::shared_ptr<tcp::socket> socket = std::make_shared<tcp::socket>(io_service);
  std::shared_ptr<tcp::resolver> resolver = std::make_shared<tcp::resolver>(io_service);
  tcp::resolver::query query(address, port);

  auto connectHandler = [socket, callbacks]
                        (const boost::system::error_code& errorCode, const tcp::resolver::iterator& it)
  {
    if (errorCode) {
      callbacks.onConnectionError("Could not connect: " + errorCode.message());
    } else if (it == tcp::resolver::iterator()) {
      callbacks.onConnectionError("Could not connect!");
    } else {
      callbacks.onConnected(std::move(*socket));
    }
  };

  auto resolveHandler = [socket, resolver, callbacks, connectHandler]
                        (const boost::system::error_code& errorCode, const tcp::resolver::iterator& it)
  {
    if (errorCode) {
      callbacks.onConnectionError("Could not resolve address: " + errorCode.message());
    } else {
      boost::asio::async_connect(*socket, it, tcp::resolver::iterator(), connectHandler);
    }
  };

  resolver->async_resolve(query, resolveHandler);
}

First of all, the Callbacks is just a struct with two callbacks: onConnected(tcp::socket) and onConnectionError(const std::string&).

We'll create a tcp::socket and a tcp::resolver inside shared_ptr since they need to "survive" this whole procedure and can't be copied (atleast not tcp::socket. It can however be moved, but not using C++11 lambdas (?)).

Then we'll just create our two callbacks. resolveHandler needs to capture the socket, callbacks and connectHandler so that those "survive". It also needs to capture the actual resolver, otherwise I got an "Operation canceled"-error. The connectHandler just needs to capture the socket and the callbacks.

If the resolve is successful we'll call async_connect and tell it to try all endpoints. If the connection was successful we'll call our onConnected-callback using std::move and a reference to the socket. If it was not successful we'll call the onConnectionError-callback with an error message.

Does this looks sane? Are there any improvements I could make? Also, I'm wondering if the std::move(*socket) is safe? If I'm not mistaken, this will just move the socket to the onConnected-function call and leave the invalidated socket in the shared_ptr (which is deleted when the lambda returns). Or am I wrong?


texts: A doubly linked list implementation using C++ smart pointers

texts:
I am new to "modern" C++ and decided to learn about smart pointers by implementing a doubly linked list.

I have a few problems with this code: Should the tail pointer be a weak pointer? Should the head pointer be a unique pointer (If yes, then the node after head will have a weak_ptr to the head node, causing a unique_ptr and a weak pointer pointing to the same object)?

#include <iostream>
#include <memory>

template <typename T>
class LinkedList {
 public:
  LinkedList();
  int GetLength() const;
  void Print() const;
  // TODO: Implement and return an iterator.
  void Append(T data);
  // TODO: Implement and return an iterator.
  void Prepend(T data);
  bool Delete(T data);

 private:
  struct ListNode {
    T data;
    std::shared_ptr<ListNode> next;
    std::weak_ptr<ListNode> prev;

    ListNode(T data) : data(data) {}
  };
  int length;
  std::shared_ptr<ListNode> head;
  std::shared_ptr<ListNode> tail;

  void Delete(std::shared_ptr<ListNode> ptr);
};

template <typename T>
LinkedList<T>::LinkedList()
    : length(0) {}

template <typename T>
int LinkedList<T>::GetLength() const {
  return length;
}

template <typename T>
void LinkedList<T>::Print() const {
  std::shared_ptr<ListNode> h(head);
  std::cout << "List (length = " << length << "): ";
  while (h) {
    std::cout << h->data << " ";
    h = h->next;
  }
  std::cout << std::endl;
}

template <typename T>
void LinkedList<T>::Append(T data) {
  std::shared_ptr<ListNode> node_ptr(std::make_shared<ListNode>(data));
  node_ptr->prev = tail;

  if (tail) {
    tail->next = node_ptr;
    tail = std::move(node_ptr);
  } else {
    tail = std::move(node_ptr);
    head = tail;
  }

  length++;
}

template <typename T>
void LinkedList<T>::Prepend(T data) {
  std::shared_ptr<ListNode> node_ptr(std::make_shared<ListNode>(data));
  node_ptr->next = head;

  if (head) {
    head->prev = node_ptr;
    head = std::move(node_ptr);
  } else {
    head = std::move(node_ptr);
    tail = head;
  }

  length++;
}

template <typename T>
bool LinkedList<T>::Delete(T data) {
  std::shared_ptr<ListNode> ptr = head;
  while (ptr) {
    if (ptr->data == data) {
      Delete(ptr);
      return true;
    }

    ptr = ptr->next;
  }

  return false;
}

template <typename T>
void LinkedList<T>::Delete(std::shared_ptr<ListNode> ptr) {
  auto shared_prev = (ptr->prev).lock();

  if (head == ptr) {
    head = ptr->next;
  }
  if (tail == ptr) {
    tail = shared_prev;
  }

  if (shared_prev) {
    shared_prev->next = ptr->next;
  }
  if (ptr->next) {
    ptr->next->prev = ptr->prev;
  }

  length--;
}


texts: Improving the efficiency of my FizzBuzz algorithm

texts:
I worked on an exercise from codewars, which is a variation of the popular fizzbuzz game.  (If the link doesn't work, you may need to reload the page.)

In this variation, I'm supposed to find the sum of all the multiples of 3 and 5 that are less than the passed in number.

My code works, but it's horribly inefficient. It only works for smaller numbers and can't work for really large numbers

def fizz_buzz_sum(number)
  (1..number).to_a.select{|x| x % 3 == 0 && x % 5 == 0}.reduce(:+)
end

I think my problem is that I'm iterating over all the numbers in a large array and I might not have to.

Can anyone help reduce the complexity of my algorithm?


texts: Calculate FFT from windowed time-based signal

texts:
I have a time-based signal (Raw signal) sampled at 6 MHz and need to analyze it in freq. domain.
I'm learning DSP and this is very first time I work with DSP. Could you please help to check if this code is correct or not. And I have couple of questions needed to be clarify:

I've heard about linear scale and logarithm scale in order to observe the amplitude easier. Could you please explain to me, in this case, how can I get the logarithm scale?
for some function in Matlab (for example fft, spectrogram, etc), how can I get the code (just in case I want to change something to adapt my need)?

input=V5k_a100;
N=2048;     L=4096;    Fs=6e6;
spectrumTemp=[];

for index=1:length(input)/L
  slice = input(1+(index-1)*L:index*L);
  abcd = hann(L) .* slice;
  NFFT = 2^nextpow2(N);
  spectrumTemp(index, :) = fft(abcd, NFFT)/L;
end

f = [0:NFFT-1]*Fs/NFFT;
freq = f(1:length(f)/2);
time = [0:length(input)/L-1]*L/Fs;
spectrum = spectrumTemp(:, 1:length(f)/2);
mesh(time,freq',abs(spectrum'));


texts: Handling the first value for a variable, with Redux and the Backend service. Angular, Redux

texts:
I'm feeling this code is messy and also repeats between all components that needs to handle backend data. Any comment is appreciated.
//the stored version
localVersion = undefined;

//injecting the redux service and the backend service(in case there is no version defined in reduxService)
constructor( private reduxService: ReduxService, private backendService: BackendService) { }
  ngOnInit(): void {

    this.getVersion().subscribe(v => {
      this.localVersion = {...v};
    });
    this.setlocalVersion().subscribe(v => {
      this.localVersion = {...v};
    });

  }
  private getlocalVersion(): Observable<localVersionResponseModel> {
  //this is made to  get the first value for the localId.
    const id = this.reduxService.getValue<IlocalVersionStateData>(LabelsEnum.version);
    //maybe the id is not set in reduxService.
    return (id) ? this.backendService.getlocalVersion(id.localVersionId) : of(undefined);
  }

  private setlocalVersion(): Observable<localVersionResponseModel> {
    return this.reduxService.getObservableValue<IlocalVersionStateData>(LabelsEnum.version)
      .pipe(
        takeUntil(this.Unsubscribe),
        //switchMap in case of backend service response.
        switchMap(vStateData => {
          return this.backendService.getlocalVersion(vStateData.localVersionId);
        })
      );
  }

  //removes the subscription when component is destroyed
  ngOnDestroy(): void {
    this.Unsubscribe.next();
    this.Unsubscribe.complete();
  }


texts: Change the background color of the console with the help of enum

texts:
I've recently learned the concept of enum and method calling with the enum. From what I learned I've done this simple snippet which changes the background color of the console with the help of enum and method.

    public static void SetColor(RanngDe R){
        switch (R){
            case RanngDe.Blue:
                 Console.BackgroundColor = ConsoleColor.Blue;
                 break;

            case RanngDe.Green:
                 Console.BackgroundColor = ConsoleColor.Green;
                 break;
            default:
                 Console.BackgroundColor = ConsoleColor.Yellow;
                 break;
        }
    }

// Enum Declaration
public enum RanngDe{
    Blue=0,
    Green=1,
    Yellow=3
}

I'm calling RanngDe method in the main method in switch ...case block as menu driven. I know, I've used switch ...case in void SetColor(RanngDe R) method, which is my major concern, because this makes my code redundant as I'm calling it in the menu driven program.

Is this approach acceptable as good practice? If not then, how should I make this better?


texts:
I have tried to implement two methods, one for finding the size of the tree and the other for finding the height of the tree. Can they be optimized further?

  package trees;
  import java.util.LinkedList;
  import java.util.TreeSet;
public class TreeNodeImpl {

    public TreeNodeImpl left ;
    public TreeNodeImpl right;
    public int Value ;
    public int height=1;

    public TreeNodeImpl newTreeNode(int value){
        TreeNodeImpl newNode = new TreeNodeImpl();
        newNode.Value = value;
        newNode.left = null;
        newNode.right = null ;
        return  newNode;
    }

    public int   recSize(TreeNodeImpl node ){
            if(node == null){
                return 0 ;
            }
            else{
                return( recSize(node.left)+ 1 + recSize(node.right));
            }
    }
    public int recHeight(TreeNodeImpl node){

        if(node==null)
        {
            return 0;
        }
        else {

            if(node.left!=null||node.right!=null){
                height++;
                recHeight(node.left);
                recHeight(node.right);
            }
        return height;
        }
    }

    public static void main(String[] args) {
        TreeNodeImpl node = new TreeNodeImpl();
        node.Value = 6;
        node.left= node.newTreeNode(20);
        node.left.left = node.newTreeNode(30);
        node.right= node.newTreeNode(30);
        node.left.left.right = node.newTreeNode(34);
        node.left.left.left = node.newTreeNode(34);
        int Size = node.recSize(node);
        System.out.println(Size);
        int height = node.recHeight(node);
        System.out.println(height);
    }
}


texts: Historical exchange rate between currencies using Ecbxrate

texts:
I tried writing a simple python script using the python module ecbxrate that outputs to a CSV file a table with the daily exchange rate between EUR and USD since 2013.

Below is my code, it works, gives the correct output. I tried using methods rather than a long script. I specifically wanted to use Ecbxrate.

import ecbxrate
import datetime
import pandas as pd
from sqlite3 import Error
ecb_path = 'sqlite:///D://test/db/ecb.sqlite3' #path where ecb historical database is stored
outfile = 'Downloads/Exchnage_rate.csv' # CSV table name and path
store = ecbxrate.ExchangeRateStore(ecb_path)
""" We can initialise it one time also from command line but i kept it as a part of script in case there is any issue it can re initialise as per given path"""
"""This initialise the ecb data if does not exist else update if it does, we can sechdule the script to be run after 3pm to get lastest exchange rate of the day
and then it shall first update with lastest exchange rate data before writing it to file.Also I tried printing exceptions, we can follow the uniform error handling method as per standards/requirement """
def get_data():

    try:
        store.last_updated()
    except Error as e:
        print("Error with ecb database", e)
    except:
        try:
            store.initialise()
        except Error as e:
            print('Error while initialising',e)
        except:
            print('unknown error , check initialise process')
    else:
        if store.last_updated() != datetime.datetime.today().date(): #if latest data doesn't exist
            try:
                store.update()
            except Error as e:
                print('Error while updating', e)
            except:
                print('unknown error while updating')
        """else:
            print('latest data already') """
        """#Else part is not needed because  all excpetions already handleded, we can do it in case need to log the process for success."""

""" This gets the data from updated ECB database from given date range between given currencies"""
def get_exchange_rate(start_date, end_Date, from_curr, to_cuur):
    daterange = pd.date_range(start_date, end_Date)
    data = [store.get_rate(from_curr, to_cuur,single_date.strftime("%Y-%m-%d")) for single_date in daterange] #calling for all days in between
    #return (pd.DataFrame(data))
    d = pd.DataFrame(data)
    d.insert(1, 'currency_from', from_curr)
    d.insert(2,'currency_to', to_cuur)
    d.rename(columns={d.columns[0]: "Date", d.columns[3]: "Exchange_Rate" },inplace=True)
    d.to_csv(outfile, index=False) # putting it in csv of given path and name

def main():
    get_data()
    get_exchange_rate('2013-1-1', datetime.datetime.today().date(),'EUR', 'USD')

main()

Could you please review and let me know if it can be written better. Few doubts I have are:

Should I pass ecb_path as parameter to get_data() and get_exchange_Rate()? I am not sure about the best approach.
Are nested try except blocks Pythonic in this case? Can I handle it better?
Should I write a different method to write output to csv file?
Is for loop efficient in this case, to get data for bigger date range?
Should I add a check in case the output file is not created or given path is wrong?


texts: Dealing with API routes in form of interfaces

texts:
Today I had an interesting idea. I have been copy/pasting the following line for each kind of request method for every route.

http.Handle("/api/my/custom/route", mw.Chain(api.PostFunc, mw.Method("POST"), mw.Logging()))

It struck me that it looked very bad and unprofessional so I came up with a new idea.

type RouteInstructor struct {
    Instance struct {
        URL  string
        Data struct {
            Method   string
            Callback string
        }
    }
}

func Routes() {
    routes := &RouteInstructor{
        Instance: map[string]interface{}{
            URL: "/api/my/custom/route",
            Data: map[string]interface{}{
                Method:   "POST",
                Callback: api.PostFunc,
            },

            Data: map[string]interface{}{
                Method:   "GET",
                Callback: api.GetFunc,
            },
        },
    }

    mw.Routes(routes)
}

Instead of calling the mw.Chain method and http.Handle, wouldn't it be better to make a struct, pass it to a middleware method where you apply mw.Chain and everything else? Although it does become more code, I feel like it becomes easier to understand and therefore more effective.

What do you think of this new way of mine? What are pros and the cons?


texts: Searching for a sum of any series in array

texts:
I'm given this method, and requested to analyze what it does, and minimize its complexity (both time and space).
All values are known to be larger than zero.

public static boolean search(int[] a, int num) {
    for(int i = 0; i < a.length; i++)
        for(int j = i; j < a.length; j++) {
            int res = 0;
            for(int k = i; k <= j; k++)
                res += a[k];

            if(res == num)
                return true;
        }
    return false;
}

From what it looks to me it's searching for any series of consecutive numbers in the given array, that sum up to num, with an O(n3) complexity.

I've tried to rewrite it like this:

public static boolean search(int[] a, int num) {
    for (int i = 0; i < a.length; i++) {
        int sum = 0;
        for (int j = i; j < a.length; j++) {
            sum += a[j];
            if (sum == num)
                return true;
        }

        if (num > sum)
            break;
    }
    return false;
}

Which has a complexity of  (BTW, is there a better way to denote this complexity?).

What other strategies can I take to minimize the complexity even further? Can I reach O(n)?


texts:
I am new to this CompletableFuture function in Java. I have the following code below that works fine but looks quite messy IMHO.

CompletableFuture<String> cf = CompletableFuture.completedFuture(isRQMRunning_3);

if(cf.isDone()) {
    System.out.println("Value- " + cf.get());
    cf = CompletableFuture.completedFuture(startRQM_4);

    if(cf.isDone()) {
        System.out.println("Value- " + cf.get());
        cf = CompletableFuture.completedFuture(pendingChangesStatus);

        if(cf.isDone()) {
            System.out.println("Value- " + cf.get());
            cf = CompletableFuture.completedFuture(acceptPendingChanges_8);

            if(cf.isDone()) {
                System.out.println("Value- " + cf.get());
                cf = CompletableFuture.completedFuture(loadWorkspace_5);

                if(cf.isDone()) {
                    System.out.println("Value- " + cf.get());
                    cf = CompletableFuture.completedFuture(acceptPendingChanges_8);

                    if(cf.isDone()) {
                        System.out.println("Value- " + cf.get());
                        cf = CompletableFuture.completedFuture(fixConflicts_9);

                        if(cf.isDone()) {
                            System.out.println("Value- " + cf.get());
                        }
                    }
                }
            }
        }
    }
}

Is it possible to make that look a lot nicer/easier to read?


texts:
The following pascal function (compiled with Delphi) will split strings. It works perfectly, but how to improve the code? For example, to avoid using the repeat-until loop.

type
  TSarray = array of string;

function Split(Texto, Delimitador: string): TSarray;

var
  o: integer;
  PosDel: integer;
  Aux: string;

begin

  o := 0;
  Aux := Texto;
  SetLength(Result, Length(Aux));

  repeat

    PosDel := Pos(Delimitador, Aux) - 1;

    if PosDel = -1 then
    begin
      Result[o] := Aux;
      break;
    end;

    Result[o] := copy(Aux, 1, PosDel);
    delete(Aux, 1, PosDel + Length(Delimitador));
    inc(o);
  until Aux = '';
end;

Example:

var texto,deli:string;
    all_array:TSarray;
begin
deli := 'test';
texto := deli+'hi world 1'+deli+'hi world 2'+deli;
end;

all_array := Split(texto,deli);
ShowMessage(all_array[1]);
ShowMessage(all_array[2]);
end;

My plan is to use no classes, only the "uses" default

What alternatives do I have to repeat-until?


texts:
The "Almost Sorted" problem from HackerRank:

  Given an array with \$n\$ elements, can you sort this array in ascending order using only one of the following operations?

  Swap two elements.
  Reverse one sub-segment.

  Output format

  If the array is already sorted, output yes on the first line. You do not need to output anything else.
  If you can sort this array using one single operation (from the two permitted operations) then output yes on the first line and then:

  If you can sort the array by swapping \$d_l\$ and \$d_r\$, output swap l r in the second line. \$l\$ and \$r\$ are the indices of the elements to be swapped, assuming that the array is indexed from \$1\$ to \$n\$.
  Else if it is possible to sort the array by reversing the segment \$d[l\ldots r]\$, output reverse l r in the second line.  \$l\$ and \$r\$ are the indices of the first and last elements of the subsequence to be reversed.

  If an array can be sorted by either swapping or reversing, stick to the swap-based method.
  If you cannot sort the array in either of the above ways, output no in the first line.

I am trying to improve my Python so I would appreciate if somebody could review the following piece of code. I know it can be done with less code in Python, I am just not sure how.

import sys

def checkSorted(arr):
    return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))

def almostSorted(arr):
    if len(arr) == 1 or checkSorted(arr):
        print("yes")
        return

    # Find first item out of order from the left
    i = 0
    while i < len(arr) - 1 and arr[i] < arr[i+1]:
        i+=1
    first_ooo_left = i

    # Find first item out of order from the right
    i = len(arr) - 1
    while i > 0 and arr[i-1] < arr[i]:
        i-=1
    first_ooo_right = i

    # Same item?
    if (first_ooo_left == first_ooo_right):
        print("no")
        return

    l = first_ooo_left
    r = first_ooo_right
    swaps = 0
    while r-l > 0:
        if arr[l] > arr[r]:
            arr[r], arr[l] = arr[l], arr[r]
            swaps += 1
        r-=1
        l+=1

    sorted = checkSorted(arr)

    if sorted:
        if swaps == 1:
            print("yes")
            print("swap " + str(first_ooo_left+1) + " " + str(first_ooo_right+1))
        elif swaps == (first_ooo_right-first_ooo_left+1)//2:
            print("yes")
            print("reverse " + str(first_ooo_left+1) + " " + str(first_ooo_right+1))
    else:
        print("no")


texts: Switching between view controllers that are loaded in the background

texts:
I have a dining menu app that scrapes the data from a website and redisplays it in a mobile format, displayed below:

If the user swipes left and right, the app will show the previous/next meal (ex. if current meal is lunch, swiping left will show dinner).

I'm trying to come up with a more efficient way of switching between menus.  With my current implementation, each menu is a separate view controller.

When someone swipes right, it calls:

-(void)swipeleft:(UISwipeGestureRecognizer*)gestureRecognizer {
    //swipes to next meal
    MealType curMeal = currentMenu.type;
    int newMeal = [MenuLoader MealAfterMeal:curMeal];

    MenuTableController *newMenu = [self.storyboard instantiateViewControllerWithIdentifier:@"Menu"];
    newMenu.currentMeal = newMeal;

    [self.navigationController pushViewController:newMenu animated:YES];
}

When each view controller is created (including the first), it loads the menu in a background thread:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        MenuLoader *ml = [[MenuLoader alloc] init];
        currentMenu = [ml mealForType:_currentMeal Specificity:[self summaryPreference]];

        dispatch_async(dispatch_get_main_queue(), ^(void) {
            ...
        });
    });

Inside the mealForType:Specificity: call, I parse 2 separate web pages through NSURL, and combine the information from both sites:

NSURL *url = [NSURL URLWithString:urlString];
NSData *pageData = [NSData dataWithContentsOfURL:url];

Some of the optimizations I'm hoping to make are:

Preloading adjacent menus in another thread to reduce loading time when someone swipes
If someone swipes forward and then back, it should show the already loaded menu. Right now, it makes a fresh call to the server and reloads everything.
Right now, if someone swipes multiple times in a row before any of the menus finish loading, the app tries processing all of the server calls at once and this slows down the loading time.  If someone does swipe repeatedly, the current menu should take precedence, and possibly the other calls should be terminated.

It sounds like a big overhaul of my design, so I was wondering if there was a better approach to loading menus than what I currently implemented.


texts: Code that checks if two words are anagrams

texts:
I've completed a program that tests whether two words are anagrams. The program seems to work, but I was just wondering if there is anything I could be doing to make the code better. Everything is below, there is a main program and one class.

Main:

import java.util.Scanner;

public class StringTesting
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        StringUtil object = new StringUtil();

        String word1;
        String word2;

        System.out.print("Enter word one: ");
        word1 = input.next();

        System.out.print("Enter word two: ");
        word2 = input.next();

        if(object.isAnagram(word1, word2)){
            System.out.println("It's an anagram!");
        } else {
            System.out.println("It's not an anagram.");
        }
    }
}

StringUtil Class:

public class StringUtil
{
    public int countCharacters(String str, char ch)
    {
        int count = 0;

        for(byte i = 0; i < str.length(); i++){
            if(str.toLowerCase().charAt(i) == Character.toLowerCase(ch)){
                count++;
            }
        }

        return count;
    }

    public boolean isAnagram(String str1, String str2)
    {
        int count = 0;

        if(str1.length() != str2.length()){
            return false;
        }

        for(byte i = 0; i < str1.length(); i++){
            char ch = str1.toLowerCase().charAt(i);
            for(byte j = 0; j < str1.length(); j++){
                char ch2 = str2.toLowerCase().charAt(j);
                if(ch == ch2){
                    if(countCharacters(str1, ch) != countCharacters(str2, ch2)){
                        return false;
                    } else {
                        count++;
                    }
                }
            }
        }

        if(count == str1.length()){
            return true;
        } else {
            return false;
        }
    }
}


texts: Custom database Lock - implemented with IDisposable

texts:
I have a lock class, that handels a database lock. It's not important how.
It is used in the beginning of a large operation, here is how it is used today:

public void LargeOperation()
{
    try
    {
        MyLock.DoLock("SomeId");
        // Do lots of stuff that might thorw exceptions
    }
    finally
    {
        MyLock.ReleaseLock("SomeId");
    }
}

I would like to use it like this instead:

public void LargeOperation()
{
  using(new MyLock("someId"))
  {
    // Do lots of stuff that might thorw exceptions
  }
}

this works fine, but im not sure wether it is a bad idea. I have implemented IDisposable on my class MyLock but it doesn't dispose.. instead it releases the lock.
Here is how the class look:

public class MyLock : IDisposable
{
    private string _id;
    public MyLock(string id)
    {
       DoLock(id);
    }

    public static void DoLock(string id)
    {
      //..code omitted
    }

    public static void ReleaseLock(string id)
    {
      //..code omitted
    }

    public void Dispose()
    {
      ReleaseLock(_id);
    }
}

Is this abuse of the IDisposable interface?


texts: Merge sort implementation using divide-and-conquer

texts:
I was told in an interview to write a program for implementing merge sort on the concept of divide-and-conquer.

var myGlobalArray = undefined;

myGlobalArray = [8,4,17,2,1,32];
example01(myGlobalArray);

myGlobalArray = [48,14,17,2,11,132];
example01(myGlobalArray);

myGlobalArray = [45,14,5,2,1,12];
example01(myGlobalArray);

myGlobalArray = [45,-14,-5,2,1,-12];
example01(myGlobalArray);

myGlobalArray = [38,27,43,3,9,82,10];
example01(myGlobalArray);

myGlobalArray = [34,45,1,23,19,12,10];
example01(myGlobalArray);

function example01(myArray){
   var mainArray = [];

   // Divide
   createSubArray(myArray,0);

   // Conquer
   mainArray = mergeArrays(mainArray);

   console.log(myArray+" => "+mainArray[0]);

   // creates an array which contains n arrays for n numbers present in myarray
   // i.e. if array = [ 34, 1, 27, 3 ] that the below method will return
   // [ [34], [1], [27], [3] ]
   function createSubArray(subArray,index){
        var localArray = [];

        if(subArray[index] !== undefined){
            localArray.push(subArray[index]);
            mainArray.push(localArray);
            createSubArray(subArray,++index); // dividing recursively
        }
   }//createSubArray

   // merge the arrays present i.e.
   // if gblArray = [ [2,5], [1,7] ]
   // then the below method will return
   // an merged array [ [1, 2, 5, 7] ]
   function mergeArrays(gblArray){
        var mergedArrays = [],
            main_array = gblArray,
            arr = [],
            left_array = undefined,
            right_array = undefined,
            counter = 0,
            nextCounter = 0;

        do{

            while(counter < main_array.length){
                nextCounter = counter + 1;

                if(main_array[nextCounter] !== undefined){

                    left_array = main_array[counter];
                    right_array = main_array[nextCounter];

                    // merge left and right arrays and sort it
                    arr = mergeAndSort(left_array,right_array);

                    mergedArrays.push(arr);
                }else{
                    mergedArrays.push(main_array[counter]);
                }
                counter = nextCounter + 1;
            }

            main_array = mergedArrays;
            mergedArrays = [];
            counter = 0;
            nextCounter = 0;

        }while(main_array.length > 1);

        return main_array;
   }//mergeArrays

   // merges two array and sorts i.e.
   // if array1 = [1,23] and array2 = [4,12] than
   // the below method returns [1,4,12,23]
   function mergeAndSort(array1,array2){
        var array2Counter = 0,
            array1Counter = 0,
            mergedArray = [];

        while(array2Counter < array2.length && array1Counter < array1.length){

            if(array2[array2Counter] < array1[array1Counter]){
                mergedArray.push(array2[array2Counter]);
                array2Counter++;
            }else{
                mergedArray.push(array1[array1Counter]);
                array1Counter++;
            }
        }

        while(array1Counter < array1.length){
            mergedArray.push(array1[array1Counter]);
            array1Counter++;
        }

        while(array2Counter < array2.length){
            mergedArray.push(array2[array2Counter]);
            array2Counter++;
        }

        return mergedArray;
   } //mergeAndSort

}//example01

The output is:

8,4,17,2,1,32 => 1,2,4,8,17,32
48,14,17,2,11,132 => 2,11,14,17,48,132
45,14,5,2,1,12 => 1,2,5,12,14,45
45,-14,-5,2,1,-12 => -14,-12,-5,1,2,45
38,27,43,3,9,82,10 => 3,9,10,27,38,43,82
34,45,1,23,19,12,10 => 1,10,12,19,23,34,45

But by looking at my implemented merge-sort program, the inteviewer said that it doesn't follow the divide-and-conquer concept.

I tried to convince him that method mergeArrays and mergeAndSort do the divide-and-conquer, but he didn't agreed. Where am I going wrong?


texts:
This is my first attempt to do any hashing. I wanted to make a class that handled everything I needed to implement PBKDF2. The only question I have is am I ok to store the iterations in the database record or is this a bad practice? I was planning on creating a column to store salt, another for the hashed password, and possibly one for the amount of iterations. My thought with the iterations was that I read that it should increase every so often so when creating new users or they update their passwords it would pull the value to pass in from the database.

    public static byte[] GenerateSalt()
    {
        using (var randomNumberGenerator = new RNGCryptoServiceProvider())
        {
            var salt = new byte[32];
            randomNumberGenerator.GetBytes(salt);

            return salt;
        }
    }

    public static byte[] HashPassword(byte[] password, byte[] salt, int iterations)
    {
        using (var rfc2898 = new Rfc2898DeriveBytes(password, salt, iterations))
        {
            return rfc2898.GetBytes(32);
        }
    }

    public static bool CompareByteArrays(byte[] array1, byte[] array2)
    {
        if (array1.Length != array2.Length)
        {
            return false;
        }

        for (int i = 0; i < array1.Length; i++)
        {
            if (array1[i] != array2[i])
            {
                return false;
            }
        }

        return true;
    }


texts:
I made an algorithm to calculate when the user has to purchase material adjusting the date in which the order has to be made, I'm using datagridviews to make it work, but I was wondering if there is a better way using a DataTable.

private void Suggestion()
{
  for (int i = 1; i < dataGridView9.RowCount; i++)
    {
        string PartNumber = dataGridView9.Rows[i - 1].Cells["PartNumber"].Value.ToString();
        string Requested_Date = dataGridView9.Rows[i - 1].Cells["Requested_Date"].Value.ToString();
        string material = dataGridView9.Rows[i - 1].Cells["Material"].Value.ToString();
        string requierd_Qty = dataGridView9.Rows[i - 1].Cells["Requierd_Qty"].Value.ToString();

  for (int l = 1; l < dataGridView10.RowCount; l++)
    {
        string partNumber = dataGridView10.Rows[l - 1].Cells["PartNumber"].Value.ToString();
        double leadTime = double.Parse(dataGridView10.Rows[l - 1].Cells["PUR LT"].Value.ToString());

        if (partNumber == material)
        {
            DateTime _requested_Date = Convert.ToDateTime(Requested_Date);
            DateTime suggestedDate = GetWorkDays.AddWorkdays(_requested_Date, Convert.ToDouble(leadTime));

            try
            {
                oleDbCmd = new OleDbCommand("InsertSuggested", connection);
                oleDbCmd.CommandType = CommandType.StoredProcedure;

                oleDbCmd.Parameters.Add("@PartNumber", OleDbType.VarChar, 30).Value = material.ToString();
                oleDbCmd.Parameters.Add("@AdjustedDate", OleDbType.Date, 50).Value = _requested_Date;
                oleDbCmd.Parameters.Add("@SuggestedDate", OleDbType.Date, 50).Value = suggestedDate;
                oleDbCmd.Parameters.Add("@Qty", OleDbType.VarChar, 30).Value = requierd_Qty;

                connection.Open();
                oleDbCmd.ExecuteNonQuery();
            }
            catch (OleDbException error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                connection.Close();
            }
            break;
        }
      }
    }
  }

I want to know if there a better way of achieving this. Right now there inst that much data, but in the long run their might be. If there are other comments of the code please let me know.

Edit:changed variable names to correct ones.


texts: Semantic HTML5 structure and Google penalty

texts:
I'm in need for clarity. I'm at an annoying step in my development of a website, and I have read a lot about semantic structure etc, but I'm a bit nervous for my current structure, so I would like to ask your expertise to see, if I might get problems with search engine bots with this setup.

    Skip menuen

                <svg id="header-logo" class="header-logo" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title desc" viewBox="0 0 158 24.7">
                    <title id="title" itemprop="headline">Brand Name</title>
                    <desc id="desc" itemprop="description">- brand description</desc>

                </svg>

            <button id="hamburger-btn">

            </button>

page

page

page

page

page

page

                    <button id="siteLogin" class="nav-btn">
                        Admin login
                        <svg class="nav-admin-icon nav-icons">
                            <use xlink:href="img/generel/svg-system.svg#admin-icon"></use>
                        </svg>
                    </button>

                <button id="siteSearch" class="nav-btn">
                    Søg
                    <svg class="nav-search-icon nav-icons">
                        <use xlink:href="img/generel/svg-system.svg#search-icon"></use>
                    </svg>
                </button>

Main content header

In the outline it will look like this:

Brand name - brand description

untitled nav
Main content header


texts:
I have such cases:

stock status can be in stock, undefined (there is no such field in the object) or any other text

stock status is true if it is 'in stock' or undefined
all others are false

so this is my test object

obj =
    one:
        stock: 'in stock'
    two:
        some: 'x'
    three:
        stock: 'not in stock blah blah any other text'

my method

stockCheck = (stock, msg) ->
    console.log {msg}
    return true if !stock or stock == 'in stock'

and some simply test

console.log stockCheck(obj.one.stock)?, 'should be in stock'
console.log stockCheck(obj.two.stock)?, 'should be in stock'
console.log stockCheck(obj.three.stock)?, 'should not be in stock'

is my code well for such cases?


texts:
The task is to write a class system that implements figures on the plane (point, segment, square, rectangle, triangle). Also, it is needed to provide encapsulation. There should be constructors and several methods that determine the size. Use the Has-a relationship.

Would you please review my code and say what is not correct here?

public class Pres12Task3 {

public static void main(String[] args) {
    Shape s = new Shape();
    Triangle t = new Triangle(1, 2, 3);
    System.out.println(t.width + "," + t.height + "," + t.getLength());
    t.changeSize(6);
}
}
class Shape {
int X;
int Y;

Shape() {
    X = 0;
    Y = 0;
}
public Shape(int x2, int y2) {
    // TODO Auto-generated constructor stub
}

void Move(int x, int y) {
    X = x;
    Y = y;
}}
class Point extends Shape {
Point(int x, int y) {
    // super();
    Move(x, y);
}}

class Segment extends Shape {
Segment(int x, int y) {
    super();
    Move(x, y);
}}
class Square extends Shape {
int width = 10;

Square(int w, int x, int y) {
    super(x, y);
    width = w;
}

void changeSize(int w) {
    width = w;
} }

class Rectangle extends Square {
int height = 9;

Rectangle(int w, int h, int x, int y) {
    super(w, x, y);
    height = h;
}

void changeSize(int w, int h) {
    super.changeSize(w);
    height = h;
}}

class Triangle extends Rectangle {
int length = 7;

Triangle(int l, int w, int h) {
    super(w, h, w, h);
    length = l;
}

public int getLength() {
    return length;
}

public void setLength(int length) {
    if (length > 0) {
        this.length = length;
    } else {
        this.length = 5;
    }
}

void changeSize(int w, int l) {
    super.changeSize(w, l);
    length = l;
}}


texts: Removing duplicate words from an unsorted list

texts:
I was using brute force to remove duplicate words since the lists were really small. But I want a solution that won't become too slow if the input grows.

This function creates a binary tree and inserts all words appearing on the list, then collects the unique words without sorting. Duplicate words are handled during insertion. For the tree, I'm using about the same code from Unbalanced binary search tree.

#include "bst.h"
#include <strings.h>
#include <stdlib.h>

#define LIST_TERMINATOR 1

static size_t i = 0;
static char **final_list;

static void insert(void *word)
{
    final_list[i++] = word;
}

char **unique_words(const char **words)
{
    //Binary tree containing the words
    BST unique;
    bst_init(&unique, (int(*)(const void *, const void *))strcasecmp);

    //Every word will be inserted at most 1 time
    while(*words != NULL){
        if(bst_insert(&unique, (void *)*words) == BST_NO_MEMORY){
            bst_free(&unique);
            return NULL;
        }

        ++words;
    }

    //Array to return
    final_list = malloc(sizeof(char *) * (unique.node_count + LIST_TERMINATOR));
    if(final_list == NULL){
        bst_free(&unique);
        return NULL;
    }

    //Collect words without sorting, so if the list is merged with another
    //and passed again, the tree won't become a linked list
    if(bst_iterate_top_down(&unique, insert) == BST_NO_MEMORY){
        free(final_list);
        bst_free(&unique);
        return NULL;
    }
    final_list[i] = NULL;

    bst_free(&unique);

    //Clear state
    i = 0;

    return final_list;
}

Would sorting the input then removing duplicates be faster?


texts: Is it better to create a class instance, or create an instance each time a method is called?

texts:
I am creating a converter for use in a Windows 8 XAML app (MVVM).  As you can see in the code below, the converter is used to convert a bool into one of two strings from a language resource file.
My question is, is it better to create one instance of ResourceLoader for the converter class or should I continue creating new instances each time the method is called?

class BooleanToBudgetYearStringConverter : IValueConverter
{
    private const string CALENDAR = "BudgetCycle_Calendar",
                        FISCAL = "BudgetCycle_Fiscal";

    private Windows.ApplicationModel.Resources.ResourceLoader loader;

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        string entryName = (value is bool && (bool)value) ? CALENDAR : FISCAL;  //The name of the entry desired from the entry file.
        return new Windows.ApplicationModel.Resources.ResourceLoader().GetString(entryName);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return (value is string && (string)value == new Windows.ApplicationModel.Resources.ResourceLoader().GetString(CALENDAR));
    }
}

I am specifically concerned about speed and memory use.


texts:
The ZCO is today and I did 5 problems to prepare for it overnight.  One of the problems is the CodeChef Chewing problem.

The code takes an integer N that specifies the number of chewing gums, integer K that is the maximum hardness quotient of a pair the chewing gums possible to be eaten. This is followed by N integers that specify the hardness quotient of each type of gum. My code selects only gums with a quotient less than K and adds them to a vector. A nested for loop is used to count the number of pairs for which hardness quotient of Gum_Type1+Gum_Type2 < K.

#include <iostream>
#include <vector>
#include <algorithm>
#define ll unsigned long long int
#define speedup ios::sync_with_stdio(false); cin.tie(NULL);
using namespace std;

int main(){
  speedup;
  ll N,K,hq,numPairs=0;
  vector<ll> hardness;
  cin >> N >> K;
  for(ll i=0; i< N; i++){
    cin >> hq;
    if (hq< K) hardness.push_back(hq);
  }
  sort(hardness.begin(), hardness.end());
  for(vector<ll>::iterator it=hardness.begin(); it<hardness.end();it++){
    for(vector<ll>::iterator it2=it+1;it2<hardness.end();it2++){
      if (*it+*it2 < K) numPairs+=1;
      else hardness.erase(it2);
    }
  }
  cout << numPairs<<endl;
}

For subtask 2, I'm getting TLE by 0.01s.  Could somebody help me optimize this code? I don't want to get TLEs in the exam today.


texts:
I am currently working in a project based on a microservices architecture pattern.
Services are wired up by HTTP calls. They eventually call each others for fetching or putting some data.

I am working on the web page which envelops the whole microservices. I mean, the web page actually needs to send and retrieve data from all the services (except one).
There are several times where the web page behaves as a broker, i.e.:

  Fetch some data from service 1,
  fetch some data from service 2.
  Send something to service 3 based on previous responses.

That's why I decided to implement some functions to avoid lots of duplicated code chunks. This is what I call the promise-based HTTP abstraction layer.

I am developing the web page in Typescript, by the way.

I want to mention what my request function is. The request function performs HTTP requests, unsurprisingly.
It is an axios call wrapper. However, for the sake of simplicity, since it is not that important I'll show only the header.

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
declare function request<TResult>(method: HttpMethod, url: string, body?: any): Promise<TResult>;

And, for comfort, I declared its prefixed argument different calls

const get = request.bind(this, 'GET');
const post = request.bind(this, 'POST');
// And so on ...

But I refactored this to take profit of the request type argument

const get = <TResult>(url: string, body: any) => request<TResult>('GET', url, body);
const post = <TResult>(url: string, body: any) => request<TResult>('POST', url, body);
// And so on ...

And, a waitAll function which requests to call the URLs passed in and returns a single Promise which will be resolved whenever all the requests are done.

interface HttpRequest<TResult> {
    url: string;
    request: (url: string, body?: any) => Promise<TResult>;
    body?: any;
};
const waitAll = (...reqs: HttpRequest<any>[]): Promise<any[]> =>
    Promise.all(reqs.map(req => req.request(req.url, req.body)));

With this, I can do something like

(async () => {
    const req1: HttpRequest<FirstResponse> = {
        url: `http://example.com/one`,
        request: post,
        body: {
            id: 9,
            data: [`hi`, `there`]
        }
    };
    const req2: HttpRequest<SecondResponse> = {
        url: `http://example.com/one`,
        request: get
    };

    const results = await waitAll(req1, req2);
    const [r1, r2] = results;

    const body = { ...r1, ...r2 };
    const finalResponse = await post<ThirdResponse>(`http://example.com/three`, body);

    // do something w/ final response
})();

This is working but I notice some wrong things.
It feels weird the HttpResponse<> object, that wraps the url and the body that, in fact, will be called inside its own request property function.
And when I call waitAll, I'd expect my r1 and r2 to be of the matching type (I mean, r1 must be
 of type FirstResponse, and r2 must be of type SecondResponse) just like finalResponse is of type ThirdResponse.

I am pretty sure there are lots of improvements to achieve a better-looking API and, the most important thing, take profit of Typescript type safety.

Any thoughts are welcome.


texts: Create Form Controls based on the properties of a class

texts:
Is there a better way to create Form Controls for properties of a class? Right now, I iterate through all properties of a class and have a method to create the Form Control for that property based on the type of the property.

private void AddControl(PropertyInfo p, string name = null, Color? c = null, int count = 0)
{
    Label newLabel = new Label();
    TableLayoutPanel tp = new TableLayoutPanel();
    Control ctrl = new Control();

    tp.ColumnCount = 2;
    tp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 200F));
    tp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 215F));
    tp.Margin = new Padding(0);
    tp.Name = "tp";
    tp.RowCount = 1;
    tp.RowStyles.Add(new RowStyle(SizeType.Absolute, 28F));
    tp.Size = new System.Drawing.Size(380, 28);
    tp.Location = new Point(0, 14 + num * 28);

    newLabel.Name = "lbl_" + num;
    newLabel.Text = GetPropertyAttributes(p); // gets a custom attributes for the property
    newLabel.AutoSize = true;
    newLabel.Anchor = AnchorStyles.Left;

    tp.Controls.Add(newLabel);
    ToolTip myToolTip = new ToolTip();

    switch (p.PropertyType.Name)
    {
        case "String":
            ctrl = new TextBox();
            ctrl.Tag = "String";
            ctrl.Size = new System.Drawing.Size(170, 20);
            goto case "common";
        case "Boolean":
            ctrl = new CheckBox();
            goto case "common";
        case "Array[]":
            Console.WriteLine("Array");
            break;
        case "Int32":
            ctrl = new TextBox();
            ctrl.Tag = "Int";
            ctrl.Size = new System.Drawing.Size(40, 20);
            goto case "common";
        case "Double":
            ctrl = new TextBox();
            ctrl.Tag = "Double";
            ctrl.Size = new System.Drawing.Size(40, 20);
            goto case "common";
        case "IList`1":
            if (ClassExists(p.Name)) // ClassExists checks if the property is a class itself
            {
                ctrl = new Button();
                ctrl.Text = "Add";
                ctrl.Tag = p;
                ctrl.AutoSize = true;
                ctrl.Click += new EventHandler(AddButton_Click);
            }
            else
            {
                // TODO create gridview
            }
            goto case "common";
        case "common":
            ctrl.Anchor = AnchorStyles.Left;
            ctrl.Name = name ?? GetPropertyAttributes(p);
            ctrl.Font = new Font("Consolas", 9);
            ctrl.KeyPress += new KeyPressEventHandler(textBoxKeyPress);
            if (c != null)
            {
                tp.BackColor = c ?? Color.Black;
            }
            tp.Controls.Add(ctrl);
            formControls.Add(tp); // List<Control>
            break;
        default:
            ctrl = new Button();
            ctrl.Text = "Add";
            ctrl.Tag = p;
            ctrl.AutoSize = true;
            ctrl.Click += new EventHandler(AddButton_Click);
            goto case "common";
    }
}

private void AddControls()
{
    foreach (Control ctrl in formControls)
    {
        MainPanel.Controls.Add(ctrl); // MainPanel is a Panel Control
    }
}

Can it be simplified? I may have to add more types to it.


texts: Read file real time with while loop and trigger action on change

texts:
I want to read a file real time with a while loop that is being fed by the stdout of a process (inotifywait). The output could be multiple lines, but I as soon as I've found name of a specific file in a line, I want to discard all the other lines. How can you do that without breaking the while loop? I think my current code will be hard to maintain.

What I want:

 #!/bin/bash

 FILENAME=config.txt

 while read -r OUTPUT_DATE OUTPUT_FILE OUTPUT_EVENT; do

     # check if file name is found on line
     # grep -q will give me an exit code of 0
     # if file is found
     echo "$OUTPUT_FILE" | grep -q "^$FILENAME"

     if [ $? -eq 0 ]; then
         # perform an action(restart nginx, for example)!
         # and discard the other lines but do no break loop
     fi
 done < <(inotifywait -m -e close_write --timefmt '%Y%m%d%H%M' --format '%T %f %e' ./)

Depending on the texteditor, inotifywait can emit multiple lines output for a single modified file, like:

201710092031 config.txt CLOSE_WRITE,CLOSE <-- I was looking for config.txt so stop reading lines
201710092031 config.txt CLOSE_WRITE,CLOSE
201710092031 .config.txt.edited CLOSE_WRITE,CLOSE

My current workaround: (save date and time in hidden file and prevent update if multiple actions occur too fast after each other)

#!/bin/bash

FILENAME=config.txt
FILENAME_EDITED=~/ahn/.$FILENAME.edited

while read -r OUTPUT_DATE OUTPUT_FILE OUTPUT_EVENT
do
    echo $OUTPUT_FILE | grep -q "^$FILENAME"

    if [ $? -eq 0 ]; then
        # if the date + time of changed file is similar to
        # the date + time in hidden file, or if hidden file
        # does not exist, perform action and update date+time
        # in hidden file
        if ( [ -f "$FILENAME_EDITED" ] && [ $( cat "$FILENAME_EDITED" ) != "$OUTPUT_DATE" ] ) || [ ! -f "$FILENAME_EDITED" ]; then
            echo Restart process etc.
        fi
    fi
done < <(inotifywait -m -e close_write --timefmt '%Y%m%d%H%M' --format '%T %f %e' ./)


texts: Querying the same fields for many different values on AppEngine

texts:
I'm creating a gradebook.  Many students earn a grade in many standards each.  I'm hoping to get help analyzing the code below for efficient use of asynchronous result fetching. ofy is an Objectify object, which is basically just a convenience wrapper over the async fetching capabilities of AppEngine.

public List<StandardScoreDAO> getStandardScores(
        ArrayList<Long> studentIdLongs, ArrayList<Long> standardIdLongs)
{
    ObjectifyService.register(StandardScoreDAO.class);
    Objectify ofy = ObjectifyService.begin();

    List<Iterator<StandardScoreDAO>> results = new ArrayList<Iterator<StandardScoreDAO>>();

    for (Long studentId : studentIdLongs)
    {
        for (Long standardId : standardIdLongs)
        {
            results.add(ofy.query(StandardScoreDAO.class)
                    .filter("measuredUserId =", studentId)
                    .filter("standardId =", standardId)
                    .iterator());
        }
    }

    ArrayList<StandardScoreDAO> ret = new ArrayList<StandardScoreDAO>();

    for (Iterator<StandardScoreDAO> i : results)
    {
        while (i.hasNext())
        {
            ret.add(i.next());
        }
    }

    return ret;
}

As you can see, if there are 100 studentIds and 100 standardIds, this is 10,000 queries.  AppEngine will only run 10 in parallel. Aiee! I don't know if it's at all realistic to expect this to finish in 30 seconds (testing soon), but I wonder if anyone sees a much better way to organize this.


texts:
I was looking at this answer on SO to handle units in java.  The concept was interesting to me, except I didn't like that it had to be per object that had mass, instead of encapsulating a Mass class on its own so the pattern need not be repeated.  This is what I came up with.

public class Main
{

  public static void main(String args[]){
    Mass x = Mass.from_oz(2.3);
    System.out.println("x in kg: " + x.get_kg());
    System.out.println("x in oz: " + x.get_oz());

    Mass y = Mass.from_lb(1.2);
    System.out.println("y in kg: " + y.get_kg());
    System.out.println("y in lb: " + y.get_lb());

    Mass z = Mass.add(x, y);
    System.out.println("x + y in kg: " + z.get_kg());

    z.add(Mass.from_kg(2.0));
    System.out.println("x + y + 2.0kg in kg: " + z.get_kg());

  }
}

public class Mass{
    private double mass;
    private static double LB_PER_KG = 2.20462;
    private static double OZ_PER_LB = 16;

    private static double lb_to_kg(double value){
        return value * (1/LB_PER_KG);
    }
    private static double kg_to_lb(double value){
        return value * (LB_PER_KG);
    }
    private static double kg_to_oz(double value){
        return value * (LB_PER_KG*OZ_PER_LB);
    }
    private static double oz_to_kg(double value){
        return value * (1/(LB_PER_KG*OZ_PER_LB));
    }

    public double get_kg(){
        return this.mass;
    }
    public double get_lb(){
        return kg_to_lb(this.mass);
    }
    public double get_oz(){
        return kg_to_oz(this.mass);
    }

    public void set_kg(double value){
        this.mass = value;
    }
    public void set_lb(double value){
        this.mass = lb_to_kg(value);
    }
    public void set_oz(double value){
        this.mass = oz_to_kg(value);
    }

    private Mass(double value){
        set_kg(value);
    }

    public static Mass from_kg(double value){
        return new Mass(value);
    }
    public static Mass from_lb(double value){
        return new Mass(lb_to_kg(value));
    }
    public static Mass from_oz(double value){
        return new Mass(oz_to_kg(value));
    }

    public Mass add(Mass rhs){
        this.mass += rhs.mass;
        return this;
    }
    public Mass sub(Mass rhs){
        this.mass -= rhs.mass;
        return this;
    }
    public Mass div(Mass rhs){
        this.mass *= rhs.mass;
        return this;
    }
    public Mass mul(Mass rhs){
        this.mass /= rhs.mass;
        return this;
    }

    public static Mass add(Mass lhs, Mass rhs){
        return new Mass(lhs.mass).add(rhs);
    }
    public static Mass sub(Mass lhs, Mass rhs){
        return new Mass(lhs.mass).sub(rhs);
    }
    public static Mass mul(Mass lhs, Mass rhs){
        return new Mass(lhs.mass).mul(rhs);
    }
    public static Mass div(Mass lhs, Mass rhs){
        return new Mass(lhs.mass).div(rhs);
    }

}

Looking for any criticism, in addition to answers to these questions:

am I doing class arithmetic in java right?  It doesn't have overloading of operators, so I'm not sure what the convention is for arithmetic.
I didn't use lower camel case for the unit part of functions and variables, despite lower camel case being the convention, I felt it was harder to see toKg or toKG especially when this theoretically could be used with different units where Nm and nm would be two different things.
is there a better way to manage the conversion functions, seem like I have to add two every time I add a new unit?  what about units that are power of 10 convertible like for kg vs g?  Is there a special pattern I could employ there (eg kg, g, mg, etc...)?


texts: Get chat message data from table, grouped by date

texts:
Giving the following table:

id sender_id receiver_id msg  date_added
    1    2          5       hii     2018-10-24 16:42:41
    2    5          2       hello     2018-10-25 16:42:41

I want to extract data as:

[2018-10-24]=>[{
                sender_id=>2,
                receiver_id=>5,
                msg=>hii}],
[2018-10-25]=>[{
               sender_id=>5,
                receiver_id=>2,
                msg=>hello
              }]

I'm getting it by first querying for the date and then grouping by dates. After, I loop through thoses dates to retrives date's data.

However, I think using loops with a lot of dates and users will slow the app quickly

The code I've used is:

 //the dates is used to get the dates from table using group by
$dates = $this->get_date_list($checkArr);
////then i loop through each date to get the corresponding data
foreach($dates as $key=>$value){
$msg = $this->get_msg_by_date($value,$checkArr);
$data[$value] = $msg;
}

//here is the code to get the date from the date column
public function get_date_list($checkArr){
$sql = "Select date(date_added) as new_date from tb_chats where (sender_id = $checkArr[sender_id] AND receiver_id = $checkArr[receiver_id]) OR (sender_id = $checkArr[receiver_id] AND receiver_id = $checkArr[sender_id]) GROUP BY new_date";
$query = $this->db->query($sql);
$data  = $query->result_array();
return array_column($data,'new_date');
}

//here is the code to get the data for the looped dates
public function get_msg_by_date($date,$checkArr){
$sql = "Select * from tb_chats where (sender_id = $checkArr[sender_id] AND receiver_id = $checkArr[receiver_id] AND date_added LIKE '$date%') OR (sender_id = $checkArr[receiver_id] AND receiver_id = $checkArr[sender_id] AND date_added LIKE '$date%')";
$query = $this->db->query($sql);
$data  = $query->result_array();
return $data;
}


texts: Binary tree inorder traversal without stack or recursion

texts:
I was looking for ways to traverse a binary tree and came across things like Morris Traversal. Except I don't like the idea of modyfying my tree, nor use stack or recursion. Not finding other solution, I wrote my own algorithm. Basically it's depth-first search, but every node has counter of type integer indicating how many times the method traversed this node. Given every node has a parent and two children, this counter takes values from 0 to 2. Therefore the method executes 3 times for every node. Here's the code:

Node root;

public void Traverse() {
    Node node = root;
    while(node != null) {
        node = Get(node);
    }
}

Node Get(Node node) {
    Node child;
    if(node.Counter == 0) {
        child = node.Left;
    }
    else if(node.Counter == 1) {
        child = node.Right;
        System.Console.WriteLine(node);//display node
    }
    else {
        node.Counter = 0;//reset counter
        if(node.Parent != null) {
            node.Parent.Counter++;
            return node.Parent;
        }
        else {
            return null;
        }
    }
    if(child == null) {
        node.Counter++;
        return node;
    }
    return child;
}

My question: in what terms if any, this code is better than Morris traversal or using stack?


texts:
How should I go about creating a registration page in Windows forms? I can easily create a registration page, but I'm not sure if it's the best way. I'd have a service account that is hard coded, and it creates entries in a user table. I don't like to hard code passwords, but I don't know of another way. I guess in every case I'd end up having to hard code a password, right? I do have SSL enabled, and I've Wiresharked it and was unable to read any of the traffic.

Here's a simplified example of some code I wrote a while ago:

Public Class Registration
Dim connStr As String = "server=domain.com; port=3306; user id=userid;password=password;database=db;SslMode=Required;"
Dim msc As New MySqlConnection

Private Sub registerBTN_Click(sender As System.Object, e As System.EventArgs) Handles registerBTN.Click
            Dim dr As MySqlDataReader
                dr = checkUsername.ExecuteReader()
            Dim match As Boolean = False
            While dr.Read()
                If dr("Username").ToString = usernameTXT.Text Then
                    match = True
                    Exit While
                End If
            End While
            dr.Close()
            If match = False Then
                Dim User_GUID As Guid = New Guid
                User_GUID = Guid.NewGuid()
                Dim Encrypted_Password As String = Encryption(passwordTXT.Text, User_GUID.ToString)
                    Dim mscCMD As MySqlCommand = New MySqlCommand("INSERT INTO Users (Username, UserID, Password, Profile, Email) " & _
                                                                      "VALUES (@uname, @id, @pwd, @url, @mail)", msc)
                    With mscCMD.Parameters
                        .AddWithValue("uname", usernameTXT.Text)
                        .AddWithValue("id", User_GUID.ToString)
                        .AddWithValue("pwd", Encrypted_Password)
                        .AddWithValue("url", urlOptTXT.Text)
                        .AddWithValue("mail", emailTXT.Text)
                    End With
                    mscCMD.ExecuteNonQuery()
                MsgBox("Registration successful!", MsgBoxStyle.Information)
                My.Settings.First_Run = False
                Me.DialogResult = Windows.Forms.DialogResult.OK
                Me.Close()
End Sub

Private Sub Registration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            msc.ConnectionString = connStr
            msc.Open()
        Catch ex As MySql.Data.MySqlClient.MySqlException
            Me.Close()
        End Try
    End Sub

I want to know if this is a good approach. Does this have any vulnerabilities? Is there a better way to create a user registration method?

Also, here's my encryption/decryption.

Public Function Encryption(ByVal Plaintext_Password As String, ByRef User_GUID As String) As String
    Dim guidANDPassword As String = User_GUID.ToString + Plaintext_Password
    Dim shaobj As New Security.Cryptography.SHA1CryptoServiceProvider
    Dim guidPwdBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(guidANDPassword)
    guidPwdBytes = shaobj.ComputeHash(guidPwdBytes)

    Dim Encrypted_Password As String = String.Empty

    For Each b As Byte In guidPwdBytes
        Encrypted_Password += b.ToString("x2")
    Next
    User_GUID = User_GUID.ToString()
    Return Encrypted_Password
End Function

Public Function Decryption(ByVal Plaintext_Password As String, ByVal User_GUID As String) As String
    Dim guidANDPassword As String = User_GUID.ToString + Plaintext_Password
    Dim shaobj As New Security.Cryptography.SHA1CryptoServiceProvider
    Dim guidPwdBytes() As Byte = System.Text.Encoding.ASCII.GetBytes(guidANDPassword)
    guidPwdBytes = shaobj.ComputeHash(guidPwdBytes)
    Dim Encrypted_Password_Of_Specified As String = String.Empty

    For Each b As Byte In guidPwdBytes
        Encrypted_Password_Of_Specified += b.ToString("x2")
    Next
    Return Encrypted_Password_Of_Specified
End Function


texts: Choosing evenly distributed points from a million points on a sphere

texts:
I have \$10^5\$ to \$10^6\$ points on a sphere, and want to choose some points from them which are as close as uniformly distributed as possible. For that reason, I do the following: at each step I add the point in the data which is farthest away from any point which I have already chosen. In order to do this, I find the closest distance from each point in the data to any of the points that are already chosen. Then I pick the point from the data which has the largest minimum distance to any of the points that are already chosen. The algorithm is the following:

Choose a random point from all the \$10^6\$ points, add it to the chosen set of points
For each of the \$10^6\$ points:

2.1 Find the distances to all the points which are chosen already

2.2 Find the min distance to a point which is chosen already

2.3 Find the point which is furthest away from any point which is chosen already

2.4 Add this point to the chosen points
Repeat 2 until I have enough points (say 1000 or 10000 or 100000).

data is \$10^6\$ by 3 array of points on a sphere, e.g.

[[ 0.26750522 -0.92342735  0.27517791]
 [-0.26753053  0.9228284  -0.27715548]
 [ 0.34058837  0.35873472  0.86908513]
 [-0.33563178 -0.35794416 -0.8713365 ]
 [-0.8945523  -0.15682272  0.41854847]
 [ 0.906739    0.15103321 -0.39371734]
 [ 0.49138659 -0.64830133 -0.581588  ]
 [-0.87922161  0.24492971 -0.40863039]
 [ 0.18062012  0.39852148 -0.89919798]
 [-0.49103509  0.65872966  0.57005243]
 [-0.55615839 -0.82248645 -0.11918007]
 [ 0.85802915 -0.25207255  0.44748789]
 [-0.16990087 -0.40390349  0.89888579]]

I have implemented this in Python:

import random
import numpy

N = 1000

starting_point_ind = random.SystemRandom().randint (1 , len(data))

points_from_data = numpy.array(numpy.zeros((N, 3)), dtype=float, order='C')
points_from_data[0] = data[starting_point_ind]

for i in range(1, N):
    distancesToClosestPoints = numpy.array(numpy.zeros(len(data)), dtype=float)

    for j, point in enumerate(data):
        distancesToEstablishedPoints = numpy.linalg.norm (point - points_from_data[0:i] , axis=1)

        distancesToClosestPoints[j] = distancesToEstablishedPoints.min()

    k = distancesToClosestPoints.argmax()

    points_from_data[i] = data[k]

This doesn't run very efficiently for large N, so I also tried to optimise it by doing

import random
from sklearn.metrics import pairwise_distances
import time

t0 = time.time()

N = 1000

starting_point_ind = random.SystemRandom().randint (1 , len(data))

points_from_data = numpy.array([data[starting_point_ind]])

for i in range(1, N):
    pairwise_distances_to_data = pairwise_distances (data, Y=points_from_data, metric='euclidean', n_jobs=-1)
    pairwise_distances_to_data = numpy.array(pairwise_distances_to_data)

    min_distances_to_data = numpy.amin(pairwise_distances_to_data, axis=1)

    k = min_distances_to_data.argmax()

    points_from_data = numpy.append(points_from_data, [data[k]], axis=0)

print(points_from_data)

But this still has the issue that the pairwise distances are computed each time, and has obvious memory issues for large N. I would like to hear suggestions how I can improve the performance of the algorithm.


texts: Simple JDBC Query By Example (QBE) for Spring JDBC Template

texts:
This is a quick and dirty QBE method that covers about 60% of my use cases in my DAO. I just wanted to see if someone would take a quick look at it to see if there are any issues.

public List<Order> orderQuery(Order order) {

    StringBuilder sql = new StringBuilder();
    sql.append("select * from orders ");

    List<String> clauses = new ArrayList<String>();
    List<Object> values = new ArrayList<>();

    if (order.getOrderID() != null) {
        clauses.add("order_id = ?" + order.getOrderID());
        values.add(order.getOrderID());
    }

    if (order.getAccountCode() != null) {
        clauses.add("acct_nmbr = ?");
        values.add(order.getAccountCode());
    }

    // TODO: Once I switch this to the AccountType enum, use order.getAccountType().getCode()
    if (order.getAccountType() != null) {
        clauses.add("acct_typ = ?");
        values.add(order.getAccountType());
    }

    if (order.getRsid() != null) {
        clauses.add("rsid = ?");
        values.add(order.getRsid());
    }

    if (order.getUserID() != null) {
        clauses.add("user_id = ?");
        values.add(order.getUserID());
    }

    if (order.getCurrentStatus() != null) {
        values.add(order.getCurrentStatus());
    }

    if (!clauses.isEmpty()) {
        sql.append("where ");
    }

    String whereClause = clauses.stream().collect(Collectors.joining(" and "));
    sql.append(whereClause);

    List<Order> result = jdbcTemplate.query(sql.toString(), orderRowMapper, values.toArray());
    return result;
}

Generally it's simple:
1. Put the SQL clause in a StringBuilder.
2. Check the various fields I care about and if they aren't null, add a clause for them.
3. Turn the list of SQL where clauses into a single string
4. Build the entire SQL statement.
5. Execute it with Spring JDBC Template.

Any external input?