texts: Calculating a pattern-match score on a ten-element array

texts:
I have a method in Python that is extremely slow:

def patternRecognition(self):
    patRecStartTime = time.time()
    plotPatAr = []
    patFound = 0

    for eachPattern in self.patternAr:
        sim1 = 100.00 - abs(self.percentChange(eachPattern[0], self.patForRec[0]))

        if sim1 > 50:
            sim2 = 100.00 - abs(self.percentChange(eachPattern[1], self.patForRec[1]))
            if sim2 > 50:
                sim3 = 100.00 - abs(self.percentChange(eachPattern[2], self.patForRec[2]))
                if sim3 > 50 :
                    sim4 = 100.00 - abs(self.percentChange(eachPattern[3], self.patForRec[3]))
                    if sim4 > 50 :
                        sim5 = 100.00 - abs(self.percentChange(eachPattern[4], self.patForRec[4]))
                        if sim5 > 50:
                            sim6 = 100.00 - abs(self.percentChange(eachPattern[5], self.patForRec[5]))
                            if sim6 > 50 :
                                sim7 = 100.00 - abs(self.percentChange(eachPattern[6], self.patForRec[6]))
                                if sim7 > 50 :
                                    sim8 = 100.00 - abs(self.percentChange(eachPattern[7], self.patForRec[7]))
                                    if sim8 > 50:
                                        sim9 = 100.00 - abs(self.percentChange(eachPattern[8], self.patForRec[8]))
                                        if sim9>50:
                                            sim10 = 100.00 - abs(self.percentChange(eachPattern[9], self.patForRec[9]))

                                            howSim = (sim1+sim2+sim3+sim4+sim5+sim6+sim7+sim8+sim9+sim10)/10.00

                                            if howSim > 70:
                                                patFound = 1
                                                plotPatAr.append(eachPattern)

    if patFound == 1:
        for eachPatt in plotPatAr:
            futurePoints = self.patternAr.index(eachPatt)

            if self.performanceAr[futurePoints] > self.patForRec[29]:
                #do something
            else:
                #do something

Does anyone have any suggestions on making this method execute quicker? When the array gets to 50,000 elements, it takes about 1 second to execute and increases as the array patternAr grows. I read that converting the for loop into a map would make it quicker, however, I have not been able to figure it out.

I should mention that percentChange is very simple:

def percentChange(self, startPoint,currentPoint):
    try:
        x = ((float(currentPoint)-startPoint)/abs(startPoint))*100.00
        if x == 0.0:
            return 0.000000001
        else:
            return x
    except:
        return 0.0001

Initial code with sample data here.


texts: Converting a query result into an key=>value pairs for a lookup table

texts:
My app has a number of lookup tables stored in a MySQL database that are used for various purposes such as a select element.

Unfortunately, the query results aren't in an easily-digestible format and need some massaging to be more useful to me.

For example, when you query one of the lookup tables for all values, you get an array like this:

 0 => ['level_id' => 1, 'level' => 'Trivial'],
 1 => ['level_id' => 2, 'level' => 'Moderate']
 2 => ['level_id' => 3, 'level' => 'Challenging'],
 3 => ['level_id' => 4, 'level' => 'Formidable']

But for my purposes, this is what I want:

 1 => 'Trivial',
 2 => 'Moderate',
 3 => 'Challenging',
 4 => 'Formidable'

(Note that the array keys are the same as the record id).

If the array has more than one additional column, the result will be contained in sub-arrays:

 3 => ['level' => 'Challenging', 'description' => 'Foobar'],
 4 => ['level' => 'Formidable', 'description' => 'Bazbat']

This is all very trivial, but I wrote this function that I'd like you to review to know if there is a better way to do this in PHP.

The function needs to be generic so it can use any lookup array without having to know the column names.

<?php
// Turn an array into a key=>value pair. Assumes the key is the first item in the sub-array.
public function column_into_keys(array $array): array {

    // get the name of the column that contains the record id
    $key = key($array[0]);

    foreach($array as $row) {

        // pop the new key off the top of the array
        $id = array_shift($row);

        // is there only one item left in the array?
        if (count($row) == 1)
            // get the first value
            $result[$id] = current($row);
        else
            // get all of the values
            $result[$id] = $row;
    }

    return $result;
}


texts:
I developing an algorithm to read a row from a table (specifically, I'm reading from an Excel file).

I have three conditions about when to terminate the Read operation:

When an empty cell is found (recognized by an ElementNotFoundException
When a cell with errors is found (which corresponds to a null value)
Both the two previous conditions

This is the current algorithm:

public IEnumerable<string> ReadRow(string spreadsheet, int column, int row, ReadOptions readOptions = ReadOptions.ReadUntilEmpty)
{
    var values = new List<string>();

    if (readOptions.HasFlag(ReadOptions.ReadUntilEmpty) && readOptions.HasFlag(ReadOptions.ReadUntilCellError))
    {
        try
        {
            for (var currentColumn = column; ; currentColumn++)
            {
                var value = ReadCell(spreadsheet, currentColumn, row);

                // Cell has errors, so we exit from the loop
                if (value == null) break;

                values.Add(value);
            }
        }
        catch (ElementNotFoundException)
        {
            // The row is terminated
            // so we exit the loop withouth loggin any error
        }
    }
    else if (readOptions.HasFlag(ReadOptions.ReadUntilCellError))
    {
        for (var currentColumn = column; ; currentColumn++)
        {
            try
            {
                var value = ReadCell(spreadsheet, currentColumn, row);

                // Cell has errors, so we exit from the loop
                if (value == null) break;

                values.Add(value);
            }
            catch (ElementNotFoundException)
            {
                // The ReadOptions is not setted on ReadUntilEmpty
                // so we just ignore empty cells
            }
        }
    }
    else if (readOptions.HasFlag(ReadOptions.ReadUntilEmpty))
    {
        try
        {
            for (var currentColumn = column; ; currentColumn++)
            {
                var value = ReadCell(spreadsheet, currentColumn, row);

                values.Add(value);
            }
        }
        catch (ElementNotFoundException)
        {
            // The row is terminated
            // so we exit the loop withouth loggin any error
        }
    }

    return values;
}

And just for reference, the enumeration used:

[Flags]
public enum ReadOptions
{
    ReadUntilEmpty,
    ReadUntilCellError
}

How can I improve it?

Also, any idea on how I can reuse this code to read a column instead a row?


texts: Project Euler #11 - Largest product in a grid C++

texts:
https://projecteuler.net/problem=11

Any thoughts? Also, when measuring with chrono it takes supposedly 4 ms to compute, is this reliable value? Previous problems took little longer to compute so I'm suspicious, and I'm still a beginner so I'm not sure how long it "should" take or if chrono is good for measuring computing time.

#include <fstream>
#include <vector>
#include <string>

int main()
{
    std::ifstream input("grid.txt");
    std::vector<std::vector<int>> numbers(20, std::vector<int>(20));

    char c;
    std::string str;

    int row{ 0 };
    int column{ 0 };
    //convert from ascii to decimal
    while (input.get(c))
    {
        str += c;
        if (((int)c - 48 == -16) || ((int)c - 48 == -38)) //space or new line
        {
            numbers[row][column] = std::stoi(str);
            column++;
            str.clear();
        }
        if (column == 20)
        {
            row++;
            column = 0;
        }
    }
    int product;
    int maxProduct{ 0 };
    for (int i = 0; i < 20; i++)
    {
        product = 0;
        for (int j = 0; j < 20; j++)
        {
            // horizontal
            if (j >= 3)
            {
                product = numbers[i][j] * numbers[i][j - 1] * numbers[i][j - 2] * numbers[i][j - 3];
                if (product > maxProduct)
                    maxProduct = product;
            }

            if (j <= 16)
            {
                product = numbers[i][j] * numbers[i][j + 1] * numbers[i][j + 2] * numbers[i][j + 3];
                if (product > maxProduct)
                    maxProduct = product;
            }
            // vertical
            if (i >= 3)
            {
                product = numbers[i][j] * numbers[i - 1][j] * numbers[i - 2][j] * numbers[i - 3][j];
                if (product > maxProduct)
                    maxProduct = product;
            }

            if (i <= 16)
            {
                product = numbers[i][j] * numbers[i + 1][j] * numbers[i + 2][j] * numbers[i + 3][j];
                if (product > maxProduct)
                    maxProduct = product;
            }
            // diagonal
            if (i >= 3 && j >= 3)
            {
                product = numbers[i][j] * numbers[i - 1][j - 1] * numbers[i - 2][j - 2] * numbers[i - 3][j - 3];
                if (product > maxProduct)
                    maxProduct = product;
            }
            if (i <= 16 && j <= 16)
            {
                product = numbers[i][j] * numbers[i + 1][j + 1] * numbers[i + 2][j + 2] * numbers[i + 3][j + 3];
                if (product > maxProduct)
                    maxProduct = product;
            }
            if (i >= 3 && j <= 16)
            {
                product = numbers[i][j] * numbers[i - 1][j + 1] * numbers[i - 2][j + 2] * numbers[i - 3][j + 3];
                if (product > maxProduct)
                    maxProduct = product;
            }
            if (i <= 16 && j >= 3)
            {
                product = numbers[i][j] * numbers[i + 1][j - 1] * numbers[i + 2][j - 2] * numbers[i + 3][j - 3];
                if (product > maxProduct)
                    maxProduct = product;
            }
        }
    }

    return 0;
}


texts: Producing every string of a given length using some range of characters

texts:
Ever since I was a kid I wanted to understand how brute force programs work. I have not been able to make sense of any of the examples throughout the internet, so it became a personal challenge to make my own. Now that I have a couple Java classes under my belt, I realized I could tackle this problem with a linked list. Any advice about best practices, better algorithms, or how to make the existing one faster are welcome.

The problem to solve is to produce every possible combination of characters for a given range of characters and a given string length. This is purely for the purpose of personal learning.

public class BruteForce {

    final int minASCII = 97;
    final int maxASCII = 122;
    final int stringLength = 4;

    CharNode firstNode = new CharNode(minASCII);

    public BruteForce() {

        CharNode tempNode = firstNode;
        //Create stringLength number of CharNodes as a doubly linked list
        //The last node is used as an end of string marker
        for(int i = 0; i < stringLength; i++) {
            CharNode nextNode = new CharNode(minASCII - 1);
            tempNode.setNextNode(nextNode);
            nextNode.setPreviousNode(tempNode);
            tempNode = nextNode;

            //Link the last node with the first node, and the first node with
            //the last node to make it a circular linked list
            if (i == stringLength - 1) {
                nextNode.setNextNode(firstNode);
                firstNode.setPreviousNode(nextNode);
            }
        }
        //keep printing and incrementing the nodes until the last
        //marker node is incremented
        while (firstNode.getPreviousNode().getData() == (minASCII - 1)) {
            printData();
            firstNode.incrementData();
        }
    }

    private void printData() {

        CharNode tempNode = firstNode;

        while (tempNode.getData() != (minASCII -1)){
            System.out.print((char)tempNode.getData());
            tempNode = tempNode.getNextNode();
        }
        System.out.println();
    }

    /*
     * One CharNode represents one character. Each CharNode links to
     * the next CharNode and to the previous CharNode. Based on the
     * circular doubly linked list data structure.
     */
    private class CharNode {

        private int data = 0;
        private CharNode nextNode = null;
        private CharNode previousNode = null;

        public CharNode(int data) {
            this.data = data;
        }

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

        public int getData() {
            return data;
        }

        public void setNextNode(CharNode nextNode) {
            this.nextNode = nextNode;
        }

        public CharNode getNextNode() {
            return nextNode;
        }

        //Automatically increment the next node and reset data to minASCII
        //once maxASCII is reached
        public void incrementData() {
            if (data >= maxASCII) {
                this.getNextNode().incrementData();
                data = minASCII;
            }
            else
                data++;
        }

        public CharNode getPreviousNode() {
            return previousNode;
        }

        public void setPreviousNode(CharNode previousNode) {
            this.previousNode = previousNode;
        }
    }

    public static void main(String[] args) {
        new BruteForce();
    }
}


texts: Refactoring code duplication so the same textArea is not used in 4 different classes

texts:
Looking for the best way to do this.
Currently in 4 different classes I have:

textArea = new JTextArea(10, 55) {
    {
        setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics g) {
        for (int i = 0; i < list.size(); i++) {
            if(i == lineIndex)
                g.setColor(Color.black);
                g.drawRect(0, 20, 750, 20);
        }
        super.paintComponent(g);
    }
};

I've simplified down what I actually have.
As you can see there is duplication. The only data that is different is what is in the list.
A list is passed into each of these classes
There are some other stuff in the class which depends on the textarea and the lineIndex variable changes in the class depending on what the user does. I call the repaint() method of the textarea when I need the textarea to draw something else. The paintcomponent does a simple draw.

I'm not sure of the best way for each of the classes to contain the textarea so I dont have duplication. In each of the classes I have an addList(List list) method which the textareas need to use.

Hope I explained this ok.

Thanks


texts: Asynchronously loading a point in chart on drag

texts:
I have some code that asynchronously loads some point in a chart when a users drag it:

private void UpdateHistoryAndReSizeWhenDrag(string param, long duration)
    {
        lock (Lock)
        {
            if (Boxes.Count() > 0)
            {
                BoxStruct temp = Boxes.Where(key => key.id == param).FirstOrDefault();
                if (temp != null)
                {
                    int index = Boxes.IndexOf(Boxes.Where(key => key.id == param).First());
                    if (index >= 0)
                    {
                        double ChartLastPoint = Boxes[index].Series.Points[0].X;
                        double LastShownPoint = (from x in Boxes where x.id == param select x.PlotModel.Axes[0].ActualMinimum).Min();
                        double PMActualMinimumY = (from x in Boxes where x.id == param select x.PlotModel.Axes[0].ActualMinimum).Min();
                        double PMActualMaximumY = (from x in Boxes where x.id == param select x.PlotModel.Axes[0].ActualMaximum).Max();
                        if (LastShownPoint < ChartLastPoint)
                        {
                            string StartTime = (ConvertToUnixTime(DateTime.FromOADate(LastShownPoint)) - (10800 + duration * 4)).ToString();
                            string EndTime = (ConvertToUnixTime(DateTime.FromOADate(LastShownPoint)) - 10800).ToString();
                            List<DataPoint> LoadedPoints = LoadPointsRange(param, StartTime, EndTime).Points;
                            Boxes[index].Series.Points.InsertRange(0, LoadedPoints);
                        }
                        if (Boxes.Count > 0 & index < Boxes.Count)
                        {
                            var temp1 = Boxes[index].Series.Points.Where(key => key.X > PMActualMinimumY && key.X < PMActualMaximumY);

                            if (temp1 != null & temp1.Count() > 0)
                            {
                                double max = temp1.Select(p => p.Y).Max();
                                double min = temp1.Select(p => p.Y).Min();
                                Boxes.Where(k => k.id == param).First().PlotModel.Axes[1].Reset();
                                Boxes.Where(k => k.id == param).First().PlotModel.Axes[1].Zoom(min, max);
                            }
                        }
                    }
                }
            }
        }
    }

This function calls something like:

                UpdateHistoryAsyc UHA = new UpdateHistoryAsyc(UpdateHistoryAndReSizeWhenDrag);
            IAsyncResult result = UHA.BeginInvoke(item, CurrentDuration, null, null);

Where boxes looks like:

        private ObservableCollection<BoxStruct> boxes;
    public ObservableCollection<BoxStruct> Boxes
    {
        get { return boxes; }
        set { boxes = value; RaisePropertyChanged("Boxes"); }
    }

How can I improve this LINQ code?


texts: Converting binary value from BitArray to an int and back in C#

texts:
What I am creating is essentially a binary clock face with touch input for setting values as well as displaying - so I need to convert both ways between an int and a binary sequence in a BitArray.

I cobbled this together (borrow and modifying a bit from a couple different examples I found):

    public class BinaryConverter
    {
        public static BitArray ToBinary(int numeral)
        {
            BitArray binary = new BitArray(new int[] { numeral });
            bool[] bits = new bool[binary.Count];
            binary.CopyTo(bits, 0);
            return binary;
        }

        public static int ToNumeral(BitArray binary, int length)
        {
            int numeral = 0;
            for (int i = 0; i < length; i++)
            {
                if (binary[i])
                {
                    numeral = numeral | (((int)1) << (length - 1 - i));
                }
            }
            return numeral;
        }
    }

It isn't especially verbose, but in my head before I started it should have been a couple of lines per method, perhaps better leveraging some .NET classes like System.Convert (though, I can't quite see how to do that). Is there a cleaner way to do this? Do you have any other suggestions for improvement?


texts:
I was wondering if there is any way to make this code smaller/condensed. It is for a school project which says it has to be as small as it can be and I am not sure whether it can go any smaller.

num1 = float(input("Give first number "))#Get first number
num2 = float(input("Give second number ")) #Get second number
ans = num1 + num2 #Work out answer
if ans % 1 == 0: #If its a whole number
    print (int(ans)) #Convert to int so its for example 14 instead of 14.0
else: #If not a whole number
    print (ans) #Print the answer


texts:
I'm just starting to look into Haskell. I've written a naive Fibonacci implementation, and I've also written a more advanced one that uses tail-call recursion for efficiency.

module Fibonacci where

import System.Environment

fibonacci :: Integer -> Integer
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n
    | n < 0 = error "Cannot find a negative fibonacci number"
    | otherwise = fibonacci (n - 1) + fibonacci (n - 2)

fibonacci' :: Integer -> Integer
fibonacci' n
    | n < 0 = error "Cannot find a negative fibonacci number"
    | otherwise = fibHelper n 0 1
    where
        fibHelper :: Integer -> Integer -> Integer -> Integer
        fibHelper n a b
            | n == 0 = a
            | otherwise = fibHelper (n - 1) b (a + b)

firstNumberFrom :: [String] -> Integer
firstNumberFrom [] = 10
firstNumberFrom args = read $ args !! 0

main = do
    args <- getArgs
    let num = firstNumberFrom args in
        putStrLn $ show (fibonacci' num)

I'd appreciate any reviews on correctness and idiomatic usage.


texts: Non-nullable reference type default parameters in C# 8

texts:
I was working to upgrade some code to C# 8.0 and came across an interesting pattern with default parameters and non-nullable reference types. I'm working if it's clear enough to the caller.

Given this pre C# 8.0 code,

Task FooAsync(
   Bar bar = null,
   CancellationToken ct = default)
{
    bar = bar ?? new Bar(); // some sensible default
}

the bar parameter is flagged as one to potentially make nullable (Bar? bar = null). This would indicate to the caller that they can pass null.

However, if I want to encourage the caller not to pass null for the parameter, I could do something like this in C# 8.0:

Task FooAsync(
   Bar bar = null!,
   CancellationToken ct = default)
{
    bar ?? = new Bar(); // some sensible default
}

Is this a sensible approach to avoid passing null into the parameter? I know the caller can still do: FooAsync(bar: null!) but that obviously sticks out.


texts: Bootstrap 3.0 Carousel gallery post WordPress

texts:
I have working code to show in index.php and content-gallery.php of WordPress with Bootstrap 3.0 Carousel.

But, I know it's not clean code.  Could anyone help me clean/improve it?

This is the code we need to generate Bootstrap Carousel:

        ...

    ...

This is the content of my content-gallery-php:

 <?php function_indicators($post) ?>

 <?php function_slides($post) ?>

And here are 3 functions to my functions.php:

function wp_get_attachment( $attachment_id ) {

    $attachment = get_post( $attachment_id );
    return array(
        'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
        'caption' => $attachment->post_excerpt,
        'description' => $attachment->post_content,
        'href' => get_permalink( $attachment->ID ),
        'src' => $attachment->guid,
        'title' => $attachment->post_title
    );
}

function functions_indicators() {
$special_gallery = get_post_gallery( $post, false );
$ids = explode( ",", $special_gallery['ids'] );
$html = '
';
foreach( $ids as $id ) {
    $link   = wp_get_attachment_url( $id );
    $class = ( $i == 0 ) ? 'active ' : '';
    $i++;
    $b=1;
    $html .= '

';
}
$html .= '
';
echo $html;

}

function function_slides() {
$special_gallery = get_post_gallery( $post, false );
$ids = explode( ",", $special_gallery['ids'] );
$html = '
';
foreach( $ids as $id ) {
    $link   = wp_get_attachment_url( $id );
    $attachment_meta = wp_get_attachment($id);
    $class = ( $i == 0 ) ? 'active ' : '';
    $i++;
    $html .= '
' . '

'.$attachment_meta['title'].'

'.$attachment_meta['description']. '

';
}
$html .= '
';
echo $html;}


texts:
I have this class that needs to do three things:

Determine if a string is 8 characters or longer
Determine if a string has a number in it
Determine if a string has a capital letter in it

NB: I don't want to use regex. Is there a better way of doing this?

class ValidateString
  def initialize(string)
    @string = string

    if valid
      puts @string
    end
  end

  def valid
    if has_number? and has_upper? and has_length?
      return @string
    end
  end

  def has_number?
    @string.count("0-9") > 0
  end

  def has_upper?
    @string =~ /[A-Z]/
  end

  def has_length?
    @string.length >= 8
  end
end


texts: Rust version of basic functional prime stream - can this be made less clunky?

texts:
I'm looking at implementing the basic functional not-quite-Eratosthenes prime stream in Rust.  I like to try it when I start learning a language.

Here's the bog standard Haskell version:

primes :: [Integer]
primes = sieve (2 : [3, 5..])
  where
    sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p /= 0]

in Rust, I think a reasonable transliteration is something like:

struct Primes {
    iter: Option<Box<Iterator<Item=u32>>>
}

impl Iterator for Primes {
    type Item = u32;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        let mut iter = self.iter.take().unwrap();
        let res = iter.next().unwrap();
        self.iter = Some(Box::new(iter.filter( move |x| x % res != 0)));
        Some(res)
    }
}

fn main() {
    let primes = Primes { iter: Some(Box::new(2..)) };
    for p in primes.take(20) {
        println!("{}", p);
    }
}

Leaving aside the algorithm (of course there are nicer ways to do primes!),
this feels a bit verbose - is there a simpler way to construct an iterator with accumulating filters?  The Option of Box feels quite clunky, but if I understand right, that's the best way to replace a field on self.


texts: For an array, check if an index exists where the sum of the elements to the left of it is equal to the sum of the elements right of it

texts:
Problem

Extended from this HackerRank problem.

  Given an array A of length n, determine if there exists an element in the array such that the sum of the elements on
  its left is equal to the sum of the elements on its right.
  If there are no elements to the left/right, then the sum is considered to be zero.

For example, [ 1, 1, 1, 2 ], the sum of elements to the left and right of index 2 are equal.

Approach

The following description is for the left-to-right evaluation of the array of values. In my implementation, I do both the
left-to-right and right-to-left evaluations in the same loop.

Given an array of values, start with the first and last index. These will be the initial values of the left and
right sums and the initial left and right indices
Increment the left index by 1 and decrement the right index by 1

If the left index is less than the right index, add the value at the right index to the right sum
If the left index is greater than the right index, subtract the value at the left index from the right sum
If the left and right sums are the same, then return early
Else, add the value at the left index to the left sum

After exiting the loop, check if the left sum is equal to the right sum

Implementation

public class BalancedArraySumIdentifier {
    public static boolean isBalanced(int[] values) {
        int leftToRightLeftSum = 0;
        int leftToRightRightSum = 0;

        int rightToLeftRightSum = 0;
        int rightToLeftLeftSum = 0;

        for (int i = 0; i < values.length; i++) {
            int j = values.length - 1 - i;

            if (i < j) {
                leftToRightRightSum += values[j];
                rightToLeftLeftSum += values[i];
            } else if (i > j) {
                leftToRightRightSum -= values[i];
                rightToLeftLeftSum -= values[j];
            }

            if (leftToRightLeftSum == leftToRightRightSum || rightToLeftLeftSum == rightToLeftRightSum) {
                return true;
            }

            leftToRightLeftSum += values[i];
            rightToLeftRightSum += values[j];
        }

        return leftToRightLeftSum == leftToRightRightSum || rightToLeftLeftSum == rightToLeftRightSum;
    }
}


texts:
So this is my code and I would like to add subtraction, multiplication and division. If you have any suggestions on algorithms to use I would be very happy to see it. I do not wish to copy the code, I just want an outline of how to simply, and efficiently create a calculator. I want to make a calculator for KIDS with a friendly UI maybe showing dogs, cats, food etc. as the buttons. With 1 dog/cat for the 1 button and so on.....
I wish to put ads in this application, but I want the ads just to be under a donation/ad tab.

Tell me what you think, questions, comments and concerns would be very much appreciated to help develop my app :)

package com.nickmarcoose.addingcalculatorfree;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Addition extends Activity
{
  EditText amount1;
  EditText amount2;
  TextView views;
  Button Addition1;
  double a;
  double b;
  double c;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initControls();
  }

  private void initControls()
  {
    amount1=(EditText)findViewById(R.id.amount1);
    amount2=(EditText)findViewById(R.id.amount2);
    views=(TextView)findViewById(R.id.view);
    Addition1=(Button)findViewById(R.id.start);
    Addition1.setOnClickListener(new Button.OnClickListener()
    {
      public void onClick (View  view) { calculate();}
    });
  }

  private void calculate()
  {

    a=Double.parseDouble(amount1.getText().toString());
    b=Double.parseDouble(amount2.getText().toString());
    c=b+a;
    views.setText(Double.toString(c));
  }
}


texts:
I'm trying to create a handler to set the profile picture for the user. Don't worry about the validation as I will clean that up, because that's for testing purposes. This is how far I went. I'm using Intervention package to manipulate the image and re-size it. As far as I know, this is not the controller's responsibility to upload the file, re-size it, append file names etc...

What's a good way to separate this from the controller? I'm thinking about a service class that does all of that and then inject that to the constructor and call it from the setProfilePicture() method. Is that a good way?

public function setProfilePicture()
{
    $profile_picture = Input::file('profile_picture');

    $rules = ['profile_picture' => 'required|min:10|image|real_image|'];

    $validator = Validator::make(['profile_picture' => $profile_picture], $rules);

    if ($validator->fails()) {
        return Response::json([
            'success' => 'false',
            'message' => 'The selected file is not an image.'
            ]);
    }

    // Don't worry about the validation, I will fix that up to something like this.
    /*
    try {
        $this->coverPhotoForm->validate(Input::all());
    } catch (FormValidationException $e) {
        return Response::json(['success' => 'false'])
    }
    */

    $extension = $profile_picture->getClientOriginalExtension();
    $file_name = $profile_picture->getClientOriginalName();

    $image = Image::make($profile_picture);

    $name = sha1(time() . $file_name);
    // Sample: domain.com/photos/4952058f4d990c21019c7bc6a319bddcba6cbfa9.png
    $destination = photos_path() . '/' . $name . '.' . $extension;

    $image->fit(300, 300);
    $image->save($destination);

    $image = Auth::user()->photos()->create([
        'profile_picture' => true,
        'path' => $name . '.' .$extension
    ]);

    return Response::json(['success' => 'true', 'image_path' => '/photos/' . $image->path]);
}


texts: Is there a better way to implement this string builder?

texts:
I have a function that returns a string that indicates if an element is the same as another element(s). The logic is:

function duplicates(duplicatesArray, id = 1) {
    var duplicates = '';

    var count = 1;

    var length = duplicatesArray.length;

    var _id = null;

    for (var i = 0; i < length; i++) {
        _id = duplicatesArray[i];

        if (_id !== id) {
            count++;

            if (length == 2) {
                duplicates = duplicates + ' ' + _id;

                return duplicates;
            } else if (count < length) {
                duplicates = duplicates + ' ' + _id;

                if (count + 1 < length) {
                    duplicates = duplicates + ',';
                }
            } else {
                duplicates = duplicates + ' and ' + _id;
            }
        }
    }

    return duplicates;
}

The above outputs:

console.log(
    'This item is the same as item ' + duplicates(
        [1, 2]
    )
); // This item is the same as item 2

console.log(
    'This item is the same as item ' + duplicates(
        [1, 2, 3]
    )
); // This item is the same as item 2 and 3

console.log(
    'This item is the same as item ' + duplicates(
        [1, 2, 3, 4]
    )
); // This item is the same as item 2, 3 and 4

This function takes in an id (here, I am defaulting it to id = 1 for the purpose of brevity) and it compares that id to elements in the first argument, which is an array of other IDs. The comments after the console.logs above is the expected output, I'm just wondering if there is a more succinct way of approaching this.


texts:
I've coded this @Stateless session bean:
package br.eti.rslemos;

import java.util.function.Supplier;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

@Stateless
public class FunctionalEJB {
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public <R> R executeInTransaction(Supplier<R> supplier) {
        return supplier.get();
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void executeInTransaction(Runnable runnable) {
        runnable.run();
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public <R> R executeInNewTransaction(Supplier<R> supplier) {
        return supplier.get();
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void executeInNewTransaction(Runnable runnable) {
        runnable.run();
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public <R> R executeOutsideTransaction(Supplier<R> supplier) {
        return supplier.get();
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void executeOutsideTransaction(Runnable runnable) {
        runnable.run();
    }
}

All their methods do the same thing: they delegate their job to their argument.
They are the ultimate - perhaps just too literal - implementation of Floyd Marinescu "EJB Command" Design Pattern (in MARINESCU, Floyd, EJB™ Design Patterns: Advanced Patterns, Processes, and Idioms, 2002).
The six methods are nothing more than 2 x 3:

2 argument types: Supplier or Runnable, for void;
3 transaction attributes (that make sense here): REQUIRED, REQUIRES_NEW and NOT_SUPPORTED.

You may use the functional EJB from another session bean (or any other class, collocated with the functional EJB):
package br.eti.rslemos.client;

import javax.ejb.Stateless;

import br.eti.rslemos.FunctionalEJB;

@Stateless
public class ClientEJB {
    @Inject
    private FunctionalEJB ejb;

    public ClientResponse service (ClientRequest request) {
        String someString = "Hello, world!";

        return ejb.executeInNewTransaction(() -> {
            // and here goes code that can take/use anything available at this
            // anonymous method's closures, for example:
            // - the argument (request)
            // - any effectively final variable defined before invocation (someString)
            // - any field or method of ClientEJB

            return new ClientResponse(....);
        });
    }
}

This implementation departs a bit of what Marinescu had in mind. Back then (2002), EJB had only remote interfaces, and his idea was to save on network traffic.
My functional EJB clearly only works for local or no interface EJB (because the anonymous classes created by the arrow operator are not serializable), and that means collocation, and that means zero network traffic to save.
On the other hand the obvious advantage of such functional EJB is that I don't have to resort to UserTransaction to gain fine-grained access to transactions (well, perhaps only in more intricate cases).
I think this arrangement is better than fiddling with UserTransaction, in that the language forces you to either commit or rollback a transaction (or suspend and then get back, in case of executeOutsideTransaction).
Now comes the question: does this functional EJB breaks the spec?
The only way I can think this somehow wreaks havoc with the specs lay within the state carried through anonymous class' closure.
There is one special case that I think may cause errors (or may invoke unspecified behavior): entities obtained in the outside transaction carried along the closure and being used on the inside transaction.


texts: Asks the user for an input, stores and prints it to the console c#

texts:
My code is very simple, it asks for an input then stores the input. I am new to c# and wanted to know if it was possible to both ask and accept the input on one line.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            var input = GetInput();
            Console.WriteLine("Your input:\n{0}", input);

        }
        static string GetInput()
        {
            Console.WriteLine("Please input somthing");
            var input = Console.ReadLine();
            return input;

        }
    }
}

All feedback welcome!


texts:
I need to write a function in Python that makes sure the user entered a valid JavaScript origin. If I understand it correctly, the origin includes the scheme, hostname and port (port and scheme might be implicit, defaulting to 80 and http respectively), so would this be a correct way to validate it?

import urlparse

def validate_javascript_origin(origin):
    parsed = urlparse.urlsplit(origin)

    if parsed.scheme and parsed.scheme not in ["http", "https"]:
        raise ValueError("Only the http and https url schemes are supported.")

    if not parsed.netloc:
        raise ValueError("The origin must include a hostname.")

    if parsed.path or parsed.query or parsed.fragment:
        raise ValueError("The origin must not contain a path, query string or fragment.")

The origin will be used to pass as the preferredOrigin to window.postMessage.

The main thing I'm worried about is that I'm not sure how credentials in the url (username:password@example.com) are handled.

Going to http://username@frederikcreemers.be, and getting location.originin javascript returns http://frederikcreemers.be, so the origin doesn't include credentials. Would it be sufficient to add a condition like this to the function above:

if "@" in parsed.netloc:
    raise ValueError("The origin must not contain credentials.")


texts:
I implemented a method, to create an object based on a series of strings that are passed to it, of any depth or length. The way I implemented the solution was to map over the arguments. Assuming that strings are passed in the form x.a, it then splits the string by the '.', returning just a single object with that key if the array only had one element otherwise, it was passed through a reducer to produce an array of objects which would then be merged into one object.

I'd like to make this better/ are there any concerns with using a reducer in a map function, since it's on the order of O(n2)?

type TKeys = string[]
type TTarget = {
  [key: string]: TTarget | string,
}
type TTemplate = {
  target: TTarget,
  props: ReadonlyArray<string>
}
interface ITemplate {
  target: {
    [key: string]: string | TTemplate["target"]
  },
  props: ReadonlyArray<string>
}
const createObject = <T>(...keys: TKeys): T => (
  keys.map(key => {
    const props = key.split('.');
    const reducerTemplate: ITemplate = {
      target: {},
      props: ['']
    }

    return props.length < 2
      ? {
          [key]: ''
        }
      : props.reduce((obj: ITemplate, prop: string) => {
          const target: ITemplate["target"] = obj.target
          if (obj.props.length === 0) {
            console.log(obj, prop);
            obj.props = [prop];
            target[prop] = {};
            return obj;
          }
          const object: ITemplate["target"] = obj
            .props
            .reduce((prev: TTemplate["target"] , next: string) => (target[next] || prev[next]), {})
          const atEnd: boolean = props.indexOf(prop) === props.length - 1
          object[prop] = atEnd
            ? ''
            : {}
          obj.props = [
            ...obj.props,
            prop
          ];

          return atEnd
            ? target
            : obj;
        }, reducerTemplate)
  }).reduce((main: {} | TTarget, obj: TTarget ): TTarget => ({
    ...main,
    ...obj
}), {}))

Example Usage:

createObject('a.b.c.d', 'hello.world', 'test')
//outputs
    {
    a: {
        b: {
            c: {
                d: '',
            },
        },
    },
    hello: {
        world: '',
    },
    test: '',
}
createObject('hello')
//outputs
{ hello: '' }
createObject('a.b')
//outputs
{
    a: {
        b: '',
    },
};


texts: Safely pruning merged topic branches locally

texts:
Background

My team develops in a git monorepo. User stories are broken into very small discrete sub-tasks and merged directly into master, rather than into a feature branch for the story.

Topic branches

Our topic branch names are all of the form issue/<developer username>/<subtask ticket>.

Those are pushed to origin and merged via a code-reviewed pull-request process.

Release branches

We also maintain long-lived release branches named release/sprint/<number> used for hot-patching.

Release branches are never re-merged to master. The individual fixes, if relevant in the current release, are re-implemented in another branch or applied as a patch. There are few enough of them to manage manually.

Work

This works well for us, but it means we have hundreds of topic branches hanging around as developers often forget to delete them as they go.

I wrote a simple bash script to

Sync up with origin (we have only one),
Figure out which branches have been merged into master (or, optionally, a different branch, so far nobody has used that),
Delete locally-merged branches,
Optionally run the gc

The verbose prompting at every stage is intentional as reassurance.

Concerns

Primarily, is this "safe", meaning:

Have I used an appropriate method to list branches?
Have I used an appropriate method for deleting branches?
Have I accounted for all possible pathways that could result in destruction of a local branch?
Have I adequately guarded against destruction of a local branch not merged into master?
Should I verify that topic branches have been merged into origin's master and not the local master, in the event that a user mistakenly merges locally and loses their branch?

I'm very happy for any additional comments, no matter how nit-picky.

Code

#!/bin/bash
MERGED_INTO=${1:-"master"}

statistics() {
  echo
  echo "Remaining local branches:"
  git branch

  echo
  echo "These local branches are not merged into ${MERGED_INTO}:"
  git branch --no-merged ${MERGED_INTO}

  echo
  echo "Size of local repo: $(git count-objects)"

  git status
}

error () {
  echo "WARNING: Something went wrong. Aborting..."
  if [[ ${1} ]]; then echo "The previous command exited with ${?}"; fi

  echo "This is the current state of your working copy:"
  git status
}

confirm () {
  read -r -p "Are you sure? [y/N] " response
  case ${response} in
    [yY][eE][sS]|[yY])
      true
      ;;
    *)
     echo "Ok, aborting..."
     echo
     false
     ;;
  esac
}

check_on_main_branch() {
  local current_branch;
  current_branch=$(git symbolic-ref -q --short HEAD)
  if [ "${current_branch}" != "${MERGED_INTO}" ]; then
    echo "You should be on '${MERGED_INTO}' for this operation. I can switch branches for you."
    confirm && git checkout "${MERGED_INTO}" || error $?
  fi
}

delete_local_merged_branches() {
  git branch --merged ${MERGED_INTO} | egrep -v "(^\*|${MERGED_INTO})" | xargs git branch --delete
}

# Step 1
echo "Fetching remote branch state"
git fetch --all

# Step 2
echo "The following local branches have been merged into ${MERGED_INTO} and will be deleted locally:"
git branch --merged ${MERGED_INTO} | egrep -v "(^\*|${MERGED_INTO})"
confirm && delete_local_merged_branches

# Step 3
echo "Would you like to run the garbage collector?"
confirm && \
 echo "Before garbage collecting: $(git count-objects)" && \
 git gc

trap statistics EXIT
trap error SIGHUP SIGINT SIGTERM


texts: Enum string parse and get custom attribute assign to array

texts:
I wrote a code which:
- parse string to my enum
- get description from enum
- assign to string[] array

private readonly string[] allowed;

public AuthorizeRoles(params object[] arrayParam)
{
    allowed = (arrayParam.Select(myField => Enum.Parse(typeof (MyEnum), myField.ToString()))
        .Select(temp => temp.GetType().GetField(temp.ToString()))
        .Select(field => GetCustomAttribute(field, typeof (DescriptionAttribute)))).OfType<DescriptionAttribute>()
        .Select(attribute => attribute.Description)
        .ToArray();
}

Could you tell me if it possible to improve this code for better efficiency and clean code.


texts: Follow-up: Find number of times that difference of array values are equals to a number

texts:
This question is follow-up to this question.

Sample Calculation

10-21=-11
10-34=-24
10-45=-35
10-56=-46
21-10=11     <
21-34=-13
21-45=-24
21-56=-35
34-10=24
34-21=13
34-45=-11
34-56=-22
45-10=35
45-21=24
45-34=11   <<
45-56=-11
56-10=46
56-21=35
56-34=22
56-45=11   <<<

Code

Set<Integer> tchars = new HashSet<>();
        tchars.add(10);
        tchars.add(21);
        tchars.add(34);
        tchars.add(45);
        tchars.add(56);
        int number = 11;
        int counter = 0;

        Iterator it = tchars.iterator();
        while (it.hasNext()) {
            Integer inte = (Integer) it.next();
            if (tchars.contains(inte + number)) {
                System.err.println(inte + " " + number);
                counter++;
            }
        }
        System.err.println(counter);


texts:
I've created my first Android drawable, a hourglass shaped image, and I'm curious what can be improved with it. It seems weird having to use 4 paths, but I couldn't get it to work any other way.
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="34dp"
        android:viewportHeight="34"
        android:viewportWidth="24">

    <group>
        <path
            android:pathData="M0,10L0,0M0,0L24,0M24,0L24,10"
            android:strokeColor="@color/ColorPrimary"
            android:strokeWidth="3"/>

        <path
            android:pathData="M0,10L24,24"
            android:strokeColor="@color/ColorPrimary"
            android:strokeWidth="1.7"/>
        <path
            android:pathData="M24,10L0,24"
            android:strokeColor="@color/ColorPrimary"
            android:strokeWidth="1.7"/>
        <path
            android:pathData="M0,24L0,34M0,34L34,34M24,34L24,24"
            android:strokeColor="@color/ColorPrimary"
            android:strokeWidth="3"/>

    </group>
</vector>

Reason I tagged it SVG, is the docs page mentions

android:pathData
Defines path data using exactly same format as "d" attribute in the SVG's path data. This is defined in the viewport space.


texts:
I can't seem to get fieldset's to react properly when using display:table and display:table-cell even if I reset the default values, it just reacts oddly in a variety of ways in different browsers/devices, so as a result I have actually removed all fieldset's and replaced them with div's.

Is this a semantically accurate method to label a radio group? or is there a better more semantic method aside from using fieldset/legend?

<form method="get" novalidate>

      Pet Type

          <input id="r3" name="same2" type="radio" />
          Cat

          <input id="r4" name="same2" type="radio" />
          Dog

</form>

I've always approached it in this manner, but to avoid using flexbox and floats I used the above instead.

<form method="get" novalidate>
<fieldset class="table">

      <legend for="r1-group">Pet Type</legend>

          <input id="r3" name="same2" type="radio" />
          Cat

          <input id="r4" name="same2" type="radio" />
          Dog

</fieldset>
</form>

Should I be bolstering this with Schema's microdata and aria to improve semantics instead?


texts:
I've become a bit rusty in Java. This is an attempt at brushing up my skills.

  In computer science, merge sort is an efficient, general-purpose,
  comparison-based sorting algorithm.

Questions

How can I improve my test cases? (TestNG)
I've used Java-11 here, can I use better idioms?
Can this implementation improved for performance?
Can style / readability improved?

Code

Sorting.java

import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;

public class Sorting {

    /**
     * Day 08 - Merge Sort
     *
     * @param data       data array
     * @param comparator comparator of given data type
     * @param ascending  sort order
     * @param <T>        data type
     * @return sorted array (in place)
     */
    public static <T> T[] mergeSort(T[] data, Comparator<T> comparator, boolean ascending) {
        Objects.requireNonNull(data);
        Objects.requireNonNull(comparator);
        if (data.length <= 1) return data;
        var actualComparator = ascending ? comparator : comparator.reversed();
        return mergeSort(data, actualComparator, 0, data.length - 1);
    }

    private static <T> T[] mergeSort(T[] data, Comparator<T> comparator, int start, int stop) {
        if (start >= stop) return data;
        int pivot = start + (stop - start) / 2;
        mergeSort(data, comparator, start, pivot);
        mergeSort(data, comparator, pivot + 1, stop);
        return merge(data, comparator, start, pivot, stop);
    }

    private static <T> T[] merge(T[] data, Comparator<T> comparator, int start, int pivot, int stop) {
        T[] left = Arrays.copyOfRange(data, start, pivot + 1);
        T[] right = Arrays.copyOfRange(data, pivot + 1, stop + 1);
        int lPos = 0;
        int rPos = 0;
        int pos = start;
        while (lPos < left.length && rPos < right.length) {
            if (comparator.compare(left[lPos], right[rPos]) <= 0) {
                data[pos++] = left[lPos++];
            } else {
                data[pos++] = right[rPos++];
            }
        }
        while (lPos < left.length) {
            data[pos++] = left[lPos++];
        }
        while (rPos < right.length) {
            data[pos++] = right[rPos++];
        }
        return data;
    }
}

TestMergeSorting.java

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMergeSorting {
    @Test
    public void testMergeSort() {
        Assert.assertEquals(asc(6, 5, 9, 3, 2, 1), ar(1, 2, 3, 5, 6, 9));
        Assert.assertEquals(asc(1, 1, 1, 1, 2, 1), ar(1, 1, 1, 1, 1, 2));
        Assert.assertEquals(asc(2, 1, 1, 1, 1, 2, 1), ar(1, 1, 1, 1, 1, 2, 2));
        Assert.assertEquals(asc(1, 1, 1, 1, 1, 2, 1), ar(1, 1, 1, 1, 1, 1, 2));
        Assert.assertEquals(asc(3, 2, 1), ar(1, 2, 3));
        Assert.assertEquals(asc(1, 2, 3), ar(1, 2, 3));
        Assert.assertEquals(asc(2, 0, -1, 2, 1), ar(-1, 0, 1, 2, 2));

        Assert.assertEquals(dsc(1, 2, 3), ar(3, 2, 1));
        Assert.assertEquals(dsc(3, 2, 1), ar(3, 2, 1));
        Assert.assertEquals(dsc(2, 0, -1, 2, 1), ar(2, 2, 1, 0, -1));

        Assert.assertEquals(asc(2, 1), ar(1, 2));
        Assert.assertEquals(asc(1), ar(1));
        Assert.assertEquals(asc(), ar());
        Assert.assertEquals(dsc(1), ar(1));
        Assert.assertEquals(dsc(), ar());
    }

    @Test(expectedExceptions = {NullPointerException.class})
    public void testNullExcept() {
        Sorting.mergeSort(null, Integer::compare, true);
    }

    private static Integer[] ar(Integer... objects) {
        return objects;
    }

    private static Integer[] asc(Integer... objects) {
        return Sorting.mergeSort(objects, Integer::compare, true);
    }

    private static Integer[] dsc(Integer... objects) {
        return Sorting.mergeSort(objects, Integer::compare, false);
    }
}


texts:
Is there any way I can cut down on code? I'm new to this.

Sub addtest()

    Dim decision As Char
    Dim fullline As String = " "

    Dim word(9), def(9), minorerror1(49), minorerror2(49), minorerror3(49), minorerror4(49), minorerror5(49) As String

    Console.Clear()
    Console.WriteLine("Please select the year of students you wish to save the test for: ")
    Console.WriteLine()
    Console.WriteLine("3 - Year 3")
    Console.WriteLine("4 - Year 4")
    Console.WriteLine("5 - Year 5")
    Console.WriteLine("6 - Year 6")

    Console.WriteLine()

    Dim testyear As Integer = Console.ReadLine()

    Select Case testyear

        Case 1
        Case 2
        Case 3
        Case 4

    End Select

    Console.WriteLine("Please enter 10 of your selected words, defenitions and selected amount minor errors to be featured in the following test")

    FileOpen(5, "F:\Computing\Spelling Bee\testtests.csv", OpenMode.Append)

    Console.Clear()

    Do

        counter = counter + 1
        Console.Write("Word: ")
        word(counter) = Console.ReadLine
        Console.Write("Defenition: ")
        def(counter) = Console.ReadLine

        Console.WriteLine("Type in a max of 5 minor errors")

        Console.Write("Minor error 1: ")
        minorerror1(counter) = Console.ReadLine
        Console.Write("Minor error 2: ")
        minorerror2(counter) = Console.ReadLine
        Console.Write("Minor error 3: ")
        minorerror3(counter) = Console.ReadLine
        Console.Write("Minor error 4: ")
        minorerror4(counter) = Console.ReadLine
        Console.Write("Minor error 5: ")
        minorerror5(counter) = Console.ReadLine

    Loop Until counter = 9
    Console.Clear()

    Console.WriteLine("Are you sure you want to save this test? (y/n) ")
    decision = Console.ReadLine
    If decision = "y" Or decision = "Y" Then
        For counter As Integer = 0 To 9
            fullline = testyear & "," & word(counter) & "," & def(counter) & "," & minorerror1(counter) & "," & minorerror2(counter) & "," & minorerror3(counter) & "," & minorerror4(counter) & "," & minorerror5(counter)
            PrintLine(5, fullline)
            Console.WriteLine("Word: " & (word(counter.ToString)) & " Defenition: " & (def(counter.ToString)) & " Minor error 1: " & (minorerror1(counter.ToString)) & " Minor error 2: " & (minorerror2(counter.ToString)) & " Minor error 3: " & (minorerror3(counter.ToString)) & " Minor error 4: " & (minorerror4(counter.ToString)) & " Minor error 5: " & (minorerror5(counter.ToString)))
        Next
        FileClose(5)
        Console.Clear()
        staffmenu()
    ElseIf decision = "n" Or decision = "N" Then
        addtest()

    End If

End Sub


texts:
I have the following backbone function to read a JSON schema and draw the tree structure (as in the screenshot below). I want to make sure if checking against the type as object/array is alright or if there is a better way to do it.

traverseJSONSchema: function (root, rootName, level, rank, resultPane) {
    var height = this.nodeHeight,
            width = this.containerWidth,
            margin = width / 6,
            x = 0,
            overhead = rank * margin,
            y = level * height;
    var tempParent = resultPane.append("g").attr("class", "nested-group");
    if (root.type === "object") {
        if (rootName !== "") {
            var nodeText = rootName + ":" + root.type;
            var node = new DataMapper.Models.Node({parent: tempParent, text: nodeText, x: x, y: y, type: this.get('type'), category: "object", height: height, width: width});
            node.drawContainerNode(overhead); //leave overhead space and draw text
            rank++;
            level++;
        }
        var nestedParent = tempParent.append("g").attr("class", "nested-group");
        var keys = root.properties; //select PROPERTIES
        for (var i = 0; i < Object.keys(keys).length; i++) {   //traverse through each PROPERTY of the object
            var keyName = Object.keys(keys)[i];
            var key = keys[keyName];
            level = this.traverseJSONSchema(key, keyName, level, rank, tempParent);
        }
    } else if (root.type === "array") {
        var keys = root.items; //select ITEMS
        if (rootName !== "") {
            var nodeText = rootName + ":" + root.type + "[" + keys.type + "]";
            var node = new DataMapper.Models.Node({parent: tempParent, text: nodeText, x: x, y: y, type: this.get('type'), category: "array", height: height, width: width});
            node.drawContainerNode(overhead);
            rank++;
            level++;
        }
        level = this.traverseJSONSchema(keys, "", level, rank, tempParent); //recurse through the items of array
    } else if (["string", "integer", "number", "boolean"].indexOf(root.type) > -1) {    //when the type is a primitive
        tempParent.classed("nested-group", false);
        if (rootName !== "") {
            var nodeText = rootName + ":" + root.type;
            var node = new DataMapper.Models.Node({parent: tempParent, text: nodeText, x: x, y: y, type: this.get('type'), category: root.type, height: height, width: width});
            node.drawContainerNode(overhead);
            rank++;
            level++;
        }
    }
  return level;
}


texts:
My main goal is to perform the conversion on a list of strings. Is this a sensible approach or should I refactor?

Please note that I cannot use Boost in my work.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

char fix_delim(char ch) {
    return ch == '\\' ? '/' : ch;
}

std::string& fix_str(std::string& str) {
   std::transform(str.begin(), str.end(), str.begin(), fix_delim);
   return str;
}

int main() {
   std::list<std::string> files;
   files.push_back("folder\\file1");
   files.push_back("folder\\file2");

   //simple example of fix_delim
   std::string one("folder\\file1");
   std::transform(one.begin(), one.end(), one.begin(), fix_delim);

   //Is this a good way to solve this problem of replacing all instances of \ with / in a list of strings?
   std::transform(files.begin(), files.end(), files.begin(), fix_str);

   return 0;
}


texts: "When to take medicine" CodeChef Challenge MEDIC

texts:
I just submitted this code to solve the "When to take medicine" challenge on CodeChef:

#include <iostream>
#include <string>
#include <sstream>

int countDays(int dd, int subtract)
{
    return ((subtract - dd) / 2) + 1;
}

int main()
{
    int t {0};
    std::cin >> t;
    std::cin.ignore();
    while (t--)
    {
        std::string date {};
        std::getline(std::cin, date);
        std::stringstream ss {date};
        int yy {0}, mm {0}, dd {0};
        std::string temp {};
        std::getline(ss, temp, ':');
        yy = std::stoi(temp);
        std::getline(ss, temp, ':');
        mm = std::stoi(temp);
        std::getline(ss, temp, ':');
        dd = std::stoi(temp);
        int subtract {0};
        bool leap {false};
        if (yy % 4 == 0 && (!(yy % 100 == 0) || yy % 400 == 0))
        leap = true;
        switch (mm)
        {
        case 2:
            if (leap)
                subtract = 29;
            else
                subtract = 59;
                break;
        case 4: case 6: case 9: case 11:
            subtract = 61;
        break;
        default:
            subtract = 31;
        }
        std::cout << countDays(dd, subtract) <<'\n';
    }
}

In short, it is a program to tell how many days a guy has took his pill correctly, considering that he has to take a pill every 2 days and only takes it in odd or even days, depending on the day he started to take the pill. We provide a number of test cases in the first line and then we provide a date in a single line in the format yyyy:mm:dd. Check the link above if you're interested in reading the whole problem.

The thing is that I am not really satisfied with the way I am parsing the string separated by the char :

I also want to mention that I want to stay away from any C code like the scanf() function. It would make things a lot easier, but I don't want to use C in C++.

So, how could I redesign my string parse code to make it look nicer? I am just a newbie with C++ so all feedback / criticism is greatly appreciated.


texts:
I have a Windows-service and this service will connect to an ftp server and do download, upload, and rename operations.

My service runs every 30 seconds, so the ftp server will be busy during these operations.

My question is: is my code useful for this job? Because my download/upload/rename functions open a webrequest each process? I use FtpWebRequest and FtpWebResponse

I write only the download functions, the other functions are similar.

Download function:

    public Result Download(string localPath,string remotePath,string fileName)
    {
        Result _result = new Result();
        FtpWebRequest requestFileDownload = null;
        FtpWebResponse responseFileDownload = null;

        try
        {

            //
            requestFileDownload =
                (FtpWebRequest)WebRequest.Create(remotePath + fileName);
            //
            requestFileDownload.Credentials =
                new NetworkCredential(this.Username, this.Password);
            //
            requestFileDownload.Method =
                WebRequestMethods.Ftp.DownloadFile;

            responseFileDownload =
                (FtpWebResponse)requestFileDownload.GetResponse();

            using (Stream responseStream = responseFileDownload.GetResponseStream())
            {
                FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create);

                int Length = 2048;
                Byte[] buffer = new Byte[Length];

               int bytesRead;
               while((bytesRead = responseStream.Read(buffer, 0, Length)) > 0)
               {
                  writeStream.Write(buffer, 0, bytesRead);
               }

                writeStream.Close();

            }

            return _result;

        }
        catch (Exception x)
        {
            _result.Error = true;
            _result.ErrorMessage = x.StackTrace;
            _result.ErrorFileName = fileName;
            _result.ErrorFilePath = remotePath + fileName;

            return _result;
        }
        finally
        {
            requestFileDownload = null;
            responseFileDownload = null;

        }

    }

    public struct Result
    {
        public bool Error;
        public string ErrorMessage;
        public string ErrorFileName;
        public string ErrorFilePath;
        public List<string> Files;
    }


texts: Hackerrank "Hash Tables: Ransom Note" Javascript Solution

texts:
Here is the original problem,
and here's my solution:

function main() {
    var m_temp = readLine().split(' ');
    var m = parseInt(m_temp[0]);
    var n = parseInt(m_temp[1]);
    magazine = readLine().split(' ');
    ransom = readLine().split(' ');

    var freqs = {}
    for (var i = 0; i < m; i++){
      freqs[magazine[i]] = (freqs[magazine[i]] || 0) + 1;
    }

    var result = "Yes"
    for (var j = 0; j < n; j++){
      if (freqs[ransom[j]] && freqs[ransom[j]] > 0){
          freqs[ransom[j]] -= 1;
      } else {
          result = "No"
          break;
      }
    }

    console.log(result)
}

I wonder if there's a more efficient solution than this? Thanks! I understand forEach could be used for code brevity, but I'm just using for loop for the extra performance benefit (https://coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-instead)


texts: PHP function to extract numbers from the list whose squares are exceed some threshold

texts:
This is my naive approach:

$sample1 = [3, -20, 1, -19, -4, 6, 77, -1, 0, 6];
$sample3 = [4, 5, -7, 0, 2, 44, -3, -5, 66, -7];
$sample4 = [4, 25, 1, 6, 9, 5, 999, 4, 43, 2];

$sample2 = [];
for ($i = 0; $i < mt_rand(10, 30); $i++) {
  $sample2[] = mt_rand(-1000, 1000);
}

extractNumbersThatSquaresAreGreaterThan($sample1);
extractNumbersThatSquaresAreGreaterThan($sample2);
extractNumbersThatSquaresAreGreaterThan($sample3);
extractNumbersThatSquaresAreGreaterThan($sample4);

var_dump($sample1);
//var_dump($sample2);
var_dump($sample3);
var_dump($sample4);

function extractNumbersThatSquaresAreGreaterThan(&$list, $boundary = 26) {
  foreach ($list as $key => $value) {
    if (pow($value, 2) <= $boundary) {
      unset($list[$key]);
    }
  }
}

Any hints for optimization? Is it possible, I've tried few, but in the end it was more complicated (and slower) solution


texts:
I got thousands of files with a specific file extension in thousands of sub folders. Now, what is the fastest way to search with a pattern? I tried the method DirectoryInfo.GetFiles(rootfolder) (~8 minutes) and a recursive custom method (~5 minutes).

 private void WalkDirectoryTree(DirectoryInfo dr, string searchname)
    {
        System.IO.FileInfo[] files = null;
        System.IO.DirectoryInfo[] subDirs = null;
        try
        {
            files = dr.GetFiles(searchname + ".*");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        if (files != null)
        {
            foreach (FileInfo fi in files)
            {
                allFiles.Add(fi);
            }
            subDirs = dr.GetDirectories();

            foreach (DirectoryInfo di in subDirs)
            {
                WalkDirectoryTree(di, searchname);
            }
        }
    }

Is there any faster way to do it?


texts:
In order to solve a equation where the left hand side appears under an integral on the right hand side:

$$
B(p^2) = C\int_0^{p^2}f_1\left(B(q^2),q^2\right)\mathrm{d}q^2 + C\int_{p^2}^{\Lambda^2} f_2\left(B(q^2),q^2\right)\mathrm{d}q^2
$$

I have written the following code to do solve this equation iteratively:

import numpy as np
import time

def solver(alpha = 2.):

    L2 = 1 # UV Cut-off
    N = 1000 # Number of grid points
    maxIter = 100 # Maximum no. of iterations

    # The grid on which the function is evaluated
    p2grid = np.logspace(-10, 0, N, base=10)
    dq = np.array([0] + [p2grid[i+1]-p2grid[i] for i in range(len(p2grid)-1)])

    Bgrid = np.ones(N)
    Bgrid_new = np.empty(N) # Buffer variable for new values of B

    C = alpha / (4*np.pi)

    for j in range(maxIter):

        for i, p2 in enumerate(p2grid):
            # If lower and upper limit of an integral are the same, set to 0
            if i > 0:
                n = i + 1
                int1 = np.add.reduce((p2grid[0:n] * 3*Bgrid[0:n] /\
                        (p2 * (p2grid[0:n] + Bgrid[0:n]**2))) * dq[0:n])
            else:
                int1 = 0

            if i < N - 1:
                int2 = np.add.reduce((3*Bgrid[i:] /
                            (p2grid[i:] + Bgrid[i:]**2)) * dq[i:])
            else:
                int2 = 0
            # Write new values to buffer variable
            Bgrid_new[i] = C * (int1 + int2)

        # Calculate relative error (take the maximum)
        maxError = np.max(np.abs((Bgrid - Bgrid_new)/Bgrid_new))
        # Copy values from buffer to working variable
        Bgrid = np.copy(Bgrid_new)
        # If the change in the last iteration was small enough, stop
        if (maxError < 10**-4):
            break

    print "Finished in", j+1, "iterations, relative error:", maxError
    return p2grid, Bgrid/np.sqrt(L2)

t0 = time.clock()
p2grid, Bgrid = solver()
print "Time:", time.clock() - t0, " seconds"

I am wondering if there a speedups possible:

I am using np.add.reduce instead of np.sum, which is about 0.2 secs faster on my system
I tried to move the code where int1 and int2 are calculated to a separate function, no improvement here
Using [... for enumerate(p2grid)] instead of the for-loop seems not be faster either
The profiler says almost all time is still spent in the reduce method.

I can't see how this code can be optimized further (as most time is spent in a function of the NumPy lib), but I can't believe I wrote the most efficient code either.

If there are no optimizations possible at code level, is there anything else I should try or look into, like different interpreters or something like that?


texts: Install, configure, and maintain content for Ubuntu webserver

texts:
I made a script for my Ubuntu server(s) running on Google Cloud Platform. The idea behind it is I can create a new instance and paste this script in Google Cloud so it runs it on the new instance and every time it reboots. The script works, so no problem there.

The idea is that it installs all the required software to run my website the first time it boots up and then clones my git repository to /var/www/html/. Every other time it boots it only updates the software and then pulls the changes from the git repository.

My questions:

From what I understand, it's not very wise to put your git password in the startup script but I know no other way to automate this fully. Can this be done in another way while keeping it fully automated?
Cloning the git repository gave an error about the folder not being empty so I just deleted it upfront. It works now but I am not sure if that's the way to go ...

Here is my startup script:

file="/var/www/check.txt"

if [ -e $file ]
then
sudo apt-get update
sudo git -C /var/www/html pull https://username:password@bitbucket.org/username/repository.git
else
sudo apt-get update
sudo apt-get install apache2 libapache2-mod-php5 php5-mcrypt php5-mysql git -y
sudo cat <<EOF > /etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
        DirectoryIndex index.php index.cgi index.pl index.html index.xhtml index.htm
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF
sudo rm -rf /var/www/html
sudo git clone https://username:password@bitbucket.org/username/repository.git /var/www/html/ /var/www/html/
sudo cat <<EOF > /var/www/check.txt
aanwezig!
EOF
fi


texts: OpenGL fragment shader optimization questions

texts:
My (simple) game engine has one big fragment shader for the whole scene.
Right now, with multiple objects, collision detection and bloom post-processing (4 linear passes) I get frame times of ~18ms at 1080p on my AMD RX550 (2GB) - which is quite okay for me.

But I think that I can squeeze more fps out of my setup.
Since increasing the window size dramatically influences the frame times, I figure that the issue might be the fragment shader.

It works a little bit like this:

main()
{
    outputcolor = objectbasecolor; // from uniform
    if(switchForTextureDiffuse > 0) // >0 means "use a texture"
    {
        outputcolor *= texture(uniformTexture, vTextureCoords);
    }

    // the same goes for normal map, specular map and emissive map
    // with the needed calculations only being done if a switch
    // (i.e. switchForNormalMapping > 0) is set to 1.

    for(int i = 0; i < lightcount; i++) // lightcount is a uniform as well
    {
        // do light calculations (dot product, use light color, calculate falloff, etc.)
        // and add the illumination to the color output
    }
}

Now, I know that if/else is no good idea, especially in a fragment shader. But I do not want to rebuild this shader completely from scratch only to find out that the ifs/elses did no harm to my frame times at all.

From your experiences, what really makes the frame times be better?

Use texture compression (like DXT1, DXT5) instead of just uncompressed bitmaps?
Get rid of all ifs and elses by creating a lot of different shaders (like one for only diffuse and normal maps and another shader for using diffuse, normal and specular maps?
Reduce the number of frame buffers for bloom effect (right now I have the normal framebuffer, one for vertical blur and one for horizontal blur) by creating more texture attachments for only one framebuffer?

Point 2 would be a really great heap of work, so I need to be sure that this really has an effect on my frame times.
Also, I would have to switch GL programs a lot, because not all of my models have normal or specular maps. And I read that switching render programs also takes a lot of time.

Cheers and thanks for your inputs!

P.S.: I know deferred lighting would also be a huge performance increase if there are many light sources in the scene, but the number of lights will not be > 3.


texts: Find all nodes in tree, without a sibling

texts:
Find all nodes of trees, without siblings.

This question is attributed to GeeksForGeeks.

I'm looking for code reviews, optimizations and best practices.

  public class PrintNodesWithoutSiblings<T> {

        private TreeNode<T> root;

        public PrintNodesWithoutSiblings(List<T> items) {
            create(items);
        }

        private void create (List<T> items) {
            root = new TreeNode<T>(items.get(0));

            final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
            queue.add(root);

            final int half = items.size() / 2;

            for (int i = 0; i < half; i++) {
                if (items.get(i) != null) {
                    final TreeNode<T> current = queue.poll();
                    int left = 2 * i + 1;
                    int right = 2 * i + 2;

                    if (items.get(left) != null) {
                        current.left = new TreeNode<T>(items.get(left));
                        queue.add(current.left);
                    }
                    if (right < items.size() && items.get(right) != null) {
                        current.right = new TreeNode<T>(items.get(right));
                        queue.add(current.right);
                    }
                }
            }
        }

        private static class TreeNode<T> {
            private TreeNode<T> left;
            private T item;
            private TreeNode<T> right;

            TreeNode(T item) {
                this.item = item;
            }
        }

        public List<T> nonSiblingNodes() {
            if (root == null) {
                throw new IllegalStateException("Empty tree. Tree cannot be empty.");
            }

            final List<T> list = new ArrayList<T>();
            findNonSiblingNodes(root, list);
            return list;
        }

        private void findNonSiblingNodes(TreeNode<T> node, List<T> list) {
            if (node == null) {
                return;
            }

            if (node.left != null && node.right != null) {
                findNonSiblingNodes(node.left, list);
                findNonSiblingNodes(node.right, list);
            } else if (node.left != null) {
                list.add(node.left.item);
                findNonSiblingNodes(node.left, list);
            } else if (node.right != null) {
                list.add(node.right.item);
                findNonSiblingNodes(node.right, list);
            }
        }
    }

    public class PrintNodesWithoutSiblingTest {

        @Test
        public void test1() {
            PrintNodesWithoutSiblings<Integer> ps1 = new PrintNodesWithoutSiblings<Integer>(Arrays.asList(1, 2, 3, 4, null, 6, null));
            assertTrue(Arrays.asList(4, 6).equals(ps1.nonSiblingNodes()));
        }

        @Test
        public void test2() {
            PrintNodesWithoutSiblings<Integer> ps2 = new PrintNodesWithoutSiblings<Integer>(Arrays.asList(1, 2, null, 4, null, null, null));
            assertTrue(Arrays.asList(2, 4).equals(ps2.nonSiblingNodes()));
        }
    }


texts: Reimplementing enumerate() to produce a sequence or iterator

texts:
Apparently it is possible to implement enumerate so it produces a sequence when given a sequence, and produces an iterable otherwise. Sequence can be safely reversed. This works by replacing the builtin function. Other similar functions could be made this way, too.

class EnumeratedSequence:
    def __init__(self, items):
        self.items = items

    def __getitem__(self, index):
        return (index,self.items[index])

    def __len__(self):
        return len(self.items)

def enumerate(items):
    if hasattr(items, '__getitem__'):
        print 'Sequence detected'
        return EnumeratedSequence(items)
    else:
        print 'Iterator detected'
        return __builtin__.enumerate(items)

print list(reversed(enumerate('abcdef')))
print list(enumerate(reversed('abcdef')))

Which outputs:

Sequence detected
[(5, 'f'), (4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')]
Iterator detected
[(0, 'f'), (1, 'e'), (2, 'd'), (3, 'c'), (4, 'b'), (5, 'a')]

This was a solution to a problem of reversed(enumerate(...)) failing.


texts: Script for showing/hiding on click - how can I write this code cleaner?

texts:
I have this simple code, but it's messy - how do I do it cleaner?
It works like this: If you click on the menu-btn1 the div shows up, and hide others, but if you click on menu-btn1 again it will hide as well.
let coll = document.getElementsByClassName('collection');
let dis = document.getElementsByClassName('display');
let drop = document.getElementsByClassName('drop');

document.getElementById("menu-btn1").addEventListener("click", function() {
  if(coll[0].style.display == 'none') {
    coll[0].style.display = 'block';
    dis[0].style.display = 'none';
    drop[0].style.display = 'none';
  } else {
    coll[0].style.display = 'none';
  }
});

    collection

There is nothing important in css really, only the grid positioning.


texts: Make code more memory efficient, or shorter

texts:
//rename files
    if(!empty($_FILES[$desktop_fieldname_1280x800]['name'])){
                file_exists($desktop_filename_1280x800 = mb_strtolower($desktop_dir_1280x800 . 'wall_desktop_1280x800_' .
                $_FILES[$desktop_fieldname_1280x800]['name']));
            }
    if(!empty($_FILES[$desktop_fieldname_1366x768]['name'])){
                file_exists($desktop_filename_1366x768 = mb_strtolower($desktop_dir_1366x768 . 'wall_desktop_1366x768_' .
                $_FILES[$desktop_fieldname_1366x768]['name']));
            }
    if(!empty($_FILES[$desktop_fieldname_1920x1080]['name'])){
                file_exists($desktop_filename_1920x1080 = mb_strtolower($desktop_dir_1920x1080 . 'wall_desktop_1920x1080_' .
                $_FILES[$desktop_fieldname_1920x1080]['name']));
            }

With the above code, basically what I'm doing is renaming the files properly + consistently. What my code seems to be bit redundant to me, I think this can be done with some kind of loop or arrays, but I'm a newbie and not sure how it will be. So would like to ask your help to make this code more memory efficient, or shorten the code in some way.


texts:
I have wrote the following algorithm to print out the Nth twin prime numbers:

def isprime(x):
    for i in range(2, (x + 2) / 2):
        if x % i == 0:
            return False
    return True

inputIndex = int(raw_input())
tempIndex = 1
n=2
while True:
    if isprime(n) & isprime(n + 2):
        if inputIndex == tempIndex:
            print "%d,%d" % (n,n+2)
            break
        else:
            tempIndex += 1
    n += 1

I am looking to optimize the speed and cannot import libraries like math and so or store a list of primes.


texts: Validating CSV headers against an expected list

texts:
My application (legacy code) reads a CSV input file with an expected format with regards to Column names as follows:

1st column - Should say "Marker"
2nd column - Should say "Category"
3rd column ... to ... N columns - These are the actual data columns. Should have number starting with 1 and increasing by 1 going right.

In other words, 3rd column should have "1", 4th column header should have "2".

Example CSV file with 10 data columns (total of 12 columns in file):

Marker,Category,1,2,3,4,5,6,7,8,9,10
TODD,Sea,0.001062344,0.001931534,0.002334951,0.002738369,0.003141786,0.003545203,0.004788256,0.005917489,0.007025671,0.008078547
JAMIE,Fork,0.00133847,0.002433581,0.002941854,0.003450128,0.003958402,0.004466676,0.006032825,0.007455569,0.00885179,0.010178331
LENNY,PITCH,0.001686365,0.003066119,0.003706504,0.004346889,0.004987274,0.005627659,0.007600883,0.009393428,0.011152557,0.012823893

My code that does this validation (and it works) is as follows:

fileStream = new FileStream(delimitedFileName, FileMode.Open,
   FileAccess.Read, FileShare.Read);
csvStreamReader = new StreamReader(fileStream);
string headerLine = csvStreamReader.ReadLine();
var headers = headerLine.Split(delimiter, '\\');

if (!string.Equals(headers[0], "Marker", StringComparison.InvariantCultureIgnoreCase)
|| (!string.Equals(headers[1], "Category", StringComparison.InvariantCultureIgnoreCase)))
{
    throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv).");
}

for (int i = 2; i < headers.Length; i++)
{
    if (!string.Equals(headers[i], (i-1).ToString(),
        StringComparison.InvariantCultureIgnoreCase))
    {
    throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv).");
    }
}

I want to avoid doing it like this, in 2 steps.

Is there a way to do some sort of delegate or Action to do the 2nd section, i.e. validate that the data column names are correct, for a variable number of data columns?

I want to avoid doing it in 2 separate sections as shown above, and have duplicate throw new Exception code for essentially the same exception.


texts: Generating a dynamically expandable form with multiple similar categories

texts:
Overview:

Here's the look of my form.

In this example, I have a form that allows dynamically adding fields in each category. Like, I can add multiple attractions like 5 attractions, same goes for Featured artists, so basically I can add an infinite set of data per category in this form.

So after submitting, all those fields (dynamic fields) are sent in array format. It checks if the category have at least one file uploaded. The function here is already correct, it gives the output.

if (count(array_filter($_FILES['attraction']['name'])) > 0) {

    $attraction_status = true;

    $attraction = $_FILES['attraction'];
    $attraction['tmp_name']['image'] = true;
    $attraction_field = Field::incrementFieldComparison($attraction['tmp_name'], $request->post('attraction_name'), $request->post('attraction_description'));

    $attraction_name        = implode('|', $attraction_field->field_1);
    $attraction_description = implode('|', $attraction_field->field_2);
    $attraction_image       = implode('|', $attraction_field->reference);
}

The problem is, I have like 7 categories in this form. So basically, I have this same chunk of code for seven times with different type of category.

if (count(array_filter($_FILES['featured_artist']['name'])) > 0) {

    $featured_artist_status= true;

    $featured_artist= $_FILES['featured_artist'];
    $featured_artist['tmp_name']['image'] = true;
    $featured_artist_field= Field::incrementFieldComparison($attraction['tmp_name'], $request->post('featured_artist_name'), $request->post('featured_artist_description'));

    $featured_artist_name = implode('|', $featured_artist_field->field_1);
    $featured_artist_description = implode('|', $featured_artist_field->field_2);
    $featured_artist_image = implode('|', $featured_artist_field->reference);
}

Is this fine, as long as I'm getting the right output? I'm concerned about the repetition of code. Is there any way to improve this code if this is a bad practice of coding?


texts:
I am not very familiar with JavaScript and I'am a little confused with the object oriented peculiarities of it. I am trying to create a Caesar shift using the concepts of objects, methods and properties in JavaScript. I am using an HTML form to take input from user and OnClick return the encoded cipher text to user. This is what I have. I'm pretty much sure about my logic but I guess my object creation and method calls fall through. Am I doing it right?

<form>
Enter Plaintext : <input type = "text" name = "plaintext" id = "plaintext">
Enter Shift:      <input type = "text" name = "shift" id = "shift">
 --How do I get the input from here and create my caesar object and pass the constructor the shift from this text box?
<input type="button" value="Encode" onclick ="encode()"> --How do I call the encode() method with input from the plaintext text box?
</form>


texts:
Given an array and a value, find all the triplets in the array whose sum is equal to the given value. For example, if the given array is {12, 3, 4, 1, 6, 9} and the given sum is 24, then this is one triplet (12, 3 and 9) which contributes to the total sum of 24.
Solution for given example:
6, 9, 9
6, 6, 12
3, 9, 12
Conditions:

The ordering of the numbers in the solution does not matter.

Duplicate triplet is not allowed.

A number is not allowed to be used multiple times.

This question was asked here.
Here is my code which addresses all the issues. One concern is the code looks a little muddy which I want to avoid in the production grade code. Any constructive feedback is appreciated.
Runtime: O(n2)
GitHub
public class ThreeSum {

    static class Triplet {
        final List<Integer> triplets;

        public Triplet(int x, int y, int z) {
            triplets = Arrays.asList(x, y, z);
            Collections.sort(triplets);
        }

        @Override
        public int hashCode() {
            return Objects.hash(triplets.get(0), triplets.get(1), triplets.get(2));
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof Triplet) {

                Triplet other = (Triplet) o;
                return other.triplets.get(0) == this.triplets.get(0) &&
                        other.triplets.get(1) == this.triplets.get(1) &&
                        other.triplets.get(2) == this.triplets.get(2);
            }

            return false;
        }

        @Override
        public String toString() {
            return String.format("(%d, %d, %d)", triplets.get(0), triplets.get(1), triplets.get(2));
        }
    }

    public static Set<Triplet> findTriplets(int numbers[], int targetSum) {
        Set<Triplet> triplets = new HashSet<>();

        // insert all pairs in the look up table
        Map<Integer, int[]> lookup = new HashMap<>();
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                int total = numbers[i] + numbers[j];
                lookup.put(total, new int[]{i, j});
            }
        }

        // look for the complement, if found viola! here you go with the triplet
        for (int currentIndex = 0; currentIndex < numbers.length; currentIndex++) {
            int complement = targetSum - numbers[currentIndex];

            if (lookup.containsKey(complement)) {
                int indexes[] = lookup.get(complement);

                if (currentIndex != indexes[0] && currentIndex != indexes[1]) {
                    int x = numbers[indexes[0]], y = numbers[indexes[1]];
                    triplets.add(new Triplet(x, y, numbers[currentIndex]));
                }
            }
        }

        return triplets;
    }
}


texts: Create release package from git tag with Powershell

texts:
In my deployment I need to generate a zip file from a git repo. I have the basic work done with how to pull the latest tag and create the zip file. I ended wanting to update the files that are pulled down to have the last modified of the last commit instead of when I just checked them out.

# Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
param(
    [string] $tag = "",
    [string] $gitURI = "https://github.com/jquery/jquery.git",
    [string] $checkForNewTagsOnly = "Y" #if yes then it will exit if the folder already exists
)
$Currentlocation = "C:\_Builds"
New-Item -ItemType Directory -Force -Path $Currentlocation

Set-Location $Currentlocation
if( $checkForNewTagsOnly -eq "Y"){
    git clone $gitURI --depth 1 master --single-branch
    Set-Location $Currentlocation\master
    git fetch --tags
    $tag = git describe --tags $(git rev-list --tags --max-count=1)
    $tag = $tag|split-path -leaf
}

if([string]::IsNullOrWhiteSpace($tag)){($tag = Read-Host "Enter the tag")}

if( $checkForNewTagsOnly -eq "Y" -and (Test-path $Currentlocation\$tag)){
    Write-Host "$tag already exists, nothing to do"
    exit
}

New-Item -ItemType Directory -Force -Path $Currentlocation
If (Test-path $Currentlocation\$tag) {Remove-item $Currentlocation\$tag}

Set-Location $Currentlocation
git clone $gitURI --recurse-submodules --single-branch --shallow-submodules --branch $tag $tag
Set-Location $Currentlocation\$tag

Write-Host "$tag checked out, running clean up on $Currentlocation"
Get-ChildItem -filter *test* -Directory -recurse -force | remove-item -force -recurse

$ToDelete = "*.gitignore","*.gitattributes","*.gitmodules"
FOREACH ($Item IN $ToDelete) {
    FOREACH ($File IN (Get-ChildItem -recurse | Where-Object {$_.name -like "$Item"})) {
        $FullName = $File.FullName
        Write-Host "Deleting $FullName" -ForegroundColor Green
        Remove-Item $File.FullName
    }
}

Write-Host "fixing the file dates, since git doesn't keep the dates, let's update it the last commit date"
FOREACH ($File IN (Get-ChildItem -recurse)) {
    $FullName = $File.FullName
    $lastModifiedDate = git log -1 --date=short --format=%cd "$FullName"
    $File.LastWriteTime = $lastModifiedDate
    $File.CreationTime = $lastModifiedDate
}

Get-ChildItem -Include .git -recurse -force | remove-item -force -recurse

Write-Host "$tag cleaned, creating zip file"
If (Test-path $Currentlocation\$tag.zip) {Remove-item $Currentlocation\$tag.zip}

Compress-Archive -Path $Currentlocation\$tag -DestinationPath $Currentlocation\$tag.zip

Write-Host "Good Job, the package is created $tag.zip"


texts: Pascal Triangle calculation with BigIntegers

texts:
On a well known programming challenges website(CW) there is a Kyu2 eggs height problem that can be solved utilizing a variation of Pascals Triangles properties.

The problem asks to solve f(n, m) and the solution is the sum of Pascal's Triangle row m up to cell/column n, so the sum of
f(i) = (m + 1 - i) * f(i-1) / i for i = 1 to n.

On the second variation of that problem (Kyu1) it is asked that you solve the same challenge linearly with the f(n, m) output being orders of magnitude bigger.

I've tried to solve the challenge with the code below, but it exceed the allowed time constrains to solve the challenge.

using System.Numerics;
public class EggChallenge
{
    private static BigInteger mo = new BigInteger(998244353);
    public static BigInteger Height(BigInteger n, BigInteger m)
    {
        return n == 0 || m == 0 ? 0 : BigInteger.Remainder(SumHeight(n+1, m), mo);
    }

    public static BigInteger SumHeight(BigInteger n, BigInteger m)
    {
        BigInteger BigInt = new BigInteger(1);
        BigInteger BigIntegerSum = new BigInteger(0);

        for(int i = 1; i < n; i++)
        {
            BigInt = BigInteger.Divide(BigInteger.Multiply(m + 1 - i, BigInt), (BigInteger)i);
            BigIntegerSum = BigInteger.Add(BigIntegerSum, BigInt);
        }

        return BigIntegerSum;
    }
}

The above code solves test cases such as:

EggChallenge.Height(10000,100000);
EggChallenge.Height(80000,100000);
EggChallenge.Height(3000,BigInteger.Pow(2,200));

But it's not able to beat the actual challenge time constrains.

I don't think the algorithm is what to improve has it seems to run at O(n), but I could be very wrong.

So far I've tried memorization in a BigInteger[] to release the cost of the constant addition, but it performed worst then the current code.

My question is how would this code be improved performance wise, which techniques could be applied to improve code performance?, and if possible why are those the best to apply?

initial challenge details
linear challenge details


texts:
I am trying to find the best way(/most efficent way) to setup my console program's menu. The way I have it set up is that I have a Menu class and then I use a menu pointer called currentMenu and I just change where it is pointing to. it runs fairly well so far but I'd like to know what I could do to improve it

So Far it is seperated into 3 files(main.cpp,menu.h and menu.cpp)
Full Code is here: https://repl.it/@SamuelHabtu/StudyBuddy-CLI

Menu.h:

#ifndef MENU_H
#define MENU_H
#include <iostream>
#include <string>
class menu
{
public:
  std::string name;
  menu *prev;
  menu *right;
  menu *down;
  menu *up;
  void displayMenu();
};
#endif

Menu.cpp:

#include "menu.h"
void menu::displayMenu()
{
  std::string userInput;
  std::cout<<name<<" menu:\n";
  if(prev != 0)
  {
    std::cout<<"0:"<<prev->name<<" menu\n";
  }
  if(up != 0)
  {
    std::cout<<"1:"<<up->name<<" menu\n";
  }
  if(down != 0)
  {
    std::cout<<"2:"<<down->name<<" menu\n";
  }
  if(right != 0)
  {
    std::cout<<"3:"<<right->name<<" menu\n";
  }
}

Here is the function that I use to "fill" each menu

void buildMenu(menu *menu,std::string name,class menu *prev,class menu* up,class menu* down,class menu* right)
{
  menu->name = name;
  menu->prev = prev;
  menu->right = right;
  menu->down = down;
  menu->up = up;
}

This is How I am handling the Userinputs:

bool valid(std::string userInput,menu *currentMenu)
{
  if(userInput != "1" && userInput != "2" && userInput != "3" && userInput != "0")
  {
    std::cout<<"invalid input \n";
    return false;
  }
  if(userInput == "0" && currentMenu->prev == 0)
  {
    std::cout<<"invalid input \n";
    return false;
  }
  if(userInput == "1" && currentMenu->up == 0)
  {
    std::cout<<"invalid input \n";
    return false;
  }
  if(userInput == "2" && currentMenu->down == 0)
  {
    std::cout<<"invalid input \n";
    return false;
  }
  if(userInput == "3" && currentMenu->right == 0)
  {
    std::cout<<"invalid input \n";
    return false;
  }
  return true;
}

mainloop for the menu statemachine:

  while(go)
  {
    currentMenu->displayMenu();
    std::cin>>userInput;
    while(!valid(userInput,currentMenu)|| (userInput.size() > 1))
    {
      std::cin.clear();
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
      std::cin>>userInput;
    }
    switch(userInput[0])
    {
    case '0':
      currentMenu = currentMenu->prev;
      break;
    case '1':
      currentMenu = currentMenu->up;
      break;
    case '2':
      currentMenu = currentMenu->down;
      break;
    case '3':
      currentMenu = currentMenu->right;
    }
  }


texts: Improve this function that compares jQuery versions

texts:
Please help me improve this function that compares the jQuery version currently available (or not) with the one required.

function(need) {
    if (typeof(jQuery) != 'undefined') {
        if (!need) return true;
        var re = /(\d+)\.(\d+)\.(\d+)/,
            cur = re.exec(jQuery.fn.jquery),
            need = re.exec(need);
        return (need[1] <= cur[1] && need[2] <= cur[2] && need[3] <= cur[3]);
    } else return false;
}


texts: Python: keeping track of info across classes by storing a variable to self

texts:
I wrote the following code to test a score-keeping class.  The idea was to keep score of a game such that the score was kept across multiple classes and methods.

I'm looking for any input on being more efficient, more 'pythonic' and/or just better.

import os

class Foo():
    def __init__(self):
        self.stored_end = 0

    def account(self, a, b):
        c = float(a) + b
        print a
        print b
        print c
        self.stored_end = c
        print self.stored_end

    def testy(self, q, v):
        print "\n"
        print " _ " * 10
        z = float(q) + v
        print self.stored_end
        self.stored_end = self.stored_end + z
        print " _ " * 10
        print self.stored_end

class Bar():
    def __init__(self):
        pass

    def zippy(self, a, b):
        print " _ " * 10
        print "this is zippy"
        foo.testy(a, b)

class Baz():
    def __init__(self):
        pass

    def cracky(self, g, m):
        y = g + m
        print " _ " * 10
        print "calling stored_end"
        foo.stored_end = foo.stored_end + y
        print " _ " * 10
        print "this is cracky"
        print "y = %r" % y
        print foo.stored_end

os.system("clear")
foo = Foo()
foo.account(5, 11)
foo.testy(100, 100)
bar = Bar()
bar.zippy(10, 100)
baz = Baz()
baz.cracky(1000, 1)


texts: Creating nodes for linked list in a while loop in C

texts:
I am trying to create nodes for a linked list in a while loop. The code works, but it is not very pretty. How would I get the same results the proper way?

root = malloc(sizeof(struct node)); // Allocates memory for first node
pointer = root; // Set pointer to first node
char buf[MAXBUF]; // Buffer for each line

int size = 1; // Counts nodes.

/* Write to list */
while(fgets(buf, MAXBUF, f) != NULL) // Puts each line in a node through buffer
{
    strncpy(pointer->data, buf, MAXBUF); // Puts line in character array in node
    pointer->next = malloc(sizeof(struct node)); // Allocates memory for new node
    size++; // Increments for each node. Root is 1, so first round in loop is 2
    pointer = pointer->next; // Sets pointer to next node
}
size--; // Removes 1 count for last node
free(pointer); // Frees last allocated node
pointer = NULL;