texts: Find the max value between minimum values in sub-arrays

texts:
I have an array of integers, I have to find all sub-arrays of different size from 1 to len(array). In every sub-array, I have to find the minimum value in it, once done I have to find the maximum value between the minimum values of all the subarrays of the same size. Finally, I have to return these maximum values in a list.
So the first value in my list will always be the maximum integer in the array, the second value will be the maximum between the minimum values of the sub-arrays size 2, and so on; the last value in the list will always be the minimum integer of the array.
Original problem here: Min Max Riddle
def min_max_subarrays(arr):
    result = [max(arr), ]
    w = 2
    while w < len(arr):
      temp = 0
      for i, n in enumerate(arr[:-w+1]):
        x = min(arr[i:i+w])
        if x > temp:
          temp = x
      result.append(temp)
      w += 1
    result.append(min(arr))
    return result

The function is correct but I'm sure there's a way to reduce time complexity. I feel one loop is unnecessary but I'm struggling to find a way to remove it.


texts: Producer-Consumer using low level synchronization

texts:
I saw a tutorial from a site where it showed the use of ArrayBlockingQueue as a thread-safe concurrent data-structure . Just for learning purposes , i tried to build something similar using synchronized and wait-notify methods in java. I'm really very new to java.util.concurrent and i'm hoping someone could guide me to some improvements and point out the bad parts of this code i wrote :

import java.util.ArrayList;
import java.util.Random;

public class LowLevelProducerConsumer {
    ArrayList<Integer> list = new ArrayList<Integer>();
    private final int size = 10;
    private int elems = 0;
    Object lock = new Object();
    Random r = new Random(System.currentTimeMillis());

    public void producer() {
        while (true) {
            synchronized (lock) {
                try {
                    while (elems != size) {
                        list.add(r.nextInt(100));
                        elems++;
                    }
                } finally {
                    // allows consumer to remove an entry
                    lock.notify();
                }
            }
        }
    }

    public void consumer() throws InterruptedException {
        Thread.sleep(100); // any better way to ensure producer runs first ?
        int ran = 0;
        while (true) {
            // consumer tries to acquire lock here , but it can do so only after
            // producer has called notify
            synchronized (lock) {

                // do i need a lock.wait() here somewhere ?

                ran = r.nextInt(10);

                if (ran == 7) { // just an arbitrary condition

                    int loc = r.nextInt(list.size());
                    int data = list.remove(loc);
                    System.out.format(
                            "%d removed from index %d , size : %d\n",
                            data, loc, list.size());
                    // decrementing elems to let the producer work again
                    elems--;
                    Thread.sleep(300);
                }

                // release the lock so that producer can fill things up again
                lock.notify();
            }
        }

    }

    public static void main(String[] args) {
        final LowLevelProducerConsumer low = new LowLevelProducerConsumer();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                low.producer();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    low.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

ps : i'v kept my understanding of how the code works in the comments. Any correction to them would be much appreciated.


texts: Runge-Kutta 2nd order of differential equations

texts:
Could I improve this somehow (not numerically, just C-wise)?  Do I need to allocate the array since I am returning it and not just using it inside the function?

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

/* Approximates a solution to a differential equation on the form:
   y'(t) + ay(t) = x(t)
   y(0) = b
*/
double* runge_kutta_2nd_order(double stepSize, double a, double b, double (*x) (double), double upto)
{
    int resultSize = ((int) (upto / stepSize)) + 2;
    double yt = b;
    double time;
    double k1,k2,ystar1,ystar2;
    int index = 1;

    //double *results = (double*) malloc(resultSize * (sizeof(double)));
    double *results = malloc(resultSize * sizeof(*results));
    if(results == NULL)
    {
        printf("\nCould not allocate memory. Exiting program.");
        exit(0);
    }

    results[0] = b;

    for(time = 0; time < upto; time += stepSize) //<=
    {
        k1 = x(time) - a * yt;
        ystar1 = yt + stepSize * k1;
        k2 = x(time + stepSize) - a * ystar1;
        ystar2 = yt + (k1 + k2) / 2 * stepSize;
        yt = ystar2;
        results[index] = ystar2;
        index++;
    }
    return results;
}

void free_results(double **r)
{
    free(*r);
    *r = NULL;
}

double insignal(double t)
{
    return exp(t/2)*(sin(5*t) - 10*cos(5*t));
}

int main(void)
{
    int i;
    double *res = runge_kutta_2nd_order(0.01,-1,0,&insignal,10);

    printf("\nRunge Kutta 2nd order approximation of the differential equation:");
    printf("\ny'(t) - y(t) = e^(t/2) * (sin(5t) - 10cos(5t))");
    printf("\ny(0) = 0");
    printf("\n0 <= t <= 10");

    for(i=0; i<1001; i+=100){
        printf("\ni = %lf => y = ", 0.01*i);
        printf("%lf", res[i]);
    }
    printf("\n");

    free_results(&res);

    return 0;
}


texts: LeetCode: N-ary Tree Level Order Traversal

texts:
https://leetcode.com/problems/n-ary-tree-level-order-traversal/

Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example, given a 3-ary tree:

We should return its level order traversal:

[
     [1],
     [3,2,4],
     [5,6]
]

Note:

The depth of the tree is at most 1000.
The total number of nodes is at most 5000.

Please comment about space and time complexity.
Thanks.

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GraphsQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/n-ary-tree-level-order-traversal/
    /// </summary>

    [TestClass]
    public class N_aryTreeLevelOrderTraversal
    {
        [TestMethod]
        public void N_aryTreeLevelOrderTraversalTest()
        {
            List<Node> node3 = new List<Node>();
            node3.Add(new Node(5, null));
            node3.Add(new Node(6, null));

            List<Node> node1 = new List<Node>();
            node1.Add(new Node(3, node3));
            node1.Add(new Node(2, null));
            node1.Add(new Node(4, null));

            Node root = new Node(1, node1);
            var result = LevelOrder(root);
            IList<IList<int>> expected = new List<IList<int>>();
            expected.Add(new List<int>{1});
            expected.Add(new List<int>{3,2,4});
            expected.Add(new List<int>{5,6});

            for (int i = 0; i < 3; i++)
            {
                CollectionAssert.AreEqual(expected[i].ToArray(), result[i].ToArray());
            }

        }
        public IList<IList<int>> LevelOrder(Node root)
        {
            IList<IList<int>> result = new List<IList<int>>();
            Queue<Node> Q = new Queue<Node>();
            if (root == null)
            {
                return result;
            }

            Q.Enqueue(root);

            while (Q.Count > 0)
            {
                List<int> currentLevel = new List<int>();
                int qSize = Q.Count;
                for (int i = 0; i < qSize; i++)
                {
                    var curr = Q.Dequeue();
                    currentLevel.Add(curr.val);
                    if (curr.children != null)
                    {
                        foreach (var child in curr.children)
                        {
                            Q.Enqueue(child);
                        }
                    }
                }
                result.Add(currentLevel);
            }
            return result;
        }
    }
}


texts: Hash table with complex variable-length keys

texts:
I'm trying to implement the game Snake in Javascript and getting the computer to play it by itself, and want to check whenever the snake loops (repeats the same set of moves twice) so I can kill it.

To do this, the first thing that came to mind is saving the state the entire game at every frame (the state being the position of the snake's head and body segments, as well as the position of the 'pallet' it's looking to eat) in some sort of dictionary, and checking every frame if the new state of the game exists in this dictionary.

I don't quite know what's the best/most efficient/most readable way to implement this is. Here's what I tried so far:

const Snake = {
  direction: new Vector2(0, 1), // Up
  pallet: Vector2.random(0, 100, 0, 100).floor(),
  head: Vector2.random(0, 100, 0, 100).floor(),
  body: [], // Array of Vector2's
  loopHistory: {}, // Records every state
  checkForLoop: function () {
    // Current state of the system:
    const arr = [this.direction.hash(), this.pallet.hash(), this.head.hash(), ...this.body.map(x => x.hash())];
    //True if a loop is found, false if the state is completely new:
    let found = true;
    let obj = this.loopHistory;
    for (let i = 0; i < arr.length; i++) {
      if (!obj.hasOwnProperty(arr[i])) {
        //This is a part of the state that has never been seen before (new pallet position, new body segment etc.)
        found = false;
        // Record it for the next time:
        obj[arr[i]] = {};
      }
      obj = obj[arr[i]];
    }
    return found;
  }
}

loopHistory and checkForLoop are the relevant bits. Here's the Vector2 class for reference:

 const Vector2 = function (x, y) {
   this.x = x;
   this.y = y;
 };

 Vector2.random = function (xmin, xmax, ymin, ymax) {
   return new Vector2(
     xmin + Math.random() * (xmax - xmin),
     ymin + Math.random() * (ymax - ymin)
   );
 };
 Vector2.prototype.hash = function () {
   return this.x + 73856093 * this.y;
 };
 Vector2.prototype.floor = function () {
   return new Vector2(Math.floor(this.x), Math.floor(this.y));
 };

The issue with this implementation is it generates a massive ever growing arbitrarily deep object (loopHistory) for every game being run. With each game there could be thousands of states before the snake actually loops to its death, and there could be up to one hundred games running at once. The solution feels inefficient and clumsy and difficult to read/maintain, plus it takes a lot of memory, but that seems inevitable. So I'm looking for the go-to solution for situation like this, if one exists, or just any better implementation.

Please help me kill the snake! Thanks in advance for answers.

Edit: I forgot to mention that the behavior of the snake is only dependent on the state of the system that we captured earlier (head position, body positions, pallet position) so if it finds itself in the exact same circumstance it will inevitably react the same way and repeat the same moves.


texts: Count to target with javascript extended

texts:
I previously asked for a review at Count to target with JavaScript, and it was a great help. I'm now looking for comments on the extended version. This code very simply counts in the direction of a particular target number, with the count slowing down as the target gets nearer.  The target number is stored in a nearby file and is often modified by other processes (so this should display a gradual change towards the new number.

Please be as brutal as you like with ways to improve the code or the algorithm (I'm aware there should be comments) - I'm a recreational programmer and would like to be improving my skills. This is absolutely my first use of AJAX and I'm amazed it worked at all :)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN "http://www.w3.org/TR/html4/strict.dtd">

  <title>Count to a particular target</title>

Starting


texts: Implementation of Stack using Linked List

texts:
Please review my code and help me to improve it. I have written this code using template. Can I use more C++11? Is using top in this code is necessary?

#include <iostream>

template<class T>
class Stack{
 struct Node{
 T data;
 Node *next;
 Node(T val):data(val),next(nullptr) {}
 };
 Node *head;
 int top;

 public:
     Stack(){
     top=-1;
     head=nullptr;
     }
    ~Stack();
     bool stack_empty();
     void push(T);
     T pop();

     void display(std::ostream& out = std::cout) const
     {
       Node *node=head;
       while(node!=nullptr){
        out<<node->data<<" ";
        node=node->next;
       }
     }
};
template<class T>
bool Stack<T>::stack_empty(){
  if(top==-1)
    return true;
  else
    return false;
}

template<class T>
void Stack<T>::push(T val){

  if(top>=-1){
    top++;
    Node *node=new Node(val);
    Node *tmp=head;
    if(tmp==nullptr) head=node;
    else{
        while(tmp->next!=nullptr)
            tmp=tmp->next;
        tmp->next=node;
    }
  }
  else
    std::cout<<"Overflow"<<std::endl;
}

template<class T>
T Stack<T>::pop(){
  if(stack_empty()==true)
    std::cout<<"Underflow"<<std::endl;
  else{
    top--;
    Node *node=head;
     while(node->next!=nullptr){
        node=node->next;
     }
    return node->data;
  }
}

template<class U>
std::ostream & operator <<(std::ostream& os, const Stack<U>& s){
s.display(os);
return os;
}

template<class T>
Stack<T>::~Stack(){
Node *tmp=nullptr;
  while(head){
    tmp=head;
    head=head->next;
    delete tmp;
  }
  head=nullptr;
}
int main()
{
 Stack<int> stack1;

 stack1.push(3);
 stack1.push(4);
 stack1.push(11);
 stack1.push(30);
 std::cout<<stack1<<std::endl;
 std::cout<<stack1.pop()<<std::endl;
    return 0;
}


texts: SKAction on SKLabel with array of Strings

texts:
I have an SKLabel attached to a parent SKNode and an array of strings:

let configText:[String] = [
                            "Configuration",
                             "Do stuff",
                             "Do more stuff",
                             "Nil",
                             "It is the void"]

The array is looped through with the following:

parentNode_Label.run(
  SKAction.sequence([
    SKAction.run{
      if self.counter == self.configText.count - 1
      { self.counter = 0 } },
    SKAction.wait(forDuration: 3.0),
    SKAction.run { self.sprite_Label.text = self.configText[self.counter + 1] },
    SKAction.fadeIn(withDuration: 0.5),
    SKAction.wait(forDuration: 3.0),
    SKAction.fadeOut(withDuration: 0.5),
    SKAction.run{ self.counter += 1 }
    ]).forever()
)

extension SKAction
public func forever() -> SKAction { return SKAction.repeatForever( self ) }
}

It works but seems kind of clunky/hacky. Is there a simpler, more efficient yet readable way to do this?


texts: Testing whether a string contains valid JSON by calling json_decode()

texts:
I had a code review and got told by the senior programmer that it was very bad programming practice to use the json_decode() function of php to determine if a string was not in JSON format.

My argument was that the json_decode function has a fail case (returning NULL) and this exists for reasons such as the purpose I was using it for.

I got sat down one on one and told to never pass data to a function that was not intended for the function (in this case referring to passing a hex string to the json_decode() function).

Is what I did bad coding practice? How should I have written the code?

Here is the php code of what I basically did:

//example JSON Data
/*
$ExampleData = '
{
    "test": "48656c6c6f20576f726c64"
}
';
*/

//the most common case is that a hex string sent to the php script
$ExampleData = "48656c6c6f20576f726c64";

$jsonData = json_decode($ExampleData);

//one in every 1000 responses is JSON data
if($jsonData)
{
    //extract varaibles from the json
    print ("JSON data recieved");
}
else
{
    //response is hex so carry out normal function
    print ("Hex Data recieved");
}

try it online


texts: Excuse me, how many of you are new here? Mind if I JOIN you?

texts:
I had perceived an uptick in new reviewers around here, and I wanted to see if the data backed that observation up. It's been a while since I've written any SQL, so this was a nice little exercise in using the Stack Exchange Data Explorer.

The query finds the first question and first answer from every user, and then groups those first posts by week. It turns out that I was right, but the growth of first questions is outpacing the growth of first answers.

The query feels repetitive and I'm not a huge fan of the Full Outer Join.
Is there a better way to write this?

WITH FirstAnswers
AS (
  SELECT
    Users.Id UserId
    ,dateadd(week, datediff(week, 0, Convert(Date,Min(Posts.CreationDate))), 0) WeekOf
  FROM Posts
  INNER JOIN Users
    ON Posts.OwnerUserId = Users.Id
  WHERE PostTypeId = 2 --answer
    AND Posts.CreationDate > '2011-Jan-01' --There was very little activity prior to this date. Including it skews the graph.
  GROUP BY Users.Id
),

FirstQuestions
AS (
  SELECT
    Users.Id UserId
    ,dateadd(week, datediff(week, 0, Convert(Date,Min(Posts.CreationDate))), 0) WeekOf
  FROM Posts
  INNER JOIN Users
    ON Posts.OwnerUserId = Users.Id
  WHERE PostTypeId = 1 --question
    AND Posts.CreationDate > '2011-Jan-01' --There was very little activity prior to this date. Including it skews the graph.
  GROUP BY Users.Id
)

SELECT ISNULL(a.WeekOf,b.WeekOf) As WeekOf
  , a.AnswerCount, b.QuestionCount
FROM (
  SELECT WeekOf, Count(UserId) AnswerCount
  FROM FirstAnswers
  GROUP BY WeekOf
) a
FULL OUTER JOIN (
  SELECT WeekOf, Count(UserId) QuestionCount
  FROM FirstQuestions
  GROUP BY WeekOf
 )b
ON a.WeekOf = b.WeekOf
ORDER BY WeekOf


texts: Flux architecture implementation (vanilla JS)

texts:
I'm trying to better understand flux-style architecture, so I wrote this snippet to clarify how a simple flux system can be designed. I was wondering if my implementation is valid, or if I've missed something.

const application = () => {
  /* Init the model */
  let model = {
    page: null
  };

  /* redirects the reference from the old state to the new */
  const updateState = newState => model = newState;

  /* a reducer method, more are easily added */
  const UPDATE_PAGE = (model, newPage) => {
    let newState = Object.assign({}, model);
    newState.page = newPage;
    updateState(newState);
  };

  /*
   * dispatch is a core function, directing every action
   * to the proper reducer depending on the `type`
   */
  const dispatch = action => {
    action.type === 'UPDATE_PAGE' ?
      UPDATE_PAGE(model, action.page)
      : null;
  };

  /* An action mutating state */
  let updatePageAction = {
    type: 'UPDATE_PAGE',
    page: 1
  };

  console.log('initial model: ', model);

  /* simply dispatch the action */
  dispatch(updatePageAction);

  /* and the state is updated! */
  console.log('updated model: ', model);
};

application();


texts:
I am trying to solve the Travelling Salesman Problem. This function creates the first level in the form of a linked list.

This is what the levels look like:

This is the code that creates it:

vector<pot> noviNivo;
    int tempInt = vozliscaG - 1;

    for (int i = 0; i < vozliscaG-1; i++) {

        pot temp;
        temp.iz_vozlisca = tempInt;
        temp.v_vozlisce = 0;
        temp.cena = mat[tempInt][temp.v_vozlisce];
        temp.mnozica.push_back(false);
        tempInt--;
        noviNivo.push_back(temp);

    }

    for (int i = 1; i < vozliscaG - 1; i++) {
        noviNivo[i-1].naslednji = &noviNivo[i];
    }

Also, sorry that the variables names are in another language, but I think aren't really relevant to the question. My question is, am I using the pointers and dereferencing them correctly or will I run into problems further on in the code? Also, I am doing it this way because I don't want to end up with a vector of pointers to the struct, I just want the vector of the structs.


texts: Removing whitespace in self-closing node and keeping UTF-8 hex entity values intact?

texts:
I work with some xml files which have UTF-8 characters like &#x00A9;, &#x00EB; but they are converted to their image counterparts i.e. ©, ë, whenever I use XDocument to modify the file and also the self-closing nodes e.x.  become  i.e. an extra whitespace is added to the node, but I want to keep the entities like ©, ë etc as it is and also remove the extra whitespace in the self-closing nodes.

Currently I'm doing it in below fashion (sample example code)

var path = @"C:\Users\Temp\sample.xml";
var content=File.ReadAllText(path);
//replace all "&" with "&amp;" to prevent conversion of entity
var newcontent=content.Replace("&", "&amp;");
File.WriteAllText(path,newcontent);
XDocument doc = XDocument.Load(path, LoadOptions.PreserveWhitespace);
string _count = doc.Descendants("fig").Count().ToString();
doc.Descendants("fig-count").First().Value = _count;
doc.Save(path, SaveOptions.DisableFormatting);
//replace all "&amp" with "&" to go back to the original state and also replace all whitespace
//in the self-closing nodes after the XDocument process complets
var x=File.ReadAllText(path);
var y=x.Replace(" />", "/>");
File.WriteAllText(path,y.Replace("&amp;", "&"));

Can anyone show me a more efficient way of doing this?


texts: Leetcode longest substring with no duplicates

texts:
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        longest = ''
        max_len = 0
        for key,value in enumerate(s):
            if value in longest:
                longest = longest[longest.index(value)+1:] + value
            else:
                longest+=value
            max_len = max(max_len,len(longest))
        return max_len

Here is my solution for leetcode's "longest-substring-without-repeating-characters question". I don't quite understand why my time complexity is so efficient (99% out of all python submissions). Since strings are immutable in python, assuming a strength of length n, won't my algorithm be $$ 1+2+3+...n-1+n = O(n^2)$$ time? But the optimal solution is on \$O(n)\$ yet the runtime from the testcases says my solution is just as good as the optimal one provided?Am I missing something. Also I am having a hard time proving the space complexity for my solution as well.


texts: Extracting Country Names from Cell Values

texts:
This fairly clunky looking VBA script successfully pulls names of countries from an Array, but could it be made shorter?

Mass of text from Column C onward in each row may contain the names of countries, which I want to pull into the corresponding cell in row A. What I have so far is not pretty...

Sub PullCountries()
Dim Rng As Range
Dim Block As Range
Dim i As Long
i = 1

Dim LastRow As Long
LastRow = Range("B1").End(xlDown).Row

While i <= LastRow
Set Rng = Range("B" & i)
Set Block = Rows(i)

Range("I1").Value = i

If InStr(1, Range("C" & i), "Canada") Or InStr(1, Range("D" & i), "Canada") Or InStr(1, Range("E" & i), "Canada") Then
Rng.Offset(0, -1).Value = "Canada"
i = i + 1
ElseIf InStr(1, Range("C" & i), "United States") Or InStr(1, Range("D" & i), "United States") Or InStr(1, Range("E" & i), "United States") Then
Rng.Offset(0, -1).Value = "United States"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Britian") Or InStr(1, Range("D" & i), "Britian") Or InStr(1, Range("E" & i), "Britian") Then
Rng.Offset(0, -1).Value = "UK"
i = i + 1
ElseIf InStr(1, Range("C" & i), "UK") Or InStr(1, Range("D" & i), "UK") Or InStr(1, Range("E" & i), "UK") Then
Rng.Offset(0, -1).Value = "UK"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Spain") Or InStr(1, Range("D" & i), "Spain") Or InStr(1, Range("E" & i), "Spain") Then
Rng.Offset(0, -1).Value = "Spain"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Portugal") Or InStr(1, Range("D" & i), "Portugal") Or InStr(1, Range("E" & i), "Portugal") Then
Rng.Offset(0, -1).Value = "Portugal"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Ireland") Or InStr(1, Range("D" & i), "Ireland") Or InStr(1, Range("E" & i), "Ireland") Then
Rng.Offset(0, -1).Value = "Ireland"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Japan") Or InStr(1, Range("D" & i), "Japan") Or InStr(1, Range("E" & i), "Japan") Then
Rng.Offset(0, -1).Value = "Japan"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Greece") Or InStr(1, Range("D" & i), "Greece") Or InStr(1, Range("E" & i), "Greece") Then
Rng.Offset(0, -1).Value = "Greece"
i = i + 1
ElseIf InStr(1, Range("C" & i), "Italy") Or InStr(1, Range("D" & i), "Italy") Or InStr(1, Range("E" & i), "Italy") Then
Rng.Offset(0, -1).Value = "Italy"
i = i + 1

ElseIf Application.WorksheetFunction.CountA(Rng.Offset(0, 1)) = 0 Then
i = i + 1

Else: i = i + 1
End If
Wend
End Sub

Obviously, this isn't pretty. And given that the task is very repetitive, I reckon it could be made shorter. If this is possible, how could I start.

Furthermore, would it be possible to pull from an array of countries pre-prepared in another worksheet, and refer to that instead of inserting the actual names into the code, as is done here? And finally, if a range contained more than one country, how could I expand the code to pull that information too?


texts: How to download tgz file from a url and decompress it efficiently?

texts:
I have a .tgz file that I need to download given a url inside a Testing folder and then decompress it. I am able to download the .tgz file successfully from the url and also able to successfully decompress it without any issues. My .tgz file will be approx 100 MB max. I am using SharpZipLib library here to decompress.
There are two parts to this:

Download .tgz file from a url in a particular folder.
If file is downloaded successfully then only decompress .tgz file in that same folder othewise not.

Below is my code:
private void DownloadTGZFile(string url, string fileToDownload)
{
    using (var client = new WebClient())
    {
        client.DownloadFile(url + fileToDownload, "Testing/configs.tgz");
    }
    Stream inStream = File.OpenRead("Testing/configs.tgz");
    Stream gzipStream = new GZipInputStream(inStream);

    TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
    tarArchive.ExtractContents("Testing/");
    tarArchive.Close();

    gzipStream.Close();
    inStream.Close();
}

Question:
I wanted to check on below things:

Is using WebClient efficient here? If not, then what can I use to download the file efficiently for me considering file size is 100 MB max?
Also can I add a timeout here so that if I am not able to download the file in that time period, then it just times out. But it should retry for 3 times (or with some retry policy) and skip it if not able to by logging an error for the last try.
And if it is able to download the .tgz file successfully then decompress it in the same folder.

I am a newbie who started working with C# so still confuse on usage of WebClient and not sure if it is the right way to do it also. And this will be a production code so wanted to see what's the best way to re-write this whole code if there is any.


texts: Chatroom log in with no 3rd party libraries

texts:
So, I'm creating a chatroom with no 3rd party libraries and currently I'm logging people in like this:

public void run() {
    try {
        this.running = true;
        ServerSocket ss = new ServerSocket(1000);
        while (this.running) {
            this.threadPool.execute(new InfoGrabber(ss.accept()));
        }
    } catch (IOException ex) {
        Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private class InfoGrabber implements Runnable {

    private final Socket socket;

    public InfoGrabber(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Object obj = ois.readObject();
            if (obj instanceof ClientInformation) {
                clientManager.addClient(new ClientClass((ClientInformation) obj, new ClientConnection(socket, ois, ((ClientInformation)obj).getUUID())));
                System.out.println("Client connected");
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Is there a better way to do this?
Git for more context https://github.com/CjStaal/ChatRoom
I have a systemQueue set up which takes SystemMessage which is a string, and an object. I want to be able to make this better, and have it more encapsulated and modular to allow easier maintainability and expandability. In the long run, I want it to be able to authenticate against a SQL database.


texts:
I want to convert these loops into simple loop. I want the code to look neat and short. I saw answers related to LINQ but couldn't make out from that. Are there any other possible ways for this snippet?

XmlDocument manifestXmlFile = new XmlDocument();
manifestXmlFile.Load(manifestFileName);

foreach (XmlNode rules in manifestXmlFile.DocumentElement.ChildNodes)
{
    foreach (XmlNode ruleNode in rules)
    {
        foreach (XmlNode childNodeAttributes in ruleNode)
        {
            foreach (XmlNode childNodeAttrib in childNodeAttributes.ChildNodes)
            {
                XmlElement ruleElement = (XmlElement)ruleNode;
                foreach (XmlNode childNodeConditions in childNodeAttrib.ChildNodes)
                {
                    foreach (XmlNode childNodeCond in childNodeConditions.ChildNodes)
                    {
                        if (childNodeCond.Name.ToUpper() == "CONDITION")
                        {
                            if (childNodeCond.Attributes["type"].Value.ToUpper() == "HEALTHY")
                            {
                                string ruleId = ruleElement.Attributes["ruleid"].Value;
                                string attributeName = childNodeAttrib.Attributes["name"].Value;
                                string attributeType = childNodeAttrib.Attributes["type"].Value;
                                string condTypeValue = childNodeCond.Attributes["type"].Value;
                                string operatorValue = childNodeCond.Attributes["operator"].Value;
                                string healthyConditionValue = childNodeCond.FirstChild.InnerText;

                                var guid = new Guid(ruleId);

                                //Conversion of enum types
                                PsmsOperator psmsOperator = (PsmsOperator)Enum.Parse(typeof(PsmsOperator), operatorValue, true);
                                TypeCode psmsAttributeType = (TypeCode)Enum.Parse(typeof(TypeCode), attributeType, true);

                                Rule rule = new Rule(guid, attributeName, healthyConditionValue, psmsOperator);

                                Rule(attributes, guid);
                           }
                        }
                    }
                }
            }
        }
    }
}

Is there any other better way than this or LINQ?


texts:
I have a serious nesting of ifs in a helper code and I would like to making cleaner. I would like to avoid case if possible as well.

I know there is probably a more object-oriented approach to this but I can't seem to know how.

I'm flooded with stuff like this:

  def print_flight_options_status(invitation)
    if invitation.group.travel_class == 'none'
      not_allowed
    elsif invitation.refused_flight_options?
      not_needed
    elsif invitation.selected_flights?
      waiting_reservation
    elsif invitation.flight_options.empty?
      not_sent_yet
    elsif invitation.requested_more_flight_options?
      rejected
    else
      waiting_guest_input
    end
  end

  def print_event_terms_status(invitation)
    if invitation.event_terms_status.nil?
      "Aguardando"
    elsif invitation.accepted_event_terms?
      "Aceito"
    elsif invitation.rejected_event_terms?
      "Declinado"
    elsif invitation.cancelled_event_terms?
      "Cancelado"
    end.html_safe
  end


texts:
The previous iteration at Parallel for loop in Java 8 - follow-up.

The changes are as follows:

MyTask is removed.
Synchronization removed. Now the user is assumed not to tamper with the input list concurrently while some forp is working on it.
Actual forp implemented using Java 8 -facilities.

The only changed file (ParallelFor.java):

package net.coderodde.util;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * This class implements the parallel for loop. It is assumed that two distinct
 * tasks in the loop are independent, i.e., one task needs no output data from
 * another task.
 *
 * @author Rodion Efremov
 * @version I
 */
public class ParallelFor {

    /**
     * Implements the actual parallel for loop. The user is responsible for not
     * to modify inputList while some invocation of
     * forp is using it.
     *
     * @param         the type of input data.
     * @param <O>        the type of output data.
     * @param inputList  the list of individual arguments to the routine to
     *                   parallelize.
     * @param body       the actual function transforming an input datum into an
     *                   output datum. May be specified in the form of a
     *                   lambda expression.
     * @return the list of output data in the same order as input data.
     */
    public static final
        List<O> forp(final List inputList,
                     final Function body) {
            return inputList.parallelStream()
                            .map(body)
                            .collect(Collectors.toList());
    }
}


texts: Determining which command line arguments are numeric

texts:
I am working on using STL and in general safe C++ practices. Instead of posting large samples of code I am working with a small sample to catch problems before I move onto larger ones.

How do you find out if an istringstream found an input that is not of the desired type?  That is, you have a string and you want to verify if it is a float or not.

Using the program below, when I input

[mehoggan@desktop argument_processing]$ ./args 1 2 3 4 2y

I get:

1 2 3 4 2

which is not what I want, since not all arguments where numeric.

I should of gotten:

ERROR: 2y is not numeric

What improvements would you make to this small program?

#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>

namespace CLP {
    using std::vector;
    using std::istringstream;
    using std::string;
    using std::cerr;
    using std::endl;

    vector<float> all_numeric_arguments( int argc, char *argv[ ] ) {
        vector<float> v_argv;
        vector<string> v_tmp;
        copy( &argv[1],&argv[argc],back_inserter( v_tmp ) );
        for( vector<string>::iterator it=v_tmp.begin( );it!=v_tmp.end( );it++ ) {
            istringstream iss( (*it) );
            float f=0.0;
            if( iss >> f >> std::dec ) {
                v_argv.push_back( f );
            } else {
               cerr << "ERROR: " << (*it) << " is not numeric " << endl;
               return v_argv;
            }
        }
        return v_argv;
    }
}

int main( int argc, char *argv[ ] ) {
    std::vector<float> v = CLP::all_numeric_arguments( argc, argv );
    if( v.size( ) == (unsigned)(argc-1) ) {
        copy( v.begin( ),v.end( ),std::ostream_iterator<float>( std::cout," " ) );
        std::cout << std::endl;
    }
}


texts: Print Bootstrap 3 Tabs Component using only one foreach Loop

texts:
I'm using Bootstrap 3 to build a tab-panel component, based on information coming from the end-user. I don't like how there's a second foreach loop, but I don't know how else to print the HTML correctly.

Given an array structured like this:

[
    {
        "title": "Title 1",
        "content": "Lorem Ipsum"
    },
    {
        "title": "Title 2",
        "content": "Lorem Ipsum"
    }
]

And a "view" template structured like this:

<?php $panels = rwmb_meta("ssc_tabpanels") ?>
<?php if( !empty($panels) ): ?>

            <?php foreach($panels as $i => $p): ?>

                <a href="#tab-<?php echo $i ?>" data-toggle="tab"><?php echo $p['title'] ?>

            <?php endforeach; ?>

            <?php foreach($panels as $i => $p): ?>
            <div class="tab-pane" id="tab-<?php echo $i ?>"><?php echo $p['content'] ?>

            <?php endforeach; ?>

<?php endif; ?>

What suggestions do you have for removing the second foreach loop while still maintaining the correct bootstrap code?


texts: std::vector composition with self populating super-powers

texts:
I have written a deliberately pretty simple class that wraps a std::vector to basically make it capable of self-populate itself with random generated numbers, simply to  be able to test the result of some sorting algorithms that I'm working on.

This is only a hobby project, it is not production code :-) so I'd like to know if there are any ways to improve this design or my approach.

Besides good practices, style and design, two of my biggest doubts are:

populate(): If I had used std::iota() followed by std::shuffle, as explained on the comments, I believe that the code would be much smaller, simpler and would kind-of have the same result (it wouldn't allow repeated numbers, as it does now).
std::mt19937 and std::uniform_int_distribution: mostly, if their implementation looks... OK. Looks like the need to explicitly seed the vector is inevitable, but I don't really like it. :-( this would obviously be avoided if I used my std::iota() implementation. I feel like this breaks the class' "super-powers".

Edit: Forgot to add that, regarding number 2, I'm also a bit curious about the way I'm seeding the engine. Does it looks correct?

Following, the header file:

#ifndef algorithmicVec_H
#define algorithmicVec_H

#include <vector>
#include <random>
#include <chrono>
#include <cstdint>

/**
*  std::vector composition with pseudo-random number self-populating capabilities
*/
class algorithmicVec {
private:
  std::vector<uint32_t> vec;
  static std::mt19937 gen;
  static std::uniform_int_distribution<uint32_t> uint_dist99;

  /**
  *  Returns a random uint32_t within the range of 0..99
  */
  uint32_t getRandomNumber();

public:
  /**
  *  Seeds static std::mt19937 with the current time in milliseconds since epoch
  */
  static void seed();

  /**
  *  Populates the vector with n elements using a std::uniform_int_distribution
  *  fed with std::mt19937.
  *
  *  Using std::iota() followed by std::shuffle was considered, but not implemented
  *  mostly because random generated numbers seemed more interesting at the time,
  *  even to observe the result of the tested algorithms with possible repeated numbers.
  */
  void populate (int sz);

  /**
  *  Returns item at position pos
  */
  uint32_t at(int pos);

  /**
  *  Returns an iterator to the first item of the vector
  */
  std::vector<uint32_t>::iterator begin();

  /**
  *  Returns an iterator past-to-the-end of the vector
  */
  std::vector<uint32_t>::iterator end();
};

#endif

The implementation file:

#include "algorithmicVec.hpp"

std::mt19937 algorithmicVec::gen;
std::uniform_int_distribution<uint32_t> algorithmicVec::uint_dist99(0, 99);

void algorithmicVec::seed() {
  unsigned long seed = std::chrono::system_clock::now().time_since_epoch() /
                       std::chrono::milliseconds(1);
  gen.seed(seed);
}

void algorithmicVec::populate (int sz) {
  for (int i = 0; i < sz; ++i) {
    vec.push_back(getRandomNumber());
  }
}

uint32_t algorithmicVec::getRandomNumber() {
  return uint_dist99(gen);
}

uint32_t algorithmicVec::at(int pos) {
  return vec.at(pos);
}

std::vector<uint32_t>::iterator algorithmicVec::begin() {
  return vec.begin();
}

std::vector<uint32_t>::iterator algorithmicVec::end() {
  return vec.end();
}

A minimal test case:

#include <iostream>
#include "algorithmicVec.cpp"

int main() {
  algorithmicVec::seed();
  algorithmicVec myVec;
  myVec.populate(10); // populates myVec with 10 random numbers
  for (auto a: myVec) {
    std::cout << a << std::endl;
  }
}


texts: Javascript - Replace lots of if statements

texts:
I have a a couple of different radio buttons which return an ethnicity and a gender. The script runs inside an internal application so rather than returning "boy", "girl" or "both" I get back 7707330, 7707333, and 7707336. Similar from the ethnicity radio button.

I then need to validate data based on the combonation of ethnicity and gender. This was a pretty simple task but I have ended up with 15 if statements! It all works as it should, but there must be a cleaner solution?

    function test(radioResults) {

    var1 = radioResults[0].toString();
    var2 = radioResults[1].toString();
    roll = parseFloat(parent.roll);

    if (var2 == '7707330') {
        gender = 'boy';
    }
    if (var2 == '7707333') {
        gender = 'girl';
    }
    if (var2 == '7707336') {
        gender = 'both';
    }

    if (var1 == '7707341') {
        maori(gender);
    }
    if (var1 == '7707344') {
        pasifika(gender);
    }
    if (var1 == '7707347') {
        all(gender);
    }
}

function maori(gender) {
    //Maori
    if (gender == 'boy') {
        ethnicity = parseFloat(parent.getMBoys);
        validation(ethnicity);
    }
    if (gender == 'girl') {
        ethnicity = parseFloat(parent.getMGirls);
        validation(ethnicity);
    }
    if (gender == 'both') {
        ethnicity = parseFloat(parent.getTotalM);
        validation(ethnicity);
    }
}

function pasifika(gender) {
    //Pasifika
    if (gender == 'boy') {
        ethnicity = parseFloat(parent.getPBoys);
        validation(ethnicity);
    }
    if (gender == 'girl') {
        ethnicity = parseFloat(parent.getPGirls);
        validation(ethnicity);
    }
    if (gender == 'both') {
        ethnicity = parseFloat(parent.getTotalP);
        validation(ethnicity);
    }
}

function all(gender) {
    //All
    if (gender == 'boy') {
        ethnicity = parseFloat(parent.getBoys);
        validation(ethnicity);
    }
    if (gender == 'girl') {
        ethnicity = parseFloat(parent.getGirls);
        validation(ethnicity);
    }
    if (gender == 'both') {
        ethnicity = parseFloat(parent.getTotalRoll);
        validation(ethnicity);
    }
}

function validation(ethnicity) {

    percent = ethnicity * 5 / 100;

    if (ethnicity - percent > roll || (ethnicity + percent < roll)) {
        parent.document.getElementById('CF_7784443').value = "FAIL";
    } else {
        parent.document.getElementById('CF_7784443').value = "PASS";
    }
}


texts: Reduce one for loop to decrease time complexity

texts:
I'm using NumPy to find out langrage polynomial interpolation. I'm using 2 for loop to find out langrage polynomial, but I want to reduce 2nd for loop so that my code time complexity can be less. Can you guys please suggest me how I can cut a for loop to increase my time complexity.
import numpy as np
import matplotlib.pyplot as plt
class LagrangePolynomial:
    def __init__(self, data_x, data_y):

        assert type(data_x) == np.ndarray, "data_x is not numpy array"
        assert type(data_y) == np.ndarray, "data_y is not numpy array"
        assert len(data_x) == len(data_y), "length of data_x and data_y must be equal"

        self.x = data_x
        self.y = data_y

        self.degree = len(data_x) - 1

    def __str__(self):
        strL = f"LagrangePolynomial of order {self.degree}\n"
        strL += "p(x) = "
        count=0
        for i in self.y:
            if i == 0:
                continue
            elif i >= 0:
                strL += f"+ {i}*l_{count + 1}(x) "
            else:
                strL += f"- {-i}*l_{count + 1}(x) "
            count+=1
        return strL
    def __call__(self,x):
        y_interp = np.zeros(len(x))
        for i in range(len(x)):
            #remove this for loop.
            for j in range(self.degree + 1):
               upper=np.prod(np.delete(self.x - x[i],j))
               lower=np.prod(np.delete(self.x[j] - self.x, j))
               y_interp[i] +=(upper/lower)*self.y[j]
        return y_interp
data_x = np.array([-3.,-2.,-1.,0.,1.,3.,4.])
data_y = np.array([-60.,-80.,6.,1.,45.,30.,16.])

p = LagrangePolynomial(data_x, data_y)

#generating 100 points from -3 to 4 in order to create a smooth line
x = np.linspace(-3, 4, 100)
print(p)
y_interp = p(x)
plt.plot(x, y_interp, 'g--')
plt.plot(data_x, data_y, 'ro')
plt.legend(['interpolated', 'node points'], loc = 'lower right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Lagrange Polynomial')

plt.show()


texts: Python program to get all non unique elements in an array

texts:
Given an array of ints as input:

non_unique([1, 2, 3, 1, 3]) returns [1, 3, 1, 3]
non_unique([1, 2, 3, 4, 5]) returns []
non_unique([5, 5, 5, 5, 5]) returns [5,5,5,5,5]
non_unique([10, 9, 10, 10, 9, 8]) returns [10, 9, 10, 10, 9]

The code itself:

def checkio(originalList: list) -> list:

    checked_list = []
    result_list = []

    for i, number in enumerate(originalList):
        if number in checked_list:
            result_list.append(number)
        else:
            if (len(originalList) - 1) - i > 0:
                if number in originalList[i+1:]:
                    result_list.append(number)
        checked_list.append(number)

    return result_list

How can be the code improved?


texts: Project Euler #10 in Ruby - summation of primes

texts:
I'd like to have some feedback as to the performances of the algorithm.

class Sumprime
    attr_accessor :number

    def initialize(number)
        self.number = number
        prime_serie
    end

    def is_prime?(num)
        counter = 2
        root_num = Math.sqrt(num).ceil
            while counter <= root_num
                    if num % counter == 0 && num != counter
                        return false
                        break
                    else
                        counter += 1
                    end
            end
            return true
    end

    def percentage_prime
        ((prime_serie.size / number.to_f) * 100)
    end

    def prime_serie
        prime_array = [1]
        counter = 2
        while counter < number
            if is_prime?(counter)
                prime_array << counter
                counter += 1
            end
            counter += 1
        end
        prime_array.inject(:+)
    end
end


texts:
I have read this and I want to know how the solution that I came up with in my interview compares with the top solution.

public static String reverseWords(String s) {
    if (s == null) return null;
    else if (s.equals("")) return "";
    else {
        s = s.trim();
        int index;
        for (index = 0; index < s.length(); index++) {
            if (s.charAt(index) == ' ') break;
        }
     String res = reverseWords(s.substring(index)) + " " + s.substring(0, index);
        return res.trim();
    }
}

My code is more space inefficient, as I was concatenating instead of appending, so I created many copies of new strings. What about time complexity though? They both seem to be in \$O(n)\$ time, but I'm not sure about the constant factors.

Also, how does split() specifically perform against charAt()? I knew about the split() operation, but I opted for charAt() because I thought that split() was more expensive (wasn't sure; but I think it does some regex processing, which may be expensive). Should I have opted for split() instead?


texts:
I am a recent beginner in Java and have attempted a simple Caesar cipher (using only lowercase):

public class RunEncryption
{
    public static void main(String[] args)
    {
        SecretMessage test1 = new SecretMessage();
        test1.setMessage("hello");
        test1.display();
        test1.encrypt(1);
    }

}

This is my class with the main method in it:

public class SecretMessage
{
    String message;

    void setMessage(String newMessage) {
        message=newMessage;
    }

    void display() {
        System.out.println(message);
    }

    void encrypt(int key) {
        int len = message.length();
        for(int i=0; i<len; i++) {
            char c = message.charAt(i);
            c = (char)(c+key);
            System.out.print(c);
        }
    }

}

This works thankfully. I will get to wrapping the letters around. But I want to ask if there is anything maybe unconventional about this or if it is inefficient code. Any help would be appreciated as I am still a beginner. Also, how long does it take to make this code? It took me far too long.


texts:
I have a class that I use to communicate with some hardware equipment (a step motor to be precise):

public class HdCommunicator : IDisposable
{
    private TcpClient client;
    public HdCommunicator(TcpClient _client)
    {
        client = _client;

        //create and start the listener
        Thread t = new Thread(new ThreadStart(() => { Listen(); }));
        t.Start();
    }

    public void SendCommand(int data)
    {
        NetworkStream ns = client.GetStream();
        var msgToSend =
            Encoding.UTF8.GetBytes("mr " + data + ",1" + Environment.NewLine);
        ns.Write(msgToSend, 0, msgToSend.Length);

        ns.Flush();
    }

    private void Listen()
    {
        while (client.Connected)
        {
            try
            {
                NetworkStream ns = client.GetStream();

                byte[] bytes = new byte[1024];
                int bytesRead = ns.Read(bytes, 0, bytes.Length);

                string response = Encoding.ASCII.GetString(bytes, 0, bytesRead);

                //TODO raise event
                Console.WriteLine("Response: " + response);
            }
            catch (Exception ex)
            {
                if (!client.Connected)
                { /*ignore*/ }
                else
                {
                    Console.WriteLine("Listener error: " + ex.Message);
                }
            }
        }
    }

    public void Dispose()
    {
        client.Close();
    }
}

And this is how I currently use it:

    static int port = 503;
    static string host = "192.168.33.1";

    static void Main(string[] args)
    {
        HdCommunicator comm = new HdCommunicator(new TcpClient(host, port));

        string res = "";
        while (res != "e")
        {
            Console.WriteLine("Where to send: ");
            res = Console.ReadLine();

            if (res != "e")
                comm.SendCommand(int.Parse(res));
        }

        comm.Dispose();

        Console.WriteLine("Finished");
        Console.ReadLine();
    }

Am I utilizing the TCP Client correctly? I'm particularly concerned about the streams' usage and disposing of them. Am I doing it right?


texts: Reverse binary representation of an int (only significant bits)

texts:
This based on this question in StackOverflow. The accepted answer uses Convert.ToString(int, base) to get the binary string, reverses it and converts it back to int. Nice trick!

I have very little experience with bit twidling (using Flags is about it :p ) so I decided to try and code the solution to this problema without using Convert.

I came up with the following solution. I'd like to know easier ways to do this as there are probably many much better than the one I found.

public static IEnumerable<bool> ToBinary(this int n)
{
    for (int i = 0; i < 32; i++)
    {
        yield return (n & (1 << i)) != 0;
    }
}

public static int ToInt(this IEnumerable<bool> b)
{
    var n = 0;
    var counter = 0;

    foreach (var i in b.Trim().Take(32))
    {
        n = n | (i ? 1 : 0) << counter;
        counter++
    }

    return n;
}

private static IEnumerable<bool> Trim(this IEnumerable<bool> list)
{
    bool trim = true;

    foreach (var i in list)
    {
        if (i)
        {
            trim = false;
        }

        if (!trim)
        {
            yield return i;
        }
    }
}

And now you'd use it like this:

var reversed = n.ToBinary().Reverse().ToInt();


texts: Ensuring array of worksheets are present

texts:
I have a sub which should only continue running if 4 specific worksheets are present. From online reading, such as @Tim Williams's comment in Test or check if sheet exists, I know that using an error thrown, to determine a course of action, can be frowned upon, but I found similar usage to mine in both that question and here.

Here is a simplified version:

Private Sub Test()

 If AllSheetsPresent Then MsgBox "Doing something"

End Sub

Private Function AllSheetsPresent() As Boolean

  AllSheetsPresent = True

  Dim SheetsArr()

  On Error GoTo errhand
  SheetsArr = ThisWorkbook.Sheets(Array("Response Times", "Incidents", "Calls", "Resources", "NoC, CPR"))

  Exit Function

errhand:
  If Err.Number = 9 Then
      AllSheetsPresent = False
      MsgBox "Sheets are missing from..."
      End
  End If

End Function

Notes:

For the purposes of testing I am using ThisWorkbook. It would otherwise be a workbook variable passed to the function.

Questions:

Is there a better way to perform this validation?
Related to 1) are there any risks associated with this approach I should be aware of?
If AllSheetsPresent Then MsgBox "Doing something" feels in some way superfluous as if False the code has stopped anyway. Again, this feels like an extension of 1) can this be re-written in a better way?

As this is working code I have posted here in the hope it is the right place to ask.


texts: Sorting an ArrayList of Vehicles using quick sort

texts:
For an assignment I have to sort an ArrayList of Vehicle objects using the quick sort method. I have come up with two implementations for this, which would be the best to use? Is method 1 considered quick sort since it splits the array?

Method 1

protected ArrayList<Vehicle> quickSort(ArrayList<Vehicle> list)
{
    if (list.size() <= 1)
        return list; // Already sorted

    ArrayList<Vehicle> sorted = new ArrayList<Vehicle>();
    ArrayList<Vehicle> lesser = new ArrayList<Vehicle>();
    ArrayList<Vehicle> greater = new ArrayList<Vehicle>();
    Vehicle pivot = list.get(list.size()-1); // Use last Vehicle as pivot
    for (int i = 0; i < list.size()-1; i++)
    {
        //int order = list.get(i).compareTo(pivot);
        if (list.get(i).compareTo(pivot) < 0)
            lesser.add(list.get(i));
        else
            greater.add(list.get(i));
    }

    lesser = quickSort(lesser);
    greater = quickSort(greater);

    lesser.add(pivot);
    lesser.addAll(greater);
    sorted = lesser;

    return sorted;
}

Method 2

protected ArrayList<Vehicle> quickSort(ArrayList<Vehicle> list, int a, int b)
{
    if (a >= b)
        return list;

    Vehicle pivot = list.get(b);

    int left = a;
    int right = b;

    while (left < right)
    {
        while(list.get(left).compareTo(pivot) < 0)
            left++;

        while(list.get(right).compareTo(pivot) > 0)
            right--;

        if (right > left);
        {
            Collections.swap(list, left, right);
        }
    }

    quickSort(list, a, right-1);
    quickSort(list, right+1, b);

    return list;
}

Now the problem with Method 2 is that my protected quickSort is called from

public ArrayList<Vehicle> quickSort()
{
    return quickSort(vehicleList);
}

which I'm not allowed to modify, so I'd need to overload the method again and call my version with the two extra integer parameters. Would this just be messy doing another overload?


texts:
I want to check if there is page variable (in URL) and if it is, if it's correct - it cannot be number 1 because this is default page and it should be valid int from 2 to max number of pages (not octal and not hexadecimal).

<?php

$_GET['page'] = '01'; // this line is only for testing

$selPage = 1;
$totalPages = 10;

if (isset($_GET['page'])) {
    $selPage = filter_var($_GET['page'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 2, 'max_range' => $totalPages]]);
    if ($selPage === false) {
        exit('redirection'); // this line for test only - in fact make 301 redirection here to correct url
    }
}
echo $selPage;

Could it be improved anyway, or is it the best and shortest it can be?


texts:
I'm working on a problem to sort array by low, medium and high -- in-place tweak original array. I'm looking for advice, especially any algorithm implementation efficiency. My current bottleneck of implementation is that I have to do partition twice, by low+medium and high, then do low and medium partition on low+medium part. I'd like to do partition only once.

'''
You have an unsorted array of integers and a
function........string getCategory(integer)........
which deterministically returns 1 of three possible strings:
"low", "medium", or "high", depending on the input integer.
You need to output an array with all the "low" numbers at the bottom,
all the "medium" numbers in the middle, and all the "high" numbers at the top.
This is basically a partial sort. Within each category, the order of the numbers does not matter...
For example, you might be give the array [5,7,2,9,1,14,12,10,5,3].
For input integers 1 - 3, getCategory(integer) returns "low",
for 4 - 10 it returns "medium," and for 11 - 15 it returns "high".
You could output an array (or modify the given array) that looks like this: [3,1,2,5,5,9,7,10,14,12]
'''

def getCategory(value):
    if 1<=value<=3:
        return 'low'
    elif 4<=value<=10:
        return 'medium'
    else:
        return 'high'
def partial_sort(numbers):
    low_and_medium_index = 0
    high_index = len(numbers)-1
    while low_and_medium_index <= high_index:
        while low_and_medium_index <= high_index and \
                        getCategory(numbers[low_and_medium_index]) != 'high':
            low_and_medium_index+=1
        while low_and_medium_index <= high_index and \
                        getCategory(numbers[high_index]) == 'high':
            high_index -= 1
        if low_and_medium_index < high_index:
            numbers[low_and_medium_index], numbers[high_index] = numbers[high_index], numbers[low_and_medium_index]
        else:
            break
    low_index = 0
    medium_index = low_and_medium_index - 1
    while low_index <= medium_index:
        while low_index <= medium_index and \
                        getCategory(numbers[low_index]) == 'low':
            low_index+=1
        while low_index <= medium_index and \
                        getCategory(numbers[medium_index]) == 'medium':
            medium_index -= 1
        if low_index < medium_index:
            numbers[low_index], numbers[medium_index] = numbers[medium_index], numbers[low_index]
        else:
            break

    return numbers

if __name__ == "__main__":
    print partial_sort([5,7,2,9,1,14,12,10,5,3])


texts: A simple function that removes empty or tags containing just ' '

texts:
I've written a function that should get rid of empty p, span, etc tags and those with just ' ' and am looking for ways to improve it. My original solution was very 'wet', but I've managed to come up with a drier solution.

The Original HTML:

text

&nbsp;

text

text

text

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

My Original Solution:

/*
    How to make this drier?
    ORIGINAL UNCLEAN SOLUTION
*/
    var ps = document.getElementsByTagName('p'),
    spans = document.getElementsByTagName('span'),
    strongs = document.getElementsByTagName('strong');

    for (let el of ps) {
        if (el.innerHTML == '&nbsp;') { // can't also include if '' at this stage
            el.parentNode.removeChild(el);
        }
    }
    for (let el of spans) {
        if (el.innerHTML == '&nbsp;' || el.innerHTML == '') {
            el.parentNode.removeChild(el);
        }
    }
    for (let el of strongs) {
        if (el.innerHTML == '&nbsp;' || el.innerHTML == '') {
            el.parentNode.removeChild(el);
        }
    }
    for (let el of ps) {
        if (el.innerHTML == '') {
            el.parentNode.removeChild(el);
        }
    }

My 'drier' solution:

/*
    MY CLEANER SOLUTION
*/
    var ps = document.getElementsByTagName('p'),
    spans = document.getElementsByTagName('span'),
    strongs = document.getElementsByTagName('strong');

    for (let el of ps) {
        cleaner(el);
    }
    for (let el of spans) {
        cleaner(el);
    }
    for (let el of strongs) {
        cleaner(el);
    }

    function cleaner(el) {
        if (el.innerHTML == '&nbsp;' || el.innerHTML == '') {
            el.parentNode.removeChild(el);
        }
    }

Would someone mind quickly running over both solutions and verifying that my 2nd solution is best? Also, I wonder whether that could be improved, or whether anyone has any better ideas for a solution? Thanks for the help here - for brevity, I'm looking at writing concise but also clear code.


texts:
This code shows two ways to calculate size of array of any type. I would like to know, which should be preferred? Is there any advantage/disadvantage?

#include <iostream>

// First method
template<typename Arr>
std::size_t array_size_1(const Arr& arr)
{
  return sizeof(arr)/sizeof(arr[0]);
}
// Second method
template<typename T, std::size_t sz>
std::size_t array_size_2(const T (&arr)[sz])
{
  return sz;
}

int main() {
  int arr[] = {1,2,3,4,5};
  std::string sarr[] = {"abc", "def", "ghj"};
  std::cout << array_size_1(arr) << "\n";
  std::cout << array_size_2(sarr) << "\n";
  return 0;
}


texts: Fetch and print all properties of an object graph as string

texts:
Below I have setup an extension method that takes any object, cycles through its properties, and prints each out to a Console window in the format Name: Value.

  Specification / Scope:

  Handle only single objects (no collections)

code

public static string PropertiesToString<T>(this T obj, int tabs = 0) where T : class
{
    int initTabs = tabs;
    string result = string.Empty;
    PropertyInfo[] propertyInfo = obj.GetType().GetProperties();
    foreach (PropertyInfo property in propertyInfo)
    {
        string name = property.Name;
        object value = property.GetValue(obj, null);
        Type valueType = value.GetType();
        if (valueType.IsValueType || valueType.Name.Equals("String"))
        {
            for (int i = 0; i < tabs; i++)
            {
               result += "    ";
            }
            result += string.Format("{0}: {1}\n", name, value == null ? string.Empty : value.ToString());
        }
        else
        {
            result += string.Format("{0}:\n", name);
            result += value.PropertiesToString(++tabs);
        }
        tabs = initTabs;
    }
   return result;
}

Here is a class I'm using to test this code, along with the lines responsible for creating an instance of the class and writing its properties to the Console:

Class:

public class Circle : IShape
{
    public Circle(double x, double y, double radius)
    {
        Center = new Point
        {
            X = x,
            Y = y
        };
        Radius = radius;
    }

    public Point Center { get; set; }
    public double Radius { get; set; }

    public double Area(int precision = 2)
    {
        return Math.Round(Radius * Radius * Math.PI, precision);
    }
}

Main:

public static void Main(string[] args)
{
    IShape circle = new Circle(5, 5, 10);
    Console.WriteLine(circle.PropertiesToString());
    Console.ReadLine();
}

The above method will also cycle through nested objects and print those to the Console as well, adding in tabs for readability's sake.

I'm kind of unfamiliar with System.Reflection and was wondering if there was a more efficient way I could approach doing something like this.


texts: 99 simple asynchronous bottles on the wall

texts:
I have some basic code which registers functions, with given variables, to be executed after a certain time has elapsed. I will roll this code into my software project when it is ready. If it works it works but since I've never done this before I am the Padawan and one of you out there, who's written code like this before, is the Jedi Master.
Here is my code:

#include <unistd.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>

typedef union EventArgument {
    int i;
    float f;
} event_argument;

typedef int (*event_function_ptr)(event_argument);

typedef struct EventList {
    event_function_ptr ptr;
    long time;
    event_argument arg;
    struct EventList* next;
} event_list;

event_list events_head;

int register_event (event_function_ptr event_funciton, long in_time, event_argument arg);

int event_print_int (event_argument arg) {printf("%i\n", arg.i);}
int event_print_float (event_argument arg) {printf("%f\n", arg.f);}
int event_kill (event_argument arg) {exit(arg.i);}

int event_99_bottles (event_argument arg) {
    if (arg.i == 0) {
        printf("no more bottles of beer on the wall!");
        event_argument arg_new;
        arg_new.i = -1;
        register_event (&event_kill, 5000, arg_new);
    } else {
        printf("%i bottles of beer on the wall. Take one down and pass it around,\n", arg.i);
        event_argument arg_new;
        arg_new.i = arg.i - 1;
        register_event (&event_99_bottles, 1000, arg_new);
    }

}

long current_time;

//loop from event_head until event.next is NULL or event.next.time strictly greater than current_time + in_time then malloc and insert in list.
int register_event (event_function_ptr ptr, long in_time, event_argument arg) {
    event_list* p = &events_head;
    event_list* q = malloc(sizeof(event_list));
    q->ptr = ptr;
    q->time = current_time + in_time;
    q->arg = arg;

    while (p->next != NULL && p->next->time <= q->time) {
        p = p->next;
    }
    q->next = p->next;
    p->next = q;
}

//loop through events in order and execute functions, then remove from list until event_head.next == NULL or event_head.next.time is greater than current_time.
int check_events (void) {
    while (events_head.next != NULL && events_head.next->time <= current_time) {
        event_list* p = events_head.next;
        p->ptr(p->arg);
        events_head.next = p->next;
        free(p);
    }
}

int update_time (void) {
    struct timeval time_val;
    gettimeofday(&time_val, 0);
    current_time = time_val.tv_usec / 1000 + time_val.tv_sec * 1000;
}

int main(void) {
    events_head.next = NULL;
    update_time();
    event_argument arg;
    arg.i = 99;
    register_event (&event_99_bottles, 20000, arg);
    arg.i = 512;
    register_event (&event_print_int, 5000, arg);
    arg.f = 3.1415;
    register_event (&event_print_float, 15000, arg);
    arg.i = 58008;
    register_event (&event_print_int, 7000, arg);

    while (1) {
        update_time();
        check_events();
        usleep(900000);
    }
}

Does this look good?
Is there anything missing?
Is there anything you think I should know now that will benefit me in future?


texts: Serialize and deserialize binary search tree

texts:
Is there any good advice on how to improve performance in terms of algorithm time complexity? I am using a recursive solution and am not sure if any faster non-recursive solution exists.

import sys
class TreeNode:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
    def serialize_tree(self, result):
        result.append(self.value)
        if self.left:
            self.left.serialize_tree(result)
        if self.right:
            self.right.serialize_tree(result)
    def print_tree(self, result):
        result.append(self.value)
        if self.left:
            self.left.print_tree(result)
        else:
            result.append('#')
        if self.right:
            self.right.print_tree(result)
        else:
            result.append('#')
    @staticmethod
    def deserialize_tree(source):
        if len(source) == 1:
            return TreeNode(source[0], None, None)
        cur = TreeNode(source[0], None, None)
        for i,v in enumerate(source):
            if i == 0:
                root_value = v
                continue
            if v > root_value:
                break
        if v > root_value:
            cur.right = TreeNode.deserialize_tree(source[i:])
        if v > root_value and i - 1 > 0:
            cur.left = TreeNode.deserialize_tree(source[1:i])
        if not (v > root_value) and i == len(source) - 1:
            cur.left = TreeNode.deserialize_tree(source[1:i+1])

        return cur

if __name__ == "__main__":
    #   5
    #  3 6
    # 2   7
    root = TreeNode(5, TreeNode(3, TreeNode(2, None, None), None), TreeNode(6, None, TreeNode(7, None, None)))
    result = []
    root.serialize_tree(result)
    print result
    new_root = TreeNode.deserialize_tree(result)
    result2 = []
    new_root.print_tree(result2)
    print result2


texts: Calculate the Degrees of a Clock Hand Based on Input Time

texts:
I'm a novice programmer. I started with Java years back and now mostly use VBA to automate tasks for my internships. I want to graduate from VBA and get into Python/R to properly automate tasks.
The below code is my first Python project. I would like any of you to point out how it can be improved.

The program is meant to take in a time in HH:MM format and print out at what degrees (from 12:00) each of the hands will be at. This was adapted from a common finance interview brainteaser guide.

I'm thinking that if I get some good suggestions for this code I'll go ahead and make one that includes a second hand.

input_time = input("Please input a time (HH:MM)")

time = input_time.split(":")

clock_degrees = 360
clock_hours = 12
clock_minutes = 60
clock_degreesperhour = clock_degrees/clock_hours
clock_degreesperminute = clock_degrees/clock_minutes

miunte_hand_degrees = int(time[1])*clock_degreesperminute

if (time[0] == "12"):
    time[0] = "0"

hour_hand_degrees = (int(time[0])*clock_degreesperhour)+((int(time[1])/clock_minutes)*clock_degreesperhour)

print("When the time is", input_time, 'the hour hand is at', hour_hand_degrees, "° and the minute hand is at", miunte_hand_degrees, "°")


texts:
This is a simple word frequency counter in Java. I am just wondering if I can improve or compact this code better.  You choose a file to be counted with a JFileChooser, and the results get outputted into a file.  The biggest struggle I had was sorting the HashMap by values. I got it to work but I feel like it should be easier to sort.  I'm also wondering if I should break up my code in main into more methods.  I saw a Python script of this that does the same thing but in half the lines of code.  Is that just Java or does my code need touching up?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JFileChooser;

public class FrequencyCounter {

    public static void main(String[] args) throws IOException {
        JFileChooser fc = new JFileChooser();
        File file = null;
        fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
        if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
        }
        FileReader is = new FileReader(file);
        char[] scriptBytes = new char[(int) file.length()];
        is.read(scriptBytes);
        is.close();
        String script = new String(scriptBytes);
        String[] words = script.split("[ \\r?\\n\\-]");
        List<String> wordList = new ArrayList<>(Arrays.asList(words));
        wordList = cleaner(wordList);
        HashMap<String, Integer> counter = new HashMap<>();
        for (String word : wordList) {
            if (counter.containsKey(word))
                counter.put(word, counter.get(word) + 1);
            else
                counter.put(word, 1);
        }
        counter = entriesSortedByValues(counter);
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(file.getAbsolutePath().replace(file.getName(), "") + "result_" + file.getName())));
        for (Entry<String, Integer> ent : counter.entrySet()) {
            writer.write(ent.getKey() + " " + ent.getValue());
            writer.newLine();
        }
        writer.close();
    }

    private static List<String> cleaner(List<String> words) {
        for (int i = 0; i < words.size(); i++) {
            words.set(i, words.get(i).replaceAll("[1234567—890!@#$%^&*()_+|\\-=~`{}\\[\\]:;\"<>,.?/]","").toLowerCase());
        }
        words.removeAll(Arrays.asList(""));
        return words;
    }

    private static <K,V extends Comparable<? super V>>
        HashMap<K, V> entriesSortedByValues(Map<K,V> map) {

        List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());

        Collections.sort(sortedEntries,
            new Comparator<Entry<K,V>>() {
                @Override
                public int compare(Entry<K,V> e1, Entry<K,V> e2) {
                    return e2.getValue().compareTo(e1.getValue());
                }
            }
        );
        HashMap<K,V> result = new LinkedHashMap<K,V>();
        for (Entry<K,V> ent : sortedEntries)
            result.put(ent.getKey(), ent.getValue());

        return result;
    }

}


texts: Project Euler #14: Longest Collatz Sequence starting point

texts:
Problem statement:

  The following iterative sequence is defined for the set of positive integers:

  n → n/2 (n is even)
  n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following sequence:

  13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.
Here is my implementation written in Python, awaiting your feedback.

from time import time
from operator import itemgetter

def collatz_count(n, count={1: 1}):
    """uses cache (count) to speed up the search, returns sequence
    length for the given number"""
    try:
        return count[n]
    except KeyError:
        if n % 2 == 0:
            count[n] = collatz_count(n / 2) + 1
        else:
            count[n] = collatz_count(n * 3 + 1) + 1
    return count[n]

def run_test():
    """uses the previous function, returns number that generates the
    largest sequence"""
    time1 = time()
    items = sorted([(x, collatz_count(x)) for x in range(1, 1000000)],
                   key=itemgetter(1), reverse=True)
    maximum = items[0]
    print(f' Starting number: {maximum[0]} \n Sequence length:
    {maximum[1]} \n '
          f'Calculated in: {time() - time1} seconds.')

if __name__ == '__main__':
    run_test()


texts:
I have two lists of dictionaries. Both lists always have the same ids.
I want to get the following result:

{9: {'av': 4, 'nv': 45}, 10: {'av': 0, 'nv': 0}, 8: {'av': 0, 'nv': 30}}

The following code is working but I wonder if this is the best solution?

l1 = [{'id': 9, 'av': 4}, {'id': 10, 'av': 0}, {'id': 8, 'av': 0}]

l2 = [{'id': 9, 'nv': 45}, {'id': 10, 'nv': 0}, {'id': 8, 'nv': 30}]

l3 = {x['id']: {'av': x['av']} for x in l1}
l4 = {x['id']: {'nv': x['nv']} for x in l2}

{key: value.update(l4[key]) for key, value in l3.items()}

>> {9: {'av': 4, 'nv': 45}, 10: {'av': 0, 'nv': 0}, 8: {'av': 0, 'nv': 30}}


texts:
I have implemented a ThreadPoolExecutor that will run a Consumer<T> only on elements not already consumed. This code uses Java 8.

The background behind this is that I scan a directory every x time units for which files are present, I must maintain a 100% accuracy on finding files and other mechanisms such as JNotify or a simple plain WatcherService do not achieve that.

public class SingleExecutionThreadPoolExecutor<E> extends ThreadPoolExecutor {
    private final Consumer<E> consumer;
    private final List<E> elementsInProcess = new ArrayList<>();

    public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.consumer = consumer;
    }

    public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
        this.consumer = consumer;
    }

    public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
        this.consumer = consumer;
    }

    public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        this.consumer = consumer;
    }

    public void execute(E element) {
        if (!elementsInProcess.contains(element)) {
            super.execute(() -> consumer.accept(element));
            elementsInProcess.add(element);
        }
    }

    @Override
    @Deprecated
    public void execute(Runnable command) { }
}

It is called using the following classes and snippets:

public final class UniqueTimePath {
    private final Path path;
    private final FileTime fileTime;

    public UniqueTimePath(final Path path) {
        this.path = path;
        try {
            this.fileTime = Files.getLastModifiedTime(path);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

    public Path getPath() {
        return path;
    }

    public FileTime getFileTime() {
        return fileTime;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final UniqueTimePath other = (UniqueTimePath) obj;
        if (!Objects.equals(this.path, other.path)) {
            return false;
        }
        if (!Objects.equals(this.fileTime, other.fileTime)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "{" + path + ", " + fileTime + "}";
    }
}

private SingleExecutionThreadPoolExecutor<UniqueTimePath> executor;
//...
executor = new SingleExecutionThreadPoolExecutor<>(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), fileConsumer);
//...
Files.list(directory)
        .map(UniqueTimePath::new)
        .forEach(executor::execute);


texts:
I just wrote a snow animation in Python. I think this is fairly clean but I have a few things that I don't like.

from random import randrange
import time

# Snow animation
# Snow is simply the `#` symbol here. Half of the snow moves at 1 char
# per frame, while the other half moves at 0.5 chars per frame. The
# program ends when all the snow reaches the bottom of the screen.
# The viewing area is 80x25. It puts 100 snow flakes to output, half
# fast, and half slow. Every frame it dispenses 4 flakes, 2 fast and
# 2 slow ones, at random locations at the top of the viewing area.

screen = {'x': 80, 'y': 20}
drops = []

def createRainDrop(x, y, speed):
    return {'x': x, 'y': y, 'speed': speed}

def createRandomDrops():
    dropCount = 4
    for i in range(dropCount):
        yield createRainDrop(randrange(0, screen['x']), 0, min((i % 2) + 0.5, 1))

def moveDrops():
    for drop in drops:
        speed = drop['speed']
        drop['y'] = drop['y']+speed

def drawDrops():
    out = [''] * screen['y']
    for y in range(screen['y']):
      for x in range(screen['x']):
        out[y] += '#' if any([drop['x'] == x and int(drop['y']) == y for drop in drops]) else ' '

    return '\n'.join(out)

def dropsOnScreen():
    return any([drop['y'] < screen['y'] for drop in drops])

drops += createRandomDrops()

while dropsOnScreen():
    if len(drops) < 100:
        drops += createRandomDrops()

    print(drawDrops())
    moveDrops()
    time.sleep(0.100)

For example, I don't know how to remove the duplicate line drops += createRandomDrops(), and drawDrops() feels a bit like a hack.

I confess! While writing this it was rain, not snow!


texts: Finding the percentile corresponding to a threshold

texts:
I need to find which percentile of a group of numbers is over a threshold value. Is there a way that this can be speed up? My implementation is much too slow for the intended application. In case this changes anything, I am running my program using mpirun -np 100 python program.py. I cannot use numba, as the rest of this program uses try/except statements.

import numpy as np
my_vals = []
threshold_val = 0.065
for i in range(60000):
    my_vals.append(np.random.normal(0.05, 0.02))

upper_bound = 100
lower_bound = 0
perc = 50.0
val = np.percentile(my_vals, perc)
while abs(val - threshold_val) > 0.00001:
    print val
    if val > threshold_val:
        upper_bound = perc
        perc = (perc + lower_bound)/2
    else:
        lower_bound = perc
        perc = (perc+upper_bound)/2
    val = np.percentile(my_vals, perc)

print perc


texts: Incrementing specified list values, with "catch-up"

texts:
I completed a coding challenge recently in which my function was to be given two parameters: N, the number of counters to be used (numbered 1 through N) - and A, an array of integers. Iterating through the array A, when the index of a counter occurs, that counter is incremented by 1. When an index of N+1 occurs, all of the counters are reset to the maximum counter at that point.

def solution(N, A):
    li = [0] * N
    #print('A is %s' % A)
    #print('N is %s' % N)
    max_val = 0

    for i in A:
        i = i-1
        #print('i is %s' % i)
        #print('li is %s' % li)
        if i == N:
            #print('  in if')
            li = [max_val] * N
        else:
            #print('  in else')
            li[i] = li[i] + 1
            if li[i] > max_val:
                max_val = li[i]

    return li

[Using Python 3.6]
(See related question.)


texts:
I have DatabaseContext class.

public interface IDatabaseContext : IDisposable
{
    SqlConnection Connection { get; }
}

public class DatabaseContext : IDatabaseContext
{
    private readonly string _connectionString;
    private SqlConnection _connection;

    public DatabaseContext(string connectionString)
    {
        _connectionString = connectionString;
    }

    public SqlConnection Connection
    {
        get
        {
            if (_connection == null)
                _connection = new SqlConnection(_connectionString);

            if (_connection.State != ConnectionState.Open)
                _connection.Open();

            return _connection;
        }
    }

    public void Dispose()
    {
        if (_connection != null && _connection.State == ConnectionState.Open)
            _connection.Close();
    }
}

And I use it in PageService class using dependency injection, for example:

public class PageService
    {
        private readonly IDatabaseContext _databaseContext;

        public PageService(IDatabaseContext databaseContext)
        {
            _databaseContext = databaseContext;
        }

        public IEnumerable<CustomPage> GetAllPages()
        {
            IEnumerable<CustomPage> pages;
            using (var db = _databaseContext)
            {
                //using Dapper.Net to get list of pages.
                pages = db.Connection.GetList<CustomPage>();
            }
            return pages;
        }
    }

Do you see any improvement / issue of my DatabaseContext class?


texts:
If I have a List<List<T> like the following :

Name    City   Id
Anna     NY     1
Joe      NJ     2

How can I transpose it efficiently in order to have :

Name    Anna     Joe
City    NY       NJ
Id      1        2

I tried the following

public static void MatrixTranspose<T>(ref List<List<T>> matrix)
{
   var h = matrix.Count - 2;
   var w = matrix[0].Count - 1;

   for (var i = 0; i < h; ++i)
   {
      for (var j = i + 1; j < w; ++j)
      {
          var tmp = matrix[i][j];
          matrix[i][j] = matrix[j][i];
          matrix[j][i] = tmp;
       }
   }
}

That seems to be working on paper I believe? But I feel like I'm doing too much permutations. Is there a way to optimize it? Also, is the use of ref correct here?


texts: Iterate over list and valid email address

texts:
I have the following code:
(emailList type is List<string>)

//Add All emails
foreach (var mail in emailList)
{
    var isEmail = Regex.IsMatch(mail.Trim(), @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

    if (isEmail)
    {
        email.BccRecipients.Add(mail.Trim());
        sbInfoLog.Append($"Email: {mail.Trim()}\n");
    }
    else
    {
        sbAlertLog.Append($"Not valid email address: {mail}\n");
    }
}

I'm looking for another way to:

To validate the email address
To Iterate over the list (Maybe with ForEach etc..)

Any suggestions?


texts: Which of these two is better in terms of readability and function?

texts:
I have two different ways of populating a List with querying another List. They are:

var list = _surveyList.Where(x => x.Date == selectedDate).Select(s => s.Joint).ToList();

And:

var list = from s in _surveyList
           where s.Date.Equals(selectedDate)
           select s.Joint;

They functionally do the same thing. My question is which is better in terms of readability, and function? Does one have more overhead than the other? Is one way more preferred than the other?


texts:
It's a part of code where two Threads ("priests") talk to each other. One asks and waits for the second to answer - then something happens depending on what has been answered by second thread.

I have two simple questions:

Regarding structuring code as MVP: I am not sure it's valid to keep all the thread logic in the same file where psvm is. Should I rather move it in separate files? What's the best approach?
I know that garbage collection in Java is automated, yet after reading this I've decided it would be polite to JVM to null all the objects I don't need to hint it on that they might be collected. Is it even sane? Or just extra hassle?

This is the code:

package View;

class Genesis {

private boolean turnToTalk, agreed;
private Priest priestOne, priestTwo;

public static void main(String[] args) {
    Genesis genesis = new Genesis();
    genesis.PriestsTalk();
}

private void PriestsTalk() {
    turnToTalk = true;
    Thread0 thread0 = new Thread0();
    thread0.run();
}

class Thread0 implements Runnable {
    @Override
    public void run() {
        turnToTalk = false;

        Thread1 thread1 = new Thread1();
        thread1.run();

        while (!turnToTalk) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // after thread woke up
        if (agreed) {
            // do some work
            } else {
                // do some work
            }
        } else {
            PriestsTalk();
        }
    }
}

class Thread1 implements Runnable {
    @Override
    public void run() {
        synchronized (this) {
            while (turnToTalk) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            Random r = new Random();
            int i = r.nextInt(2);
            String answer =
                    i != 0 ? "Yes" : "No";

            if (answer.equals("Yes")) {
                agreed = true;
                turnToTalk = true;
                r = null;
                answer = null;
                notify();
            } else {
                agreed = false;
                turnToTalk = true;
                r = null;
                answer = null;
                notify();
            }
        }
    }
}

Full code is here, just 4 files.


texts:
Based on the answer to my question on StackOverflow, I have ended up with the following code:

public class ColumnDataBuilder<T>
{
    public abstract class MyListViewColumnData
    {
        public string Name { get; protected set; }
        public int Width { get; protected set; }
        public ColumnType Type { get; protected set; }
        public delegate TOUT FormatData<out TOUT>(T dataIn);

        protected abstract dynamic GetData(T dataRow);

        public string GetDataString(T dataRow)
        {
            dynamic data = GetData(dataRow);
            switch (Type)
            {
                case ColumnType.String:
                case ColumnType.Integer:
                case ColumnType.Decimal:
                    return data.ToString();
                case ColumnType.Date:
                    return data.ToShortDateString();
                case ColumnType.Currency:
                    return data.ToString("c");
                    break;
                case ColumnType.Boolean:
                    var b = (bool)data;
                    if (b) return "Y";
                    else return "N";
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

    }

    public class MyListViewColumnData<TOUT> : MyListViewColumnData
    {

        public MyListViewColumnData(string name, int width, ColumnType type, FormatData<TOUT> dataFormater)
        {
            DataFormatter = x => dataFormater(x); // Per https://stackoverflow.com/a/1906850/298754
            Type = type;
            Width = width;
            Name = name;
        }
        public Func<T, TOUT> DataFormatter { get; protected set; }
        protected override dynamic GetData(T dataRow)
        {
            return DataFormatter(dataRow);
        }
    }
 }

This is called from a factory method (in ColumnDataBuilder) as

public MyListViewColumnData Create<TOUT>(string name, int width, ColumnType type, MyListViewColumnData.FormatData<TOUT> dataFormater)
{
    return new MyListViewColumnData<TOUT>(name, width, type, dataFormater);
}
public MyListViewColumnData Create(string name, int width, MyListViewColumnData.FormatData<DateTime> dataFormater)
{
    return new MyListViewColumnData<DateTime>(name, width, ColumnType.Date, dataFormater);
}
...

That, in turn, is called from my code as:

builder.Create("Date", 40, x => x.createdDate);

and

private ListViewItem CreateListViewItem<TDATA>(IEnumerable<ColumnDataBuilder<TDATA>.MyListViewColumnData> columns, TDATA rowData)
{
    var item = new ListViewItem();
    foreach (var col in columns)
    {
        item.SubItems.Add(col.GetDataString(rowData));
    }
    item.SubItems.RemoveAt(0); // We generate an extra SubItem for some reason.
    return item;
}

How can I refactor this so that I'm not using dynamic, but still preserve the syntax as it currently exists in the code?


texts:
I'm changing an HTML datepicker value (#date) into 3 separate values in order to post them to a booking engine. I've managed to get it to work but there is a lot of repetition and the original #date value is also submitted unnecessarily.

The engine takes these parameters:

date_day=27&date_month=9&date_year=2013&nights=3&people=2&ref=558&langClient=eng&expr=EUR`

HTML

 <form id="quick_res" action="#" method="post" name="availability">

                Date :<input type="date" name="date" id="date" placeholder="12/09/13">

                Nights :<input type="number" name="nights" id="nights" placeholder="2">

                Guests :<input type="number" name="people" id="people" placeholder="2">

                <input name="ref" type="hidden" id="ref" value="558" />
                <input name="langClient" type="hidden" id="langClient" value="eng" />

                Currency :
                    <select name="expr" id="expr">
                        <option value="EUR" selected="selected">EURO</option>
                        <option value="USD">US Dollar</option>
                        <option value="ARS">Argentine Peso</option>
                        <option value="AUD">Australian Dollar</option>
                        </select>

                <input type="submit" name="submit" class="secondary button radius text-center" value="Click to Book">

    </form>

jQuery

 $('#date').on('change', function() {
     var new_val = $(this).val().split('-'),
         dateYear = parseInt(new_val[0]),
         dateMonth = parseInt(new_val[1]),
         dateDay = parseInt(new_val[2]);

    $('<input>', {
        type: 'hidden',
        name: 'date_day',
        id: 'date_day',
        value: dateDay

    }).appendTo('#anchor');

    $('<input>', {
        type: 'hidden',
        name: 'date_month',
        id: 'date_month',
        value: dateMonth

    }).appendTo('#anchor');

    $('<input>', {
        type: 'hidden',
        name: 'date_year',
        id: 'date_year',
        value: dateYear

    }).appendTo('#anchor');

 });


texts:
Option 1 - nice and simple

private void GetFileReady()
{
    private StringBuilder fileContents = new StringBuilder();
    using (var sr = new StreamReader("C:\A big file.txt"))
    {
        fileContents.Append(sr.ReadToEnd());
    }
}

Option 2 - less simple

private void GetFileReady2()
{
   private StringBuilder fileContents = new StringBuilder();
   const int bufferSize = 1024;
   var buffer = new Char[bufferSize];
   var count = bufferSize;

   using (var sr = new StreamReader("C:\A big file.txt"))
   {
       while (count > 0)
       {
           count = sr.Read(buffer, 0, bufferSize);
           fileContents.Append(buffer, 0, count);
       }
   }
}

Would option 2 be better for something esoteric like memory allocation?


texts:
I've written a script in Python to scrape app name, developer and price from ITunes site.

In its first page there are 10 different recommended app links which my scraper is able to track down and scrape the aforesaid fields going to their concerning page. The quantity of the apps should be 11. Previously, the scraper was printing only 10 results skipping the content from first page. However, there is a line in my scraper (I've written a comment next to it to make you identify) which I've added in such a way so that the scraper do not fail to skip the content of first page from printing.

With this extra line in it, the scraper has got a clumsy look. It didn't impact on the performance, though! It runs smoothly now and brings results without leaving anything to complain. How can I give it a better look along with any improvement?

This is what I've written:

import requests
from bs4 import BeautifulSoup

main_link = "https://itunes.apple.com/us/app/candy-crush-saga/id553834731?mt=8"

def get_links(url):
    response = requests.get(url)
    get_content(url)              # This is the very line which let the scraper harvest documents from the first page
    soup = BeautifulSoup(response.text,"html.parser")
    for title in soup.select("a.name"):
        get_content(title.get("href"))

def get_content(new_links):
    req = requests.get(new_links)
    broth = BeautifulSoup(req.text,"html.parser")
    item ={
    "app_name": broth.select("h1[itemprop=name]")[0].text,
    "developer": broth.select("div.left h2")[0].text,
    "price": broth.select("div.price")[0].text
    }
    print(item)

get_links(main_link)


texts: How to Make This JavaScript Snippet DRY (Don't Repeat Yourself)?

texts:
I have the following JavaScript function:

function registerEvents() {
    var isTapholding = false;
    $(document).delegate('.add-control .add-image', 'tap', function (evt) {
        handleAddControlEvent(this);
    });
    $(document).delegate('.delete-image', 'tap', function (evt) {
        evt.stopPropagation();
        handleDeleteControlEvent(this);
    });
    $(document).delegate('.edit-control', 'tap', function (evt) {
        if (isTapholding)
            return;
        handleEditControlEvent(this);
    });
    $(document).delegate('.edit-control', 'vmouseup', function (evt) {
        setTimeout(function () {
            isTapholding = false;
        }, 100);
    });
    $(document).delegate('.add-control .insert-image', 'tap', function (evt) {
        handleInsertImageEvent(this);
    });
    setTimeout(function () {
        $(document).delegate('.edit-control', 'taphold', function (evt) {
            evt.stopPropagation();
            isTapholding = true;
            handleEditControlTapHoldEvent(this);
        });
    }, 100);
}

How I can make this DRY (Don't Repeat Yourself)?