texts:
I have implemented in C# a stack data structure, without using any existing C#/.NET containers (data structures). I have used TDD technique to implement this requirements, so you can find tests, too. All my tests are passing, so I guess stack is behaving correctly.

I would be very pleased to have a code review for this implementation.

Please do not recommend a generic implementation :-)

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StackDataStructure;

namespace StackTesting
{
    [TestClass]
    public class Tests
    {
        [TestMethod]
        public void TestEmptyStackSize()
        {
            var stack = new Stack();
            Assert.IsTrue(stack.IsEmpty());
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void EmptyStackPopException()
        {
            var stack = new Stack();
            stack.Pop();
        }

        [TestMethod]
        public void PushingAndPoppintItemsToStack()
        {
            var stack = new Stack();
            stack.Push(1);
            Assert.AreEqual(1, stack.Size);
            stack.Push(2);
            Assert.AreEqual(2, stack.Size);
            Assert.AreEqual(2, stack.Pop());
            Assert.AreEqual(1, stack.Size);
            Assert.AreEqual(1, stack.Pop());
            Assert.IsTrue(stack.IsEmpty());
            Assert.IsTrue(stack.Size == 0);
            stack.Push(10);
            Assert.IsTrue(stack.Size == 1);
            Assert.IsTrue(10 == stack.Pop());
            Assert.IsTrue(stack.IsEmpty());
        }
    }
}

using System;

namespace StackDataStructure
{
    internal class Node
    {
        internal int value;
        internal Node underTop;
    }

    public class Stack
    {
        private int size;
        private Node top;

        public int Size { get { return size; } }

        public bool IsEmpty()
        {
            return top == null;
        }

        public int Pop()
        {
            if (IsEmpty())
                throw new InvalidOperationException("Stack is empty");

            int value = top.value;
            top = top.underTop;
            size--;
            return value;
        }

        public void Push(int v)
        {
            top = new Node{
                value = v,
                underTop = top
            };
            size++;
        }
    }
}


texts: Codility's stonewall 100% solution - different paths such as if,else if,etc, do the same thing

texts:
Here is the task description for the codility's stonewall problem. I would like to get a feedback on my code, and I specify at the bottom what the title states. (I had to make the figure by hand, because I couldn't paste the site's one for some reason, but it can be seen here, if mine doesn't look right)

  Task description

  You are going to build a stone wall. The wall should
  be straight and N meters long, and its thickness should be constant;
  however, it should have different heights in different places. The
  height of the wall is specified by an array H of N positive integers.
  H[I] is the height of the wall from I to I+1 meters to the right of
  its left end. In particular, H[0] is the height of the wall's left end
  and H[N−1] is the height of the wall's right end.

  The wall should be built of cuboid stone blocks (that is, all sides of
  such blocks are rectangular). Your task is to compute the minimum
  number of blocks needed to build the wall.

  Write a function:

  class Solution { public int solution(int[] H); }

  that, given an array H of N positive integers specifying the height of
  the wall, returns the minimum number of blocks needed to build it.

  For example, given array H containing N = 9 integers:

  H[0] = 8 H[1] = 8    H[2] = 5   H[3] = 7
    H[4] = 9 H[5] = 8    H[6] = 7   H[7] = 4    H[8] = 8
  the function should return 7. The shows one possible arrangement of seven
  blocks.

  Write an efficient algorithm for the following assumptions:

  N is an integer within the range [1..100,000]; each element of array H
  is an integer within the range [1..1,000,000,000].

And here is my 100% O(N) time complexity solution.
As the title says, I find it kinda weird that different paths do the same thing. Should I fix that? if so... how? the logic is correct. And should I care? Thinking in bigger problems, if many paths do the same thing, and requirements change, I should change code in many places, which is not recommended.

using System;
using System.Collections.Generic;
using System.Linq;

class Solution {
    public int solution(int[] H) {
        Stack<int> heightsStack = new Stack<int>();
        int blocksCounter = 0;

        for (int height = 0; height < H.Length; height++)
        {
            if (heightsStack.Count > 0)
            {
                while (heightsStack.Count > 0 && heightsStack.Peek() > H[height])
                {
                    heightsStack.Pop();
                }
                if (heightsStack.Count > 0)
                {
                    if (heightsStack.Peek() < H[height])
                    {
                        blocksCounter++;
                        heightsStack.Push(H[height]);
                    }
                }
                else
                {
                    blocksCounter++;
                    heightsStack.Push(H[height]);
                }
            }
            else
            {
                blocksCounter++;
                heightsStack.Push(H[height]);
            }
        }
        return blocksCounter;
    }
}


texts:
I have a working logon for a WinForms Project. I use the program.cs file to launch the login form. I am not so sure there isn't a better way of implementing this.
Here is my program.cs file:
    using System;
    using System.Windows.Forms;
    using WindowsFormsApp.Presenters;
    using WindowsFormsApp.Views;
    using Autofac;
    using DbContexts;
    using Serilog;

    namespace WindowsFormsApp
    {
        internal static class Program
        {
            public static IContainer Container { get; private set; }
            public static string UserName { get; set; }

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            private static void Main()
            {
                var builder = new ContainerBuilder();

                builder.Register(c => new MyContext());

                Container = builder.Build();

                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .WriteTo.Console()
                    .WriteTo.RollingFile("log-{Date}.txt")
                    .CreateLogger();
                Log.Information("Application Started");

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var loginForm = new LoginForm();
                var results = loginForm.ShowDialog();

                if (results == DialogResult.Cancel)
                    System.Environment.Exit(1);

                while (results != DialogResult.OK)
                {
                    results = loginForm.ShowDialog();
                    if (results == DialogResult.Cancel)
                        System.Environment.Exit(1);
                }

                var mainFormView = new MainFormView();

                mainFormView.Tag = new MainFormPresenter(mainFormView);

                Application.Run(mainFormView);
            }
        }
    }

Any suggestions or comments are welcome.


texts:
I need concurrent HashMap of List as value with following behavior:

count of read/write ops approximately equals
support add/remove values in lists
thread safe iterations over lists

After some research I implemented ConcurrentMapOfList, but I'm not sure in his correctness.

public class ConcurrentMapOfList<Key, ListValue> {
    private final ConcurrentMap<Key, ConcurrentList<ListValue>> values
            = new ConcurrentHashMap<Key, ConcurrentList<ListValue>>();

    public void add(Key key, Value value) {
        List<Value> list = values.get(key);

        if (list == null) {
            final ConcurrentList<Value> newList = new ConcurrentList<Value>();
            final ConcurrentList<Value> oldList = values.putIfAbsent(key, newList);

            if (oldList == null) {
                list = newList;
            } else {
                list = oldList;
            }
        }

        list.add(value);
    }

    public List<ListValue> remove(Key key) {
        return values.remove(key);
    }

    public boolean remove(Key key, ListValue value) {
        final List<ListValue> list = values.get(key);

        if (list == null) {
            return false;
        }

        return list.remove(value);
    }

    public List<ListValue> obtainListCopy(Key key) {
        final ConcurrentList<ListValue> list = values.get(key);

        if (list == null) {
            return Collections.emptyList();
        }

        return list.clone();
    }

    public void removeAll() {
        values.clear();
    }

    private class ConcurrentList<V> extends ArrayList<V> {
        final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        final Lock readLock = lock.readLock();
        final Lock writeLock = lock.writeLock();

        @Override
        public boolean add(V v) {
            writeLock.lock();
            try {
                return super.add(v);
            }finally {
                writeLock.unlock();
            }
        }

        @Override
        public V remove(int index) {
            writeLock.lock();
            try {
                return super.remove(index);
            }finally {
                writeLock.unlock();
            }
        }

        @Override
        public ConcurrentList<V> clone() {
            readLock.lock();
            try {
                return (ConcurrentList<V>)super.clone();
            }finally {
                readLock.unlock();
            }
        }
    }
}


texts: Code reduction possible with modulo operator?

texts:
I'm trying to model a puzzle in order to resolve it with the Choco solver.

One of the constraint I'm coding is cyclical (it's triplet which follow themselves) like the following example:

s.post(LogicalConstraintFactory.ifThen(
    IntConstraintFactory.member(mvt[i], new int[]{1, 2, 3}),
    IntConstraintFactory.not_member(mvt[i + 1], new int[]{1, 2, 3})
));
s.post(LogicalConstraintFactory.ifThen(
    IntConstraintFactory.member(mvt[i], new int[]{4, 5, 6}),
    IntConstraintFactory.not_member(mvt[i + 1], new int[]{4, 5, 6})
));
s.post(LogicalConstraintFactory.ifThen(
    IntConstraintFactory.member(mvt[i], new int[]{7, 8, 9}),
    IntConstraintFactory.not_member(mvt[i + 1], new int[]{7, 8, 9})
));
// and so one...

I think that my library isn't very known so the mathematics equivalent is :

if(foo[i] is in {1, 2, 3}) then
    foo[i+1] shouldn't be in {1, 2, 3}
if(foo[i] is in {4, 5, 6}) then
    foo[i+1] shouldn't be in {4, 5, 6}
...

Any idea of how I can model this problem with modulo (to avoid writing each triplet)?


texts: Evaluating Fibonacci-sequence-based recurrence relation (SPOJ Flibonakki)

texts:
I have a function fib2 which returning two values as Tuple but I want to print the product of tuples returned by function fib2. I am new to Haskell so please explain it to me in a simple way.

This problem is from SPOJ which I have already solved using C and again I am trying it in Haskell:

  For each \$n\$, find \$G(n) \mod 1000000007\$, where
  $$\begin{align*}
G(0) &= 0 \\
G(n) &= G(n-1) + f(4n - 1), \qquad n > 0 \\
f(i) &= \mathrm{the\ i^{th}\ Fibobacci\ number}
\end{align*}$$

  The first line of input specifies the number of test cases.

Now my code is working fine but I'm getting TLE in this problem. Can someone show me how to optimize Fibonacci in Haskell?

import Data.List
import Data.Maybe
import Control.Monad
import qualified Data.ByteString.Char8 as C

fib2 0 = (1, 1)
fib2 1 = (1, 2)
fib2 n
 | even n    = ((a*a + b*b)`mod` 1000000007, (c*c - a*a)`mod` 1000000007)
 | otherwise = ((c*c - a*a)`mod` 1000000007, (b*b + c*c)`mod` 1000000007)
 where (a,b) = fib2 (n `div` 2 - 1)
       c     = a + b

solve n = (a*b)`mod`1000000007
    where (a,b) = fib2((2*n-1)`mod`2000000016)

main = C.getContents >>= putStrLn . unlines . map (show.solve.fromIntegral . fst . fromJust . C.readInteger) . tail . C.words


texts: How can I make this SQL Bit scalar function more efficient?

texts:
I'd like to make this SQL scalar function more efficient.  How can I do that?

CREATE FUNCTION [dbo].[fnFilterBySampleType]
(
    @context VARCHAR(10),
    @contextId INT,
    @sampleTypeId INT
)
RETURNS BIT
AS
BEGIN

    IF (
        @context = 'batch' AND @sampleTypeId = 247
        AND EXISTS(
            SELECT *
            FROM batch
            WHERE batchid = @contextId
            AND (batch.sampletypeid = @sampleTypeId OR batch.sampletypeid IS NULL)
        )
    ) RETURN 1

    IF (
        @context = 'batch' AND @sampleTypeId = 3301
        AND EXISTS(
            SELECT *
            FROM batch
            WHERE batchid = @contextId
            AND batch.sampletypeid = @sampleTypeId
        )
    ) RETURN 1

    IF (
        @context = 'batch' AND @sampleTypeId IS NULL
        AND EXISTS(
            SELECT *
            FROM batch
            WHERE batchid = @contextId
            AND batch.sampletypeid IS NULL
        )
    ) RETURN 1

    IF (
        @context = 'sample' AND @sampleTypeId = 247
        AND EXISTS(
            SELECT *
            FROM sample
            WHERE sampleid = @contextId
            AND ([sample].sampletypeid = @sampleTypeId OR [sample].sampletypeid IS NULL)
        )
    ) RETURN 1

    IF (
        @context = 'sample' AND @sampleTypeId = 3301
        AND EXISTS(
            SELECT *
            FROM sample
            WHERE sampleid = @contextId
            AND sample.sampletypeid = @sampleTypeId
        )
    ) RETURN 1

    IF (
        @context = 'sample' AND @sampleTypeId IS NULL
        AND EXISTS(
            SELECT *
            FROM sample
            WHERE sampleid = @contextId
            AND [sample].sampletypeid IS NULL
        )
    ) RETURN 1

    RETURN 0

END


texts: First Python program: pick and display alien characteristics

texts:
This is my first Python program and all it does is print out a description of the specific "Alien Class" that the user inputs.

Looking for tips and pointers and what I can do better and what I am doing well.

# Initializing the alien army with different alien classes

alien_army = {
    'rogue': {
        'name': 'rogue',
        'color': 'green',
        'size': 'small',
        'speed': 'fast',
        'damage': 'small'
    },
    'warrior': {
        'name': 'warrior',
        'color': 'blue',
        'size': 'medium',
        'speed': 'average',
        'damage': 'heavy'
    },
    'hunter': {
        'name': 'hunter',
        'color': 'dark green',
        'size': 'average',
        'speed': 'average',
        'damage': 'average'
    }
}

# Adding an Alien class 'Monk' to the alien_army

alien_army['monk'] = {
    'name': 'monk',
    'color': 'light gray',
    'size': 'small',
    'speed': 'quick',
    'damage': 'average'
}

class_names = []
for k, v in alien_army.items():
    class_names.append(k)

# Function that shows the alien that the user typed

def showPickedAlien(a):
    print(f"{a['name'].upper()}'S are {a['color'].title()} in color, {a['size'].lower()} in size, {a['speed'].lower()} in speed and they do a {a['damage'].lower()} amount in damage.")

# While loop flag to run or stop loop

input_enabled = True

# While loop to keep displaying the alien class that the user inputs

while input_enabled:
    user_input = input("Which class do you want to see? ").lower()
    input_alien = alien_army.get(user_input)

    # Checking if user entered a valid alien class name

    if user_input in class_names:
        showPickedAlien(input_alien)
    else:
        print(f"{user_input.upper()} is not a valid alien class name.")

    # Asking user if they want to see another alien class or not

    input_for_quit = input("Do you want to see another class? ").lower()

    # Determining if the user wants the loop to stop or not

    if input_for_quit == 'no' or input_for_quit == 'n':
          print("Goodbye.")
          input_enabled = False
    elif input_for_quit == 'yes' or input_for_quit == 'y':
          input_enabled = True


texts:
I'm currently working on building a simple REST API using Ruby on Rails. I noticed that a lot of the things I did were a bit redundant, especially the models. Just to clarify: I want this to be a REST API which returns JSON, without any views (I want to be able to access it from different applications, mainly Apache Cordova). Within Cordova I wanted to use ReactJS.

Sadly, my Rails controllers all look like this:

class StudentsController < ApplicationController
  def index
    @students = Student.all
    render json: @students
  end

  def create
    if @student.present?
      render nothing: true, status: :conflict
    else
      @student = Student.new(student_params)
      if @student.save
        render json: @student
      else
        render nothing: true, status: :bad_request
      end
    end
  end

  def show
    @student = Student.find(params[:id])
    render json: @student.classes
  end

  def update
    @student = Student.find(params[:id])
    @student.update(student_params)
    if @student.save
      render json: @student
    else
      render nothing: true, status: :bad_request
    end
  end

  def delete
    if Student.destroy(params[:id])
      render nothing: true, status: :ok
    else
      render nothing: true, status: :bad_request
    end
  end

  private
    def student_params
      params.permit(:first_name, :last_name, :grade_id)
    end
end

I literally got three of them with only the classname changed. Is there a smarter way to organize this? I may have to change override some functions, but some functions will be identical.

I also have a few database relationships, for example grades and classes to teachers and students. Does anyone have some information about best practices for this? I seem to be creating a lot of "relationship" tables for these many-to-many relationships.

For the RoR Rest API Part I found this tutorial.


texts:
This class acts as an asynchronous event handler that will execute all attached tasks in an async/await context. Requires Nuget Immutables. Example usage:
class MyEventArgs : EventArgs {}
async Task SomeAsyncMethodAobject src, EventArgs args) {
    Console.WriteLine("Task A...");
    await Task.Delay(2000);
}
async Task SomeAsyncMethodB(object src, EventArgs args) {
    Console.WriteLine("Task B...");
    await Task.Delay(1000);
}

static async Task Main(string[] args) {
    AsyncEvent<MyEventArgs> Events;
    Events = new AsyncEvent<MyEventArgs>();
    Events += SomeAsyncMethodA;
    Events += SomeAsyncMethodB;
    await Events?.InvokeAsync(this, new MyEventArgs());
    // Use below to discard task and not event task to finish.
    // _ = Events?.InvokeAsync(this, new MyEventArgs()).ConfigureAwait(false);
}

Source for the AsyncEvent<EventArgsT> class:
// T is the EventArgs class type to pass to the callbacks on Invoke.
public class AsyncEvent<T> where T : EventArgs {
    // List of task methods to await.
    public ImmutableList<Func<object, T, Task>> Invokables;

    // on += add new callback method to AsyncEvent.
    public static AsyncEvent<T> operator+(AsyncEvent<T> source, Func<object, T, Task> callback) {
        if (callback == null) throw new NullReferenceException("Callback is null! <AsyncEvent<T>>");
        if (source == null) return null;
        if (source.Invokables == null) source.Invokables = ImmutableList<Func<object, T, Task>>.Empty;
        source.Invokables = source.Invokables.Add(callback);
        return source;
    }

    // on -= remove existing callback from AsyncEvent.
    public static AsyncEvent<T> operator -(AsyncEvent<T> source, Func<object, T, Task> callback) {
        if (callback == null) throw new NullReferenceException("Callback is null! <AsyncEvent<T>>");
        if (source == null) return null;

        source.Invokables = source.Invokables.Remove(callback);
        return source;
    }

    // Invoke the tasks asynchronously with a cancelation token.
    public async Task InvokeAsync(object source, T evArgs, CancellationToken token) {
        List<Task> tasks = new List<Task>();
        if (Invokables != null)
            foreach (var callback in Invokables)
                if (!token.IsCancellationRequested)
                    tasks.Add(callback(source, evArgs));

        await Task.WhenAll(tasks.ToArray());
    }

    // Invoke the tasks asynchronously.
    public async Task InvokeAsync(object source, T evArgs) {
        List<Task> tasks = new List<Task>();
        if (Invokables != null)
            foreach (var callback in Invokables)
                tasks.Add(callback(source, evArgs));

        await Task.WhenAll(tasks.ToArray());
    }
}


texts:
Module for generating a PWM signal. The req_value_i input gets a duration value of the signal. Furthermore, the module can be stopped by deassertion of the enable_i input.
`timescale 1ns / 1ps

 module pwm #
(
    parameter integer PWM_COUNTER_WIDTH = 8
)
(
    input  logic                             clk_i,
    input  logic                             s_rst_n_i,
    input  logic                             enable_i,

    input  logic [PWM_COUNTER_WIDTH - 1 : 0] req_value_i,

    output logic                             channel_o
    );

    logic [PWM_COUNTER_WIDTH - 1 : 0] counter;

    always_comb begin
        channel_o = (req_value_i != counter) ? 1'h1 : 1'h0;
    end

    always_ff @ (posedge clk_i) begin
        if (1'h0 == s_rst_n_i) begin
            counter <= {PWM_COUNTER_WIDTH{1'h0}};
        end
        else if (1'h1 == enable_i) begin
            counter <= counter + 1'h1;
        end
    end

endmodule


texts: Converting a binary string to an ASCII string, the longer way

texts:
I had an interview recently and discovered that I'd forgotten some of the basics.  I've been playing around again and have written a function that will take a binary string (there is no validation yet) and returns the ASCII representation of said string.

I'm looking for advice or tips on how it could be improved. I don't want to use any of the API functions, this is more of a playground scenario in which I might be able to learn something.

public static String convertBinaryStringToString(String string){
    StringBuilder sb = new StringBuilder();
    char[] chars = string.replaceAll("\\s", "").toCharArray();
    int [] mapping = {1,2,4,8,16,32,64,128};

    for (int j = 0; j < chars.length; j+=8) {
        int idx = 0;
        int sum = 0;
        for (int i = 7; i>= 0; i--) {
            if (chars[i+j] == '1') {
                sum += mapping[idx];
            }
            idx++;
        }
        System.out.println(sum);//debug
        sb.append(Character.toChars(sum));
    }
    return sb.toString();
}

Sample output:

01101000 01100101 01101100 01101100 01101111
104
101
108
108
111
hello


texts:
This is a simple program to create neural networks. It only includes weighting of connections and activation values for the neurons. It doesn't include any learning feature of any kind, and it is really just a first attempt at creating something resembling a neural network.

Main.java

package uniliniarnetwork;

public class Main {

public static void main(String[] args) {
    Neuron inputNode = new Neuron(0,1,"InputNode",1);

    Neuron hiddenNode_One = new Neuron(0.5f,0.9f,"HiddenNode_One",1);
    Neuron hiddenNode_Two = new Neuron(0.5f,0.9f,"HiddenNode_Two",1);
    Neuron hiddenNode_Three = new Neuron(0.5f,0.9f,"HiddenNode_Three",1);

    Neuron outputNode = new Neuron(0,0.9f,"OutputNode",3);

    inputNode.connect(hiddenNode_One);
    inputNode.connect(hiddenNode_Two);
    inputNode.connect(hiddenNode_Three);

    hiddenNode_One.connect(outputNode);
    hiddenNode_Two.connect(outputNode);
    hiddenNode_Three.connect(outputNode);

    inputNode.input(1);
}

}

Neuron.java

package uniliniarnetwork;

import java.util.ArrayList;

public class Neuron {
private float activationValue, weight;
private String neuronName;
private ArrayList<Neuron> outputs = new ArrayList<Neuron>();
private float[] inputs;
int inputCounter = 0, nInputs;

public Neuron(float activationValue, float weight, String neuronName, int nInputs){
    this.activationValue = activationValue;
    this.weight = weight;
    this.neuronName = neuronName;
    this.nInputs = nInputs;

    inputs = new float[nInputs];
}

public void connect(Neuron neuron){
    outputs.add(neuron);
}

public void input(float inputValue){
    inputs[inputCounter] = inputValue;
    inputCounter++;

    if(inputCounter == nInputs){
        fire();
    }
}

public void fire(){
    float sum = 0;
    for(int i = 0; i < nInputs; i++){
        sum+=inputs[i];
    }

    float signal = sum*weight;

    if(signal > activationValue){
        for(int i = 0; i < outputs.size(); i++){
            outputs.get(i).input(signal);
        }
    } else{
        for(int i = 0; i < outputs.size(); i++){
            outputs.get(i).input(0);
        }
    }
    System.out.println(neuronName + ":" + signal);
}
}

Basically main creates Neuron objects from the Neuron class which have an activationValue and a weight value. I know it's not perfect and it doesn't include most of the most important features of a neural network.

My question is whether this is a good place to build from towards more advanced neural networks, for example those which can classify images. It would be greatly appreciated if you could explain in terms a high-school student (with only a rudimentary understanding of calculus) would understand.


texts: Find all the paths of tree that add to a input value

texts:
This code is attributed to Stack Overflow itself here. The path which adds to the sum, which need not be starting from the root, not be ending at the leaf, i.e. a path can be between root and a leaf.

I'm looking for code review, optimizations and best practices. I'm also looking for a solution better than \$O(n^2)\$ time complexity, if such exists. I'm also verifying space complexity to be \$O(n)\$, where \$n\$ in both the cases is the number of treenodes.

Also, the code specifically demands me to print, making unit testing not possible. Are there any pointers on how such code could be tested?

public class AllPathsAddingSum {

    private TreeNode root;

    public AllPathsAddingSum(List<Integer> items) {
        create (items);
    };

    /**
     * Constructs a binary tree in order of elements in an array.
     * After the number of nodes in the level have maxed, the next
     * element in the array would be a child of leftmost node.
     */
    private void create(List<Integer> items) {
        if (items.size() == 0) {
            throw new IllegalArgumentException("There should atleast be single item in the tree");
        }

        root = new TreeNode(items.get(0));

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

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

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

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

    private static class TreeNode {
        private TreeNode left;
        private int item;
        private TreeNode right;

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

    /**
     * Prints all the paths that add to the input value.
     * @param value the value, that all the nodes of a path should add upto.
     */
    public void printAllSumPaths(int value) {
        traverse(root, value);
    }

    private void traverse(TreeNode node, int value) {
        if (node == null) return;

        computePaths(node, 0, value, new ArrayList<Integer>());

        traverse(node.left, value);
        traverse(node.right, value);
    }

    private void computePaths(TreeNode node, int sum, int value, List<Integer> path) {
        if (node == null) return;

        sum = sum + node.item;
        path.add(node.item);

        if (sum == value) {
            for (Integer i : path) {
                System.out.print(i + " ");
            }
            System.out.println();
        }

        computePaths(node.left, sum, value, path);
        computePaths(node.right, sum, value, path);

        path.remove(path.size() - 1);
    }

    public static void main(String[] args) {
        AllPathsAddingSum sumPaths = new AllPathsAddingSum(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        sumPaths.printAllSumPaths(4);

        sumPaths = new AllPathsAddingSum(Arrays.asList(1, 0, 0, -1));
        sumPaths.printAllSumPaths(0);
    }
}


texts: Looking for meta data which matches certain criteria and was created after a certain date

texts:
I've got the below SQL statement which runs in MySQL on a WordPress installation. I'm looking for meta data that matches certain criteria and was created after a certain date.

However, WordPress doesn't store the date that metadata was added to posts, so I've created the metadata itself (wpcf-post-likes), the date it was added (wpcf-post-like-date) and a third piece of metadata which is created at the same time that contains the IDs of the previous two delimited by an exclamation mark (wpcf-post-like-date-link).

I then use the following SQL statement to get likes on posts written by the current author (example ID included in the SQL code below) after a certain date. It works, but it takes about 7 - 8 seconds to run, which is far from ideal. Is there a more efficient version of the same statement?

SELECT `meta_id` FROM `wp_postmeta`
WHERE   `post_id` IN (
            SELECT `ID` FROM `wp_posts` WHERE post_author = $user_id
        ) AND
        `meta_value` IN (

        SELECT CONCAT(combined_ids_a.`meta_id`, '!', combined_ids_b.`meta_id`) AS `combined_meta_id` FROM (

            SELECT `meta_id`, 'like_id' AS `meta_type` FROM `wp_postmeta`
            WHERE `meta_key` LIKE 'wpcf-post-likes'
            AND `meta_value` NOT LIKE '1837'
            AND `meta_id` IN
            (SELECT SUBSTRING_INDEX(`meta_value`, '!', 1) FROM `wp_postmeta` WHERE `meta_key` LIKE 'wpcf-post-like-date-link' ORDER BY `meta_id` DESC)

            UNION

            SELECT  `meta_id`, 'like_date' AS `meta_type`  FROM `wp_postmeta`
            WHERE `meta_key` LIKE 'wpcf-post-like-date'
            AND `meta_value` > '01-02-2016 09:20:34'
            AND `meta_id` IN
            (SELECT SUBSTRING_INDEX(`meta_value`, '!', -1) FROM `wp_postmeta` WHERE `meta_key` LIKE 'wpcf-post-like-date-link' ORDER BY `meta_id` DESC)

        ) AS combined_ids_a JOIN

        (

            SELECT `meta_id`, 'like_id' AS `meta_type` FROM `wp_postmeta`
            WHERE `meta_key` LIKE 'wpcf-post-likes'
            AND `meta_value` NOT LIKE '1837'
            AND `meta_id` IN
            (SELECT SUBSTRING_INDEX(`meta_value`, '!', 1) FROM `wp_postmeta` WHERE `meta_key` LIKE 'wpcf-post-like-date-link' ORDER BY `meta_id` DESC)

            UNION

            SELECT  `meta_id`, 'like_date' AS `meta_type`  FROM `wp_postmeta`
            WHERE `meta_key` LIKE 'wpcf-post-like-date'
            AND `meta_value` > '01-02-2016 09:20:34'
            AND `meta_id` IN
            (SELECT SUBSTRING_INDEX(`meta_value`, '!', -1) FROM `wp_postmeta` WHERE `meta_key` LIKE 'wpcf-post-like-date-link' ORDER BY `meta_id` DESC)

        ) AS combined_ids_b

        );


texts: Converting  tags to horizontal responsive barcharts

texts:
I am writing my first jQuery plugin that converts li tags to horizontal responsive barcharts. I am looking for some feedback and suggestions regarding the implementation.

(function($) {
    $.fn.barcharts = function(options) {

        // Establish default settings
        var defaults = {
            animationSpeed  : 500
        };

        // Merge
        var options = $.extend({}, defaults, options);

        // Gather
        var $targets = $(this).find('.bar-group-item');

        // Render
        $.each($targets, function() {

            var $li = $(this),
                newWidth = $li.data('bar-value')/100*$li.width();

            // Construct the item to be displayed
            var $div = $('
', {
                width: 0,
                text: $li.text()
            });

            // Remove previous contents
            $li.empty();

            // Append to current item
            $div.appendTo($li);

            // Reveal
            $div.animate({width: newWidth}, options.animationSpeed);

        });
    };

}(jQuery));
.bar-group {
    list-style: none;
    padding-left:0;
}

.bar-group-item {
    width: 100%;
    background-color: #34495e;
    color: #ffffff;
    margin: 5px 0 5px 0;
}

.bar-group-item div {
    background-color: #2980b9;
    white-space: nowrap;
}

England

Spain

Zimbabwe

Lakers

Heat

Raptors

Los Angeles

Miami

Toronto


texts:
I've spent the best part of a day on this question. It is marked as Expert level. There are about fifteen submission test cases and my solution manages to satisfy the first four. However, from there on in it hits timeouts due to performance issues.

Hackerrank question

There doesn't seem to be much information or solutions for this question around, so I would appreciate if anyone had any suggestion on how I can improve the performance. Maybe I need to go back to the drawing board with my approach.

N = number of elements in the array
K = The height difference allowed
H = Array of heights
queries = 2D array of ranges within which you must find the number of matching pairs (i.e. how many fighters in this range meet the height requirements to fight each other)

My approach is to copy the subset (I know this is slow and would like to get around it somehow)and then run a quicksort over this new subset.

With this we can now quickly figure out what heights are within range of each other (i.e. if we get height = 1 and we know k = 2, then the maximum height he can fight against is going to be 3).

    static int[] solve(int n, int k, int[] h, int[][] queries) {
    // N = no. heights
    // K = Difference
    // L & R = First and Last fighters
    int[] results = new int[queries.length];
    int count = 1;
    int pairs = 0;
    int l, r =0;

    for(int j=0; j<queries.length; j++) {
        l = queries[j][0];
        r = queries[j][1];
        int[] range = Arrays.copyOfRange(h, l, r+1);

        int[] sortedSubset = sort(range);

        for(int i=0; i<sortedSubset.length-1; i++) {
            count = i+1;
            while((count != sortedSubset.length) && sortedSubset[count] <= (sortedSubset[i]+k)) {

                // While the current number is still in range of the number we are checking i.e. (number + k)
                pairs++;
                count++;
           }
        }
        results[j] = pairs;
        pairs = 0;
    }

    return results;
}

  A Sumo wrestling championship is scheduled to be held this winter
  in the HackerCity where N wrestlers
  from different parts of the world are going to participate.
  The rules state that two wrestlers can fight against each other
  if and only if the difference in their height
  is less than or equal to K, (i.e.)
  wrestler A and wrestler B can fight
  if and only if |height(A)-height(B)|≤K.

  Given an array H[], where
  H[i] represents the height of the ith
  fighter, for a given l, r where 0 <= l <= r < N, can you count the
  number of pairs of fighters between l and r (both inclusive) who
  qualify to play a game?

  Input Format
  The first line contains an integer N and K separated by
  a single space representing the number of Sumo wrestlers who are going
  to participate and the height difference K.
  The second line contains N integers separated by a single space,
  representing their heights
  H[0] H[1] ... H[N - 1].
  The third line contains Q, the number of queries.
  This is followed by Q lines each having two integers l and r
  separated by a space.

  Output Format
  For each query Q, output the corresponding value of
  the number of pairs of fighters for whom the absolute difference of
  height is not greater that K.

  Constraints
  1 <= N <= 100000
  0 <= K <= 109
  0 <= H[i] <= 109
  1 <= Q <= 100000
  0 <= l <= r < N

  Sample Input

5 2
1 3 4 3 0
3
0 1
1 3
0 4

  Sample Output

1
3
6

  Explanation
  Query #0: Between 0 and 1 we have i,j as (0,1) and
  |H[0]-H[1]|=2 therefore output is 1.
  Query #1: The pairs (H[1],H[2]) (H[1],H[3])
  and (H[2],H[3]) are the pairs such that |H[i]-H[j]| <=2.
  Hence output is 3.
  Query #2: Apart from those in Query #1, we have
  (H[0],H[1]), (H[0], H[3]), (H[0], H[4]), hence 6.

  Timelimits

  Timelimits are given here


texts:
I was wondering if this implementation of insertion sort could be improved. Are there any things that I have done wrong?

template<typename Element>
void insertion_sort(Element arr[], size_t size) {
    size_t index, index_sorted;
    for (index = 0u; index < size; ++index) {
        auto temp = arr[index];
        index_sorted = index - 1;
        while (arr[index_sorted] >= 0 && arr[index_sorted] > temp) {
            arr[index_sorted + 1] = arr[index_sorted--];
        }
        arr[index_sorted + 1] = temp;
    }
}


texts: Check if a stack of Integers contains a sequence of consecutive values

texts:
Write a method isConsecutive that takes a stack of integers as a
  parameter and that returns whether or not the stack contains a
  sequence of consecutive integers starting from the bottom of the stack
  (returning true if it does, returning false if it does not).
  Consecutive integers are integers that come one after the other, as in
  5, 6, 7, 8, 9, etc. So if a stack s stores the following values:

  bottom [3, 4, 5, 6, 7, 8, 9, 10] top

  Then the call of isConsecutive(s) should return true. If the stack had
  instead contained this set of values:

  bottom [3, 4, 5, 6, 7, 8, 9, 10, 12] top

  Then the call should return false because the numbers 10 and 12 are
  not consecutive. Notice that we look at the numbers starting at the
  bottom of the stack.

  The following sequence of values would be consecutive except for the
  fact that it appears in reverse order, so the method would return
  false: bottom [3, 2, 1] top

  Your method must restore the stack so that it stores the same sequence
  of values after the call as it did before. Any stack with fewer than
  two values should be considered to be a list of consecutive integers.
  You may use one queue as auxiliary storage to solve this problem.

I'm looking for ways to improve my future code. I was also wondering if it's better practice to use generics in cases like these? I'll also accept other methods of solving this problem as the correct answer. My main goal is to try to take away something that will make me a better programmer; if you have advice to shed, please don't hesitate to share it!

public boolean isConsecutive(Stack<Integer> s) {
    boolean consecutive = true;
    Queue<Integer> q = new LinkedList<Integer>();
    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    while (!q.isEmpty()) {
        s.push(q.poll());
    }

    while (!s.isEmpty()) {
        q.offer(s.pop());
    }

    while (q.size() > 1) {
        int first = q.poll();
        int second = q.poll();
        consecutive &= (second - first == 1);
        s.push(first);
        s.push(second);
    }

    if (!q.isEmpty()) {
        int first = q.poll();
        int second = s.peek();
        consecutive &= (second - first == 1);
        s.push(first);
    }
    return consecutive;
}


texts:
I recently read about the C++17 static inline member declaration and thought that this will make templates a little bit cleaner, since static members can now be initialized inside a templated class.

Because of this I wanted to create a neat little Singleton template (since it is the perfect example where static members are needed).

Now to my questions: Is there something I potentially missed, i.e. are there possibilities to create copies of a derived Singleton? Is it a good idea to use CRTP for a Singleton in general? What a about the move constructor, do I need to handle it as well?

Here is the template:

template < typename T >
class Singleton {
  public:
    static T& GetInstance() {
      static MemGuard g; // clean up on program end
      if (!m_instance) {
        m_instance = new T();
      }
      return *m_instance;
    }

    Singleton(const Singleton&) = delete;
    Singleton& operator= (const Singleton) = delete;

  protected:
    Singleton() { };
    virtual ~Singleton() { }

  private:
    inline static T * m_instance = nullptr;

    class MemGuard {
      public:
        ~MemGuard() {
          delete m_instance;
          m_instance = nullptr;
        }
    };
};

And here a possible derived type:

class Test final : public Singleton<Test> {
  friend class Singleton<Test>;
  public:
    void TestIt() { };
  private:
    Test() {}
    ~Test() { /* Test intern clean up */ }
};


texts:
Since Boost.Any library does not work well with Move-Only types, I had to write my own alternative:

#include <typeindex>
#include <type_traits>
#include <utility>
#include <exception>

class TAny {
public:
    TAny() = default;
    TAny(const TAny &a) {
        *this = a;
    }
    TAny &operator=(const TAny &a) {
        if (this != &a) {
            ptr = a.ptr->clone();
        }
        return *this;
    }
    TAny(TAny &&a) {
        *this = std::move(a);
    }
    TAny &operator=(TAny &&a) {
        if (this != &a) {
            ptr = a.ptr;
            a.ptr = nullptr;    // swap
        }
        return *this;
    }
    template <typename T>
    TAny(const T &t) {
        *this = t;
    }
    template <typename T>
    TAny &operator=(const T &t) {
        if (ptr) delete ptr;
        typename std::conditional<
            std::is_copy_constructible<T>::value,
            return_placeholder_by_copying<T>,   // sadece true is açılacak (umarım)
            return_placeholder_nullptr>::type do_something;
        ptr = do_something(t);
        return *this;
    }
    template <typename T>
    TAny(T &&t) {
        *this = std::move(t);
    }
    template <typename T>
    TAny &operator=(T &&t) {
        if (ptr) delete ptr;
        ptr = new impl<T>(std::move(t));
        return *this;
    }
    ~TAny() {
        delete ptr;
    }
    struct placeholder {
        std::type_index type_information { typeid(void) };
        virtual placeholder *clone() = 0;
        virtual void *object() = 0;
        virtual ~placeholder() {  }
    };
    template <typename T>
    struct impl : placeholder {
        impl(T const &t) : val(t) { type_information = typeid(T); }
        // ^^^ why doesn't this code cause problems for move-only types???
        // answer is http://stackoverflow.com/questions/21166762/forcing-the-compiler-to-generate-code-for-all-member-functions-of-a-template-cla
        // unless explicitly instantiated, compiler doesn't generate
        // whole code for the class. (meaning not includes every member
        // function, even doesn't do deletedness checking! --> is it standard?)

        impl(T &&t) : val(std::move(t)) { type_information = typeid(T); }
        virtual placeholder *clone() {
            typename std::conditional<
                std::is_copy_constructible<T>::value,
                return_placeholder_by_copying<T>,   // sadece true is açılacak (umarım)
                return_placeholder_nullptr>::type do_something;
            return do_something(val);
        }
        virtual void *object() { return (void *) &val; }
        T val;
    };
    template <typename Tx>
    struct return_placeholder_by_copying {  // iyi template magic kastım yalnız :O
        placeholder *operator()(const Tx &t) {
            return new impl<Tx>(t);
        }
    };
    struct return_placeholder_nullptr {
        template <typename... Args>
        placeholder *operator()(Args&&... args) {
            return nullptr;
        }
    };
    placeholder *ptr { nullptr };
};

class BadAnyCast : public std::exception {
public:
    const char *what() const noexcept {
        return "Bad Any Cast!!!";
    }
};

template <typename T>
T AnyCast(TAny &a) {
    if (std::type_index(typeid(typename std::remove_reference<T>::type)) == a.ptr->type_information) {
        return (T)
            (*static_cast<
                typename std::remove_reference<T>::type*
            >(a.ptr->object()));
    }
    throw BadAnyCast();
}

What do you suggest me to improve this?


texts:
I've just started delving into JavaFX, and the following is essentially my "Hello World". Although it's simple, I question the code formatting and wonder if I'm breaking any conventions, especially if explicitly concerning the library.

I also find myself concerned with what best promotes readability. Unfamiliarity brought many an alteration between styles. e.g. for statements, whether it is preferable to instantiate, modify and add an object all at once or simply pairing similar things together and modifying them wherever necessary and adding them at the end -- my final code here is an amalgamation of both styles.

This last bit may be delving a bit into SO/Programmers territory, but I'm curious.  I found myself using anonymous inner classes as it made methods easily transportable; I've hitherto not used it more than once in a program, is this bad form? If so, why?

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class DrawingLines extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Legato's Lines");

        Group root = new Group();
        Scene scene = new Scene(root, 300, 150, Color.GRAY);

        Line redLine = new Line(10, 10, 200, 10) {
            {
                setStroke(Color.RED);
                setStrokeWidth(3);
                getStrokeDashArray().addAll(10d, 5d, 15d, 5d, 20d);
                setStrokeDashOffset(0);
            }
        };
        Line whiteLine = new Line(10, 30, 200, 30) {
            {
                setStroke(Color.WHITE);
                setStrokeLineCap(StrokeLineCap.ROUND);
                setStrokeWidth(10);
            }
        };
        Line blueLine = new Line(10, 50, 200, 50) {
            {
                setStroke(Color.BLUE);
                setStrokeLineCap(StrokeLineCap.BUTT);
                setStrokeWidth(5);
            }
        };

        Slider slider = new Slider(0, 100, 0) {
            {
                setLayoutX(10);
                setLayoutY(95);
            }
        };

        Text offsetText = new Text("Stroke Dash Offset: 0") {
            {
                setX(10);
                setY(80);
                setStroke(Color.WHITE);
            }
        };

        slider.valueProperty().addListener(
            (ov, curVal, newVal) -> offsetText.setText(
                "Stroke Dash Offset: " + Math.round(slider.getValue()))
        );
        redLine.strokeDashOffsetProperty().bind(slider.valueProperty());

        root.getChildren().add(redLine);
        root.getChildren().add(whiteLine);
        root.getChildren().add(blueLine);
        root.getChildren().add(slider);
        root.getChildren().add(offsetText);

        primaryStage.setScene(scene);
        primaryStage.show();
    }
}


texts:
I have written a code that finds whether the entered words are anagrams or not. I tested and it works, but I know that there are some details that I must change or modify. So what do you think I have to change in this code?

function findAnagram (firstWord, secondWord) {
var testWord = "";
var c = 0;
while (c < secondWord.length || c < firstWord.length) {
    while (secondWord[c] == " " || firstWord[c] == " ") {
    secondWord = secondWord.replace(" ", "");
    firstWord = firstWord.replace(" ", "");
}
c++;
}

if (firstWord.length == secondWord.length) {
    for (var i = 0; i < firstWord.length; i++) {
    for (var k = 0; k < secondWord.length; k++) {
        if (firstWord[i] == secondWord[k]) {
            testWord += firstWord[i];
            secondWord = secondWord.replace(secondWord[k], "")
            break;
        }
    }
}
}
if (firstWord == testWord){
    return "Anagram !";
}
else {
    return "Not an Anagram";
}
}
console.log(findAnagram("funeral", "real fun"));


texts:
I need to go and rework a bunch of notation in a large body of work. But I might change my mind later, so I want to move to defining the notation a bit more semantically (e.g. writing \v x to represent a vector, so I can later decide to format vectors in different ways).

On thing that is currently wrong with it is that I write A_i to represent that \$i^{\text {th}}\$ column vector. After looking at other similar works, I have concluded that A_{:,i} would be clearer. So I have defined a macro to smartly determine if a : should be added.

I called it \i to be concise since I will be writing it often.

\documentclass{article}

\usepackage{xparse,xstring,etoolbox}

\renewcommand{\v}[1]{\tilde{#1}} % a vector

\newcommand{\ind}[2]{#1_{#2}} % indexed

%% Smart indexing and naming code

\newcommand{\ifupper}[3]{
    \normalexpandarg
    \exploregroups
    \StrCount{ABCDEFGHIJKLMNOPQRSTUVWXYZ}{#1}[\uppercount]
    \ifnumgreater{\uppercount}{0}{#2}{#3}
}

%smart index
\DeclareDocumentCommand{\i}{u{_} m}{
    \ifupper{#1}%
    {% just a single uppercase character, i.e. a matrix
        %make sure the index is the right length
        \StrCount{#2}{,}[\indcount]
        \ifnumgreater{\indcount}{0}
        { % Got multiple indexes so all good
            \ind{#1}{#2}
        }
        { % Only 1 index so grab the column
            \ind{#1}{{:,#2}}
        }
    }%
    {% Not just a single upper case character
        \ind{#1}{#2}
    }
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Example document
\begin{document}

        \begin{tabular}{r l}
  $\i {\v x}_i$ & the $i$th element of the vector $\v x$\\
  $\i{X}_{i,j}$ & the row $i$ and column $j$ element of the matrix $X$\\
  $\i{X}_i$ & the $i$th column vector of the matrix $X$\\
  $\i{X}_{i,:}$ & the $i$th row vector of the matrix $X$\\
 \end{tabular}

\end{document}

Example document output

Crossref


texts: How can I improve this 31-bit SuperFastHash implementation in VBA?

texts:
I'm implementing a variation of the SuperFastHash in VBA for use in Excel (32-bit version, so no LongLong available) to hash strings.

To get around the limitations of signed 32-bit Long values, I'm doing the addition and bit-shifting using Double types, and then converting from Double to Long in a way that truncates it at 31 bits (the maximum positive value -- don't want to deal with two's complement and signs).

I'm getting answers and avoiding overflows so far, but I have a suspicion I'm making some mistakes in translation, since most implementations use all 32 bits of a uint and also deal with individual bytes from an array rather than 16-bit values coming from AscW().

Any suggestions of improvement, especially of the string-handling, bit-shifting, or  the final avalanche?

Public Function shr(ByVal Value As Long, ByVal Shift As Byte) As Long
    shr = Value
    If Shift > 0 Then shr = shr \ (2 ^ Shift)
End Function

Public Function shl(ByVal Value As Long, ByVal Shift As Byte) As Long
    If Shift > 0 Then
        shl = LimitDouble(CDbl(Value) * (2& ^ Shift))
    Else
        shl = Value
    End If
End Function

Public Function LimitDouble(ByVal d As Double) As Long
    '' Prevent overflow by lopping off anything beyond 31 bits
    Const MaxNumber As Double = 2 ^ 31
    LimitDouble = CLng(d - (Fix(d / MaxNumber) * MaxNumber))
End Function

Public Function SuperFastHash(ByVal dataToHash As String) As Long
    Dim dataLength As Long
    dataLength = Len(dataToHash)
    If (dataLength = 0) Then
        SuperFastHash = 0
        Exit Function
    End If
    Dim hash As Long
    hash = dataLength
    Dim remainingBytes As Integer
    remainingBytes = dataLength Mod 2
    Dim numberOfLoops As Integer
    numberOfLoops = dataLength \ 2
    Dim currentIndex As Integer
    currentIndex = 0
    Dim tmp As Double
    Do While (numberOfLoops > 0)
        hash = LimitDouble(CDbl(hash) + AscW(Mid$(dataToHash, currentIndex + 1, 1)))
        tmp = shl(AscW(Mid$(dataToHash, currentIndex + 2, 1)), 11) Xor hash
        hash = shl(hash, 16) Xor tmp
        hash = LimitDouble(CDbl(hash) + shr(hash, 11))
        currentIndex = currentIndex + 2
        numberOfLoops = numberOfLoops - 1
    Loop
    If remainingBytes = 1 Then
        hash = LimitDouble(CDbl(hash) + AscW(Mid$(dataToHash, currentIndex + 1, 1)))
        hash = hash Xor shl(hash, 10)
        hash = LimitDouble(CDbl(hash) + shr(hash, 1))
    End If
    '' Final avalanche
    hash = hash Xor shl(hash, 3)
    hash = LimitDouble(CDbl(hash) + shr(hash, 5))
    hash = hash Xor shl(hash, 4)
    hash = LimitDouble(CDbl(hash) + shr(hash, 17))
    hash = hash Xor shl(hash, 25)
    hash = LimitDouble(CDbl(hash) + shr(hash, 6))
    SuperFastHash = hash
End Function


texts: 'StrictInt' Python object class that prohibits casting numbers with non-integer components to `int`

texts:
Inspired by and created because of python3 utility: convert safely to int and driven partly by the 'refactor' in my answer.

The aforementioned question and my answer drove me to go and do a thing while bored at work - I created a new object class called StrictInt that behaves much like the function created by the original poster of that question/thread, but as an object class instead.

This object class is a subclass of int (which is  the superclass.  It's designed to work just like an int, but when you cast a str, int, or float to the StrictInt object, it will only convert the value if it is indeed an integer.

Because I'm crazy, you'll also need the typing module, but most Python 3 installs have that, if not, grab it from pip3.

This is the code used for the StrictInt class, and any required imports, in the strictint.py file:

from typing import Union, Any

class StrictInt(int):
    def __new__(cls, value, *args, **kwargs):
        # type: (Union[int, float, str], Any, Any) -> int

        if not isinstance(value, (int, StrictInt, float, str)):
            t = str(type(value)).replace("<class '", "").replace("'>", "")
            raise TypeError("Cannot convert type '{type}' to strict integer".format(type=t))

        try:
            f = float(value)
        except ValueError:
            f = None

        if not f:
            raise ValueError("Cannot convert a non-number to a strict integer.")

        if not f.is_integer():
            raise ValueError("Cannot convert value due to non-integer parts.")

        return super(StrictInt, cls).__new__(cls, int(f))

There is a set of unit tests I've been using as well (tests.py):

from strictint import StrictInt
import unittest

class TestStrictInt(unittest.TestCase):

    def test_float_conversion(self):
        # Non-integer parts present in a float, should raise ValueError
        self.assertRaises(ValueError, StrictInt, 3.14159)
        # Float that is equal to an int should be equal.
        self.assertEqual(3.0, StrictInt(3.0))

    def test_ints(self):
        # int(3) should equal StrictInt(3).
        self.assertEqual(3, StrictInt(3))

    def test_nonnumeric_string(self):
        # Not a number at all.
        self.assertRaises(ValueError, StrictInt, "I Am A Teapot")
        # Number with an invalid character in it, so Not a Number.
        self.assertRaises(ValueError, StrictInt, " 3.14159")
        # Has numeric content, but not a valid number due to dots.
        self.assertRaises(ValueError, StrictInt, "3.14.156")

    def test_numeric_string(self):
        # int('3') should equal StrictInt('3')
        self.assertEqual(int('3'), StrictInt('3'))
        # int(float('3.0')) is equal to int(3.0), and should equal StrictInt('3.0')
        self.assertEqual(int(float('3.0')), StrictInt('3.0'))
        # String with a number that has a decimal part should raise ValueError
        self.assertRaises(ValueError, StrictInt, '3.14159')

if __name__ == '__main__':
    unittest.main(warnings='ignore')

Any and all improvement suggestions are welcome.  This works pretty well and fairly quickly from what I've tested, but I value everyone's opinions.


texts: Efficient way to calculate the sum of all primes between a range

texts:
Problem
I'm trying to write a code in which Q questions are asked and each question contains two numbers A and B. For each question, I have to find the sum of all primes between integers A and B (inclusive). I've written a program that works, but it isn't fast enough to pass all the restrictions. Is there any way to improve the efficiency of my code?
Restrictions
1≤Q≤10^5
1≤A≤B≤10^5
Time limit: 0.6s
import java.io.*;
import java.util.*;

public class sumofprimes{
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    static StringTokenizer st;
    static boolean isPrime(int n){
        if(n==1)return false;
        for (int i=2; i*i<=n; i++)
            if (n%i==0) return false;
        return true;
    }

    static int sum(int a, int b){
        int sum=0;
        for(int i=b; i>=a; i--) {
            boolean prime=isPrime(i);
            if(prime) sum+=i;
        }
        return sum;
    }
    public static void main(String[] args)throws IOException{
        int q=readInt();
        for(int i=0; i<q; i++){
            int a=readInt(), b=readInt();
            System.out.println(sum(a,b));
        }
    }
    static String next () throws IOException {
        while (st == null || !st.hasMoreTokens())
           st = new StringTokenizer(br.readLine().trim());
    return st.nextToken();
    }
    static int readInt () throws IOException {
    return Integer.parseInt(next());
    }
}


texts: Caesar Cipher Encryption / Decryption in Python

texts:
I'm trying to write a Python program to predict the most likely substitution for a Caesar cipher. I managed to get it working, but it just seems very clunky and slow, especially because I need to preserve cases and non-alphabetical characters.

Would it be cleaner / more pythonic to use the chr() and ord() functions instead of the ALPHABET list?
Any suggestions on how I could improve it overall (while also maintaining relative readability)?

Thank you so much!
ALPHABET = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
FREQUENCIES = [.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007]

def getGoodness(msg):
    msg_length = sum([1 for i in msg if i.isalpha()])
    msg_frqs = [round(msg.count(a) / msg_length, 4) for a in ALPHABET]
    diffs = [abs(a - b) for a, b in zip(msg_frqs, FREQUENCIES)]
    avg_diff = round(sum(diffs) / len(diffs), 4)
    return avg_diff

def shift(string, n):
    shifted = [i for i in string]
    for char in range(len(shifted)):
        if shifted[char].isalpha():
            new_char = ALPHABET[(ALPHABET.index(shifted[char].lower()) + n) % len(ALPHABET)]

            if shifted[char].isupper():
                new_char = new_char.upper()
            shifted[char] = new_char
    return ''.join(shifted)

#########################################

msg = "Oqqcfrwbu hc ozz ybckb zokg ct ojwohwcb, hvsfs wg bc kom o pss gvcizr ps opzs hc tzm. Whg kwbug ofs hcc gaozz hc ush whg toh zwhhzs pcrm ctt hvs ufcibr. Hvs pss, ct qcifgs, tzwsg obmkom psqoigs pssg rcb'h qofs kvoh viaobg hvwby wg wadcggwpzs. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Ccv, pzoqy obr mszzck! Zsh'g gvoys wh id o zwhhzs. Poffm! Pfsoytogh wg fsorm!"

goodness = []
shifted = []
for i in range(26):
    goodness.append(getGoodness(shift(msg, i)))
    shifted.append(shift(msg, i))
gdict = dict(zip(goodness, shifted))
print(gdict.get(min(gdict.keys())))


texts: Extracting the last component (basename) of a filesystem path

texts:
fn basename<'a>(path: &'a str, sep: char) -> Cow<'a, str> {
    let pieces = path.split(sep);
    match pieces.last() {
        Some(p) => p.into(),
        None => path.into(),
    }
}

Usage:

println!("'{}'", basename("foo", '/'));    // outputs 'foo'
println!("'{}'", basename("bob/", '/'));   // outputs ''
println!("'{}'", basename("/usr/local/bin/rustc", '/')); // outputs 'rustc'

I think the split() into a match on last() is kind of elegant.
I know there is some work needed to handle both str and String, I am not sold on the use of Cow and needing to define a lifetime for the string.

I am not sold on Cow because later on I need to extract from it.

let prog = basename(&args[0], '/').into_owned();

It feels like I am working too hard.


texts: Simple yet threadsafe file cache in java

texts:
I'm attempting to cache contents of a file to avoid frequent reads, using a very simple implementation in a single class. The file contains a list of emailids, one per line. The file changes rarely, and the cache should be updated immediately when it does. So I've checked the file's timestamp in each read operation. The class will be used in servlets and rest apis - as member variable. Although I've synchronized the only public method of the class, I'm not sure whether the code is threadsafe. Do I need to add/change something here to ensure thread safety ?

public class CachedFile {

    private File file ;
    private long lastModified ;
    private List<String> fileLines ;
    private boolean fileCached ;

    public CachedFile( final String inputFileName )
    {
            file = new File( inputFileName ) ;
            fileCached = false ;
    }

    public synchronized List<String> getLines() throws IOException
    {
            //if file is not cached or if its modified after the last read, read & cache it
            if( fileCached == false || fileModifiedAfterLastRead() )
            {
                    readFile() ;
            }

            return fileLines ;
    }

    private void readFile() throws IOException
    {
            //read file to cache
            fileLines = FileUtils.readLines( file ) ;

            //cache the last modified time
            lastModified = file.lastModified() ;

            //set the cached flag to true
            fileCached = true ;
    }

    private boolean fileModifiedAfterLastRead()
    {
            return( file.lastModified() > lastModified ) ;
    }
}


texts:
Can someone help me make this code more professional?  I'm trying my best to find something similar, but I wasn't successful.

I want to avoid the repeat of the code for every single value and also I can't find a solution to avoid select. I only get it run when I repeat the code and count rng, rng1, rng2 etc.

Sub a()
    Dim cell As Range, i As Integer, wks As Worksheet
    Dim rng As Range
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range

    Set Bereich = Sheets("Tabelle1").Range("B2:B" & Cells(Rows.Count, 1).End(xlUp).Row)

                For Each cell In Bereich
                    If cell.Value = "EURUSD" Then
                        If Not rng Is Nothing Then
                        Set rng = Union(rng, Rows(cell.Row))
                        Else
                        Set rng = Rows(cell.Row)
                        End If
                    End If
                Next cell

                rng.EntireRow.Select
                With Selection
                ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
                Sheets(ActiveSheet.Name).Name = "EURUSD"
                rng.EntireRow.Copy Worksheets("EURUSD").Cells(5, 1)
                End With

'--------------------------------------------------------------------------------
            Sheets("Tabelle1").Select
                For Each cell In Bereich
                    If cell.Value = "GBPUSD" Then
                        If Not rng1 Is Nothing Then
                        Set rng1 = Union(rng1, Rows(cell.Row))
                        Else
                        Set rng1 = Rows(cell.Row)
                        End If
                    End If
                Next cell

                rng1.EntireRow.Select
                With Selection
                ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
                Sheets(ActiveSheet.Name).Name = "GBPUSD"
                rng1.EntireRow.Copy Worksheets("GBPUSD").Cells(5, 1)
                End With

'--------------------------------------------------------------------------------
            Sheets("Tabelle1").Select
                For Each cell In Bereich
                    If cell.Value = "AUDUSD" Then
                        If Not rng2 Is Nothing Then
                        Set rng2 = Union(rng2, Rows(cell.Row))
                        Else
                        Set rng2 = Rows(cell.Row)
                        End If
                    End If
                Next cell

                rng1.EntireRow.Select
                With Selection
                ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
                Sheets(ActiveSheet.Name).Name = "AUDUSD"
                rng2.EntireRow.Copy Worksheets("AUDUSD").Cells(5, 1)
                End With

'--------------------------------------------------------------------------------
            Sheets("Tabelle1").Select
                For Each cell In Bereich
                    If cell.Value = "NZDUSD" Then
                        If Not rng3 Is Nothing Then
                        Set rng3 = Union(rng3, Rows(cell.Row))
                        Else
                        Set rng3 = Rows(cell.Row)
                        End If
                    End If
                Next cell

                rng1.EntireRow.Select
                With Selection
                ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
                Sheets(ActiveSheet.Name).Name = "NZDUSD"
                rng3.EntireRow.Copy Worksheets("NZDUSD").Cells(5, 1)
                End With
End Sub


texts:
This is my first program written in C++.  I chose to make this public in order to receive suggestions on further improvements and to know if I'm using any "forbidden" code.

I'm asking because I initially put a lot of gotos in the program, but later found out that using goto was "evil."  Therefore, after a lot of trial and error, I removed them all and replaced them with a couple of do-while loops. I must say using do-while makes the final code much easier to read.

Please let me know if you still see any "forbidden" code.

#include <iostream>
#include <string>

using namespace std;

int main () {

    string name, favfood, age, y_n_decision;

    do {

        cout << "welcome to my program in c++" << endl;
        cout << "Please enter your name" << endl;
        getline (cin, name);

        cout << "enter your favourite food" << endl;
        getline (cin, favfood);
        cout << "awesome! " << favfood << " is my favourite food too" << endl;

        cout << "enter your age" << endl;
        getline (cin, age);

        cout << " so your name is " << name << " and your fav food is "
        << favfood << " and your age is " << age << endl;

        cout << "please press Y to restart, or Q to quit" << endl;

        do {

            getline (cin, y_n_decision);

            if (y_n_decision == "q") {
                cout << "quitting now" << endl;
                return 0;
            }

            else if (y_n_decision == "y") {
                cout << "nice! you typed y. Exiting current loop and returning to int main() aka the beginning." << endl;
                break;
            }

            else {
                cout << "you didn't type either y or q. YOU MUST PRESS Y OR Q OR I WILL PROMPT U FOREVER!!" << endl;
            }

        } while (y_n_decision == "y" || "n");

    } while (y_n_decision == "y" || "n");

    return 0;
}

EDITED:

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;
using std::cin;

int main () {

    string name, favfood, age;
    string y_n_decision;

    while (y_n_decision != "y" || y_n_decision != "q") {
        cout << "welcome to my program in c++" << endl;
        cout << "Please enter your name" << endl;
        getline (cin, name);

        cout << "enter your favourite food" << endl;
        getline (cin, favfood);
        cout << "awesome! " << favfood << " is my favourite food too" << endl;

        cout << "enter your age" << endl;
        getline (cin, age);

        cout << " so your name is " << name << " and your fav food is "
        << favfood << " and your age is " << age << endl;

        cout << "please press y to restart, or q to quit" << endl;

        while (y_n_decision != "y" || y_n_decision != "q") {

            getline (cin, y_n_decision);

            if (y_n_decision == "q") {
                cout << "quitting now" << endl;
                return 0;
            }

            else if (y_n_decision == "y") {
                cout << "nice! you typed y. Exiting current loop and returning to int main() aka the beginning." << endl;
                break;
            }

            else {
                cout << "you didn't type either y or q. YOU MUST PRESS y OR q OR I WILL PROMPT U FOREVER!!" << endl;
            }
        }

    }
    return 0;
}


texts:
For full disclosure: this is an assignment for my programming class and I just want tips or advice on some of the code.

Assignment details just for background information purposes:

  Write a program that will read a number 1-100 from the user, and the
  name of a data file, and will tell the user what word is in the file
  and how many times the numbers shows up in the data file. Validate
  input number (keep asking until valid) and validate the file was
  successfully open.

  text file contents: Darling 10 20 21 19 20

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>  // Needed for exit()
using namespace std;

int main()
{
    ifstream inputFile;
    string fileName;
    int value;

    cout << "Enter the file name: ";
    getline(cin, fileName);

    // Open the file
    inputFile.open(fileName.c_str());

    // Check for successful opening
    if(inputFile.fail())
    {
       cerr << "Error Opening File" << endl;
       exit(1);
    }

    cout << "\nThe file has been successfully opened for reading.\n";

    cout << "Pick a number between 1 through 100. ";
    cin >> value;

    if (value >= 1 && value <= 100)
    {
     cout << value << " is in the acceptable range.\n";
    }
    else
    {
     cout << "Please enter a number from 1 to 100. ";
     cin >> value;
    }

    string word;
    int number;
    int count = 0;

    infile >> number;

    // Read a file until you've reached the end
    while (!inputFile.eof())
    {
        if (number == x)
        {
            sum1++
        }
        infile >> number;
    }
    cout << sum1;

    while (!inputFile.eof())
    {
       inputFile >> word;
        if (word == "input")
        {
            count++;
        }
    }

    // Close the file
    inputFile.close();
    return 0;
}

Any tips or advice would be greatly appreciated since I'm lost when it comes to the fstream portion of this assignment right now.

UPDATED

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>  // Needed for exit()
using namespace std;

int main()
{
    ifstream inputFile;
    string fileName;
    int value, x;

    cout << "Enter the file name: ";
    getline(cin, fileName);

    // Open the file
    inputFile.open(fileName.c_str());

    // Check for successful opening
    if(inputFile.fail())
    {
       cerr << "Error Opening File" << endl;
       return(1);
    }

    cout << "Pick a number between 1 through 100. ";
    cin >> value;

    do
{
    cout << "Pick a number between 1 through 100. ";
    int value;
    cin >> value;

} while (value < 1 || value > 100);

    string word;
    int number;
    int count = 0;

    infile >> number;

    // Read a file until you've reached the end
    while (!inputFile.eof())
    {
        if (number == x)
        {
            sum1++
        }
        inputFile >> number;
    }
    cout << sum1;

    while (!inputFile.eof())
    {
       inputFile >> word;
        if (word == "input")
        {
            count++;
        }
    }

    // Close the file
    inputFile.close();
    return 0;
}


texts: Code that prints ASCII bowties to screen given inputs

texts:
The goal of this program is to take an input from Stdin and output some ASCII bowties to Stdout. The first integer in the input represents the number of test cases. Each test case contains 2 ints and a char. The first int represents the length in rows of the bowties, the second int the number of bowties, and the third the character to make the bowtie out of.

Input:

2
5 2 #
11 1 !

Output:

#      # #      #
##    ## ##    ##
# #[]# # # #[]# #
##    ## ##    ##
#      # #      #

!            !
!!          !!
! !        ! !
!  !      !  !
!   !    !   !
!    ![]!    !
!   !    !   !
!  !      !  !
! !        ! !
!!          !!
!            !

This program calculates the internal and external spaces and concatenates them plus the material for the bowtie together for the first half. The second half of the bowties are achieved by copying the first half (I couldn't figure out the absolute value function).

I'm a self-taught Java programmer so I don't know much about conventions on when to use void versus return methods and how to structure my code.

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        int sets, width, bowties, length, intspaces, extspaces, mid, counter;
        char mat;

        sets = in.nextInt();
        for(int i = 1; i <= sets; i++)
        {
            length = in.nextInt();
            bowties = in.nextInt();
            mat = in.next().charAt(0);
            width = length + 3;
            mid = length/2 + 1;
            counter = 2;
            String[] out = new String[length];

            for(int x = 0; x < mid; x++)
            {
                if(x == 0)
                {
                  intspaces = width - 2;
                  String intspace = space(intspaces, length);
                  out[x] = mat + intspace + mat;
                }
                else if(x != (mid-1))
                {
                  intspaces = width - 2 * (x + 1);
                  extspaces = x - 1;
                  String intspace = space(intspaces, length);
                  String extspace = space(extspaces, length);
                  out[x] = mat + extspace + mat + intspace + mat + extspace + mat;
                }
                else
                {
                  extspaces = x - 1;
                  String extspace = space(extspaces, length);
                  out[x] = mat + extspace + mat + "[]" + mat + extspace + mat;
                }
            }

            for(int x = mid; x < length; x++)
            {
              int count = x - counter;
              out[x] = out[count];
              counter += 2;
            }

            if(bowties != 1)
            {
            stringMulti(out, length, width, bowties);
            }

            for(int x = 0; x < length; x++)
            {
              System.out.println(out[x]);
            }
            System.out.println();

        }
    }
    public static String space(int spaces, int length)
    {
        StringBuilder sb = new StringBuilder(length - 2);
        for(int i = 1; i <= spaces; i++)
        {
            sb.append(" ");
        }
        return sb.toString();
    }

    public static void stringMulti(String out[], int length, int width, int sets)
    {
      for(int x = 0; x < length; x++)
      {
        StringBuilder sb = new StringBuilder(width + sets * (width + 1));
        sb.append(out[x]);
        for(int y = 1; y < sets; y++)
        {
       sb.append(" ");
       sb.append(out[x]);
        }
        out[x] = sb.toString();
      }

    }
}


texts: Performance of Median routine using min performs abysmally

texts:
I am writing a routine to calculate median using the minimum of the numbers and then changing the value of the minimum to a large value outside the range of numbers (assuming you know the nature of the numbers).  I know I could use many other proven techniques, but have chosen to play around with this one.

I don't see why the performance is poor. There are 3 loops, however, only two are nested at any one time.  There is no sorting involved, only finding the first occurrence of a minimum and making the new value outside the range.  If it finds the same number a second time, it ignores the number until the next iteration.  It iterates for half of the total series before the median is found.  It works dandy except for the speed.

How do I improve the efficiency of this code?

float trashMin(float array[], unsigned int length, float median){
    //what we want to do in this routine is find the lowest in the array
    //we then make the lowest number, the same as the highest possible number and
    //after iteratively going through the array 1/2 of the full length we will find the median

    unsigned int halflength = (length / 2) + 1;
    unsigned int i = 0;
    unsigned int j = 0;
    unsigned int k = 0;
    float highNumber = 999.0;//this is an arbitrary number, well outside of range of the number series
    float median = 0;

    for (i = 0; i < halflength; ++i)
    {
        float lowestInArray = array[0];
        bool firstTime = true;// is it the first time we see this number

        for (j = 0; j < length; ++j)
        {// find the lowest and highest number in the array
            float comparitor = array[j];
            lowestInArray = (lowestInArray < comparitor) ? lowestInArray : comparitor;
        }//end j

        // now that we know which is the smallest number, eliminate only 1st occurance of it
        for (k = 0; k < length; ++k)
        {
            float comparitor = array[k];
            if (comparitor == lowestInArray && firstTime == true)
            {
                array[k] = highNumber;
                firstTime = false;
            }
        }//end k
        median = lowestInArray;
    }//end i
    return median;
}


texts: Use Python to determine the repeating pattern in a string

texts:
I am writing an algorithm to count the number of times a substring repeats itself. The string is between 1-200 characters ranging from letters a-z. There should be no left overs at the end of the pattern either and it should be split into the smallest possible combination.

answer("abcabcabcabc"):output = 4
answer("abccbaabccba"): output = 2
answer("abcabcd"): output = 1

My code:

import re
def answer(s):
    length = len(s)
    x=[]
    reg = ""
    for i in range(1, length+1):
        if length % i == 0:
            x.append(i)
    repeat = len(x)*10
    for _ in range(0, repeat):
        a = length/max(x)
        print(length)
        print(max(x))
        print(a)
        for _ in range(0, a):
            reg = reg + "."
        exp = re.findall(reg, s)
        print exp
        if all(check==exp[0] for check in exp):
            print len(exp)
            return len(exp)
        elif all(check!=exp[0] for check in exp):
            x.remove(max(x))

This is Python 2.7 code and I don't have to use regex. It just seemed like the easiest way.

Is there a better/faster/more optimal way to do this?

NOTE: it breaks if the string size is too big.

EDIT: Fixed indentation


texts:
I have an image upload script that uploads images to the server:

<?php
define("UPLOAD_DIR", "uploads/");

$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
    header('Location: edit.php');
    exit();
}

if (!empty($_FILES["myFile"])) {
    $myFile = $_FILES["myFile"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "
An error occurred.
";
        exit;
    }

    // ensure a safe filename
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // don't overwrite an existing file
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // preserve file from temporary directory
    $success = move_uploaded_file($myFile["tmp_name"],
        UPLOAD_DIR . $name);
    if (!$success) {
        echo "
Unable to save file.
";
        exit;
    }

    // set proper permissions on the new file
    chmod(UPLOAD_DIR . $name, 0644);
}

Is it safe? Are there any good tips to protect myself against attacks via the image upload?

Here's my markup, if that counts:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" id="file" capture="camera" accept="image/*">

<input type="submit" name="submit" value="Submit">
</form>


texts: Forward values from JSON file as class attributes

texts:
I have a settings file, which is loaded in once and takes the values from the settings json file and uses them as the attribute values. I was thinking of using the @property instead of overriding __getattribute__ but I feel as if there is a better, more elegant solution. Note that the application it is used in is multi-threaded.

settings.py

class SettingsMeta(type, JsonFileWrapperBase):
    _file_path = os.path.join(os.getcwd(), "..", "data", "settings.json")

    # Declarations to avoid PyCharm highlighting
    manga_save_dir, database_path, total_scrapper_threads, log_file = None, None, None, None

    _default_data = {
        "manga_save_dir": r"D:\dir",
        "database_path": r"D:\db.sqlite3",
        "log_file": os.path.join(os.getcwd(), "..", "data", "log.log"),

        "total_scrapper_threads": 1
    }

    @classmethod
    def __getattribute__(mcs, item):
        data = mcs._get_data()

        if item in data:
            return data[item]

        elif hasattr(mcs, item):
            return getattr(mcs, item)

        raise AttributeError(f"Settings has no attribute {item}")

class Settings(metaclass=SettingsMeta):
    pass

json_file_wrapper_base.py

class JsonFileWrapperBase:
    _loaded_data = None

    _file_path = ""
    _default_data = ""

    @classmethod
    def _write_default(cls):
        cls._write_data(cls._default_data)

    @classmethod
    def _write_data(cls, d):
        os.makedirs(os.path.dirname(os.path.abspath(cls._file_path)), exist_ok=True)

        try:
            with open(cls._file_path, "w") as f:
                json.dump(d, f)

        except FileNotFoundError as e:
            print(e)

    @classmethod
    def _get_data(cls):
        """
        Reads and caches the JSON file, if the file has already been cached then return the cached file, I cache
        the file to avoid users editing the file during execution and causing errors
        """

        # File has not been cached yet
        if cls._loaded_data is None:
            cls._read_file()

        return cls._loaded_data

    @classmethod
    def _read_file(cls) -> bool:
        assert cls._loaded_data is None, "_read_file should only be called once per object"

        # File doesn't exist or is not valid
        if not os.path.isfile(cls._file_path):
            cls._write_default()

        try:
            with open(cls._file_path, "r") as f:
                data = json.load(f)

                print(f"Log: Loaded {cls._file_path}")

                cls._loaded_data = data

        except FileNotFoundError as e:
            print(e)

            return False

        return True


texts: Pattern matching in an array or collection

texts:
If I had an array of integers like

+--------------------------------------------+
| 1| 0| 1| 2| 0| 1| 0| 1| 0|-1| 0| 2| 0|-2| 0|  > VALUES
+--------------------------------------------+
| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|13|14|  > INDEX
+--------------------------------------------+

I am looking for 0 which occurs 7 times in the array above.

But I need to find indexes of 0s in the array like so:

I can find 0's that occur only after a slot with a Abs(value) > 1
(rising of falling)
I can find 0's that occur only after a slot with a value > 1
(rising)
I can find 0's that occur only after slot with a negative Abs(value)

  1 (falling)

So, looking at array above my logic should show indexes

1, 4, 12, 14 - 1st and REST (rising or falling)
1, 4, 12     - 1st and RISING
1, 14        - 1st and FALLING

The indexes above are valid since the previous value was (Abs(previous) > 1). On the other hand, 0's at index 6, 8, and 10 are of no interest since the previous array value was either 1 or -1 (so Abs(previous) <= 1)

My code below works but I feel there could be a simpler more elegant solution to this

public static void Main(string[] args)
{
    int[] array = new int[15] { 1, 0, 1, 2, 0, 1, 0, 1, 0, -1, 0, 2, 0, -2, 0 };

    bool found1 = true;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == 0)
        {
            if (found1)
            {
                Console.WriteLine(i); //print 1st index of 0
                found1 = false;
            }
            else
            {
                if (Math.Abs(array[i - 1] - array[i]) > 1)
                {
                    Console.WriteLine("All: " + i);  // print every other that fits
                    //1, 4, 12, 14
                }
            }
        }
    }

    found1 = true;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == 0)
        {
            if (found1)
            {
                Console.WriteLine(i); //print 1st index of 0
                found1 = false;
            }
            else
            {
                if (Math.Abs(array[i - 1] - array[i]) > 1
                    && (array[i - 1] - array[i]) > 1)
                {
                    Console.WriteLine("Up: " + i);  // print rising
                                                    //1, 4, 12
                }
            }
        }
    }

    found1 = true;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == 0)
        {
            if (found1)
            {
                Console.WriteLine(i); //print 1st index of 0
                found1 = false;
            }
            else
            {
                if (Math.Abs(array[i - 1] - array[i]) > 1
                    && (array[i - 1] - array[i]) < 1)
                {
                    Console.WriteLine("Down: " + i);  // print falling
                                                      //1, 14
                }
            }
        }
    }

    Console.ReadLine();
}


texts:
I've recently made a test. There were four tasks. One of them was to improve following code:

public class FooFileProcessor
{
    public void ProcessFile(string filename)
    {
       Stream fileStream = File.OpenRead(filename);
       Console.WriteLine(ReadAllContent(fileStream));
       fileStream.Close();
    }

    public string ReadAllContent(Stream stream)
    {
       StreamReader streamReader = new StreamReader(stream);
       return streamReader.ReadToEnd();
    }
}

What I've suggested:

try
{
    using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
       String line = sr.ReadToEnd();
       Console.WriteLine(line);
    }
}
catch (Exception e)
{
   Console.WriteLine("The file could not be read:");
   Console.WriteLine(e.Message);
}

please, review my code and show all mistakes you've seen.


texts:
Description:

Write a method mergeMeetings() that takes a list of multiple meeting time ranges and returns a list of condensed ranges. The integers represent the number of 30-minute blocks past 9:00am.
Do not assume the meetings are in order. The meeting times are coming from multiple teams.

Code:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

class Meeting {
  int startTime;
  int endTime;

  Meeting(int startTime, int endTime) {
    this.startTime = startTime;
    this.endTime = endTime;
  }

  public String toString() {
    return startTime + " : " + endTime;
  }
}

class Main {
  static List<Meeting> mergeMeetings(List<Meeting> meetings) {
    for (int outer = 0; outer < meetings.size(); outer++) {
      Meeting outerMeeting = meetings.get(outer);

      for (int inner = 0; inner < meetings.size(); inner++) {
        Meeting innerMeeting = meetings.get(inner);

        if (overlaps(outerMeeting, innerMeeting)) {
          meetings.set(outer, merge(outerMeeting, innerMeeting));
          meetings.remove(inner);
          break;
        }
      }
    }
    return meetings;
  }

  static List<Meeting> mergeMeetings2(List<Meeting> meetings) {
    List<Meeting> merged = new ArrayList<>();

    Collections.sort(meetings, (a, b) -> a.startTime - b.startTime);

    for (Meeting current : meetings) {
      if (merged.isEmpty()) {
        merged.add(current);
        continue;
      }
      Meeting lastMerged = merged.get(merged.size() - 1);
      if (overlaps(lastMerged, current)) {
        lastMerged.endTime = current.endTime;
      } else {
        merged.add(current);
      }
    }
    return merged;
  }

  private static Meeting merge(Meeting first, Meeting second) {
    return new Meeting(first.startTime, second.endTime);
  }

  private static boolean overlaps(Meeting first, Meeting second) {
    return first.startTime < second.startTime &&
      (first.endTime == second.startTime || second.startTime < first.endTime);
  }

  static void show(List<Meeting> meetings) {
    for (Meeting meeting : meetings) {
      System.out.print(meeting + ", ");
    }
    System.out.println();
  }

  public static void main(String[] args) {
    show(mergeMeetings(new ArrayList(Arrays.asList(
      new Meeting(0, 1),
      new Meeting(3, 5),
      new Meeting(4, 8),
      new Meeting(10, 12),
      new Meeting(9, 10)
    )))); // 0 1, 3 8, 9 12

    show(mergeMeetings2(new ArrayList(Arrays.asList(
      new Meeting(0, 1),
      new Meeting(3, 5),
      new Meeting(4, 8),
      new Meeting(10, 12),
      new Meeting(9, 10)
    )))); // 0 1, 3 8, 9 12

    show(mergeMeetings(new ArrayList(Arrays.asList(
      new Meeting(1, 4),
      new Meeting(4, 5)
    )))); // 1 5

    show(mergeMeetings2(new ArrayList(Arrays.asList(
      new Meeting(1, 4),
      new Meeting(4, 5)
    )))); // 1 5

    show(mergeMeetings(new ArrayList(Arrays.asList(
      new Meeting(1, 3),
      new Meeting(2, 6),
      new Meeting(8, 10),
      new Meeting(15, 18)
    )))); // 1 6, 8 10, 15 18

    show(mergeMeetings2(new ArrayList(Arrays.asList(
      new Meeting(1, 3),
      new Meeting(2, 6),
      new Meeting(8, 10),
      new Meeting(15, 18)
    )))); // 1 6, 8 10, 15 18
  }
}

Note:
The brute force solution is intentional and I am practicing it to at least
come up with the brute force answer if not able to find the optimal solution. I am learning to quickly find little abstractions to help me think about the solution more easily for eg: the two helper methods overlaps and merge helped me to find the solution easily.
Questions:
Apart from general code review I would like to know more tips / recommendations on coming up with brute force solutions quickly.


texts:
I'm currently working on a small project that uses Java to handle a socket-based MMO browser game. I'm still at the beginning of the project and I'm currently writing a class that logs errors and debug messages to the console and writes these to the appropriate file, based on the error.

I'm wondering if this code is clean, efficient, readable, and amendable in any way shape or form.

package nl.finicky.lemonade.core;
import nl.finicky.lemonade.Lemonade;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Console {
    public static final String ANSI_RESET = "\u001B[0m";
    public static final String ANSI_BRIGHT = "\u001B[1m";
    public static final String ANSI_BLACK = "\u001B[30m";
    public static final String ANSI_RED = "\u001B[31m";
    public static final String ANSI_GREEN = "\u001B[32m";
    public static final String ANSI_YELLOW = "\u001B[33m";
    public static final String ANSI_BLUE = "\u001B[34m";
    public static final String ANSI_PURPLE = "\u001B[35m";
    public static final String ANSI_CYAN = "\u001B[36m";
    public static final String ANSI_WHITE = "\u001B[37m";
    private static File debug = new File("logs//debug.txt");
    private static File packets = new File("logs//packets.txt");
    private static File errors = new File("logs//errors.txt");

    private static PrintWriter debugWriter;
    private static PrintWriter packetWriter;
    private static PrintWriter errorWriter;

    public Console() {
        try {
            if (!debug.exists()) {
                debug.createNewFile();
            }

            if (!packets.exists()) {
                packets.createNewFile();
            }

            if (!errors.exists()) {
                errors.createNewFile();
            }

            debugWriter = new PrintWriter(new FileWriter(debug));
            packetWriter = new PrintWriter(new FileWriter(packets));
            errorWriter = new PrintWriter(new FileWriter(errors));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void start(Object message) {
        if (Lemonade.getConfiguration().getBool("logging.debug")) {
            debugWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        }

        System.out.println(ANSI_GREEN + ANSI_BRIGHT + "[START] " + message.toString() + ANSI_RESET);
    }
    public void user(Object message) {
        if (Lemonade.getConfiguration().getBool("logging.debug")) {
            debugWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        }

        System.out.println(ANSI_BLUE + "[USER] " + message.toString() + ANSI_RESET);
    }

    public void shutdown(Object message) {
        if (Lemonade.getConfiguration().getBool("logging.debug")) {
            debugWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        }
        System.out.println(ANSI_YELLOW + ANSI_BRIGHT + "[SHUTDOWN] " + message.toString() + ANSI_RESET);
    }

    public synchronized void error(Object message) {
        errorWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        System.out.println(ANSI_RED + "[ERROR] " + message.toString() + ANSI_RESET);
    }

    public synchronized void critical(Object message) {
        errorWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        System.out.println(ANSI_RED + "[ERROR] " + message.toString() + ANSI_RESET);
    }

    public synchronized void debug(Object message) {
        if (Lemonade.getConfiguration().getBool("logging.debug")) {
            debugWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        }

        System.out.println(ANSI_PURPLE + "[DEBUG] " + message.toString() + ANSI_RESET);
    }

    public synchronized void packet(Object message)
    {
        System.out.println(ANSI_BLUE + "[PACKET] " + message.toString() + ANSI_RESET);

        if(Lemonade.getConfiguration().getBool("logging.packets"))
        {
            packetWriter.write(Lemonade.getDate() + message.toString() + "\r\n");
        }
    }
}


texts:
I'm attempting to backup lots of website using this php code. The script basically goes through the whole public_html directory and adds all the folders and files recursively and zips them.

Here's what I've got so far:

if (!file_exists('/home/sites/'.$_SERVER['SERVER_NAME'].'/cbitsbackup/')) {
mkdir('/home/sites/'.$_SERVER['SERVER_NAME'].'/cbitsbackup/', 0777, true);
}
$filefront = '/home/sites/'.$_SERVER['SERVER_NAME'].'/cbitsbackup/backup-'.$_SERVER['SERVER_NAME'].'-day1';
$fileend = '.zip';
$time = time();

if(file_exists($filefront.$fileend)){
$file = $filefront.'-'.$time.$fileend;}
else{$file = $filefront.$fileend;};
zip_directory('/home/sites/'.$_SERVER['SERVER_NAME'].'/public_html',$file);

function zip_directory($source,$tempfile){
if(!extension_loaded('zip') || !file_exists($source)) return false;
$zip = new ZipArchive();
if(!$zip->open($tempfile,ZIPARCHIVE::CREATE)) return false;
$source = str_replace('\\','/',realpath($source));
if(is_dir($source) === true){
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
    foreach($files as $file){
        $file = str_replace('\\', '/', realpath($file));
        if(is_dir($file) === true) $zip->addEmptyDir(str_replace($source . '/','', $file . '/'));
        else if(is_file($file) === true) $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));}}
elseif(is_file($source) === true) $zip->addFromString(basename($source), file_get_contents($source));
return $zip->close();}

The main problem at the moment is memory constraints (64M) because I'm running on a shared hosting platform. As far as I can see, the zip file is stored in memory until it is 'completed'. This is problem because I have a lot of websites which are much over this size. Is there anyway to write the zip file progressively to disk so my script isn't killed by the system? Could I even write this in Perl to get around this limit?