texts: Iterate dictionary object efficiently in c# with pre defined keys?

texts:
I have a dictionary that I need to iterate efficiently. I already know about the keys beforehand which I need to extract from values dictionary object.
What's the best way to do that? I have around 20 entries in dictionary object as of now.

Below is how I am doing it but wanted to see if we can optimize it by just getting values of key directly since I already know about what key I need to extract from them instead of using foreach loop here which is not good in terms of performance?

  // predefined keys
  public const string ABC = "header-abc";
  public const string PQR = "header-pqr";
  public const string DEF = "header-def";
  public const string HIP = "header-hip";

  foreach (KeyValuePair<string, StringValues> v in values)
  {
      string key = v.Key;
      StringValues val = v.Value;
      if (val.Count > 0)
      {
          if (!string.IsNullOrWhiteSpace(val[0]))
          {
              switch (key)
              {
                  case ABC:
                      HeadOne = val[0];
                      HeadOneId = HeadOne;
                      break;
                  case PQR:
                      HeadTwo = val[0];
                      HeadTwoId = HeadTwo;
                      break;
                  case DEF:
                      HeadThree = val[0];
                      HeadThreeId = HeadThree;
                      break;
                  case HIP:
                      HeadFour = val[0];
                      HeadFourId = HeadFour;
                      break;
                  //.. bunch of other case block here with similar stuff
              }
          }
      }
  }

As of now it looks redundant to iterate values dictionary object since I already know about all my keys that I need to extract from values dictionary object. What's the best way (in terms of performance) to do this considering keys are already known beforehand?

One option I can think of is instead of foreach loop here can we use keys property of iterating dictionary?


texts:
I have to write an API for checked subtraction where the input minuend can be < 0 but subtrahend can't be < 0. I think I've covered all the cases of underflow and overflow. With given conditions the range of subtrahend is [Long.MIN_VALUE, Long.MAX_VALUE] and of minuend is [0, Long.MAX_VALUE]; with these limits overflow is not possible and underflow can happen if subtrahend > minuend and in that case setting Long.MIN_VALUE as the minimum possible difference seems legit.

public static long checkedSubtract(final long minuend, final long subtrahend) {
    Preconditions.checkArgument(subtrahend >= 0, "Subtrahend must be >= 0");

    long difference;
    try {
        difference = LongMath.checkedSubtract(minuend, subtrahend);
    } catch (ArithmeticException e) {
        // With the precondition of subtrahend >= 0, this operation can not
        // overflow and if it underflows, return minimum possible difference
        difference = Long.MIN_VALUE;
    }
    return difference;
}

I'd appreciate it if someone could affirm my logic and/or point out any mistake.


texts:
I am new to coding for ~1 week. I know that I learn best by doing, and so I decided to work on a small and simple project while utilizing various online sources to learn as I go.
Anyway, I decided to write a little program that asks the user to input their age and then prompts the user to enter an age they wish to be while providing them with the difference and a few little exceptions along the way.
Since I am still new and am learning on my own, I decided to reach out to this forum and see if I can get any suggestive feedback on how I can improve my code and learn some new techniques. Thank you!
Points of interest:

I have it so the code loops back until integers are inputted.

The program can be recalled by the user to enter different values.

I am still working on making it so that negative values can not be inputted.

The Code:
# This program will prompt you to state your age and then will proceed to
# calculate how long till __ age

# Introduction
print("Hello. ")

# Defining Functions
def main():
    while True:
        try:
            myAge = int(input("Please enter your age: "))
        except ValueError:
            print("I'm sorry, please enter your age as a numeric value.")
            continue
        else:
            break

    def secondV():
        while True:
            try:
                global desiredAge
                desiredAge = int(input())
                print("Do you wish to be " + str(desiredAge) + "?")
                choose()
            except ValueError:
                print("Please enter a numeric value.")
                continue
            else:
                break

    def desiredFuture():
        while True:
            try:
                global desiredAge
                desiredAge = int(input())
                while True:
                    if desiredAge < myAge:
                        print(
                            "Silly, time does not move backwards. Learn how to embrace the future, not fear it.")
                        print('Please input an age you wish to be in the FUTURE now...')
                        desiredFuture()
                        break
                    if desiredAge == myAge:
                        print("You are already " + str(desiredAge))
                        break
                    else:
                        print("Do you wish to be " + str(desiredAge) + "?")
                        choose()
                        break
            except ValueError:
                print("Please enter a numeric value.")
                continue
            else:
                break

    def choose():
        global yourWish
        yourWish = input()
        while yourWish.lower() == ("yes" or "y"):
            print("Okay... calculating...")
            import time
            time.sleep(1)
            print()
            print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
            print()
            reDo()
            break
        else:
            print("Erm... please input your desired age now:")
            secondV()

    def reDo():
        print('Would you like to try again?')
        runBack = input()
        while True:
            if runBack.lower() in {'y', 'yes'}:
                print()
                main()
            else:
                print("Okay... Goodbye!")
                break

    print("You are " + str(myAge) + ".")
    print("What is your desired age? ")
    desiredFuture()
    choose()
    print()

main()


texts: Flatten a nested dict structure in Python

texts:
For some post-processing, I need to flatten a structure like this

{'foo': {
          'cat': {'name': 'Hodor',  'age': 7},
          'dog': {'name': 'Mordor', 'age': 5}},
 'bar': { 'rat': {'name': 'Izidor', 'age': 3}}
}

Each bottom entries will appear as a row on the output. The heading keys will appear each row, flattened. Perhaps an example is better than my mediocre explanation:

[{'age': 5, 'animal': 'dog', 'foobar': 'foo', 'name': 'Mordor'},
 {'age': 7, 'animal': 'cat', 'foobar': 'foo', 'name': 'Hodor'},
 {'age': 3, 'animal': 'rat', 'foobar': 'bar', 'name': 'Izidor'}]

I first wrote this function:

def flatten(data, primary_keys):
    out = []
    keys = copy.copy(primary_keys)
    keys.reverse()
    def visit(node, primary_values, prim):
        if len(prim):
            p = prim.pop()
            for key, child in node.iteritems():
                primary_values[p] = key
                visit(child, primary_values, copy.copy(prim))
        else:
            new = copy.copy(node)
            new.update(primary_values)
            out.append(new)
    visit(data, { }, keys)
    return out

out = flatten(a, ['foobar', 'animal'])

I was not really satisfied because I have to use copy.copy to protect my input arguments. Obviously, when using flatten one does not want its input data to be altered.

So I thought about one alternative that uses more global variables (at least global to flatten) and uses an index instead of directly passing primary_keys to visit. However, this does not really help me to get rid of the ugly initial copy:

keys = copy.copy(primary_keys)
keys.reverse()

So here is my final version:

def flatten(data, keys):
    data = copy.copy(data)
    keys = copy.copy(keys)
    keys.reverse()
    out = []
    values = {}
    def visit(node, id):
        if id:
            id -= 1
            for key, child in node.iteritems():
               values[keys[id]] = key
               visit(child, id)
        else:
            node.update(values)
            out.append(node)
    visit(data, len(keys))
    return out

I am sure some Python magic will help in this case.


texts: File shredding (secure deletion) algorithm

texts:
Does anyone see anything wrong with this? I was considering using something like srm or wipe and use os.system to call it from Python code. Should I do that?

My main concern is drives and filesystems that use wear leveling. But even if the program overwrites a portion of the file that should render it useless right? And with the file renamed, there should be no way to tell what the file was.

import random
import os

def wipe(f, passes=30):
    if not os.path.isfile(f):
        return "Could not find the specified file!"
    with open(f, "ba+") as f2w:
        size = f2w.tell()
        for i in range(passes):
            f2w.seek(0)

            f2w.write(os.urandom(size))
    new_name = str(random.randint(1000,1000000000000))
    os.rename(f, new_name)
    os.remove(new_name)
    return "Success!"


texts: Unwrapping optional properties from an optional array of objects

texts:
I'm currently working with an SDK where methods return an optional array of objects with optional properties.  Only the array itself is optional, it will either be nil or always contain non-optionals.  I'm struggling to find a cleaner way to unwrap optional properties for each non-optional in the array:

class Person {
    var id: String?
}

func someOptionalArrayOfPeople() -> [Person]? {
    // returns either nil or some array of Person objects
}

let people = someOptionalArrayOfPeople()

if let unwrappedPeople = people {

    // 1
    for person in unwrappedPeople {
        if let id = person.id {
            print(id) // too many nested statements
        }
    }

    // 2
    for person in unwrappedPeople where person.id != nil {
        print(person.id!) // stil force unwrapping
    }
}

For option 1, I'm not thrilled about unwrapping the initial optional array, and I feel that there should be a way to skip the unwrapping of the id.  Option 2 attempts to do that with a where clause, but the compiler isn't smart enough to determine that person.id is non-nil even if we explicitly check that id != nil.

What are my "Swifty" options for unwrapping optional properties on an optional array of objects?  I am using Swift 2.2 with Xcode 7.3.1.


texts: Input/output for a simple Brainfuck interpreter

texts:
The following code comes from a simple Brainfuck interpreter I'm working on to learn the Rust language. Error handling is omitted for simplicity. It is tested on rustc version 1.1.0-dev (af522079a 2015-05-14) (built 2015-05-14).

The code implements just the input and output routines for the interpreter. The read_cell method reads a single byte from the Read object input and stores it in the memory cell at pointer. write_cell writes the byte a the memory cell at pointer to the Write object output.

use std::io::Read;
use std::io::Write;

pub struct Machine<In, Out> {
    pub memory: Vec<u8>,
    pub pointer: usize,
    input: In,
    output: Out,
}

impl<In: Read, Out: Write> Machine<In, Out> {
    pub fn new(input: In, output: Out) -> Machine<In, Out> {
        Machine {
            memory: vec![0; 2],
            pointer: 0,
            input: input,
            output: output
        }
    }

    pub fn read_cell(&mut self) {
        self.input.read(&mut self.memory[self.pointer..self.pointer+1]).unwrap();
    }

    pub fn write_cell(&mut self) {
        self.output.write(&self.memory[self.pointer..self.pointer+1]).unwrap();
    }
}

#[cfg(test)]
mod test {

    use super::*;

    #[test]
    fn test_write_cell() {
        let input = "".as_bytes();
        let mut output = vec![];
        {
            let mut machine = Machine::new(input, &mut output);
            machine.memory[machine.pointer] = 1;
            machine.write_cell();
        }
        assert_eq!(vec![1], output);
    }
}

There are two main points in the code that are concerning me:

I cannot find in the standard library API an obvious method to read or write a single byte. There is a better/clearer way to implement the read_cell and write_cell methods?
In the test function test_write_cell I had to declare machine inside a nested scope. If it is declared in the same scope of output I get this error at the assert_eq! line:

 cannot borrow `output` as immutable because it is also borrowed as mutable

Can I write the same test without having to nest scopes? Is so, how?

Any other comment, hint or advice will be very welcome!


texts: Split a data file into files for each time step

texts:
I have written a simple code to extract different time steps from a big text file. It works for small text files, but not for bigger text files as input.

n=0
y=[]
with open ("DEPTH.dat", "r") as input:
    for x in input:
        x = x.strip()
        if x.startswith('SCALAR'):
            n += 1
        with open("TS_"+ str(n) + ".dat", "a") as subfile:
                subfile.write("{0}\n".format(x))

The input file is like the following:

SCALAR
ND   5
ST  0
TS        10.00
    0.0022
    0.0022
    0.0022
    0.0020
    0.4881
SCALAR
ND   5
ST  0
TS        100.00
    0.1
    0.2
    0.12
    0.32
    0.15
SCALAR
ND   5
ST  0
TS        200.00
    0.34
    0.25
    1.1
    1.0020
    1.4381

In this example file, the number of nodes ND=5 , so it works very well. But when I have 1,000,000 nodes, it does not work. It does not deliver any result even after 20 days. So I know I have to write the program as a function and return the result and not to upload the whole data into memory. I have no I idea  how to do that.


texts: Manager that collects and handles multiple tasks that run on events like window.scroll, window.resize etc

texts:
I'm working on a website where different things can occur on resize and scroll events. I only want one event handler that comes into play, whenever something in the DOM must be changed.

So I created a TaskManager where you can register objects and callbacks, that are run, when the specific event is fired.

The TaskManager is injected into other objects, where this.taskManager.registerTask() is called to send all necessary information.

The TaskManager then executes all registered tasks, as soon as an event occurs. It also sends the current scrollTop-value to the callback.

class TaskManager {
  constructor() {
    this.DOM = {
      html: document.getElementsByTagName('html')[0],
    }

    this.tasks = {
      scroll: [],
      resize: [],
    };

    window.addEventListener('scroll', event => {
      window.requestAnimationFrame(timestamp => {
        this.processTasksOnScroll();
      });
    });
  }

  registerTask(type, task) {
    if (!this.tasks[type]) {
      return false;
    }

    this.tasks[type].push(task);
    return true;
  }

  processTasksOnScroll() {
    const scrollTop = window.scrollY || window.scrollTop || this.DOM.html.scrollTop;

    for (const task of this.tasks.scroll) {
      task.target[task.callback](scrollTop);
    }
  }
}

class Test {
  constructor(config) {
    this.taskManager = config.taskManager || null;

    if (this.taskManager) {
        this.taskManager.registerTask('scroll', {target: this, callback: 'onScroll'});
    }
  }

  onScroll(scrollTop) {
    console.log('Callback in Test with scrollTop: ' + scrollTop);
  }
}

const taskManager = new TaskManager();
const test = new Test({taskManager: taskManager});
.test {
  height: 120vh;
  padding: 20px;
  background: rgba(0, 0, 0, 0.2);
  text-align: center;
}

Scroll here …

Is this a good approach or could something be improved?


texts:
I am looking for feedback for the implementation for calculating factorial of a number. I have tried to do with a loop, recursion and in a mutlithreaded way.

package org.spituk.study.programs;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Class for calculating factorial of a number.
 *
 * @author Karan Khanna
 * @version 1.0
 * @since 12/8/2018
 */
public class Factorial {

    private final static int JOB_SIZE = 10;

    private final static int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();

    /**
     * Calculates the factorial of the number with loop.
     *
     * @param number whose factorial is to be calculated.
     * @return calculated factorial of the number
     */
    public long getFactorialWithLoop(final int number) {
        long factorial = 1;
        for (int index = 2; index <= number; index++) {
            factorial = factorial * index;
        }
        return factorial;
    }

    /**
     * Calculates the factorial of the number with recursion.
     *
     * @param number whose factorial is to be calculated.
     * @return calculated factorial of the number
     */
    public long getFactorialWithRecursion(final int number) {
        return factorialRecursion(number);
    }

    /**
     * Calculates the factorial of the number with multiple threads.
     *
     * @param number whose factorial is to be calculated.
     * @return calculated factorial of the number
     */
    public long getFactorialMultiThreaded(final int number) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(AVAILABLE_PROCESSORS);
        List<PartialFactorialJob> partialFactorialJobs = new ArrayList<PartialFactorialJob>();

        int startIndex = 1;
        int pivot = JOB_SIZE;

        while(pivot <= number) {
            if(pivot + JOB_SIZE > number) {
                pivot = number;
            }
            partialFactorialJobs.add(new PartialFactorialJob(startIndex, pivot));
            startIndex = pivot + 1;
            pivot = pivot + JOB_SIZE;
        }

        try {
            long factorial = 1;
            final List<Future<Long>> futureList = executor.invokeAll(partialFactorialJobs);
            for (Future<Long> future : futureList) {
                factorial = factorial * future.get();
            }
            executor.shutdown();
            return factorial;
        } catch (InterruptedException | ExecutionException e) {
            throw new Exception("Factorial couldn't be calculated.");
        }
    }

    private long factorialRecursion(final int number) {
        if (number <= 0) {
            return 1;
        }
        return number * factorialRecursion(number - 1);
    }

    private class PartialFactorialJob implements Callable<Long> {

        private final int startIndex;
        private final int endIndex;

        PartialFactorialJob(final int startIndex, final int endIndex) {
            this.startIndex = startIndex;
            this.endIndex = endIndex;
        }

        public Long call() {
            long partialFactorial = 1;
            int temp = startIndex;
            while (temp <= endIndex) {
                partialFactorial = partialFactorial * temp;
                temp++;
            }
            return partialFactorial;
        }
    }
}


texts:
I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!
Problem

There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1,
..., k-1.

While entering a password, the last n digits entered will automatically be matched against the correct password.

For example, assuming the correct password is "345", if you type "012345", the box will open because the correct password matches the
suffix of the entered password.

Return any password of minimum length that is guaranteed to open the box at some point of entering it.

Accepted Code
#include <vector>
#include <string>

class Solution {
    int n;
    int k;
    int value;
    std::vector<std::vector<bool>> visited;
    std::string base_sequence;

public:
    std::string crackSafe(int n, int k) {
        if (k == 1) {
            return std::string(n, '0');
        }

        this->n = n;
        this->k = k;
        value = 1;

        for (int index = 0; index < n - 1; index++) {
            value *= k;
        }

        visited.resize(value, std::vector<bool>(k, false));
        depth_first_search(0);
        return base_sequence + base_sequence.substr(0, n - 1);
    }

private:
    // Depth first search the neighbor value
    void depth_first_search(int neighbor) {
        for (int index = 0; index < k; index++) {
            if (!visited[neighbor][index]) {
                visited[neighbor][index] = true;
                depth_first_search((neighbor * k + index) % value);
                base_sequence.push_back('0' + index);
            }
        }
    }
};

Reference
LeetCode has a template for answering questions. There is usually a class named Solution with one or more public functions which we are not allowed to rename.

Problem

Discuss

Bellman Ford algorithm


texts:
I was eventually going to add another computer and more options to this (i.e., Rock-paper-scissors-lizard-Spock) but I wanted to make sure I was using the best practice for this type of game. Any help would be appreciated.

# The traditional paper scissors rock game

import os
def clear():
    os.system("clear")
clear()
print ("\n\nPaper, Rock, Scissors Game -(Best of five games)")
x = 0 ;  l = 0 ;  w = 0 ; d = 0 ; lt = 0 ; wt = 0 ; dt = 0
while x < 5:
  x = x + 1
  import random
  class Computer:
         pass
  comp_is = Computer()
  comp_is.opt = ('r','p','s')
  comp_is.rand = random.choice(comp_is.opt)

  if comp_is.rand == 'r':
            comp  = 'rock'
  elif comp_is.rand == 'p':
            comp  = 'paper'
  else:
        comp  = 'scissors'

  class Human:
       pass
  human_is = Human
  print
  human_is.player = raw_input(' Enter your choice of\n   r\
 for rock\n   p for paper or\n   s for scissors ... ')
  print

  class Result:
     pass
  Result_is = Result
  if comp_is.rand == human_is.player:
    print ("draw - computer chose ",  comp)
    print
    d = d + 1
    dt = dt + 1
  elif comp_is.rand == 'r' and human_is.player == 'p':
      print ("  player beats computer -computer chose ",  comp)

      print
      w = w + 1
      wt = wt + 1
  elif comp_is.rand == 'p' and human_is.player == 's':
      print ("  computer chose ",  comp)
      print ("  player beats computer-because scissors cuts paper")
      print ()
      w = w + 1
      wt = wt + 1
  elif comp_is.rand == 's' and human_is.player == 'r':
     print (" computer chose ", comp)
     print (" player beats computer-because rock breaks scissors")
     w = w + 1
     wt = wt + 1
  else :
     print ("   computer wins - computer chose  ", comp)
     print
     l = l + 1
     lt = lt + 1

  if x == 5:
    print ()
    print ()
    print ("  games  won ... ",  w)
    print ("  games lost ... ",  l)
    print ("  games drawn ... ",  d)
    print ()
    print ("  Running total overall of games won ... ", wt)
    print ("  Running total overall of games lost ... ", lt)
    print ("  Running total overall of games drawn ... ", dt)
    print ()
    w = 0 ; l = 0 ; d = 0
    again = input('Do you want to play again y for yes, n for no ..  ')
    if again == 'y':
       x = 0
    else:
      print
      if lt > wt:
         print ("You are a miserable loser,\nYou have lost more than you have won,\nPoor show indeed ")
         print ('finish')


texts: split up a string into whitespace-seperated fields

texts:
I am trying to improve my C skills, and I hope someone might be able to provide me with some feedback on the following code. I avoid strtok function intentionally.

#define MAX_SIZE 1000
int split_up(char* string, char* argv[])
{
    char* p = string;
    int argc = 0;

    while(*p != '\0')
    {
        while(isspace(*p))
            ++p;

        if(*p != '\0')
            argv[argc++] = p;
        else
            break;

        while(*p != '\0' && !isspace(*p))
            p++;
        if(*p != '\0')
        {
            *p = '\0';
            ++p;
        }

    }

    return argc;
}

int main()
{
    char *av[MAX_SIZE];
    char string[] = "this is a test";
    //int i, ac = makeargv(string, av, 2);
    int i;
    int ac = split_up(string, av);
    printf("The number of token is: %d\n", ac);
    for(i = 0; i < ac; i++)
        printf("\"%s\"\n", av[i]);

    return 0;
}


texts:
This is a simple thread safe queue that is used in a producer-consumer model.

public class ThreadedQueue<TType>
{
    private Queue<TType> _queue;
    private object _queueLock;

    protected ThreadedQueue()
    {
        _queue = new Queue<TType>();
        _queueLock = new object();
    }

    public void Enqueue(TType data)
    {
        lock (_queueLock)
        {
            // do not allow duplicates
            if (!_queue.Contains(data))
            {
                _queue.Enqueue(data);
            }

        }
    }

    public bool TryDequeue(out TType data)
    {
        data = default(TType);
        bool success = false;
        lock (_queueLock)
        {
            if (_queue.Count > 0)
            {
                data = _queue.Dequeue();
                success = true;
            }
        }
        return success;
    }
}

Is this complete and thread safe?


texts: Return the longest word (or words) in a string

texts:
I'm coding for a function that checks the longest word (or words) in a string:

If multiple words are of the same size, those words have to be displayed.
If a single word is inputted, that word has to be displayed.
Words should consist only of alphabets.

The following code has been tested and displays the correct input for the above conditions:

    //this method returns the longest word (or words) of a single string
    static void longestWord(string s)
    {
        int j = 0, k = 0, l = 0, tempLength = 0, maxLength = 0;
        List<int> indexList = new List<int>();
        char[] words = s.ToCharArray();
        StringBuilder longestWord = new StringBuilder();

        //a for loop to ignore spaces at the beginning of the string
        for (int i = 0; i <= s.Length - 1; i++)
        {
            if (((words[i] >= 'A' && words[i] <= 'Z') || (words[i] >= 'a' && words[i] <= 'z')))
            {
                j = i;
                l = i;
                break;
            }
        }

        //a for loop to get the maximum length of the longest word
        for (; j <= s.Length - 1; j++)
        {
            if (((words[j] >= 'A' && words[j] <= 'Z') || (words[j] >= 'a' && words[j] <= 'z')))
            {
                tempLength++;

                if (j == (s.Length - 1))
                {
                    if (tempLength >= maxLength)
                    {
                        maxLength = tempLength;  //this ensures the maximum length of a single word is captured
                                                 //removing this will not display single words without non-alphabets
                    }
                }
            }
            else
            {
                if (tempLength >= maxLength)
                {
                    maxLength = tempLength;
                }
                tempLength = 0;
            }
        }

        tempLength = 0;

        //a for loop to add the longest words into a list
        for (; l <= s.Length - 1; l++)
        {
            if (((words[l] >= 'A' && words[l] <= 'Z') || (words[l] >= 'a' && words[l] <= 'z')))
            {
                tempLength++;

                if (l == (s.Length - 1))
                {
                    if (tempLength >= maxLength)
                    {
                        indexList.Add(l+1); //'l+1' ensures a word that has no non-alphabet after it is captured
                                            //removing l+1 displays as 'wanted remov' - 'e' is missing
                        k++;
                    }
                }
            }
            else
            {
                if (tempLength == maxLength)
                {
                    indexList.Add(l);
                    k++;
                }
                tempLength = 0;
            }
        }

        //a for loop to append the longest words into a single word
        for (int m = 0; m <= k - 1; m++)
        {
            for (int n = (indexList[m] - maxLength); n < indexList[m]; n++)
            {
                longestWord.Append(words[n]);
            }
            longestWord.Append(" ");
        }

        Console.WriteLine(longestWord);
    }

Honestly, although this code works, I'm unsatisfied with it and would like suggestions as to how I could improve it lengthwise and in readability.


texts:
Online challenge on Hacker Rank.

Please follow the description from the above link.

import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;

class Main {
  private static List<String> substrings(String s) {
    int length = s.length();
    List<String> list = new ArrayList<>();

    for (int i = 0; i < length; i++) {
      for (int j = i + 1; j <= length; j++) {
        list.add(s.substring(i, j));
      }
    }
    return list;
  }

  private static int solve(String text, int A, int C) {
    int length = text.length();
    StringBuilder sb = new StringBuilder(length);
    Set<String> set  = new HashSet<>();

    int cost = 0;
    int len  = 0;
    for (int i = 0; i < length; i++) {
      len = sb.length();
      if (len == 0) {
        sb.append(text.charAt(0));
        set.add(sb.toString());
        cost += A;
        continue;
      }

      while (len > 0) {
        int sum = i + len;
        int end = (sum > length) ? length : sum;
        String lookAhead = text.substring(i, end);
        if (set.contains(lookAhead)) {
          if (lookAhead.length() == 1 && A <= C) {
            cost += A;
          } else {
            cost += C;
          }

          i += len - 1;
          sb.append(lookAhead);
          for (String sub : substrings(sb.toString())) {
            set.add(sub);
          } // end for
          break;
        } // end if
        else {
          if (lookAhead.length() == 1) {
            cost += A;
            sb.append(lookAhead);
            for (String sub : substrings(sb.toString())) {
              set.add(sub);
            } // end for
            break;
          }
          len--;
        } // end else
      } // end while
    } // end for
    //return sb.toString();
    return cost;
  }

  public static void main(String[] args) {
    System.out.println(solve("a", 4, 5));   // 4 A
    System.out.println(solve("ab", 4, 5));  // 8 A + A
    System.out.println(solve("aba", 4, 3)); // 11 A + A + C
    System.out.println(solve("aabaacaba", 4, 5)); // 26 A + A + A + C + A + C
    System.out.println(solve("bacbacacb", 8, 9)); // 42 A + A + A + C + C
  }
}

Note:

I have to confess this time that I really didn't know what I was doing, I spent more than couple of hours on this problem and still its faling on some test cases and times out (which I knew since its kind of brute force).

The only positive things that I can conclude from my not so worthy effort is although I came up with the basic idea pretty fast but in process of writing code I was really struggling to follow the flow and had to dance with the logic for more than an hour basically I had a hard time converting my idea to code.

Any suggestion would be really helpful as I have some major interview in couple of days so, some tips would defintely help.

Second and most important thing is that how to check the correctness of such algorithms since I had to print values several times and it became very painful.

Apart from that I would like to know an effcient algorithm.


texts: Optimizing dynamic table creation: JavaScript vs. jQuery

texts:
I'm on the road to prepare for the 70-480 Microsoft exam and I'm learning the basics of jQuery.

Now I wrote the following JavaScript function to create a table dynamically:

function MakeTableJavascript() {
    var rows = document.getElementById("rows").value;
    var cols = document.getElementById("cols").value;
    var placeholder = document.getElementById("placeholder");
    var table = document.createElement("table");
    table.setAttribute("border", "1");

    for (var r = 0; r <= rows; r++) {
        var row = document.createElement("tr");
        for (var c = 0; c < cols; c++) {
            if (r == 0) {
                var head = document.createElement("th");
                var texthead = document.createTextNode("Column " + c);

                head.appendChild(texthead);
                row.appendChild(head);
            }
            else {
                var col = document.createElement("td");
                var textrow = document.createTextNode(c.toString() + r.toString());

                col.appendChild(textrow);
                row.appendChild(col);
            }
        }
        table.appendChild(row);
    }
    placeholder.appendChild(table);
}

Then I re-wrote the same function with jQuery:

function MakeTablejQuery() {
    var rows = $('#rows').val();
    var cols = $('#cols').val();
    var placeholder = $('#placeholder').val();
    var table = document.createElement("table");

    $('table').attr("border", 1);
    for (r = 0; r <= rows; rows++) {
        var row = document.createElement("tr");
        for (var c = 0; c < cols; c++) {
            if (r == 0) {
                var head = document.createElement("th");
                var texthead = document.createTextNode("Column " + c);

                head.appendChild(texthead);
                row.appendChild(head);
            }
            else {
                var col = document.createElement("td");
                var textrow = document.createTextNode(c.toString() + r.toString());

                col.appendChild(textrow);
                row.appendChild(col);
            }
        }
        table.appendChild(row);
    }
    placeholder.appendChild(table);
}

The result in term of lines of written code is practically the same.

Surely I can use jQuery in a better way to write less code, but at the actual state I have no idea on how to do so.

Can anyone more experienced in jQuery give me a suggestion to narrow the above code?


texts: Splitting TSV file into multiple files based on content of column

texts:
I'm having to process an Amazon orders report (TSV flat file from the MWS Report API) and am needing to split the report based on sales channels (I could request them separately but need to keep API request counts as low as possible) whilst editing the contents of one of the columns (mapping a virtual SKU to its real counterpart). I'm using the CsvHelper library to handle the reading and writing, and would like to handle the file a line at a time to avoid loading the entire file into memory at once, which means as far as I know I can't use the using block on the StreamWriter and CsvWriter instances, so I made a wrapper class that implements IDisposable and calls Dispose on both writers as part of its Dispose method. I store a Dictionary of these classes using sales channel as the key, then once the file has been completed I loop through the dictionary calling Dispose on each element.

Wrapper Class:

internal class AmazonCsvWriter : IDisposable
{
    private bool _disposed;
    private readonly StreamWriter _streamWriter;
    private readonly CsvWriter _csv;

    public AmazonCsvWriter(string folder)
    {
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        _streamWriter = new StreamWriter(Path.Combine(folder, $"{DateTime.Now:yyyyMMddHHmmss}.txt"), false, Encoding.GetEncoding("Windows-1252"));
        _csv = new CsvWriter(_streamWriter);
        _csv.Configuration.Delimiter = "\t";
        _csv.Configuration.RegisterClassMap(new AmazonOrderRowMap());
        _csv.WriteHeader<AmazonOrderRow>();
        _csv.NextRecord();
    }

    public void WriteRecord(AmazonOrderRow record)
    {
        _csv.WriteRecord(record);
        _csv.NextRecord();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual  void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        if (disposing)
        {
            _csv.Dispose();
            _streamWriter.Dispose();
        }

        _disposed = true;
    }
}

Used in this function:

    public void ProcessFbaOrders(string reportFile)
    {
        try
        {
            using (var sr = new StreamReader(reportFile, Encoding.GetEncoding("Windows-1252")))
            using (var csv = new CsvReader(sr))
            {
                csv.Configuration.Delimiter = "\t";
                csv.Configuration.RegisterClassMap(new AmazonOrderRowMap());
                IEnumerable<AmazonOrderRow> records = csv.GetRecords<AmazonOrderRow>();
                foreach (AmazonOrderRow record in records)
                {
                    if (!_csvWriters.ContainsKey(record.SalesChannel))
                    {
                        _csvWriters.Add(record.SalesChannel,
                            new AmazonCsvWriter(Path.Combine(_platform.OutputFolder, record.SalesChannel)));
                    }

                    record.Sku = GetRealSku(record.Sku);

                    _csvWriters[record.SalesChannel].WriteRecord(record);
                }

            }
        }
        finally
        {
            foreach (KeyValuePair<string, AmazonCsvWriter> kvp in _csvWriters)
            {
                kvp.Value.Dispose();
            }
        }

        File.Delete(reportFile);
    }

_csvWriters is defined as:

    private readonly Dictionary<string, AmazonCsvWriter> _csvWriters;

Is this safely closing the Stream/CsvWriters or is there a better method for handling this?


texts: Determining whether a number is positive, negative or zero

texts:
I am a beginner in Python and am currently learning about making beautiful code.  I've started with a small program.  Can you please review my code?

def inputAndRes():
    try:
        a = raw_input("Enter no. :- ")
        n = int(a)
    except Exception:
        print "-----------------------------------"
        print "Please Enter No. " , "( The Number you entered is not a number )"
        inputAndRes()
    else:
        if(n>0):
            print "Number is Positive"
        if(n<0):
            print "Number is Negative"
        if(n==0):
            print "Number is ZERO"
        wantRestart()

def checkYN(checkResult):
    if (checkResult == 'Y'):
            inputAndRes()
    if (checkResult == 'N' ):
            print (" !!! Program Quit !!!")
    else:
        print ("Invalid Option Make sure that you type (Y / N)")
        print ("Continue..")
        wantRestart()

def wantRestart():
    print "\nWant to Restart Program, if Yes then Enter 'Y' and if No enter 'N' :- ",
    try:
        checkResult = raw_input(" ")
    except Exception as e:
        print ("Sorry Error Occured: ",e)
    else:
        checkYN(checkResult)
#...Start of Program...
inputAndRes()


texts:
This is a simple practice app that draws a line, and the line 'balloons' up for a second.

This code shows some issues I tend to have a little too often, where I end up defining functions inside of functions, and it feels like there's got to be a better way.

I'm also unsure of the way I updated the size and pos values in the line_expand function.

Any suggestions on how I can write cleaner code in this example?

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Rectangle, Line, Ellipse
from kivy.clock import Clock

class Test(Widget):

    def on_touch_down(self, touch):
        with self.canvas:
            Color(0, 0, 0)
            Rectangle(pos=(0, 0), size=(self.width, self.height))
            Color(1, 1, 1)
            touch.ud['ellipse'] = Ellipse(pos=(touch.x - 10, touch.y - 10), size=[20, 20])
            touch.ud['line'] = Line(points=[touch.x, touch.y], width=10)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]

    def on_touch_up(self, touch):

        def line_expand(dt):
            touch.ud['ellipse'].size = (touch.ud['ellipse'].size[0] + 1,
                                        touch.ud['ellipse'].size[1] + 1)
            touch.ud['ellipse'].pos = (touch.ud['ellipse'].pos[0] - 0.5,
                                       touch.ud['ellipse'].pos[1] - 0.5)
            touch.ud['line'].width += 0.5

        growclock = Clock.schedule_interval(line_expand, 0.01)
        def stop_clock(dt):
            Clock.unschedule(growclock)

        Clock.schedule_once(stop_clock, 1)

class TestApp(App):
    def build(self):
        return Test()

if __name__ == '__main__':
    TestApp().run()


texts: Entab.c - Program that replaces string of blanks by the min # of spaces & tabs to achieve identical output

texts:
This is Exercise 1-21 of K&R (2nd edition).

I've seen someone else's post about it but it doesn't solve the problem the way my code does, and I wasn't sure whether I was allowed to post my code as an answer and ask for feedback (it just seemed better to create a new thread and ask for advice here, didn't wanna pollute the other user's topic but if that's what I am supposed to do please let me know and I'll reply over there).

In any way, here's the approach I took to solve the problem:

  Approach:

  We'll keep track of number of spaces encountered (between nontab/nonspace characters)
  We'll keep track of characters (that aren't tabs/blanks/newlines) per input line
  We'll evaluate the "gaps" generated by spaces by:

  Evaluating whether the number of spaces in between those characters.
  A gap will be "big enough" when the number of spaces is >= TABSIZE
  Then, for all the left over spaces in our "buffer", we'll print them out individually

  Finally, we print out the character that was read in (which was not a tab/blank)

  As well as updating space count and character count if necessary.

Here's the code:

#include <stdio.h>

//Entab: replaces string of blanks by the min # of spaces & tabs
//Same tab spots as for detab (8)
//Given performance to tabs.

#define TABSIZE 8

//Approach:
//We'll keep track of number of spaces encountered (between nontab/nonspace characters)
//We'll keep track of characters (that aren't tabs/blanks/newlines) per input line
//We'll evaluate the "gaps" generated by spaces by:
//  evaluating whether the number of spaces in between those characters.
//  A gap will be "big enough" when the number of spaces is >= TABSIZE
//  Then, for all the left over spaces in our "buffer", we'll print them out individually
//Finally, we print out the character that was read in (which was not a tab/blank)
//Update space count and character count if necessary.

int main()
{
    int c, nc, ns;

    nc = ns = 0;
    while((c = getchar()) != EOF)
    {
        //if this character was a space
        if(c == ' ') {
            //increase the space count
            ++ns;
        }
        //else if the character read in is not a space
        else {

            //while one or more spaces are still "in buffer"
            while(ns > 0)
            {
                //decide whether gap in between chars is long enough for a space
                if(ns >= TABSIZE - nc)
                {
                    //if it is, then place a tab, and remove that amount of spaces
                    putchar('\t');
                    ns -= TABSIZE;
                }
                //else, if the gap is not big enough for spaces, just print them out individually
                else
                {
                    putchar(' ');
                    --ns;
                }
            }

            //if read a newline, reset char count
            //if not, increase it by one for the char we just read in
            //as well as update the total space count to 0
            if(c == '\n')
                nc = ns = 0;
            else if(c != '\t')
                ++nc;

            //finally, put this "nonspace/nontab" character just read
            //after the gap we just covered
            putchar(c);
        }
    }
}

Also, keep in mind that I am just revisiting C's K&R and I am aware that some of it may be outdated, but I'm doing my best to use what's still "useful" of the book and discard what may not be.

I'm using these notes to accompany my travels through C.


texts: Fetch, parse, and store JSON in PostgreSQL

texts:
I was given a task to read JSON from a URL and then parse it in python. Each field will be assigned to a variable to store the value. The value will then be stored into postgres table.

Example of JSON

{
 "forecasts":
[
 {
   "class": "fod_long_range_daily",
   "expire_time_gmt": 1525126617,
   "night": {
     "fcst_valid": 1525158000,
     "fcst_valid_local": "2018-05-01T19:00:00+1200",
     "golf_category": ""
   },
   "day": {
     "uv_warning": 0,
     "uv_desc": "Moderate",
     "golf_index": 10,
     "golf_category": "Excellent"
   }
 }
]
}

I was told that this way i am able to parse JSON and read it into postgres. Is this the right way to do this? Will there be performance issues?

import urllib3
import psycopg2
import json

conn = psycopg2.connect(host="localhost", database="nzaus",
user="admin", password="123321")
print("Database Connected")
cur = conn.cursor()
rowcount = cur.rowcount

http = urllib3.PoolManager()
url = "https://api.data.com/v1/geocode/-35.228208/174.095969/forecast/daily/15day.json?language=en-US&units=m&apiKey=1234"
try:
    response = http.request('GET', url)
    data = json.loads(response.data.decode('utf-8'))

    for item in data['forecasts']:
        class = None
        time = None
        fcst_valid = None
        golf_category = None

        result = []

        class = item['class']
        time  = item['expire_time_gmt']
        fcst_valid = item['night']['fcst_valid']
        golf_category = item['morning']['golf_category']
        result = [class,time,fcst_valid,golf_category]

        cur.execute("""INSERT into datatable
                       VALUES
                       ( %s,
                         %s,
                         %s,
                         %s,
                       )""",(result))
        conn.commit()
    cur.close()
 except IOError as io:
    print("cannot open")


texts:
This code is meant to sort a list of integers in place using quick sort.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def quicksort(l):
    quicksort_helper(l, 0, len(l)-1)

def quicksort_helper(l, lo, hi):
    if lo >= hi:
        return

    pivot_ind = partition(l, lo, hi)
    quicksort_helper(l, lo, pivot_ind-1)
    quicksort_helper(l, pivot_ind+1, hi)

def partition(l, lo, hi):
    pivot = l[hi]
    left = lo

    for right in range(lo, hi):
        if l[right] <= pivot:
            swap(l, left, right)
            left += 1
    swap(l, left, hi)

    pivot_ind = left
    return pivot_ind

def swap(l, i, j):
    temp = l[i]
    l[i] = l[j]
    l[j] = temp


texts:
I have been working of a basic from using React and I need your help to improve this part of my code, especially validate and onSubmit.

state = {
    email: "",
    emailError: "",
  };
  change = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

    validate = () => {
    let isError = false;
     const errors = {
      emailError: "",
    };

    if (this.state.email.indexOf("@") === -1) {
      isError = true;
      errors.emailError = "Requires valid email";
    }

    this.setState({
      ...this.state,
      ...errors
    });

    return isError;
  };
  onSubmit = e => {
    e.preventDefault();
    const err = this.validate();
    if (!err) {
      this.props.onSubmit(this.state);
      this.setState({

        email: "",
        emailError: "",
      });
    }
  };

  render() {
    return (
      <form>
        <TextField
          name="email"
          hintText="Email"
          floatingLabelText="Email"
          value={this.state.email}
          onChange={e => this.change(e)}
          errorText={this.state.emailError}
          floatingLabelFixed
        />
        <br />
        <RaisedButton label="Submit" onClick={e => this.onSubmit(e)} primary />
      </form>
    );


texts:
I've been working with Lua for a little bit, and I have finally come up with some code that can be extended to create the core of a game model.  I come from an object oriented background, so working with Lua is very different for me.

The purpose of this code would be to create the game model for a game with Lua.  Another programming language would load the scripts and then make the calls to create the Game object and to advance the turns.  Any information resulting from a game turn could be passed back to the rendering in the proper programming language.

I would love to hear about any aspect of this code, but I am new to Lua syntax so I am sure I am making rookie mistakes.

Game.lua

--This syntax loads other scripts, such as Player.lua
local player = require "Player"

local Game = {} -- the table representing the class, which will double as the metatable for the instances
Game.__index = Game -- failed table lookups on the instances should fallback to the class table, to get methods

-- syntax equivalent to "MyClass.new = function..."
function Game.new()
    local self = setmetatable({}, Game)

    self.players = {}

    self.currentTurn = 0

    return self
end

--Adding players to the game
function Game.addPlayers(self, numPlayers)
    --i has to be set to 1 for it to work properly
    for i = 1, numPlayers, 1 do
        self:addPlayer()
    end
end

function Game.addPlayer(self)
  table.insert(self.players, player.new(6))
end

--Advancing and reporting the game turns
function Game.advanceTurn(self)
  self.currentTurn = self.currentTurn + 1
end

function Game.getTurnNumber(self)
  return self.currentTurn
end

--test function to access player data
function Game.reportPlayers(self)
  for key,value in pairs(self.players) do
    print(key)
  end
end

--create the game "instance"
local game = Game.new()
game:addPlayers(2)

--these types of commands would be sent to Lua by a proper programming language
game:advanceTurn()
print(game:getTurnNumber())
game:advanceTurn()
print(game:getTurnNumber())
game:reportPlayers()

Player.lua

Player = {} -- the table representing the class, which will double as the metatable for the instances
Player.__index = Player -- failed table lookups on the instances should fallback to the class table, to get methods

-- syntax equivalent to "MyClass.new = function..."
function Player.new(startingHandSize)
    local self = setmetatable({}, Player)
    self.handSize = startingHandSize
    print(self.handSize)
    return self
end

function Player.set_handSize(self, newHandSize)
    self.handSize = newHandSize
end

function Player.get_handSize(self)
    return self.handSize
end

return Player


texts:
I would be happy to hear feedback on my implementation of HttpClient. I am not so strong with error handling so I want to improve. My thought process behind this was that IOExceptions can be recoverable and should be tried again. Where as client exception isn't. Hope to hear your thoughts.

private HttpResponse execute(int httpVerb, boolean authHeader) throws NoInternetConnectionError, IOException, ClientProtocolException {

    try {
        Log.i(TAG, "setting header and executing");
        switch (httpVerb) {
        case HTTP_POST:
            if (authHeader){
                httpPost.addHeader(header);
            }
            return httpClient.execute(httpPost);
        case HTTP_PUT:
            if (authHeader){
                httpPut.addHeader(header);
            }
            return httpClient.execute(httpPut);
        case HTTP_GET:
            if (authHeader){
                httpGet.addHeader(header);
            }
            return httpClient.execute(httpGet);
        default:
            return null;
        }
    } catch (IOException e) {
        InternetChecker internetChecker = new InternetChecker(context);
        if (internetChecker.isInternetConnected() == false) {
            throw new NoInternetConnectionError("internet not connected");
        } else {
            numberOfTries ++;
            if (numberOfTries > 2) {
                throw new IOException(e.getMessage());
            } else {
                Log.i(TAG, "executing for the " + String.valueOf(numberOfTries) + " time");
                return execute(httpVerb, authHeader);
            }
        }
    } finally {
        numberOfTries = 0;
        Log.i(TAG, "finally block run");
    }
}


texts:
Assuming I have a method with this signature

public void DoStuffWith<T>(T foo)

and I want to allow both structs and classes to be passed as T, I was wondering about how to best do the null-checking in case T is a class.

I came up with following two approaches:

1. Checking whether T is a struct or a class at runtime:

public void DoStuffWith<T>(T foo)
{
    if(!typeof(T).IsValueType && foo == null)
    {
        throw new ArgumentNullException(nameof(foo));
    }

    ...
}

2. Having two overloads with generic type constraints:

public void DoStuffWithStruct<T>(T foo) where T : struct
{
    ...
}

public void DoStuffWithClass<T>(T foo) where T : class
{
    if(foo == null)
    {
        throw new ArgumentNullException(nameof(foo));
    }

    ...
}

However, I dislike both approaches. I don't like the runtime type-checking at #1 and I don't like having multiple, differently named overloads at #2.

Which of the approaches do you suggest or do you think I should maybe consider a totally different approach altogether?

I appreciate any feedback.


texts: Better jQuery function argument with if-statement?

texts:
function check_itv(key) {

if (key.length){

    if(key=="left"){
        left_itv = setInterval(left,100);
        check_left= false;
        check_right=true;
        check_up=true;
        check_down=true;
        clearInterval(right_itv);
        clearInterval(down_itv);
        clearInterval(up_itv);
    }

    if(key=="right"){
        right_itv = setInterval(right,100);
        check_left= true;
        check_right=false;
        check_up=true;
        check_down=true;
        clearInterval(left_itv);
        clearInterval(down_itv);
        clearInterval(up_itv);
    }

    if(key=="up"){
        up_itv = setInterval(up,100);
        check_left= true;
        check_right=true;
        check_up=false;
        check_down=true;
        clearInterval(left_itv);
        clearInterval(right_itv);
        clearInterval(down_itv);
    }

    if(key=="down"){
        down_itv = setInterval(down,100);
        check_left= true;
        check_right=true;
        check_up=true;
        check_down=false;
        clearInterval(left_itv);
        clearInterval(right_itv);
        clearInterval(up_itv);
    }

}

}

check_left = true;
check_right = true;
check_up = true;
check_down = true;
left_itv = "";
right_itv = "";
up_itv = "";
down_itv = "";

Try to do shorter and better, Any idea ?

Thanks


texts: How to make the end of loop more readable in Ruby

texts:
There are some blocks in my code.

To make it easier to read, I often append comment after the end

such as

  end # end upto
  end # fileopen

Because sometimes the indentation still not easy for read.

Is there any better practice?

And my indentation is 2 spaces, is it OK for most Rubier ?

require "faker"
real_sn = 2124100000
File.open("lib/tasks/tw_books.txt", "r").each do |line|
  # author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\s+','\s')

  1.upto(1000).each do |x|

    location = Faker::Lorem.words(5)
    book_name, author, publisher, isbn, comment = line.strip.split("|||")
    ap(line)
    isbn = isbn[/\d+/]
    real_sn+=1
    bk = Book.new(:sn => real_sn,:name => book_name, :isbn=>isbn,
                  :price =>Random.rand(200..5000), :location=>location, :category=>["商業","歷史","體育","政治"].sample,
                  :author => author, :sale_type => [:fix_priced, :normal, :promotion].sample, :publisher => publisher,
                  :release_date => rand(10.years).ago, :comment => comment
                  )
    if bk.save()
      if (real_sn%100)==0
        puts book_name
      end
      Sunspot.commit
    else
      puts real_sn
      puts bk.errors.full_messages
    end
  end # end upto
end # fileopen


texts: What is a better way to get unique array Items based on key in PHP?

texts:
I'm trying to achieve a set of unique array with my following function.

The Function:

/**
* uniqueAssocArray Removes arrys which have same keys
* @param  Array $array     Array to get unique items from
* @param  String $uniqueKey the unique key
* @return Array            new array with unique items
* @author Junaid Qadir Baloch <shekhanzai.baloch@gmail.com>
*/

function uniqueAssocArray($array, $uniqueKey) {
  if (!is_array($array)) {
    return array();
  }
  $uniqueKeys = array();
  foreach ($array as $key => $item) {
    if (!in_array($item[$uniqueKey], $uniqueKeys)) {
      $uniqueKeys[$item[$uniqueKey]] = $item;
    }
  }
  return $uniqueKeys;
}

Example Array:

$actualArray = array(
    user1 => array(
        'name' => 'User1',
        'age' => '25',
        'lastLogin' => '2013-08-16'
    ),
    user1 => array(
        'name' => 'User1',
        'age' => '25',
        'lastLogin' => '2013-08-10'
    ),
    user2 => array(
        'name' => 'User2',
        'age' => '35',
        'lastLogin' => '2013-08-08'
    ),
    user1 => array(
        'name' => 'User1',
        'age' => '25',
        'lastLogin' => '2013-07-10'
    )
);

I then call the function like so:

$resultArray = uniqueAssocArray($actualArray, 'name');

But...

I wonder is there a better way to do the same ?


texts: Functionality to read large files (> 3 GB) in chunks

texts:
Here is a function I wrote that can read chunks of large files (> 3 GB). It's designed to be used contentiously so that one can use it in a while loop until it returns EOF.

It's an early prototype and is only written to work under 32-bit Linux.

I'm okay with feedback on readability, maintainability, or anything else.

/**
 * Reads a chunk of given size into memory (heap) from file. Chunk size is
 * measured in amount of pages.
 *
 * The chunk will be allocated before reading starts. So no matter what
 * the return code you always need to decref the chunk.
 *
 * Parameters:
 * - pages    : The amount of pages to read to memory. The size of a page
 *              a page differs from different systems, but it is usually 4 KiB.
 *              See getpagesize or _SC_PAGESIZE for sysconf in unistd.h for
 *              details.
 * - start_pos: The position in the file to start reading from
 * - *end_pos : Pointer to the location where the end position of the
 *              reading shall be placed. This will be the byte after the last
 *              read byte, so that read_chunk can be called with this value
 *              as start_pos directly.
 * - **chunk  : Pointer to the pointer of an byte array where the result
 *              will be placed in.
 *
 * Return values:
 * - Returns 0 on success
 * - Returns -1 if chunk size was above 2^31 bits (~ 2 GB)
 * - Returns -2 if an fseek error occured, see errno for details
 * - Returns -3 if an fread error occured, see errno for details
 * - Returns -4 on EOF
 */

int8_t read_fachunk(
        FILE *f,
        uint16_t pages,
        uint64_t start_pos,
        uint64_t *end_pos,
        struct byte_array **chunk)
{
        assert(f != NULL);
        assert(end_pos != NULL);
        assert(chunk != NULL);
        assert(pages != 0);

        uint64_t chunk_b = pages * sysconf(_SC_PAGESIZE);

        if(chunk_b > MAX_CHUNK_SIZE) {
            return -1;
        }

        uint64_t curr_pos = 0;
        int64_t err = lseek64(fileno(f), start_pos, SEEK_SET);

        *chunk = byte_array_create(chunk_b);

        if (err == -1) return -2;

        curr_pos = fread((*chunk)->bytes, sizeof(uint8_t), chunk_b, f);
        (*chunk)->curr_i = curr_pos;

        if (ferror(f) != 0) {
            err = -3;
            goto complete;
        }

        if (feof(f) != 0) {
            err = -4;
            goto complete;
        }

        err = 0;

        complete:
    *end_pos = start_pos + curr_pos;
    return err;
}


texts: Implementing redirect in Redux middleware

texts:
Let's say I have following action:

export function signIn(data) {
  return {
    type: USER_SIGN_IN,
    promise: api.post('/sign_in', data)
  }
}

and the following middleware:

export default function promiseMiddleware() {
  return next => action => {
    const { promise, type, ...rest } = action

    if (!promise) {
      return next(action)
    }

    const SUCCESS = `${type}_SUCCESS`
    const REQUEST = `${type}_REQUEST`
    const ERROR = `${type}_ERROR`

    next({ ...rest, type: REQUEST })

    return promise
      .then(res => {
        next({ ...rest, response: res.data, type: SUCCESS })
        return true
      })
      .catch(error => {
        next({ ...rest, response: error.response.data, type: ERROR })
        return false
      })
  }
}

This code is loosely based on https://github.com/reactGo/reactGo/

But what if in then callback after calling next I want to make a redirect to another path?

I did following. I passed redirect url through action:

export function signIn(data) {
  return {
    type: USER_SIGN_IN,
    promise: api.post('/sign_in', data),
    redirect: '/'
  }
}

and added another call of next method with push from react-router-redux:

import { push } from 'react-router-redux'

export default function promiseMiddleware() {
  return next => action => {
    const { promise, type, redirect, ...rest } = action

    if (!promise) {
      return next(action)
    }

    const SUCCESS = `${type}_SUCCESS`
    const REQUEST = `${type}_REQUEST`
    const ERROR = `${type}_ERROR`

    next({ ...rest, type: REQUEST })

    return promise
      .then(res => {
        next({ ...rest, response: res.data, type: SUCCESS })
        next(push(redirect))
        return true
      })
      .catch(error => {
        next({ ...rest, response: error.response.data, type: ERROR })
        return false
      })
  }
}

It seems like it works, but I'm not sure if this is a good idea or if there are some pitfalls of multiple next calls and I shouldn't do like this? Or maybe I should use dispatch method which I can get from promiseMiddleware params instead of next for redirecting?

If there are some better approaches for implementing such redirects, please, let me know.


texts: PHP performance considerations of passing variable into a function

texts:
Example code:

<?php
class MyClass {
    public $bar = array('a', 'b', 'c');
    public function getBar() {return $this->bar;}

    public function execute(array $fooArray) {
        foreach ($fooArray as $foo) {
            echo $foo.":".$this->checkBar($foo, $this->getBar())." ";// PASSED IN//
            //echo $foo.":".$this->checkBar($foo)." ";// RETRIEVED //
        }
    }

    // PASSED IN //
    public function checkBar($foo, array $fooCheck) {
        return in_array($foo, $fooCheck);
    }

    // RETRIEVED //
    /*public function checkBar($foo) {
         $fooCheck = $this->getBar();
         return in_array($foo, $fooCheck);
    }*/
}

$someClass = new MyClass();
$someClass->execute(array('a','f','c','g'));
?>

Are there any performance considerations to passing $fooCheck in as a variable into checkBar vs having MyClass::checkBar() handle calling the function itself?


texts: "Of three points supplied, is one a midpoint of the other two?"

texts:
Write a method named hasMidpoint that accepts three integers as parameters and returns true if one of the integers is the midpoint between the other two integers; that is, if one integer is exactly halfway between them. Your method should return false if no such midpoint relationship exists.

Here are two different versions of code that I wrote at two different occasions to accomplish the same thing. How can I make my code better, and is there a better way to accomplish this task?

public static boolean hasMidpoint(int a, int b, int c) {
        if ( a == b && b == c) {
            return true;
        } else if ((a + b) / 2.0 == c || (b + c) / 2.0 == a || (a + c) / 2.0 == b) {
            return true;
        } else {
            return false;
        }
    }

public static boolean hasMidpoint(int p1, int p2, int p3) {
        if((double)(p1 + p2) / 2 == p3 ||  (double) (p2 + p3) / 2 == p1 || (double) (p1 + p3) / 2 == p2){
            return true;
        }
        return false;
    }


texts: Validating a name with C#, ASP.NET Core 3.1 and Regex

texts:
This class validates that a name contains only letters and optionally spaces, hyphens and apostrophes.
public class NameAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null) return ValidationResult.Success;

        string name = value.ToString();
        var regex = new Regex(@"^[a-zA-Z]+(?:['-][a-zA-Z\s*]+)*$");

        return regex.IsMatch(name)
            ? ValidationResult.Success
            : new ValidationResult($"The name '{name}' is invalid, it should consist of only letters, and optionally spaces, apostrophes and/or hyphens.");
    }
}

One thing I wasn't sure on was the null check at the start, we've got the Required attribute if something is required and I don't want the validation to occur if the value is null. Is this an appropriate way of handling it?


texts:
I'm looking for tips on how to clean up this code and/or make it more efficient.

Keep in mind I am a seriously new programmer and if it is too advanced it's likely to go over my head.

import random
cscore = 0
pscore = 0
print 'I would like to play a game. \nThe name of the game is Rock, Paper, Scissors.'
rest = 'y'
while (rest == 'y'):
    pick = ['r', 'p', 's']
    b = (random.choice(pick))
    a = raw_input ('\nFirst Letter ')
    if a == 'r' or a == 'R':
        a = 'Rock'
    elif a == 'p' or a == 'P':
        a = 'Paper'
    elif a == 's' or a == 'S':
        a = 'Scissors'

### assign name to computer's answer
    if b == 'r':
        b = 'Rock'
    elif b == 'p':
        b = 'Paper'
    elif b == 's':
        b = 'Scissors'
    print 'You picked ' + a + '\nAnd I picked ' + b

##### compare picks
    if a == 'Rock' and b  == 'Rock':
        print 'Silly, we both picked Rock, \nthat means we tied.'
    elif a == 'Rock' and b == 'Paper':
        print 'Yes! Paper smothers Rock, therefore, I win.'
        cscore = cscore + 1
    elif a == 'Rock' and b == 'Scissors':
        print 'Crap, Rock smashes Scissors. You win.'
        pscore = pscore + 1
    elif a == 'Paper' and b  == 'Paper':
        print 'Silly, we both picked Paper, \nthat means we tied.'
    elif a == 'Paper' and b == 'Scissors':
        print 'Yes! Scissors cut Paper, therefore, I win.'
        cscore = cscore + 1
    elif a == 'Paper' and b == 'Rock':
        print 'Crap, Paper smothers Rock. You win.'
        pscore = pscore + 1
    elif a == 'Scissors' and b  == 'Scissors':
        print 'Silly, we both picked Scissors, \nthat means we tied.'
    elif a == 'Scissors' and b == 'Rock':
        print 'Yes! Rock smashes Scissors, therefore, I win.'
        cscore = cscore + 1
    elif a == 'Scissors' and b == 'Paper':
        print 'Crap, Scissors cut Paper. You win.'
        pscore = pscore + 1
    print '\nThe score is now Computer ' + str(cscore) + ' Human ' +     str(pscore)
    rest = raw_input ('\nWould you like to play again? y or n ')
print '\nThank you for playing. The final score was Computer ' + str(cscore) + ' Human ' + str(pscore)
if cscore > pscore:
    print 'Ha!, I won and you lost.'
elif cscore == pscore:
    print 'We tied in the overall score, you are a worthy opponent.'
elif cscore < pscore:
    print 'You beat me, you low down mangy son of a gun. You must have cheated.'


texts:
This is part of this topic.
Problem:
I need to read a file with BigIntegers and make some analysis "on-the-fly" with each read number (get prime numbers count, get armstrong numbers count). Right now I have this code, but it works very slow:

package ee.raintree.test.numbers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;

import ee.raintree.test.numbers.utils.MathUtils;

public class FileAnalyzer {
    private static final char SEPARATOR = ' ';
    private File file;
    private int armstrongNumbersCount;
    private int primeNumbersCount;

    public FileAnalyzer(File file) {
        this.file = file;
    }

    public void analyze() throws FileNotFoundException, IOException {
        countNumbers();
    }

    public int getArmstrongNumbersCount() {
        return armstrongNumbersCount;
    }

    public int getPrimeNumbersCount() {
        return primeNumbersCount;
    }

    private void countNumbers() throws FileNotFoundException, IOException {
        StringBuilder numberSb = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(file)) {
            char currentChar;
            while (fis.available() > 0) {
                currentChar = (char) fis.read();
                if (currentChar == SEPARATOR) {
                    analyzeNumber(new BigInteger(numberSb.toString()));
                    numberSb = new StringBuilder();
                    continue;
                }
                numberSb.append(currentChar);
            }
            if (numberSb.length() > 0) {
                analyzeNumber(new BigInteger(numberSb.toString()));
            }
        }
    }

    private void analyzeNumber(BigInteger number) {
        if(MathUtils.isArmstrongNumber(number)) {
            armstrongNumbersCount++;
        }
        if(MathUtils.isPrime(number)) {
            primeNumbersCount++;
        }
    }
}

How can I speed up this process? As I was informed - it is lack of buffering.


texts:
I coded a server-client (kind of) chat, and I need your review as I'm sure it is a mess. I used lots of tutorials and tips form different websites and forums which were posted at different times (maybe now it's a lot easier to write what I want) and slapped them on Visual Studio. It's not like I wanted it to be a chat, but a way to communicate with a server as a client.

Server-Side

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace First_Server
{
    class Program
    {

    private static void SocketThread(object obj)
    {
        var ClientSocket = (TcpClient)obj;
        while (true)
        {
            try
            {
                NetworkStream NetworkStream = ClientSocket.GetStream();
                byte[] BytesFromClient = new byte[10025];
                NetworkStream.Read(BytesFromClient, 0, ClientSocket.ReceiveBufferSize);
                string DataFromClient = Encoding.ASCII.GetString(BytesFromClient);
                DataFromClient = DataFromClient.Substring(0, DataFromClient.IndexOf("#"));
                Console.WriteLine(DataFromClient);
                string ServerResponse = DataFromClient;
                Byte[] SendBytes = Encoding.ASCII.GetBytes(ServerResponse);
                NetworkStream.Write(SendBytes, 0, SendBytes.Length);
            }
            catch (Exception StreamException)
            {
                Console.WriteLine("Connection from a client closed.");
                ClientSocket.Close();
            }
        }
    }

    static void Main(string[] args)
    {
        int Port = 42069;
        IPAddress LocalIPAddress = IPAddress.Parse("192.168.1.10");
        TcpListener ServerSocket = new TcpListener(LocalIPAddress, Port);
        TcpClient ClientSocket;
        ServerSocket.Start(); Console.WriteLine("Server started. Waiting for requests...");

        while (true)
        {
            ClientSocket = ServerSocket.AcceptTcpClient(); Console.WriteLine("Connection from a client accepted.");
            ThreadPool.QueueUserWorkItem(SocketThread, ClientSocket);
        }
    }
}
}

Client-Side

using System;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Windows.Forms;

namespace First_Client
{
  public partial class Form1 : Form
  {

    TcpClient ClientSocket = new TcpClient();

    public void msg(string Message)
    {
        textBox1.Text = textBox1.Text + Message + Environment.NewLine;
    }

    public void ServerListener(object obj)
    {
        loop:
        var NetworkStream = (NetworkStream)obj;
        byte[] FromTheServer = new byte[10025];

        try
        {
            NetworkStream.Read(FromTheServer, 0, ClientSocket.ReceiveBufferSize);
        }
        catch (Exception StreamError)
        {
            goto loop;
        }

        string StringFromServer = Encoding.ASCII.GetString(FromTheServer);
        textBox1.Text = textBox1.Text + StringFromServer + Environment.NewLine;
    }

    public Form1()
    {
        InitializeComponent();
        ClientSocket.Connect("95.76.40.237", 42069); label1.Text = "Client status: connected to server";
        ThreadPool.QueueUserWorkItem(ServerListener);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        NetworkStream NetworkStream = ClientSocket.GetStream();
        byte[] ToTheServer = Encoding.ASCII.GetBytes(textBox2.Text + "#");
        NetworkStream.Write(ToTheServer, 0, ToTheServer.Length);
        byte[] FromTheServer = new byte[10025];
        NetworkStream.Read(FromTheServer, 0, ClientSocket.ReceiveBufferSize);
        string StringFromServer = Encoding.ASCII.GetString(FromTheServer);
        msg(StringFromServer);
        textBox2.Text = "";
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void label1_Click(object sender, EventArgs e)
    {

    }
}
}


texts: How to replace the given email address with a value in a given input?

texts:
I have written the below method to replace some of the email domains like @gmail.com and @yahoo.com with a given text.
public static string RemovePersonalInfo(string input)
{
    string[] tokens = input.Split(new char[] { ' ', '\t', '\r', '\n' });
    string output = string.Empty;
    foreach (string token in tokens)
    {
        if (token.Contains("@gmail.com"))
        {
            output += " SOMETEXT";
        }
        else
        {
            output += " " + token;
        }
    }
    tokens = output.Split(new char[] { ' ', '\t', '\r', '\n' });
    output = string.Empty;
    foreach (string token in tokens)
    {
        if (token.Contains("@yahoo.com"))
        {
            output += " SOMETEXT";
        }
        else
        {
            output += " " + token;
        }
    }
    return output;
}

It is working as expected for the below input.
But I don't think it is a good solution, I can see the improvements in the code like it is not scalable, let's see tomorrow some other email domain comes, I will have to again modify the code and write another if condition. the second improvement is that I am running the loop twice, it can be done in one loop. so performance can be improved.
Or if there is any better approach than this, please suggest.
Input: test@gmail.com test@abc.com @teest@yahoo.com
Output:   SOMETEXT test@abc.com SOMETEXT
Note: I am not supposed to use the Replace method. So the only intention here is to use the same logic in basic programming languages like C and C++ as well.


texts: Copy data for a list of stocks from all Excel files in a directory

texts:
I'm trying to do the following things.

ThisWorkbook has list of stocks. By using for loop i'll select each cell. Number of rows in this sheet are 215.
Create a new workbook with the name as above cell value and name the activesheet with the above cell name.
Open a directory and loop through all the excel files, filter the above stock name and copy the data into newly created workbook in point 2.

Each file in the directory to be looped has an average size of 20MB. For each cell in point 1, it is taking 7 minutes to complete the whole operation. so it is taking 7x215 = 1505 minutes to complete the whole operation.

Sub LoopAllExcelFilesInFolder()

Dim wb As Workbook
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim fname As String
Dim FldrPicker As FileDialog
Dim filter As Range
Dim lastRow As Long
Dim finalRow As Long

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.DisplayAlerts = False
  Application.Calculation = xlCalculationManual

Set sh = ThisWorkbook.Sheets("Sheet1")
    Dim k As Long
'
    k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count

    For i = 1 To k

        Set filter = Range("A" & i)

  myPath = "E:\NSE CM historical data\NSECM-YEAR 2016\NSECM-YEAR 2016\xlsx\december\"

'Target File Extension (must include wildcard "*")
  myExtension = "*.xlsx*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

Set wb = Workbooks.Add
Application.DisplayAlerts = False
wb.SaveAs Filename:="E:\NSE CM historical data\NSECM-YEAR 2016\NSECM-YEAR 2016\xlsx\december\individual\" & filter & ".xlsx"
ActiveSheet.Name = filter

'Loop through each Excel file in folder
  Do While myFile <> ""

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

      Set wb1 = Workbooks.Open(Filename:=myPath & myFile)
        fname = Left(myFile, 12)

    wb1.Sheets(fname).Select
'    .AutoFilterMode = False
    With Worksheets(fname)
    With .Range("$B$1:$B$413994")
    .AutoFilter
   .AutoFilter Field:=1, Criteria1:=filter
    'ActiveSheet.Range("$B$1:$B$413994").Select
    wb1.ActiveSheet.Range("B2").Select
    wb1.ActiveSheet.Range(Selection, Selection.End(xlToRight)).Select
    wb1.ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
    Selection.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy

Windows(filter & ".xlsx").Activate
With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    finalRow = lastRow + 1
    End With

   wb.ActiveSheet.Range("A" & finalRow).Select
   ActiveSheet.Paste

   Application.CutCopyMode = False
    'Save and Close Workbook
      wb1.Close SaveChanges:=False
      End With
      End With

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

  wb.Close SaveChanges:=True

Next i

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub


texts: Code to plot graphs with multiple panels efficiently

texts:
I quite often plot graphs looking at how some property or function varies with different parameters. Normally, I find the analysis code can be written fairly succinctly and separated into a suitable number of functions. However, when I come to plot the graphs my code tends to come unmanageably long.

Below is a basic example, while the code for generating the graphic is modest by my standards I hope it highlights the issue. There will often be several more if statements for adding different things to a specific axis.

Do you have any pointers for keeping plot generation succinct, or is it inevitable when building custom plots?

def get_data(x, order, scale):
    '''Generates data for this example.'''

    y = scale * (x**order)

    return y

# generate the example data

orders = [2, 2.2, 2.3]
scales = [1, 2]

scale_grid, order_grid = np.meshgrid(scales, orders)

parameters = list(zip(order_grid.ravel(), scale_grid.ravel()))

my_x = np.arange(0, 10.1, 0.1)
my_ys = []

for ps in parameters:

    my_ys.append(get_data(my_x, *ps))

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

# generate the graph

my_colors = {0:'r', 1:'b', 2:'g'}

fig, ax_rows = plt.subplots(3, ncols=2)

for i, ax_row in enumerate(ax_rows):

    # plot the graphs
    ax_row[0].plot(my_x, my_ys[i*2], lw=2, color=my_colors[i])
    ax_row[1].plot(my_x, my_ys[i*2+1], lw=2, color=my_colors[i])

    # format the axes
    ax_row[0].set_ylabel('y (unit)')
    plt.setp(ax_row[1].get_yticklabels(), visible=False)

    for ax in ax_row:
        ax.set_ylim(0, 500)
        ax.set_xlim(0, 10)
        if i!=2:
            plt.setp(ax.get_xticklabels(), visible=False)
        if i==2:
            ax.set_xlabel('x (unit)')

    # add the text displaying parameters

    ax_row[0].text(0.03, 0.95,'Scale: {0:.2f}\nOrder:
                  {1:.2f}'.format(parameters[i*2][1],
                  parameters[i*2][0]),
                  transform=ax_row[0].transAxes,
                  verticalalignment='top')
    ax_row[1].text(0.03, 0.95,'Scale: {0:.2f}\nOrder:
                  {1:.2f}'.format(parameters[i*2+1][1],
                  parameters[i*2+1][0]),
                  transform=ax_row[1].transAxes,
                  verticalalignment='top')

fig.set_size_inches(5, 5)

The output graphic is here.


texts:
Just wrote an Evicting Queue implementation, as an ordinary Linked List working under the hood, in Java; which, I hope, I've made thread safe, could you review?
Code:
package com.threadsafedatastructs.EvictingQueue;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;

public class EvictingQueue<T> {
private final int MAX_SIZE;
private List<T> data = new LinkedList<>();
private volatile T o;
private volatile ArrayDeque<T> dequeO;

public EvictingQueue(int _maxSize) {
    this.MAX_SIZE = _maxSize;
}

public synchronized boolean isEmpty() {
    return data.isEmpty();
}

public synchronized int size() {
    return data.size();
}

public T head() {    /* Peek the first element */
    return this.data.get(0);
}

public T tail() {    /* Peek the last element */
    return this.data.get(this.data.size() - 1);
}

public synchronized T popFirst() {
    if (!this.data.isEmpty()) {
        o = data.remove(0);
        notifyAll();
        return o;
    }
    throw new NoSuchElementException();
}

public synchronized T popLast() {
    if (!this.data.isEmpty()) {
        o = data.remove(data.size() - 1);
        notifyAll();
        return o;
    }
    throw new NoSuchElementException();
}

public synchronized boolean push(T item) {
    if (this.data.size() <= MAX_SIZE) {
        if (this.data.size() == MAX_SIZE) {
            this.popFirst();
            this.data.add(0, item);
            notifyAll();
            return true;
        }
        this.data.add(0, item);
        notifyAll();
        return true;
    }
    throw new IndexOutOfBoundsException();
}

public synchronized boolean append(T item) {
    if (this.data.size() <= MAX_SIZE) {
        if (this.data.size() == MAX_SIZE) {
            this.popFirst();
            boolean obj = this.data.add(item);
            notifyAll();
            return obj;
        }
        boolean obj = this.data.add(item);
        notifyAll();
        return obj;
    }
    throw new IndexOutOfBoundsException();
}

public synchronized ArrayDeque<T> pollAll() {
    dequeO = new ArrayDeque<>(this.data);
    this.data.clear();
    notifyAll();
    return dequeO;
}

@Override
public String toString() {
    return data.toString();
}

public int getMAX_SIZE() {
    return MAX_SIZE;
}

}
I'm interested in that volatile variables, are they necessary? Or maybe I should add more? notifyAll() do those synchronized methods need this call?
Also, this: if (this.data.size() <= MAX_SIZE) condition seems redundant, because list data shouldn't be longer than 100 anyway; but this is the simplest way for me to limit Linked List length in Java (also, may help with tests).


texts: Date and time incrementation, using a fictional calendar / clock

texts:
I created a simple clock & calendar system using a fictional system: everything from the number of seconds in a minute, down to the number of months in a year could be different from our accepted norms (i.e. the Gregorian Calendar). (For the purposes of testing the system I have declared that there are 2 seconds in a minute and the calendar uses Elder Scrolls naming for months and days of the week.)

Eventually I'd like to incorporate this into a game, so the function setInterval that currently increments the seconds is a simple stand-in for a more sophisticated kind of game loop.

The full code (with visual output) can be found at this JSFiddle.

I'm particularly interested in feedback on this method, which handles the incrementation of time:

function incrementOneSecond() {
  secondIndex++;
  currentSecond = secondIndex;
  if (secondIndex > secondsPerMinute) {
    secondIndex = 0;
    minuteIndex++;
    currentMinute = twoDigitFormat(minuteIndex);
    if(minuteIndex > minutesPerHour) {
        minuteIndex = 0;
      hourIndex++;
      currentHour = twoDigitFormat(hourIndex);
      if (hourIndex > hoursPerDay) {
        hourIndex = 0;
        dayIndex++;
            currentDay = weekdays[dayIndex];
        if (dayIndex >= weekdays.length) {
            dayIndex = 0;
          dateNumberIndex++;
          currentDateNumber = dateNumberIndex;
          if (dateNumberIndex > monthMaxDays) {
                    dateNumberIndex = 1;
            monthIndex++;
            currentMonth = months[monthIndex];
            if (monthIndex >= months.length) {
                        monthIndex = 0;
              yearIndex++;
              currentYear = yearIndex;
            }
            }
        }
      }
    }
  }

  updateTime(currentMinute, currentHour, currentDay, currentMonth, currentDateNumber, currentYear);
}

There's a lot of repetition, so it feels like I should be able to DRY it up, but because each if statement differs slightly, I haven't been able to come up with a way of rewriting the method in a way that is more efficient but also still readable.

Other methods used:

function twoDigitFormat(input) {
    formatted = ("0" + input).slice(-2)
    return formatted;
}

function updateTime(currentMinute, currentHour, currentDay, currentMonth, currentDateNumber, currentYear) {
    timeDisplay.innerHTML = currentHour + ':' + currentMinute;
    dateDisplay.innerHTML = currentDay + '<br/>' + currentMonth + ' ' + currentDateNumber + ', ' + currentYear;
}


texts: Writing Custom functions to grab data from JSON

texts:
I'm working on a project where i am using VueJS as front-end framework.

I've so much data in JSON format to work with for that i've written a helper function to retrieve data from JSON. much like we query SQL for table rows.

here is what i wrote

function getWhere(field, value) {
   var result = [];

    $vm.services.forEach(function(object, key){
       if(object[field] == value) {
            result.push(object)
        }
    })

   return result.length == 1 ? result[0] : result;
 }

2 Questions

Is it okay to grab data from JS objects like this i mean iterating the whole object to get a single field?
Is there a built-in solution in JS or VueJS for this kind of tasks, if Yes should i use those solutions or the function i posted here is okay to use.


texts:
I am trying to resolve below problem to improve my skill. I would appreciate it if someone improve my code in a better way.
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
#include <stdio.h>
#include <stdlib.h>

#define MIN_ALPH 1
#define MAX_ALPH 26

//return number of possible encode methods
int encode(unsigned int num)
{
    int count=0;
    unsigned int ddigit;

    //encode by 2 digits
    for(int i=10; i<=num; i*=10)
    {
        ddigit = (num % (i*10)) / (i/10);
        if (ddigit >= MIN_ALPH && ddigit <= MAX_ALPH)
            count++;
    }

    //extra count for the single digit encoding since all digits are non-zero
    return ++count;
}

int main(void)
{
    /*Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
    count the number of ways it can be decoded.
    For example, the message '111' would give 3,
    since it could be decoded as 'aaa', 'ka', and 'ak'.
    You can assume that the messages are decodable.
    For example, '001' is not allowed.*/

    printf( "result: %d\n",  encode(512));
    printf( "result: %d\n",  encode(542));
    printf( "result: %d\n",  encode(112));

}


texts: A little "infile" Asynchronous Module Definition

texts:
I like the modular aspect of AMDs (Asynchronous Module Definition; see this Stack Overflow reply) and it's quite neat to structure JS.

But I typically compile all my JS files into one JS file. Therefore I don't really need the asynchronous part. So I thought I could quickly write such "infile" Module Loader.

var load=(function()
{
  var modules={};
  return function(moduleName,dependencies,module)
  {
    if(moduleName.constructor===Array)
    {
      module=dependencies;
      dependencies=moduleName;
      moduleName=undefined;
    }
    if(!((moduleName&&moduleName.constructor===String||moduleName===undefined)
         && dependencies&&dependencies.constructor===Array
         && module&&module.constructor===Function))
      throw "wrong usage";
    var ret = module.apply(null,
      dependencies.map(function(d){return modules[d]||(function(){throw "no module "+d})()})
    );
    if(moduleName)
    {
      if(!ret||ret.constructor!==Object) throw "module should be an object";
      modules[moduleName]=ret;
    }
  }
})();

load('utils',[],function(){return {veryUseful:function(){alert('hey')}}});
load(['utils'],function(utils){utils.veryUseful()});

load is used on one way to define a module and on an other way to call a function with the required modules passed as function arguments.

Demo

The goal here is to allow one to have two pieces of code written in the same file that are guaranteed to be independent.

I'm curious if you have any suggestions on any level. From the concept of such "infile" Module Loader to a hidden neat little JS feature.


texts:
I'm just learning C# and wrote a little program to check if a word contains vowels. It's fairly simple and not to exciting but I would like to know if there's easier ways to do this:

using System;

namespace check_vowels
{
    class Program
    {
        static void Main(string[] args)
        {
            string word;

            Console.WriteLine("We will check if your string contains any vowels or not.");
            Console.Write("Enter a word: ");
            word = Console.ReadLine();
            if (word.ToLower().Contains("a") || (word.ToLower().Contains("e")))
            {
                Console.WriteLine("Your word contains the vowel 'A' or the Vowel 'E', or both.");
            }
            else if ((word.ToLower().Contains("i")) || (word.ToLower().Contains("o")))
            {
                Console.WriteLine("Your word contains the vowel 'I', or 'O', or both.");
            }
            else if (word.ToLower().Contains("u"))
            {
                Console.WriteLine("Your word contains the vowel 'U'.");
            }
            else
            {
                Console.WriteLine("Your word contains no vowels.");
            }

            Console.ReadLine();
        }
    }
}

What can I do better? What did I do well? How can I shorten this?


texts:
Here is what I came to for calculation result caching/invalidating. What do you think?

How to use:

m <- matrix(1:4, 2, 2)

# note that adding properties to calculate/store
# do not require code modifications
c <- cache(m, min=min, max=max, solve=solve)
print(c$get())
print(c$min())
print(c$max())
print(c$solve())

#prints cached result
print(c$max())

#resets cache
c$set(t(m))
print(c$get())
print(c$min())
print(c$max())
print(c$solve())

Implementation:

lazy <- function(FUN, ...) {
    .val <- NULL
    function()
        if(is.null(.val))
            .val <<- FUN(...)
        else
            .val
}

cache <- function(value, ...) {
    this <- NULL
    set <- function(value) {
        this <<- lapply(list(...), lazy, value)
        this$get <<- function() value
        this$set <<- function(value) set(value)
    }
    set(value)
    lapply(setNames(nm = names(this)),
           function(f) function(...) this[[f]](...))
}

Not quite sure about last dispatching lapply. Do you know an easy way? (My first days in R...)


texts: Random Number Guessing Game Code Efficiency - Python

texts:
UPDATE: I have added:

a play-again option
score keeping thing
difficulty levels

**(but I still need help with the functions part).
I don't feel it's necessary to explain what my code does, as it is pretty self-explanatory. I have the entire program completed, but I need to put some of the components of the program into functions. I don't know how to do this. I also need to add a play again option (I have done this before, but for some reason this particular code isn't working...).
import random

#variables:
score = 0
play = True

while play:
    while True:
        try:
            difficulty = int(input("Give me a number between 1 and 3 (these are the difficulty levels) \n\n 1 = easy \n 2 = medium \n 3 = hard \n\n"))
        except:
            print("This is not a number!")
            continue

        if difficulty > 3 or difficulty < 1:
            print("That's an invalid input, please re-enter your number")
            continue
        break

    number = random.randint(1, 10 * difficulty)
    attempts = 0
    guess = 0

    while guess != number and attempts < 3:
        attempts += 1
        print("attempt number " + str(attempts))

        while True:
            try:
                guess = int(input("Guess what number I am thinking of  "))
            except:
                print("That's not a number!")
                continue

            if guess > 10 * difficulty or guess < 1:
                print("That's an invalid input, please re-enter your number.")
                continue
            break

        if guess == number:
            print("You guessed it correct!")
            score += 1
        elif abs(guess - number) == 1:
            print("You're hot on the trail!")
        elif abs(guess - number) <= 3:
            print("You're getting warmer...")
        else:
            print("You're freezing cold!!")

    if attempts == 3 and guess != number:
        print("Oops! You've run out of guesses!")
        print("The number I was thinking of was " + str(number) + ".")

    print("Your final score is " + str(score))

    text = input("If you want to play again, type 'yes' ")
    if text != "yes":
        play = False
        print("Ok, thank you for playing!")


texts: How do I put $db in a central location, but maintain variable scope

texts:
I have that $db, that I will use again and again to connect to the database. How do I put this in a central location so if I change my db I will not have to rewrite a bunch of lines of code? Everything I've tried so far just gives me an error concerning variable scope, the variable is not declared in my functions, so I am forced to simply connect and use the $db object everytime I need to access the database.

TLDR: How do I create the $db object once, and then use it again and again. Just looking for a general idea here.

function input_registration ($email, $password) {

$email_clean = htmlspecialchars($email);
$password_clean = htmlspecialchars($password);

$hash = md5($password_clean);

$db = new PDO("mysql:host=localhost;dbname=users", "root", "");

try {

$statement = $db->prepare("INSERT into userinfo(email, hash) VALUES (:email, :hash)");

$array_parameters = array(

    'email' => $email_clean,
    'hash'  => $hash

    );

$statement->execute($array_parameters);

  }

catch (Exception $error) {

    echo "Database error: ". $error->getMessage();
  }

}


texts: Android View Controller: Precondition vs ClassCastException

texts:
I am working on an Android app that has an Abstract view controller class. I am using that Abstraction and implementing it for an Android Spinner view. It has a method that assigns the view to be controlled. I implemented it as:
@Override
public void setView(@Nonnull View view) {
    super.setView(view);
    mView = (Spinner) Preconditions.checkNotNull(view);
}

I am getting feedback in a code review that would have me revise the method to:
@Override
public void setView(@Nonnull View view) {
    super.setView(view);

    Preconditions.checkNotNull(view, "The view provided is null");
    Preconditions.checkArgument(view instanceof Spinner,
            "view provided was not a Spinner view");
    mView = Spinner.class.cast(view);
}

I am unclear as to why the second is a better implementation.  From what I understand, using Class.cast() is only really useful for generics (1, 2).
Other than that, it looks like the second implementation does the same thing. It will crash the app if view is null, or crash the app if view is not an instance of Spinner.
Is there a benefit to using the Precondition instanceOf check to crash the app in testing rather than a standard ClassCastException?