texts:
We all know about the indices trick, right? Here's (hopefully) an improved version...

template <::std::size_t...> struct indices { };

namespace detail
{

template<class A, class B> struct catenate_indices;

template <::std::size_t ...Is, ::std::size_t ...Js>
struct catenate_indices<indices<Is...>, indices<Js...> >
{
  using indices_type = indices<Is..., Js...>;
};

template <::std::size_t, ::std::size_t, typename = void> struct expand_indices;

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if<A == B>::type>
{
  using indices_type = indices<A>;
};

template <::std::size_t A, ::std::size_t B>
struct expand_indices<A, B, typename ::std::enable_if<A != B>::type>
{
  static_assert(A < B, "A > B");
  using indices_type = typename catenate_indices<
    typename expand_indices<A, (A + B) / 2>::indices_type,
    typename expand_indices<(A + B) / 2 + 1, B>::indices_type
  >::indices_type;
};

}

template <::std::size_t A>
struct make_indices : detail::expand_indices<0, A>::indices_type
{
};

template <::std::size_t A, ::std::size_t B>
struct make_indices_range : detail::expand_indices<A, B>::indices_type
{
};

Usage:

#include <iostream>

#include "utility.hpp"

template <::std::size_t ...Is>
void show_indices(indices<Is...>)
{
  [](...){}((((::std::cout << Is << ::std::endl), 0))...);
}

int main()
{
  show_indices(make_indices_range<3, 9>());

  return 0;
}

Any suggestions?


texts: Fastest way to search istringstream for patterns in around 0.02 seconds

texts:
Problem
I have a stream composed of 2 columns and 1000 lines:

Column 1: contains the patterns that I want to find
Column 2: contains the values corresponding the the patterns in Column1

I want to search for the patterns in column 1, extract their corresponding values in column 2 and save them in vectors. I actually have 3 types that I want to look for which are : {type, label, name}. Therefore i'll have 3 vectors for every type .pair<string,string> represents column 1 and column 2.
vector<pair<string,string>>` types
vector<pair<string,string>> Labels
vector<pair<string,string>> names

I read the file sequentially. If I find the pattern that I am looking for in column 1 I extract the value in column 2 and append it with the corresponding vector.
All the other patterns will be saved in a vector called others.
vector<pair<string,string>> others

Sample
Column 1 contains the patterns that I want to look for{type, label, name}. and Column 2 the corresponding values
rdf-syntax-ns#type base.qualia.topic
rdf-syntax-ns#type common.topic
rdf-syntax-ns#type film.producer
rdf-schema#label  สตีฟ จอบส์
rdf-schema#label  ﺎﺴﺗیﻭ ﺝﺎﺑﺯ
rdf-schema#label  Styvas Džobsas
type.object.name ﺎﺴﺗیﻭ ﺝﺎﺑﺯ
type.object.name Styvas Džobsas
type.object.name Steve Jobs
type.object.name Steve Jobs

What is the fastest way to search and extract the values?
The following source code takes 0.04 seconds to read 1000 lines, find the patterns and extract their corresponding values.
void returnValues(const string & file, vector<pair<string,string>> & types, vector<pair<string,string>> & labels, vector<pair<string,string>> & names, vector<pair<string,string>> & others)
{
  istringstream str(file);
  string line;
  //skip first line
  getline(str,line);
  while(getline(str, line))
  {

     vector<string> values;
     line.erase(remove( line.begin(), line.end(), '\"' ), line.end());
     boost::split(values, line, boost::is_any_of("\t"));
     if(contains(values[0],"type"))
     {
         pair<string,string> fact = make_pair(values[0], values[1]);
         types.push_back(fact);
      }
      else if(contains(values[0],"label"))
      {
          pair<string,string> fact = make_pair(values[0], values[1]);
          labels.push_back(fact);
      }

      else if(contains(values[0],"name"))
      {
        pair<string,string> fact = make_pair(values[0], values[1]);
        names.push_back(fact);
      }
     else
     {
        pair<string,string> fact = make_pair(values[0], values[1]);
        others.push_back(fact);
      }
   }
}//end function


texts: Creating valid words on an n-by-n grid of characters using depth-first search

texts:
I am trying to create a word-finder game. There will be an n-by-n Board filled with Tiles.

class Tile:
    empty = None

    def __init__(self, letter):
        self.letter = letter
        #the dictionary tracks the Tiles that border a given Tile
        self.directionals = {'n':Tile.empty, 's':Tile.empty, 'w':Tile.empty, 'e':Tile.empty, 'nw':Tile.empty, 'ne':Tile.empty, 'sw':Tile.empty, 'se':Tile.empty}

class Board:
    def __init__(self, length, chars=''):
        self.length = length
        self.grid = [[] for _ in range(length)]

        for i in range(length):
            for _ in range(length):
                new_tile = Tile(randomchar()) #assume randomchar() returns a random character each time
                self.grid[i].append(new_tile)

        for i in range(length):
            for j in range(length):
                tile = self.grid[i][j]

                if i - 1 >= 0:
                    tile.directionals['n'] = self.grid[i - 1][j]
                if i + 1 < length:
                    tile.directionals['s'] = self.grid[i + 1][j]
                if j - 1 >= 0:
                    tile.directionals['w'] = self.grid[i][j - 1]
                if j + 1 < length:
                    tile.directionals['e'] = self.grid[i][j + 1]
                if i - 1 >= 0 and j - 1 >= 0:
                    tile.directionals['nw'] = self.grid[i - 1][j - 1]
                if i - 1 >= 0 and j + 1 < length:
                    tile.directionals['ne'] = self.grid[i - 1][j + 1]
                if i + 1 < length and j - 1 >= 0:
                    tile.directionals['sw'] = self.grid[i + 1][j - 1]
                if i + 1 < length and j + 1 < length:
                    tile.directionals['se'] = self.grid[i + 1][j + 1]

Starting from any Tile, the player will be able to create a word by traversing through unvisited Tiles. After successfully creating a word, the Tiles used to compose that word are reset. For example on a 4-by-4 Board:

   start         player makes 'some'   new Tiles represented by '*'
[[L A P S],         [[L A P S],          [[L A P S],
 [R O S E], ------>  [R O S  ],  ------>  [R O S *],
 [T I M E],          [T I   E],           [T I * E],
 [S O F T]]          [    F T]]           [* * F T]]

Throughout the game, I want to ensure the Board has a minimum number of words able to be made. I want to have the functionality to choose the reset Tiles such that they form words with neighboring Tiles, or else the number of available words on the Board may fall below the threshold.

To accomplish this, I implemented the below function.

def dfs(tile, word, min_word_length=2, max_word_length=5):
    visited = []

    def helper(tile, word):
        if len(word) > max_word_length:
            return
        if tile in visited:
            return
        #allwords is a list with all the words in the English dictionary
        if word in allwords and len(word) >= min_word_length:
            print(word)

        visited.append(tile)
        for direction in tile.directionals.values():
            if direction is not Tile.empty and direction not in visited:
                helper(direction, word + direction.letter)
        visited.remove(tile)

    helper(tile, word)

I would create Tiles with random letters for the Tiles needing to be reset, applying the dfs function after each Tile is plugged in to see if a valid word is formed. However, the current implementation is too inefficient: it struggles when max_word_length exceeds 5, exponentially more so on larger boards.

How can I change my implementation so that it'd be more efficient? Ideally, I would like the resetting to happen almost immediately (< 1 second). I was thinking of incorporating memoization, but am not sure how to in this case.


texts:
I did not like that get synchronizes every time I call it - because I may be calling it more than once. So I wrote the wrapper for the future interface which keeps not synchronized local variable for completion state and caches the result. I am very sure it is thread safe.
Please have a look:

package i;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureTaskWrapper<V> implements RunnableFuture<V> {

    private FutureTask<V> localFuture;
    private V result;
    //this one is not synchronized on purpose. It does not have to be.
    //It will either use wrapped class' done mechanism or eventually will     update and it will use cached result.
    private boolean done = false;

    public FutureTaskWrapper(FutureTask<V> instance) {
        localFuture = instance;
    }

    @Override
    public void run() {
        localFuture.run();
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return localFuture.cancel(mayInterruptIfRunning);
    }

    @Override
    public boolean isCancelled() {
        return localFuture.isCancelled();
    }

    @Override
    public boolean isDone() {
        if (done) {
            return true;
        } else {
            return localFuture.isDone();
        }
    }

    @Override
    public V get() throws InterruptedException, ExecutionException {
        if (done) {
            System.out.println("using cached version.");
            return result;
        } else {
            System.out.println("using version version from future.");
            result = localFuture.get();
            done = true;
            return result;
        }
    }

    @Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (done) {
            System.out.println("using cached version.");
            return result;
        } else {
            System.out.println("using version version from future.");
            result = localFuture.get(timeout, unit);
            //could clean up localFuture here.
            done = true;
            return result;
        }
    }

    //main method for testing.
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        FutureTask<String> future = new FutureTask<>(() -> {
            Thread.sleep(1000L);
            return "future";
        });
        FutureTaskWrapper<String> wrapper = new FutureTaskWrapper(future);
        executor.submit(future);
        wrapper.get();
        wrapper.get();
        wrapper.get();
        wrapper.get();

        executor.shutdownNow();
    }
}


texts: Repeatedly incrementing array elements using OpenCL

texts:
I am learning how to program in opencl and I made a simple program that simply takes an array and adds 1 to every element. I want to run it many times (this is just so that i can benchmark how it does against my cpu, I understand it is a dumb application).

I feel like the way I am doing it right now is inefficient because i seem to be instructing the gpu to do each iteration one by one instead of telling it from the start that it has to do it many times.

Here is my code (Please look for the comment "RELEVANT PART STARTS HERE":

#include <iostream>
#include <CL/cl.hpp>

int main(){
    //get all platforms (drivers)
    std::vector<cl::Platform> all_platforms;
    cl::Platform::get(&all_platforms);
    if(all_platforms.size()==0){
        std::cout<<" No platforms found. Check OpenCL installation!\n";
        exit(1);
    }
    cl::Platform default_platform=all_platforms[0];
    std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";

    //get default device of the default platform
    std::vector<cl::Device> all_devices;
    default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
    if(all_devices.size()==0){
        std::cout<<" No devices found. Check OpenCL installation!\n";
        exit(1);
    }
    cl::Device default_device=all_devices[0];
    std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";

    cl::Context context({default_device});

    cl::Program::Sources sources;

    // kernel calculates for each element C=A+B
    std::string kernel_code=
        "   void kernel simple_add(global  int* A){       "
        "       A[get_global_id(0)]=A[get_global_id(0)]+1;                 "
        "   }                                                                               ";
    sources.push_back({kernel_code.c_str(),kernel_code.length()});

    cl::Program program(context,sources);
    if(program.build({default_device})!=CL_SUCCESS){
        std::cout<<" Error building: "<<program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device)<<"\n";
        exit(1);
    }

    const int N = 1e5   ;

    // create buffers on the device
    cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(int)*N);

    int A[N] ;

    for(int i = 0;i<N;i++){
        A[i] = i;
    }

    //create queue to which we will push commands for the device.
    cl::CommandQueue queue(context,default_device);

    queue.enqueueWriteBuffer(buffer_A,CL_TRUE,0,sizeof(int)*N,A);

    int C = 1e5;

    // RELEVANT PART STARTS HERE !!!

    for(int i = 0;i<C;i++){
        cl::Kernel kernel_add=cl::Kernel(program,"simple_add");
        kernel_add.setArg(0,buffer_A);
        queue.enqueueNDRangeKernel(kernel_add,cl::NullRange,cl::NDRange(N),cl::NullRange);
        queue.finish();
    }

    // RELEVANT PART ENDS HERE !!!

    queue.enqueueReadBuffer(buffer_A,CL_TRUE,0,sizeof(int)*N,A);

    printf("%d\n",A[N-4]);

    return 0;
}


texts:
I have a class that holds functions for caching using PHPFastCache. There are quite a few static functions in here and for each one I am declaring:

$cache = phpFastCache();

Is there a better way I can do this? It just feels wrong. Below is the full class maybe there are other changes I can do.

/**
 * Class Cache
 * Using PHPFastCache to cache data
 */
class Cache
{

    /**
     * put a data in to cache with a key, and time in minuets
     * @param $key
     * @param $value
     * @param int $minuets
     * @return mixed
     */
    public static function put($key, $value, $minuets = 1)
    {
        $cache = phpFastCache();
        return $cache->set($key, $value, $minuets * 60);
    }

    /**
     * Add value to Cache if does not already exist
     * @param $key
     * @param $value
     * @param int $minuets
     * @return bool
     */
    public static function add($key, $value, $minuets = 1)
    {
        if (self::has($key)) {
            return false;
        } else {
            self::put($key, $value, $minuets);
            return true;
        }
    }

    /**
     * Check if value is in Cache
     * @param $key
     * @return mixed
     */
    public static function has($key)
    {
        $cache = phpFastCache();
        return $cache->isExisting($key);
    }

    /**
     * Add a Key to the cache forever(25years)
     * @param $key
     * @param $value
     * @return mixed
     */
    public static function forever($key, $value)
    {
        return self::put($key, $value, 1 * 60 * 60 * 24 * 365 * 25);
    }

    /**
     * Get a value from cache and then remove from cache.
     * @param $key
     * @return bool
     */
    public static function pull($key)
    {
        $value = self::get($key);
        self::Remove($key);
        return $value;
    }

    /**
     * get value out of cache, ability to specify default if key is not in the cache
     * @param $key
     * @param bool $default
     * @return bool
     */
    public static function get($key, $default = False)
    {
        $cache = phpFastCache();
        if ($default !== false && self::has($key) === false) {
            return $default;
        } else {
            return $cache->get("$key");
        }
    }

    /**
     * remove key from cache
     * @param $key
     */
    public static function forget($key)
    {
        $cache = phpFastCache();
        $cache->delete($key);
    }

    /**
     * get information on key, such as time left in cache.
     * @param $key
     * @return mixed
     */
    public static function cacheInfo($key)
    {
        $cache = phpFastCache();
        return $cache->getInfo($key);
    }

    /**
     * remove everything from the cache
     */
    public static function clearCache()
    {
        $cache = phpFastCache();
        $cache->clean();
    }


texts:
I am new to TeX and here is my attempt to (ab)use mfirstuc to define an environment that counts the words. I am looking for suggestions on how to improve the implementation.

\documentclass{article}
\usepackage{mfirstuc}
\newcounter{wordcount}
%Make sure we don't accidentally overwrite things with \def and \let
\newcommand\cwaux\relax
\newcommand\oldgmfu\relax
\newcommand\temppar\relax
%
\newtoks\temppar
\def\cwaux#1\par{\capitalisewords{#1}\par}
\newcommand*\myglsmakefirstuc[1]{\stepcounter{wordcount}#1}
\newenvironment{countwords}{%
\setcounter{wordcount}{0}\let\oldgmfu\glsmakefirstuc\let\glsmakefirstuc\myglsmakefirstuc\temppar\everypar\everypar{\cwaux}%
}{%
\everypar\temppar\let\glsmakefirstuc\oldgmfu Word count:\arabic{wordcount}%
}
\begin{document}
\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}

\begin{countwords}
One paragraph.

Another paragraph which is longer.

\end{countwords}

\begin{countwords}
The third paragraph.

I am glad to see this works.

\end{countwords}

\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}

\end{document}


texts:
I wrote 2 different implementations to find gcd of 2 big numbers. The simple one using Euclid's algorithm always beat the Binary algorithm in term of speed. Is my implementation of Binary algorithm bad?

a = 5**100 - 1
b = 5**120 - 1

def gcd_euclid_recursive(a, b):
    if b == 0: return a
    return gcd_euclid_recursive(b, a % b)

def gcd_binary_recursive(a, b):
    if a == b: return a
    if a == 0: return b
    if b == 0: return a
    if a & 1 == 0: # a is even
        if b & 1 == 1: # b is odd
            return gcd_binary_recursive(a >> 1, b)
        else: # both a and b are even
            return gcd_binary_recursive(a >> 1, b >> 1) << 1

    if b & 1 == 0: # a is odd and b is even
        return gcd_binary_recursive(a, b >> 1)

    if (a > b):
        return gcd_binary_recursive((a-b) >> 1, b)
    return gcd_binary_recursive((b-a) >> 1, a)


texts:
I'm trying to make my code easier to understand by making it more correct and maintainable.

Here's the code I'm trying to simplify:

       $(document).ready(function(){
  $('.opretbruger').on('click', function(){
    if (opretbruger() === true){

    }
  });
});

var opretbruger = function(){
  if($('#brugernavn').val() === ''){
     alert('remember Email');
      return false;
  }

  if($('#pass1').val() === ''){
    alert('remember password');
    return false;
  }

  if($('#pass2').val() === ''){
    alert('remember password');
    return false;
  }

  if($('#fornavn').val() === ''){
    alert('remember your name');
    return false;
  }

  if($('#efternavn').val() === ''){
    alert('remember your last name');
    return false;
  }

  return true;
};

Here's my attempt at simplifying it:

       $(function () {
     var $login = $("#login"),
         $pwd = $("#pass"),
         $usr = $("#brugernavn");

     $login.on("submit", function (event) {
         var msg = "Husk ",
             usr = ($usr.val().trim() !== ""),
             pwd = ($pwd.val().trim() !== "");

         msg += !usr ? " brugernavn" : "";
         msg += !usr && !pwd ? " og " : "";
         msg += !pwd ? " kodeord" : "";

         (pwd && usr) || alert(msg);

         return (pwd && usr);
     });
 });


texts: Outputting flavor text depending on inputted strings

texts:
I have this program that takes two strings from the user, stores them in mixArray, then "mixes" them with mixItUp() and outputs a bit of flavor text, depending on the combination. Duplicate combinations (red-blue, blue-red) also give the same outcome.

I've gotten to a nested switch statement that's miles shorter than my previous tries, but I'm trying figure out if there's a more optimal, or readable method to do this, since I intend to scale it up.

mixItUp() {
  this.mixArray.sort();            // Sorts the array
  switch (this.mixArray[0]) {      // Goes through the first object
    case "blue":
      switch (this.mixArray[1]) {  // Goes through the second if the first is "blue"
        case "green":
          console.log("bf");
          break;
        case "purple":
          console.log("bg");
          break;
        case "yellow":
          console.log("bp");
          break;
        default:
          console.log("??");
          break;
      }
      break;
    case "green":     // If [0] is "green"...
      switch (this.mixArray[1]) {
        case "purple":
          console.log("fg");
          break;
        case "yellow":
          console.log("fp");
          break;
        default:
          console.log("??");
          break;
      }
      break;
    case "purple":     // If [0] is "purple"...
      switch (this.mixArray[1]) {
        case "yellow":
          console.log("gp");
          break;
        default:
          console.log("??");
          break;
      }
      break;
    default:
      break;
  }
}


texts: Directory watcher and notifier for files added or removed

texts:
I have written a piece of code that notifies if something is added or removed from a folder location:

from PyQt4 import QtGui
from PyQt4 import QtCore
import sys
import os

def xor(lst1, lst2):
    """ returns a tuple of items of item not in either of lists
    """
    x = lst2 if len(lst2) > len(lst1) else lst1
    y = lst1 if len(lst1) < len(lst2) else lst2
    return tuple(item for item in x if item not in y)

class MyMainWindow(QtGui.QMainWindow):
    def __init__(self, pathToWatch=None, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi()
        self._pathToWatch = pathToWatch or "/Users/ppl/Desktop/testFolder"
        self._initialContent = os.listdir(self._pathToWatch)
        self._fileSysWatcher    = QtCore.QFileSystemWatcher()
        self._fileSysWatcher.addPath(self._pathToWatch)
        self.connectSignals()

    def connectSignals(self):
        QtCore.QObject.connect(self._fileSysWatcher, QtCore.SIGNAL("directoryChanged(QString)"),
            self,      QtCore.SLOT("slotDirChanged(QString)"))

    def setupUi(self):
        self.label = QtGui.QLabel("Watching folder")
        self.setCentralWidget(self.label)
        self.setWindowTitle("Detect Dir Change")

    @QtCore.pyqtSlot("QString")
    def slotDirChanged(self, path):
        newContent = ''.join(xor(os.listdir(path), self._initialContent))

        self._initialContent = os.listdir(path)
        msg = ""
        if newContent not in self._initialContent:
            msg = "removed: %s" % newContent
        else:
            msg = "added: %s" %  newContent
        self.label.setText("Detected Directory Change!! \n %s" % msg)

def main():
    app         = QtGui.QApplication(sys.argv)
    window      = MyMainWindow()
    window.show()
    window.raise_()

    return sys.exit(app.exec_())
if __name__ == '__main__':
  main()

I have used QFileSystemWatcher that notifies that the change happened and then I recheck the content to compare with the difference.


texts: The program that reverses bytes in two distinct ways (in C++)

texts:
Will be grateful if anyone would reasonably comment on my code. I am interested in the style only. If there will be any comments which are not related to the style I am glad to read them as well.

   #include <iostream>

    unsigned reverse0(unsigned);

    union FourBytes
    {
        unsigned _value;
        struct Word
        {
            unsigned b1 : 8;
            unsigned b2 : 8;
            unsigned b3 : 8;
            unsigned b4 : 8;
        } _word;
    };
    unsigned reverse1(unsigned);

    int main(void)
    {
        int x(1), y(2);

        ++x = y;

        std::cout << reverse0(2447) << std::endl
            << reverse1(2447) << std::endl;
        return 0;
    }

    unsigned reverse0(unsigned p)
    {
        unsigned res(0);
        for (int i(0); i < sizeof(p)*8; ++i)
        {
            unsigned ithBit( (p & (1<<i)) >> i);
            int byteNumber(sizeof(p) - (i / 8) - 1);
            res |= (ithBit << (byteNumber*8+i%8));
        }
        return res;
    }

    unsigned reverse1(unsigned p)
    {
        FourBytes fb;
        fb._value = p;

        FourBytes res;
        res._word.b1 = fb._word.b4;
        res._word.b2 = fb._word.b3;
        res._word.b3 = fb._word.b2;
        res._word.b4 = fb._word.b1;

        return res._value;
    }


texts:
I am trying to create a treenode structure based on a database table for a Dungeons and Dragons character creation program I am working on.  I have come up with an incredibly confusing way to do it, but I am wondering if anyone can give me some better ideas on how to do this more efficiently.  I have a tables called subfeats and feats.  Subfeats contains all feats from the table feats that have subfeats.  Really, all I want to do is create a parent/child treenode structure for all feats and their subfeats.  Here is my code:

foreach (DataRow subrow in ds.subfeats.Rows)
{
    subfeatSet.Add(Convert.ToString(subrow[ds.subfeats.Columns.IndexOf("subfeat")]));
}

foreach (DataRow row in ds.feat.Rows)
{
    TreeNode newNode = new  TreeNode(Convert.ToString(row[ds.feat.Columns.IndexOf("name")]));

    if (subfeatSet.Contains(newNode.Text))
    {
        // Do Nothing.
    }
    else
    {
        treeviewFeatsFeats.Nodes.Add(newNode);
        foreach (DataRow subrow in ds.subfeats.Rows)
        {
            if (Convert.ToString(subrow[ds.subfeats.Columns.IndexOf("feat")]).Equals(newNode.Text))
            {
                TreeNode subTreeNode = new TreeNode(Convert.ToString(subrow[ds.subfeats.Columns.IndexOf("subfeat")]));
                newNode.Nodes.Add(subTreeNode);

                foreach (DataRow subsubrow in ds.subfeats.Rows)
                {
                    if (Convert.ToString(subsubrow[ds.subfeats.Columns.IndexOf("feat")]).Equals(subTreeNode.Text))
                    {
                        TreeNode subsubTreeNode = new TreeNode(Convert.ToString(subsubrow[ds.subfeats.Columns.IndexOf("subfeat")]));
                                subTreeNode.Nodes.Add(subsubTreeNode);
                    }
                }
            }
        }
    }
}


texts: Calculating sum after ranged-based subtractions

texts:
The puzzle consists from something like this:

You will receive an array of integer with values, then you will receive X numbers. Each number (call it x) represents an index of a 1-indexed array. Look up the value in the array (call it y), then subtract 1 from all the values in the array in the range [x-y, x+y]. The minimum value is 0.

After the given number of operations, you must return the sum of all values in the array.

My code looks like this.

#include <cstdio>
int array[111111];

int main(){
  int m,n;
  unsigned long long int sum = 0;

  //here n is the size of the array, and m is the number of operations
  scanf("%d %d", &n, &m);

  for (int i = 0; i < n; i++){
    scanf("%d", &array[i]);
    sum+= array[i];
  }

  for (int i = 0; i < m; i++) {
    int idx;
    scanf("%d", &idx);
    int count= array[idx - 1];

    for (int j = (idx -1 -count >=0 ? idx -1 -count : 0); j < (idx + count <=n ? idx + count : n); j++)
      if (array[j]){
        sum--;
        array[j]--;
      }
  }

  printf("%d\n", sum);
}

It solves the problem, but does not pass in the worst case, that would be a ton of cases decreasing from the entire array, basically an O(n*n) (I think).

The value restrictions are:

1 ≤ N,M ≤ 100000;
Value inside array index between 0 and 50000.

Test case:

Input:

10 4
1 2 0 8 4 2 9 8 1 3
9 5 10 6

Output:

23

Visualization of the test case:

For example, the first number that is read is 9. If we treat the number sequence as a 1-indexed array, we read value 1. This means that we need to subtract 1 from every value in the range [9-1, 9+1], which corresponds to the last three elements of the array.


texts:
I know there is a simpler way of doing this, but I just really can't think of it right now. Can you please help me out?

String sample = "hello world";
char arraysample[] = sample.toCharArray();
int length = sample.length();

//count the number of each letter in the string
int acount = 0;
int bcount = 0;
int ccount = 0;
int dcount = 0;
int ecount = 0;
int fcount = 0;
int gcount = 0;
int hcount = 0;
int icount = 0;
int jcount = 0;
int kcount = 0;
int lcount = 0;
int mcount = 0;
int ncount = 0;
int ocount = 0;
int pcount = 0;
int qcount = 0;
int rcount = 0;
int scount = 0;
int tcount = 0;
int ucount = 0;
int vcount = 0;
int wcount = 0;
int xcount = 0;
int ycount = 0;
int zcount = 0;

for(int i = 0; i < length; i++)
{
    char c = arraysample[i];
    switch (c)
    {
        case 'a':
            acount++;
            break;
        case 'b':
            bcount++;
            break;
        case 'c':
            ccount++;
            break;
        case 'd':
            dcount++;
            break;
        case 'e':
            ecount++;
            break;
        case 'f':
            fcount++;
            break;
        case 'g':
            gcount++;
            break;
        case 'h':
            hcount++;
            break;
        case 'i':
            icount++;
            break;
        case 'j':
            jcount++;
            break;
        case 'k':
            kcount++;
            break;
        case 'l':
            lcount++;
            break;
        case 'm':
            mcount++;
            break;
        case 'n':
            ncount++;
            break;
        case 'o':
            ocount++;
            break;
        case 'p':
            pcount++;
            break;
        case 'q':
            qcount++;
            break;
        case 'r':
            rcount++;
            break;
        case 's':
            scount++;
            break;
        case 't':
            tcount++;
            break;
        case 'u':
            ucount++;
            break;
        case 'v':
            vcount++;
            break;
        case 'w':
            wcount++;
            break;
        case 'x':
            xcount++;
            break;
        case 'y':
            ycount++;
            break;
        case 'z':
            zcount++;
            break;
        }
}
System.out.println ("There are " +hcount+" h's in here ");
System.out.println ("There are " +ocount+" o's in here ");


texts: F# Djikstras shortest path implementation

texts:
I'm just getting my feet wet with F#, by implementing some simple algorithms. First up: Djikstras shortest path.

There is one piece I've written in this code which confuses me as to why it works: the contains function. As I understand it, List.isEmpty returns true when a list is empty; but in this case, I would want to see the opposite of that. However, not(List.isEmpty) appeared to give the opposite of what I was expecting: it still returned true on a list being empty. Why is this the case? Or am I just missing something obvious?

As for the full code listing: have I done anything massively wrong?

open System;
open System.Collections;
open System.Collections.Generic;
open System.IO;

type Node(id: int, neighbours:list<(int*int)>) =
    let mutable _ID = id
    let mutable _neighbours:list<(int * int)> = neighbours

    member this.ID
        with get() = _ID
        and set(value) = _ID <- value

    member this.AddNeighbour(id:int, distance:int) =
        let t:(int*int) = (id, distance)
        _neighbours <- _neighbours @ [t]

    member this.Neighbours
        with get() = _neighbours
        and set(value) = _neighbours <- value;

let nodes:list<Node> = [new Node(1, [(2, 3); (3, 3); (4, 1)]);
                        new Node(2, [(3, 1)]);
                        new Node(3, [(1, 3); (2, 1); (4, 10)]);
                        new Node(4, [(1, 1); (3, 10)])
                        ];

let rec remove_first pred lst =
        match lst with
        | h::t when pred h -> t
        | h::t -> h::remove_first pred t
        | _ -> [];

let contains (item:'a) (lst:list<'a>) : bool =
    let filtered = List.filter (fun I -> I = item) lst;
    List.isEmpty(filtered);

let rec Traverse (data:list<Node>, start:int, visited:list<int>):list<int> =
    let startNode = List.find (fun (E:Node) -> E.ID = start) data //Get the starting node
    let newData = remove_first (fun (E:Node) -> E.ID = startNode.ID) data //Get the new data by removing the start node from the current data
    let newVisited = visited@[startNode.ID]
    let neighbourSet = List.filter (fun (i,_) -> contains i newVisited) startNode.Neighbours //Use only the neighbours that aren't visisted

    if(List.isEmpty neighbourSet) then
        newVisited;
    else
        neighbourSet
        |> List.minBy (fun (_,d:int) -> d) //Get neighbour with smallest distance
        |> fun (i, d) -> Traverse(newData, i, newVisited); //Recurse in to the traverse function, starting at the smallest neighbour

let result = Traverse (nodes, 1, []);

let writeList (lst:list<'a>):string =
    let mutable output = "";
    for I in lst do
        output <- String.Concat(output, I);
    output;

let path = "Output.txt";
File.WriteAllText(path , writeList(result));


texts:
I try to learn amd64 assembler. This is the first thing I tried. This piece of assembly should replicate the functionality of the following piece of C code, which turns a binary sha-256 hash into a human readable form.

assembly code

1:  .ascii "0123456789abcdef"
    .global show_hash
show_hash:
    .type show_hash @function
    .func show_hash
    mov $32,%ecx
    .p2align 2
0:  xor %eax,%eax
    lodsb
    mov %eax,%edx
    shr $4,%al
    and $15,%dl
    mov 1b(%rax),%al
    mov 1b(%rdx),%dl
    mov %bl,%ah
    stosw
    dec %ecx
    jnz 0b
    mov %cl,(%rdi)
    ret
    .endfunc

C code

void show_hash(char *dst, unsigned char *src) {
  static const char *lookup = "0123456789abcdef";
  char lo, hi, byte;
  int i = 32;

  do {
    byte = *src++;
    hi = lookup[byte >> 4];
    lo = lookup[byte & 0xf];
    *dst++ = hi;
    *dst++ = lo;
  } while (i--);
}

Am I doing it right? I tried to move the lookup table (label 1) into .section rodata, but all references to it were changed to 0 in the linked program, so I put it into the text section for now.


texts: Products excluding each element of the array

texts:
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Is there a better solution for this problem?

  Note: Division is not allowed.

public class DailyCodingProblem2 {
    public static void main(String args[]) {
        int[] arr = { 1, 2, 3, 4, 5 };
        int[] ans = solution(arr, arr.length);
        System.out.println(Arrays.toString(ans));

        arr = new int[] { 3, 2, 1 };
        ans = solution(arr, arr.length);
        System.out.println(Arrays.toString(ans));
    }

    private static int[] solution(int[] arr, int n) {
        int[] left = new int[n];
        int[] right = new int[n];
        int[] res = new int[n];
        left[0] = 1;
        right[n - 1] = 1;

        for (int i = 1; i < n; i++) {
            left[i] = arr[i - 1] * left[i - 1];
        }

        for (int i = n - 2; i >= 0; i--) {
            right[i] = arr[i + 1] * right[i + 1];
        }
        for (int i = 0; i < n; i++) {
            res[i] = left[i] * right[i];
        }
        return res;
    }
}


texts: Generic database select method for within my application

texts:
I want to implement a generic Get method for my ASP MVC application, which gets data from an MS Access database.

This is what I have so far, where I am testing it on the Pallet object.

Access

Get

public List<T> Get<T>(List<string> parameters)
{
    query = DatabaseConstants.Select<T>();
    argNames = DatabaseConstants.SelectParameters<T>();
    args = new DynamicParameters();
    foreach (var p in parameters)
    {
        args.Add(argNames[parameters.IndexOf(p)], p);
    }

    return NewSelect<T>(query, args);
}

Select

public List<T> NewSelect<T>(string query, DynamicParameters args = null)
{
    using (var db = new OleDbConnection(connectionString))
    {
        return (List<T>)db.Query<T>(query, args);
    }
}

DatabaseConstants

SelectQuery

public static string SelectQuery<T>()
{
    if (typeof(T) == typeof(Pallet))
    {
        return "SELECT * FROM subGRVReceived WHERE GRVNo=@grv";
    }
    else if (typeof(T) == typeof(Sample))
    {
        return "SELECT * FROM subReceivingQC WHERE GRV=@grv AND PalletSeq=@pallet";
    }
    else if (typeof(T) == typeof(QCItem))
    {
        return "SELECT * FROM subQCItems WHERE GRV=@grv AND PalletSeq=@pallet AND SampleNo=@sampleno";
    }
    else
    {
        return string.Empty;
    }
}

SelectParameters

public static List<string> SelectParameter<T>()
{
    if (typeof(T) == typeof(Pallet))
    {
        return new List<string>() { "@GRV" };
    }
    else if (typeof(T) == typeof(Sample))
    {
        return new List<string>() { "@grv", "@pallet" };
    }
    else if (typeof(T) == typeof(QCItem))
    {
        return new List<string>() { "@grv", "@pallet", "sampleno" };
    }
    else
    {
        return new List<string>();
    }
}

The method can be called like this:

Pallets = access.Get<Pallet>(new List<string>() { grvNumber });

Once I have completed this I will also look into creating generic Insert, Update etc methods. my main goal here is to just reduce the amount of code in the project, as I currently have a seperate method for each database query.

Does anyone have any thoughts or suggestionss on this? Many thanks for taking the time to look!

___________-

I initially wanted to implement an IDatabaseObject containing Query and ParameterNames, where Pallet can inherit from this and store the values inside itself, but I got an error, as the property Pallets is of type List<Pallet>, and C# does not seem to allow me to assign the output of Get<T> to this value when I included a where T : IDatabaseObject.


texts: Count words in string and tally up the repetitive words

texts:
I'm an elixir beginner.  I'm doing the word count exercise of exercism website.  The word count exercise returns a map with the word as the key and the number of instances as value.  The exercise excludes special characters, and ignores underscores. My code works, but I'm sure there is a way to make it cleaner.  I've attached the test file so that you can see the criteria that it needs to pass.

word_count.exs

defmodule Words do
  @doc """
  Count the number of words in the sentence.

  Words are compared case-insensitively.
  """
  @spec count(String.t) :: map
  def count(sentence) do
    String.downcase(sentence)                                           |>
      String.split(~r/[\s_]/)                                           |>
      Enum.filter(fn(word) -> String.match?(word, ~r/[a-zA-z\d]/) end)  |>
      Enum.map(fn(word) -> String.replace(word, ~r/[:!&@$%^,]/, "") end)|>
      Enum.group_by(fn(word) -> word end)                               |>
      Enum.reduce(%{}, fn({k, v}, acc) -> Map.put(acc, k, Enum.count(v)) end)
  end
end

word_count_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("word_count.exs")
end

ExUnit.start
ExUnit.configure exclude: :pending, trace: true

defmodule WordsTest do
  use ExUnit.Case

  test "count one word" do
    assert Words.count("word") == %{ "word" => 1 }
  end

  test "count one of each" do
    expected = %{ "one" => 1 ,  "of" => 1 ,  "each" => 1 }
    assert Words.count("one of each") == expected
  end

  test "count multiple occurrences" do
    expected = %{ "one" => 1 ,  "fish" => 4 ,  "two" => 1 ,  "red" => 1 ,  "blue" => 1 }
    assert Words.count("one fish two fish red fish blue fish") == expected
  end

  test "ignore punctuation" do
    expected = %{"car" => 1, "carpet" => 1, "as" => 1, "java" => 1, "javascript" => 1}
    assert Words.count("car : carpet as java : javascript!!&@$%^&") == expected
  end

  test "include numbers" do
    expected = %{"testing" => 2, "1" => 1, "2" => 1}
    assert Words.count("testing, 1, 2 testing") == expected
  end

  test "hyphens" do
    expected = %{"co-operative" => 1}
    assert Words.count("co-operative") == expected
  end

  test "ignore underscores" do
    expected = %{"two" => 1, "words" => 1}
    assert Words.count("two_words") == expected
  end

  test "normalize case" do
    expected = %{"go" => 3}
    assert Words.count("go Go GO") == expected
  end

  test "German" do
    expected = %{"götterfunken" => 1, "schöner" => 1, "freude" => 1}
    assert Words.count("Freude schöner Götterfunken") == expected
  end
end


texts: Finding if a given number is in a given range based on a flag

texts:
Question Description:

Given a number n, return True if n is in the range 1..10, inclusive. Unless outsideMode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.
in1to10(5, False) → **True**

in1to10(11, False) → **False**

in1to10(11, True) → **True**

The link to the problem is here.
Below is my first attempt.  Please feel free to review it based on best practices, style and any other efficient solution.
def in1to10(n, outside_mode):
    if(n>1 and n<10):
        return not outside_mode
    else:
        return outside_mode or n is 10 or n is 1


texts: SQL Server - Iterate, aggregate, and insert

texts:
I'm trying to find an efficient way to aggregate data for reporting. Let's say I need to aggregate the following data in 5-second intervals:

CREATE TABLE RawData
(
    Result                          FLOAT,
    CaptureTime                     DATETIME
);
INSERT INTO RawData VALUES
(2.3, '2018-04-01 00:00:00'),
(2.5, '2018-04-01 00:00:01'),
(2.8, '2018-04-01 00:00:02'),
(2.8, '2018-04-01 00:00:03'),
(3.4, '2018-04-01 00:00:04'),
(5.1, '2018-04-01 00:00:05'),
(2.2, '2018-04-01 00:00:06'),
(4.1, '2018-04-01 00:00:07'),
(4.3, '2018-04-01 00:00:08'),
(5.9, '2018-04-01 00:00:09'),
...

The aggregated data will be stored in another table:

CREATE TABLE AggregateData
(
    Result                          FLOAT,
    StartCaptureTime                DATETIME,
    EndCaptureTime                  DATETIME
);

As an example: if my aggregate function is SUM, the data in AggregateData would be:

+--------+----------------------+---------------------+
| Result |   StartCaptureTime   |    EndCaptureTime   |
+--------+----------------------+---------------------+
|  13.8  | 2018-04-01 00:00:00  | 2018-04-01 00:00:05 |
|  21.6  | 2018-04-01 00:00:05  | 2018-04-01 00:00:10 |
+--------+----------------------+---------------------+

The best solution that I've come up with uses a loop:

CREATE PROCEDURE [dbo].[spPerformAggregateCalculation]
    @UpdateIntervalSeconds          INT,
    @StartTime                      DATETIME,
    @EndTime                        DATETIME
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @RunningStartTime       DATETIME = @StartTime;
    DECLARE @RunningEndTime         DATETIME = DATEADD(SECOND, @UpdateIntervalSeconds, @RunningStartTime);
    DECLARE @AggregateValue         FLOAT;

    WHILE @RunningStartTime < @EndTime
    BEGIN
        SELECT @AggregateValue =
        (
            SELECT SUM(Result)
            FROM RawData
            WHERE CaptureTime >= @RunningStartTime AND CaptureTime < @RunningEndTime
        );

        INSERT INTO AggregateData VALUES
            (@AggregateValue, @RunningStartTime, @RunningEndTime);

        SELECT
            @RunningStartTime = @RunningEndTime,
            @RunningEndTime = DATEADD(SECOND, @UpdateIntervalSeconds, @RunningEndTime);
    END
END

EXEC spPerformAggregateCalculation
    @UpdateIntervalSeconds = 5,
    @StartTime = '2018-04-01 00:00:00',
    @EndTime = '2018-04-01 00:00:10'

Is there a more efficient way to get this data? I'll be performing more complex aggregations on millions of rows on a daily basis, so every bit helps.

P.S. In case "increase your interval" is offered as a suggestion, my data will actually be aggregated in much larger intervals than 5 seconds; I just whittled the problem down for the example.

Update

Below was my final solution, based dnoeth's answer:

CREATE PROCEDURE [dbo].[spPerformAggregateCalculation]
    @UpdateIntervalSeconds          INT,
    @StartTime                      DATETIME,
    @EndTime                        DATETIME
AS
BEGIN
    SET NOCOUNT ON;

    WITH cte AS
    (
        SELECT
            -- Adjust each CaptureTime to the beginning of the interval.
            DATEADD(SECOND, -DATEDIFF(SECOND, @StartTime , CaptureTime) % @UpdateIntervalSeconds, CaptureTime) as StartCaptureTime,
            Result
       FROM RawData
       WHERE CaptureTime >= @StartTime
    )
    INSERT INTO AggregateData
    SELECT
        SUM(Result),
        StartCaptureTime,
        DATEADD(SECOND, @UpdateIntervalSeconds, StartCaptureTime)
    FROM cte
    GROUP BY StartCaptureTime
    ORDER BY StartCaptureTime;
END


texts: Binary file validity in C++/C++11: checking a binary header

texts:
I have some code for checking a binary header to see if a binary file is meant to be read by a certain program, and I could use some extra eyes to review it.

Assume the following typedefs:

namespace Types
{
    using Byte = std::uint8_t;      // From <cstdint>
    using UInt32 = std::uint32_t;
    using String = std::string;     // From <string>
}

// This is a vector of bytes loaded from a binary file.
using ByteBuffer = std::vector<Types::Byte>;    // From <vector>

Also assume the following constants:

namespace Constants
{
    const Types::String     G_BINARY_HEADER_STRING  = "A2FORMAT";
    const Types::Byte       G_BINARY_MAJOR_VERSION  = 0x00;
    const Types::Byte       G_BINARY_MINOR_VERSION  = 0x01;
    const Types::UInt32     G_BINARY_HEADER_SIZE    = 14;
}

Here is the binary-header-validating code:

bool isBufferValid (ByteBuffer &a_buffer)
{
    // Get the size of the buffer. Make a cursor here, too.
    Types::UInt32 l_size = a_buffer.size();
    Types::UInt32 l_cursor = 0;

    // Check to see if the size exceeds 14 bytes.
    if (l_size <= Constants::G_BINARY_HEADER_SIZE)
        return false;

    // Bytes #1 to #8 are the characters in the binary header string.
    for (l_cursor = 0; l_cursor < Constants::G_BINARY_HEADER_STRING.size(); ++l_cursor)
    {
        if (a_buffer.at(l_cursor) != Constants::G_BINARY_HEADER_STRING.at(l_cursor))
        {
            return false;
        }
    }

    // Byte #9 indicates the engine's major version.
    //
    // If the byte found doesn't match the current major version, then it is invalid.
    if (a_buffer.at(8) != Constants::G_BINARY_MAJOR_VERSION)
        return false;

    // Byte #10 indicates the engine's minor version.
    //
    // If this byte given is greater than the current minor version, then it is invalid.
    if (a_buffer.at(9) > Constants::G_BINARY_MINOR_VERSION)
        return false;

    // Bytes #11 through #14 make up a 32-bit unsigned integer that indicates how many
    // bytes of data reside after the binary header.
    //
    // These bytes are arranged in Little Endian Notation.
    Types::UInt32 l_sizeOfData = 0;
    for (Types::UInt32 i = 0, j = 10; j < 14; i++, j++)
        l_sizeOfData |= a_buffer.at(j) << (i * 8);

    // If the amount of bytes in the buffer, after the header, do not match the number found
    // in the integer above, then the buffer is invalid.
    if (l_size - Constants::G_BINARY_HEADER_SIZE != l_sizeOfData)
        return false;

    // Remove the header from the buffer, because it has been confirmed valid, and is
    // therefore ready to use.
    a_buffer.erase(a_buffer.begin(), a_buffer.begin() + Constants::G_BINARY_HEADER_SIZE);

    return true;
}

Is there anything I can do to make this code more efficient? Are there also any steps I can take to make this validation more effective?


texts: Finding football team with the smallest difference in goals

texts:
The file football.dat contains the results from the English Premier League for 2001/2. The columns labeled ‘F’ and ‘A’ contain the total number of goals scored for and against each team in that season (so Arsenal scored 79 goals against opponents, and had 36 goals scored against them). Write a program to print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.

Please give me advice regarding best practices.

import java.io.File
import java.io.Reader

fun main(arg: Array<String>) {
    val inputStream = File("football.dat").inputStream()
    val reader = inputStream.bufferedReader().use { it.readLines() }
    //prints first Name in array.
    println(reader.first().team)
}

fun Reader.readLines(): List<teamAndScoreDifference> {
    val arrayOfTeamsAndGoals = arrayListOf<teamAndScoreDifference>()
    forEachLine {
        //if makePair(it) is not null,
        makePair(it)?.let {
            //add makePair(it)
            arrayOfTeamsAndGoals.add(it)
        }
    }
    val result = arrayOfTeamsAndGoals
            //by lowest (GoalsScored - GoalsTaken)
            .sortedBy { it.scoreDiffere }
    return result
}

data class teamAndScoreDifference(val team: String, val scoreDiffere: Int)

fun makePair(line: String): teamAndScoreDifference? {
    val teamName = line
            .take(23)
            .substringAfter(". ")
            .substringBefore(" ")
    val goalsScoredAndTaken: String = line
            .take(52)
            .substringAfterLast("   ")
    val goalsScored =
            goalsScoredAndTaken
            .substringBefore(" ")
            .toIntOrNull()
    val goalsTaken =
            goalsScoredAndTaken
            .substringAfterLast("  ")
            .toIntOrNull()
    if (goalsScored != null && goalsTaken != null) {
        return teamAndScoreDifference(teamName, Math.abs(goalsScored - goalsTaken))
    }
    //else return null
    return null
}

football.dat:

       Team            P     W    L   D    F      A     Pts
    1. Arsenal         38    26   9   3    79  -  36    87
    2. Liverpool       38    24   8   6    67  -  30    80
    3. Manchester_U    38    24   5   9    87  -  45    77
    4. Newcastle       38    21   8   9    74  -  52    71
    5. Leeds           38    18  12   8    53  -  37    66
    6. Chelsea         38    17  13   8    66  -  38    64
    7. West_Ham        38    15   8  15    48  -  57    53
    8. Aston_Villa     38    12  14  12    46  -  47    50
    9. Tottenham       38    14   8  16    49  -  53    50
   10. Blackburn       38    12  10  16    55  -  51    46
   11. Southampton     38    12   9  17    46  -  54    45
   12. Middlesbrough   38    12   9  17    35  -  47    45
   13. Fulham          38    10  14  14    36  -  44    44
   14. Charlton        38    10  14  14    38  -  49    44
   15. Everton         38    11  10  17    45  -  57    43
   16. Bolton          38     9  13  16    44  -  62    40
   17. Sunderland      38    10  10  18    29  -  51    40
   -------------------------------------------------------
   18. Ipswich         38     9   9  20    41  -  64    36
   19. Derby           38     8   6  24    33  -  63    30
   20. Leicester       38     5  13  20    30  -  64    28


texts:
I am learning fundamental data structures, and I want to know if this is a valid implementation of a heap. Can any C# features be used to improve or extend the implementation? In addition to heapsort, what are some applications of a heap?

class BinaryHeap
{

    /// <summary>
    /// A binary heap implementation used to sort an integer array.
    ///
    /// 1. The Max-Heapify and Min-Heapify methods maintain the heap properties.
    ///
    /// 2. The Build-Heap methods produce the heap from an unordered array.
    ///
    /// 3. The HeapSort methods sort the array in place and runs in O(n ln n) time.
    /// </summary>

    private int heapSize;

    public BinaryHeap()
    {
        heapSize = 0;
    }

    private int ParentIndex(int currentIndex)
    {
        return currentIndex / 2;
    }

    private int LeftIndex(int currentIndex)
    {
        return currentIndex * 2;
    }

    private int RightIndex(int currentIndex)
    {
        return currentIndex * 2 + 1;
    }

    // Building the heap
    #region
    public void BuildMaxHeap(int[] A)
    {
        heapSize = A.Length - 1;

        for(int i = A.Length/2; i >= 0; i--)
        {
            MaxHeapify(A, i);
        }

    }
    public void BuildMinHeap(int[] A)
    {
        heapSize = A.Length - 1;
        for (int i = A.Length / 2; i >= 0; i--)
        {
            MinHeapify(A, i);
        }
    }
    #endregion

    // Maintaining heap properties
    //      MaxHeapify: Ensure that parents are larger than children
    //      MinHeapify: Ensure that children are larger than parents
    #region
    public void MaxHeapify(int[] A, int i)
    {

        int leftIndex = LeftIndex(i);
        int rightIndex = RightIndex(i);

        int largestIndex = 0;

        // Check to see which node in the tree subset has the largest value
        if (leftIndex <= heapSize && A[leftIndex] > A[i])
        {
            largestIndex = leftIndex;
        }
        else
        {
            largestIndex = i;
        }
        if (rightIndex <= heapSize && A[rightIndex] > A[largestIndex])
        {
            largestIndex = rightIndex;
        }

        // Do not make any switches if the largest node is the parent
        if(largestIndex != i)
        {
            int temp = A[largestIndex];
            A[largestIndex] = A[i];
            A[i] = temp;
            MaxHeapify(A, largestIndex);
        }

    }
    public void MinHeapify(int[] A, int i)
    {

        int leftIndex = LeftIndex(i);
        int rightIndex = RightIndex(i);
        int smallest;

        if (leftIndex <= heapSize && A[leftIndex] < A[i])
        {
            smallest = leftIndex;
        }
        else
        {
            smallest = i;
        }

        if (rightIndex <= heapSize && A[rightIndex] < A[smallest])
        {
            smallest = rightIndex;
        }

        if (smallest != i)
        {
            int temp = A[i];
            A[i] = A[smallest];
            A[smallest] = temp;
            MinHeapify(A, smallest);
        }

    }
    #endregion

    // Heapsort
    #region
    public int[] AscendingHeapSort(int[] A)
    {

        // Ensure all parents are greater than their children
        BuildMaxHeap(A);

        for (int i = A.Length - 1; i >= 0; i--)
        {
            int temp = A[0];
            A[0] = A[i];
            A[i] = temp;
            heapSize--;
            MaxHeapify(A, 0);
        }

        return A;

    }

    public int[] DescendingHeapSort(int[] A)
    {

        // Ensure all parents are less than their children
        BuildMinHeap(A);

        for (int i = A.Length - 1; i >= 0; i--)
        {
            int temp = A[0];
            A[0] = A[i];
            A[i] = temp;
            heapSize--;
            MinHeapify(A, 0);
        }

        return A;
    }
    #endregion

}


texts:
A bishop can capture any other bishop if it lies along the same
  diagonal line, so long as no other bishop is in its path.
  Given a list of coordinates of the bishops locations, and a board size, determine how many bishops are unsafe.

This code has a time complexity of \$O(N*K)\$ where N is the number of bishops, K is (N- current index).

Is there a way to improve this?

bishops = [(0, 0),
           (1, 1),
           (0, 2),
           (1, 3),
           (2, 0),
           (2, 2)]
size = 5

moves = [(1, 1), (1, -1), (-1, 1), (-1, -1)]

captured = []
for index, coordinates in enumerate(bishops):
    remaining = bishops[index + 1:]
    seen = bishops[:index + 1]
    for dx, dy in moves:
        x, y = coordinates
        while 0 <= x + dx < size and 0 <= y + dy < size:
            x += dx
            y += dy
            if (x, y) in seen:
                break
            if (x, y) in remaining:
                remaining.remove((x, y))
                capture = f"{coordinates} takes {x, y}"
                captured.append(capture)
                break

print(f"There are {len(captured)} moves")
print(*captured, sep = "\n")


texts:
I need to write a function that "packs" an array of bytes (integers between 0 and 255) into a string. I also need to be able to perform the reverse operation, to get my byte array from the string that it was packed into. This needs to be done as fast as possible. Seeing as JavaScript has 16-bit strings, I packed two bytes per character. Here is my code and tests:

function pack(bytes) {
    var str = "";
    for(var i = 0; i < bytes.length; i += 2) {
        var char = bytes[i] << 8;
        if (bytes[i + 1])
            char |= bytes[i + 1];
        str += String.fromCharCode(char);
    }
    return str;
}

function unpack(str) {
    var bytes = [];
    for(var i = 0; i < str.length; i++) {
        var char = str.charCodeAt(i);
        bytes.push(char >>> 8);
        bytes.push(char & 0xFF);
    }
    return bytes;
}

var tests = [
    [],
    [126, 0],
    [0, 65],
    [12, 34, 56],
    [0, 50, 100, 150, 200, 250]
];

console.log("starting tests");
tests.forEach(function(v) {
    var p = pack(v);
    console.log(v, p, unpack(p));
});

And the output to that is:

starting tests
[] "" []
[126, 0] "縀" [126, 0]
[0, 65] "A" [0, 65]
[12, 34, 56] "ఢ㠀" [12, 34, 56, 0]
[0, 50, 100, 150, 200, 250] "2撖죺" [0, 50, 100, 150, 200, 250]

I have a few things I'd like feedback on:

This was the first time I used bitwise operators. Is this how it should be done?
Are there any speed improvements that could be made?
Can you guys think of any way to discard that last 0 byte when encoding then decoding an array with an odd number of bytes? (see test #4)


texts: Java Stream wants to return only failure list

texts:
I have an object delivery template, which I want to delete based on a name. String array which contains delivery template name is taken as an input parameter. I use Java Stream to iterate the list. Please find the code below.

    public static List<String> deleteDeliveryTemplates(String... deliveryTemplateNames) {
    List<String> failureList = new ArrayList<String>();
    Stream<String>deliveryTemplateNamesStream= Stream.of(deliveryTemplateNames);
     deliveryTemplateNamesStream.forEach(deliveryTemplateName ->{
        try
        {
            deleteDeliveryTemplate(deliveryTemplateName);
        } catch (Exception e)
        {
            failureList.add(deliveryTemplateName);
        }
    });
    return failureList;
}

Is there a better way in JAVA 8 to return the failure list using stream. For example: using map function of Stream


texts:
I'm designing a Factory in C++ with raw pointers, but I'd like to use smart pointers when possible as is recommended with the Factory pattern in newer C++. Unfortunately my compiler is a bit old (gcc 4.4.6) and not all of the features of C++11 (let alone C++0x) are available to me.

I cannot use nullptr, which is the most troubling aspect to me. I'd love a standard review and any tips for adding smart pointers to my code.

#ifndef SERVICE_FACTORY_H_
#define SERVICE_FACTORY_H_

#include <string>
#include <map>
#include <memory>

class Service {
  public:
    virtual void free() = 0;
};

typedef Service* (*CreationFunction)(void);

class Counter : public Service {
  public:
    static Service* create() { return new Counter(); }
    void free() { delete this; }
};

class ServiceFactory {
  public:
    ~ServiceFactory() {
      _registeredServices.clear();
    }

    static ServiceFactory* getInstance() {
      static ServiceFactory instance;
      return &instance;
    }

    void registerService(const std::string &serviceName, CreationFunction fn) {
      _registeredServices[serviceName] = fn;
    }

    Service* createService(const std::string &serviceName) {
      auto it = _registeredServices.find(serviceName);
      if(it != _registeredServices.end())
        return it->second();
      return NULL;
    }
  private:
    ServiceFactory() {
      registerService("COUNTER", &Counter::create);
    }

    ServiceFactory(const ServiceFactory&) { /* Nothing implemented yet */ }

    ServiceFactory& operator=(const ServiceFactory&) { return *this; }

    std::map<std::string, CreationFunction> _registeredServices;
};

#endif // SERVICE_FACTORY_H_

EDIT

Here's a driver:

#include "ServiceFactory.h"
#include <iostream>

int main() {
  Service* counter = ServiceFactory::getInstance()->createService("COUNTER");
  if(counter) {
    std::cout << "Counter was made." << std::endl;
    counter->free();
  } else {
    std::cout << "Counter was not made." << std::endl;
  }

  return 0;
}

Here's the compilation process succeeding on ideone (with C++14).


texts:
I want to fix number of digits after '.' in digit represented by string.
Is there better solution than mine?
My code
def convert(s):
    """ Convert 1234.12345678 to 1234.123"""
    vec = s.split('.')
    if len(vec) == 2 and len(vec[1]) > 3:
        return vec[0] + '.' + vec[1][:3]
    return s


texts:
I'm asking in arbitrary sense to avoid going into any unwanted specifics.

Suppose we're to put balls in baskets.
If the there are <6 balls, they don't get to go in any basket.
If there are between 6-12 balls they take up 1 basket.
But if the balls are >12, they take up 2 baskets.

Following is WORKING FINE:

if (count($balls)<=5) {
    $baskets = 0;
} else if (count($balls) > 5 && count($balls) <12) {
    $baskets = 1;
} else {
    $answer = ceil(count($balls)/12);
}

Question: Is there a better, smarter, and/or quicker way to approach the problem, may be through loops or something?


texts: Web scraper for Football (Soccer) data with BeautifulSoup and Requests

texts:
I wrote a web scraper to get football scores from here. I'm getting the data for all seasons for the three major German leagues. It all works at the moment, but I'm sure it's possible to make it a lot more concise.

import requests
import os
import pandas as pd
from bs4 import BeautifulSoup

# base url for scrape
base_url = "http://www.weltfussball.de/"

ligen = [["Liga1", "bundesliga-2017-2018/"],
         ["Liga2", "2-bundesliga-2017-2018/"],
         ["Liga3", "3-liga-2017-2018/"]]

def get_page(ext):
  # get the page and make soup
  global soup, page
  if (ext[0] == "/"):
    ext = ext[1:]
  url = base_url + ext
  r = requests.get(url)
  page = r.content.decode('utf-8','ignore')
  soup = BeautifulSoup(page, "lxml")

def create_dir(s):
  saison = "saison-" + s.replace("/", "-")
  os.mkdir("data/%s" % saison)

def get_seasons(liga):
  global seasons_df
  # Getting all seasons
  form = soup.find("select", attrs={"name": "saison"})
  seasons = []
  season = []
  for s in form.find_all("option"):
    season.append(s.text)
    season.append(s.get("value"))
    seasons.append(season)
    season = []
  seasons_df = pd.DataFrame(seasons, columns=["Saison", "Link"])
  seasons_df["Spiele"] = "empty"
  seasons_df["Liga"] = str(liga)

def get_games(season_n):
  tables = []
  for t in soup.find_all("table", "standard_tabelle"):
    print(t.contents)
    tables.append(t)

  data_table = tables[0]

  record = []
  records = []
  trs = data_table.findAll("tr")
  for n in range(len(trs)):
    if (trs[n].contents[1].name == "th"):
      th = trs[n].find("th")
      record.append(th.text)
    else:
      if not record:
        record.append(records[-1][0])
      tds = trs[n].findAll("td")
      for p in range(len(tds)):
        record.append(tds[p].text)
      # filling empty date column with previous value
      if (record[1] == ""):
        record[1] = records[-1][1]
      records.append(record)
      record = []

  # Pasting it into a DataFrame
  df = pd.DataFrame(records)

  # Dropping empty columns
  spdf = pd.DataFrame()
  z = 0
  for key in df.keys():
    if (df[key].all() in (" - ", "\n", "\n\n")):
      print("Column %s is empty" % key)
    else:
      print("Adding %s to game DF" % key)
      spdf[z] = df[key]
      z += 1

  # Renaming the columns
  # Defining the new column names
  names = {
      0 : "Spieltag",
      1 : "Datum",
      2 : "Zeit",
      3 : "Heim",
      4 : "Auswärts",
      5 : "Score"
  }

  spdf.rename(columns=names, inplace=True)

  seasons_df["Spiele"][season_n] = spdf

# the execution starts here
for l in range(len(ligen)):
  get_page("alle_spiele/%s" % ligen[l][1])
  get_seasons(ligen[l][0])
  # Getting the data
  for i in seasons_df.index:
    if (ligen[l][0] == "Liga1"):
      try:
        create_dir(seasons_df["Saison"][i])
      except FileExistsError:
        print("Directory %s exists already" % seasons_df["Saison"][i])
      else:
        create_dir(seasons_df["Saison"][i])
    get_page(seasons_df["Link"][i])
    get_games(i)
  ligen[l].append(seasons_df)

for l in range(len(ligen)):
  l1 = ligen[l][2]
  for s in range(len(l1["Saison"])):
    sss = l1["Saison"][s].replace("/", "-")
    sss = sss[0:9]
    l1["Spiele"][s].to_csv("data/saison-%s/%s_Spiele.csv" % (sss, ligen[l][0]), sep=";")

For example, I have to get all tables with class standard_tabelle, because there are two in the page that have no otherwise distinctive attribute.

Data Table:

      ...

Table 2:

    Aktuelle Meldungen &raquo;

I would like to select the data table based on its parent
, but there are other divs with the data class, so I can't just find div with class "data".


texts: Read a csv file and insert into DB table

texts:
I've found some resources about PHP performance optimization here and there but I don't know how to start. I send 130k CSV rows in approximatively 7min. My script read CSV file and send $batch_size row per query, while doing some string operations such as changing date to the correct format or replacing , with . for the floats.
$db = new PDO("mysql:host=$db_host;port=$db_port;charset=utf8","$db_username", "$db_password");
$csv_path = "path/to/myfile.csv";
$table = "TableName";
//Start of the query
$query="USE ".$db_name.";";

$FilePath = $csv_path;
$is_not_title_row=FALSE;//Usefull not to take the first row

$row_batch_count=0;//Counter for batches

//1 data = 1 part of the row
$number_of_data=0;
$data='';

// Open file in read-only mode
$handle = fopen($FilePath, "r");

while (($data = fgetcsv($handle, 2000, ";"  ,  chr(8))) !== FALSE) {

        $number_of_data = count($data)-1;

        // Generate MySQL query
        if($is_not_title_row)
        {
            $query .= "INSERT INTO ".$table." VALUES (";

            //We read all the data of one row
            for ($c=0; $c <= $number_of_data; $c++) {

                $data[$c]=utf8_decode($data[$c]);

                $data[$c]=str_replace('/', '-', $data[$c]);
                $data[$c]=str_replace(',', '.', $data[$c]);

                //If it's a date, we convert it to the right date format
                 if (DateTime::createFromFormat('d-m-Y', $data[$c]) !== FALSE) {
                    $data[$c] = date("Y-m-d", strtotime($data[$c]));
                    $query .= "'" . mres($data[$c]) ."',";
                //If there is nothing, we send NULL value
                else if(mres($data[$c])==NULL){
                    $query .= "NULL,";
                }
                else{
                        $query .= "'" . mres($data[$c]) ."',";
                }

                //If this is the end of the INSERT INTO we remove the comma
                if($c==$number_of_data)
                {
                    $query=substr_replace($query ,"", -1);
                }

            }
            $query .= ");";

            $row_batch_count++;

            //If we are at the end of the batch, we send the query then start the creation of another
            if($row_batch_count==$batch_size)
            {
                echo "There is ".$row_batch_count." row sent
";
                echo "

";
                $query_to_execute = $db->prepare($query);
                $query_to_execute->execute();

                $query="USE ".$db_name.";";

                $row_batch_count=0;
            }

        }

        //Usefull to remove the first row
        if(!$is_not_title_row){
            $is_not_title_row=TRUE;
        }

    }

        //Without more batches, we execute the query(=we are at the end of the file)
        $query_to_execute = $db->prepare($query);
        $query_to_execute->execute();
        $query_to_execute = NULL;

Solution
Instead of doing one INSERT INTO for each row, I've simply inserted multiple row in a single INSERT INTO.
The output query looks like that :
INSERT INTO Table VALUES (x,x,x),(x,x,x),(x,x,x),(...

The csv insertion is now 30 times faster


texts: Deploy folder to desired path - PowerShell function

texts:
I am still learning PowerShell and I would like your opinion on my folder deployment PowerShell function. It basically check if a defined folder exists and creates it if it does not and writes it actions to log and console.
<#
.SYNOPSIS
Creates folder if it does not already exists.
.DESCRIPTION
This function check if defined transfer folder exists and if not it creates it on remote computer.
.PARAMETER Path
Full path of the folder.
.PARAMETER Cancel
If Cancel parameter set to true the folder deployment is canceled. This is used in pipeline when it is important to skip this
operation if last operation failed.
.EXAMPLE
Deploy-Folder -Path 'D:\Folder\Folder'
#>
function Deploy-Folder {
    param (
        [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [String]
        $Path,

        [Parameter(Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [boolean]
        $Cancel = $false
    )

    begin {
        Import-Module '.\Write-Log.psm1'
    }

    process {
        if(-not $Cancel) {
            if((Test-Path $Path) -eq $true) {
                $Message = "Successfully accessed " + $Path + " folder"
                $OperationResult  = 'Success'
            }
            else {
                try {
                    New-Item -Path $Path -ItemType "Directory"
                }
                catch {
                    $Message = "Failed to create " + $Path + " folder `n" + $_.Exception
                    $OperationResult  = 'Fail'
                }

                if((Test-Path $Path) -eq $true) {
                    $Message = "Successfully created " + $Path + " folder"
                    $OperationResult  = 'Success'
                }
            }
        }
        else {
            $Message = "Canceled " + $Path + " folder deployment"
            $OperationResult  = 'Success'
        }

        Write-Log -OperationResult $OperationResult -Message $message

        if($OperationResult -ne 'Fail') {
            $Cancel = $false
        }
        else {
            $Cancel = $true
        }

        New-Object -TypeName psobject -Property @{
            Cancel = $Cancel
        }
    }
}


texts: Efficiency and length of functions when perfomring similar tasks to classes and IDs

texts:
I'm not proficient at jQuery, however can tinker and get basic functionality working as I would like. The below code is performing a number of functions to change states of some elements in my site, and it is all working correctly.

However, I'm sure it is not the most efficient way of achieving this (fairly simple) functionality, so I'm hoping somebody can help me to make this much leaner and more efficient?

I have commented the code to explain what each line should be achieving, essentially adding and removing classes to a a number of elements. As you can see, a lot of the lines are repeated to accommodate the different states outlined in the comments, but I'm sure something perhaps like .siblings could be used to reduce the amount of code.

Any help greatly appreciated!

JS

$(document).ready(function () {
    $('#menu-button').click(function(){
        // MENU BUTTON STATES
        // If the menu button is active, then remove all classes to return to initial state
        if ($(this).hasClass('active')) {
            $(this).removeClass();
        // When in initial state, add active class
        } else {
            $(this).addClass('active');
        }

        // OVERLAY STATES
        // If in menu state, clicking menu button removes all #overlay classes to return to initial state
        if ($('#overlay').hasClass('active menu')) {
            $('#overlay').removeClass();
        // If in services state, clicking menu button removes all #overlay classes and add classes to return to menu state
        } else if ($('#overlay').hasClass('active services')) {
            $('#overlay').removeClass().addClass('active menu');
        // If in about state, clicking menu button removes all #overlay classes and add classes to return to menu state
        } else if ($('#overlay').hasClass('active about')) {
            $('#overlay').removeClass().addClass('active menu');
        // If in contact state, clicking menu button removes all #overlay classes and add classes to return to menu state
        } else if ($('#overlay').hasClass('active contact')) {
            $('#overlay').removeClass().addClass('active menu');
        // When in initial state, add classes to change to menu state
        } else {
            $('#overlay').addClass('active menu');
        }
        return false;
    });

    $('.services a').click(function(){
        // When clicking this menu item, remove all #overlay classes and add classes to return to services state
        $('#overlay').removeClass().addClass('active services');
        // Also, return menu button to initial state
        $('#menu-button').removeClass();
        return false;
    });

    $('.about a').click(function(){
        // Same as above but for about state
        $('#overlay').removeClass().addClass('active about');
        $('#menu-button').removeClass();
        return false;
    });

    $('.contact a').click(function(){
        // Same as above but for contact state
        $('#overlay').removeClass().addClass('active contact');
        $('#menu-button').removeClass();
        return false;
    });

    $('.logo').click(function(){
        // When clicking .logo, return everythign to initial state
        $('#overlay').removeClass();
        $('#menu-button').removeClass();
        return false;
    });

});


texts:
I am learning programming with Python. I am not sure if I can write a try/except block like this.

import os
import shutil
try:
    shutil.rmtree('c:/guna/newCAT1')
    print("dir newCAT1 deleted")

except:
    os.mkdir('c:/guna/newCAT1')
    print("dir newCAT1 created")
    fileIN=open('c:/guna/newCAT1/secretMSG.txt','w' )
    fileIN.writelines("the dog is green")
    fileIN.close()
else:
    print("exception code did not execute")
    os.mkdir('c:/guna/newCAT1')
    print("dir newCAT1 created")
    fileIN = open('c:/guna/newCAT1/secretMSG.txt', 'w')
    fileIN.writelines("the dog is green")
    fileIN.close()


texts: Recursive function to find the number of ways a number can be generated out of a set of numbers

texts:
I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by adding numbers from a certain set, where any number in the set can be used N times.

It is like if I have the number 10 and I want to find out how many ways 10 can be generated using [2,3,5]

2+2+2+2+2 = 10
5+3+2 = 10
2+2+3+3 = 10
5+5 = 10

to solve it I made this function:

function getNumberOfWays($money, $coins) {
    static $level = 0;
    if (!$level) {
        sort($coins);
    }

    if ($level && !$money) {
        return 1;
    } elseif (!$level && !$money) {
        return 0;
    }

    if ($money === 1 && array_search(1, $coins) !== false) {
        return 1;
    } elseif ($money === 1 && array_search(1, $coins) === false) {
        return 0;
    }

    $r = 0;
    $tmpCoins = $coins;
    foreach ($coins as $index => $coin) {
        if (!$coin || $coin > $money) {
            continue;
        }

        $tmpCoins[$index] = 0;
        $tmpMoney = $money;
        do {
            $tmpMoney -= $coin;
            if ($tmpMoney >= 0) {
                $level++;
                $r += getNumberOfWays($tmpMoney, $tmpCoins);
                $level--;
            } elseif (!$tmpMoney) {
                $r++;
            }
        } while ($tmpMoney >= 0);
    }

    return $r;
}

This function works correctly: it returns the right value.

Can I improve it in any way?


texts:
I'm trying to improve my Game of life program for school in Python, to be able to run it quicker. So if you have some ideas, I will be glad to hear them.

My current code:

def neighbourhood(m, i, j):
    num = 0
    n_board = len(m)
    for k in range(i-1,i+2):
        for l in range(j-1,j+2):
            if k < 0 or l < 0 or k >= n_board or l >= n_board:
                num = num + 0
            else:
                num = num + m[k][l]
    return num

def update(m):
    s = np.copy(m)
    n_board = len(m)
    for i in range(0, n_board):
        for j in range(0, n_board):
            if s[i][j] == 1:
                num = neighbourhood(s, i, j) - 1
                if num <= 1 or num > 3:
                    m[i][j] = 0
                else:
                    m[i][j] = 1
            else:
                num = neighbourhood(s, i, j)
                if num == 3:
                    m[i][j] = 1
                else:
                    m[i][j] = 0

def square(x, y):
    turtle.penup()
    turtle.setposition(x,y)
    turtle.setheading(0)
    turtle.pendown()
    turtle.begin_fill()
    for i in range(4):
        turtle.forward(0.9)
        turtle.left(90)
    turtle.end_fill()

def draw(m):
    turtle.clear()
    n_board = len(m)
    for i in range(n_board):
        for j in range(n_board):
            if m[i][j] == 1:
                square(j, (n_board - i - 1))
    turtle.update()

def main(n_board):
    turtle.reset()
    turtle.setworldcoordinates(0, 0, n_board, n_board)
    turtle.hideturtle()
    turtle.speed('fastest')
    turtle.tracer(0, 0)
    turtle.color('black')
    turtle.bgcolor('white')
    board=np.zeros((n_board, n_board), int)
    for i in range(n_board):
        for j in range(n_board):
            if random() < 0.5:
                board[i][j] = 1
    draw(board)
    for k in range(100):
        update(board)
        draw(board)

So as you can see for the moment i'm only doing 100 repetition and the starting board is randomly created.


texts: Have a class that holds all the interfaces

texts:
I seriously didn't know how to write this in Google, there must be an answer lying around. Here it goes:

I'm using Ninject (IoC) and ASP.NET MVC 5. I have a business layer with a couple of classes. Is it ok if I have one class that holds all these classes? Like this:

    public class BusinessLayer : IBusinessLayer
{
    public IOrganizerLogic OrganizerLogic { get; }
    public IParticipantLogic ParticipantLogic { get; }
    public IPaymentLogic PaymentLogic { get; }
    public ITournamentLogic TourmanetLogic { get; }

    public BusinessLayer(IOrganizerLogic organizerLogic, IParticipantLogic participantLogic,
        IPaymentLogic paymentLogic, ITournamentLogic tournamentLogic)
    {
        OrganizerLogic = organizerLogic;
        ParticipantLogic = ParticipantLogic;
        PaymentLogic = PaymentLogic;
        TourmanetLogic = TourmanetLogic;
    }

}


texts: Java Multitasking (String concatenation)

texts:
I would like to know if I did everything right and if there a way to do it more simple?

Task:
Task link to html file

My main:

package zad2;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    StringTask task = new StringTask("A", 70000);
    System.out.println("Task " + task.getState());
    task.start();
    if (args.length > 0 && args[0].equals("abort")) {
    /*
       <- here add the code interrupting the task after a second
          and run it in a separate thread
    */
        Thread.sleep(500);
        task.abort();
        task.startNewTread();
    }
    while (!task.isDone()) {
      Thread.sleep(500);
      switch(task.getState()) {
        case RUNNING: System.out.print("R."); break;
        case ABORTED: System.out.println(" ... aborted."); break;
        case READY: System.out.println(" ... ready."); break;
        default: System.out.println("unknown state");
      }

    }
    System.out.println("Task " + task.getState());
    System.out.println(task.getResult().length());
  }
}

My StringTask:

package zad2;

public class StringTask implements Runnable {
    String line;
    String letter;
    int amount;
    boolean isAborted;
    TaskState stat;
    boolean wasAborted = false;

    public StringTask(String s, int i){
        line = "";
        letter = s;
        amount = i;
        stat = TaskState.CREATED;
        isAborted = false;
    }
    public StringTask(String s){
        this(s, 0);
    }
    @Override
    public void run() {
        while (amount > 0 && !isAborted){
            line += letter;
            amount--;
        }
        if(wasAborted == false) stat = TaskState.READY;
        else stat = TaskState.ABORTED;
    }

    public String getResult (){
        return line;
    }
    public TaskState getState (){
        return stat;
    }
    public void start (){
        isAborted = false;
        stat = TaskState.RUNNING;
        new Thread(this).start();
        //System.out.println("start");
        //run();
    }
    public void startNewTread (){
        isAborted = false;
        stat = TaskState.RUNNING;
        new Thread(this).start();
    }

    public void abort (){
        stat = TaskState.ABORTED;
        wasAborted = true;
        isAborted = true;
    }
    public boolean isDone(){
        if (stat == TaskState.READY || stat == TaskState.ABORTED) return true;
        return false;
        }
}

My TaskState:

package zad2;
public enum TaskState {
    CREATED, RUNNING, ABORTED, READY
}


texts:
In Protractor, Jasmine expectations are patched to resolve WebDriver
  promises implicitly.

  For instance, if you need to assert a count of certain elements, you
  can use count() method (which returns a promise) directly:

expect($$(".myclass").count()).toEqual(5);

  But, newcomers to Protractor can miss that and would do the same
  resolving promises explicitly which leads to a more complex code:

$$(".myclass").then(function (elements) {
    expect(elements.length).toEqual(5);
});

I've developed an ESLint rule to try to catch this kind of explicit "count" value check. The logic behind the rule is:

It first locates the .length "member expression"
Iterates over the ancestors and checks if inside expect
Iterates over the ancestors and checks if inside a "then" callback and there is at least one argument passed to the callback function
Determines if .then was called on an "element array finder"

'use strict'

/**
 * @fileoverview Recommend using `count()` instead of `then()` and `length`
 * @author Alexander Afanasyev
 */

var isElementArrayFinder = require('../is-element-array-finder')
var isThenCallBack = require('../is-then-callback')
var isExpect = require('../is-expect')

module.exports = {
  meta: {
    schema: []
  },

  create: function (context) {
    return {
      MemberExpression: function (node) {
        if (node.property && node.object && node.property.name === 'length') {
          // remember the variable name the ".length" was used on
          var variableName = node.object.name

          // find out if we are in an expect()
          var expectAncestor
          var thenAncestor
          var ancestors = context.getAncestors(node)

          for (var i = 0; i < ancestors.length; i++) {
            expectAncestor = ancestors[i]
            if (expectAncestor && expectAncestor.type === 'CallExpression' && isExpect(expectAncestor)) {
              // find out if we are inside a then callback
              ancestors = context.getAncestors(expectAncestor)
              for (var j = 0; j < ancestors.length; j++) {
                thenAncestor = ancestors[j]
                if (thenAncestor && thenAncestor.type === 'CallExpression') {
                  var thenCallback = isThenCallBack(thenAncestor)

                  // it has to have at least one argument
                  if (thenCallback && thenCallback.params && thenCallback.params.length > 0) {
                    var thenCallbackArgument = thenCallback.params[0]

                    // the same variable is a "then" callback function argument
                    if (thenCallbackArgument && thenCallbackArgument.name === variableName) {
                      // check that it was an ElementArrayFinder resolution
                      if (thenAncestor.callee && thenAncestor.callee.object) {
                        if (isElementArrayFinder(thenAncestor.callee.object)) {
                          context.report({
                            node: node,
                            message: 'Array.length inside promise resolution function detected. Use count() instead.'
                          })
                          return
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Source code is also available on GitHub.

The rule is overly complicated, very deep and nested and not readable at all (cyclomatic code complexity is 10). What refactoring methods would you apply to improve on readability?

FYI, using standard style.


texts:
I came up with this TSQL for SQL Server 2008:

DECLARE @TimeWindowInSeconds INT

SET @TimeWindowInSeconds = 10

IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp
CREATE TABLE #Temp
    (
      Class INT,
      DT DateTime
    )

INSERT INTO #Temp (Class, DT)
SELECT 1, '2014-11-05 10:55:00'
    UNION ALL
SELECT 1, '2014-11-05 10:55:10'
    UNION ALL
SELECT 1, '2014-11-05 11:55:10'
    UNION ALL
SELECT 2, '2014-11-05 10:55:11'
    UNION ALL
SELECT 2, '2014-11-05 13:56:10'

;WITH CTE1 AS
(
    SELECT
        Class,
        DT,
        ROW_NUMBER() OVER (ORDER BY Class, DT ) AS RowNumber
    FROM #Temp
)
,CTE2 AS
(
    -- A is the successor
    SELECT
        A.Class,
        A.RowNumber,
        B.RowNumber AS RowNumber1,
        A.DT,
        B.DT AS DT2,
        DATEDIFF(second, B.DT, A.DT) AS DifferenceInSeconds,
        CASE WHEN B.DT IS NULL THEN 1 END z
    FROM CTE1 AS A
    LEFT OUTER JOIN CTE1 AS B ON A.RowNumber = B.RowNumber + 1 AND A.Class = B.Class
    AND DATEDIFF(second, B.DT, A.DT) <= @TimeWindowInSeconds

)
,CTE3 AS
(
    SELECT
        CTE2.Class,
        CTE2.DT,
        (
            SELECT
                SUM(z)
            FROM      CTE2 c
            WHERE     c.DT <= CTE2.DT AND c.Class = cte2.Class
                ) AS SubGroup
    FROM CTE2
)
SELECT
    *
FROM CTE3
    WHERE CAST(CTE3.Class AS NVARCHAR(100)) + '-' + CAST(CTE3.SubGroup AS NVARCHAR(100)) IN
    (
        SELECT CAST(CTE3.Class AS NVARCHAR(100)) + '-' + CAST(CTE3.SubGroup AS NVARCHAR(100)) FROM CTE3 GROUP BY CTE3.Class, CTE3.SubGroup
HAVING COUNT(*) > 1
    )

This clusters datetime values inside groups (class) if they fall inside the same time window and if the cluster contains more than 1 entry. Please review the code.


texts:
As part of my study on fundamentals, I have implemented the following code in JavaScript for a MinHeap data structure.

Please have a look and I look forward to your feedback for any improvements.

const swap = require('../swap');

function Heap(){
  this.heap = [];
}

Heap.prototype.getParent = function(index){
  return (index-1)/2;
}

Heap.prototype.getLeft = function(index){
  return (2*index)+1;
}

Heap.prototype.getRight = function(index){
  return (2*index)+2;
}

//inserts a new value to the min-heap
Heap.prototype.insert = function(value){
  this.heap.push(value);
  this.heapifyUp(this.heap.length-1);
  return;
}

//deletes any node at given index
Heap.prototype.delete = function(index){
  if(index === 0){
    this.heap[0] = this.heap[this.heap.length-1];
    this.heap.splice(this.heap.length-1, 1);
    this.heapifyDown(0);
    return;
  }

  this.heap[index] = this.heap[this.heap.length-1];
  this.heap.splice(this.heap.length-1, 1);
  var parent = this.getParent(index);
  (this.heap[index]<this.heap[parent])? this.heapifyUp(index) : this.heapifyDown(index);
  return;
}

//extracts min value and recalibrates minheap
Heap.prototype.extractMin = function(){
  var temp = this.heap[0];

  swap(this.heap, 0, (this.heap.length-1));
  this.heap.slice((this.heap.length-1), 1);
  this.heapifyDown(0);

  return temp;
}

//decreases the value of node at given index by given value
Heap.prototype.decrease = function(index, value){

  if((this.heap[index]-value)<0) return false;

  this.heap[index] = this.heap[index]-value;
  (index === 0) ? this.heapifyDown(0) : this.heapifyUp(index);
  return;
}

Heap.prototype.heapifyUp = function(index){

  var parent = this.getParent(index);

  while(parent>=0 && this.heap[parent]>this.heap[index]){
    swap(this.heap, parent, index);
    index = parent;
    parent = this.getParent(index);
  }

}

Heap.prototype.heapifyDown = function(index){

  var left = this.getLeft(index);
  var right = this.getRight(index);

  while(this.heap[index]>this.heap[left] || this.heap[index]>this.heap[right]){
    if(this.heap[index]>this.heap[left]){
      swap(this.heap, left, index);
      index = left;
      left = this.getLeft(index);
    }
    if(this.heap[index]>this.heap[right]){
      swap(this.heap, right, index);
      index = right;
      right = this.getLeft(index);
    }
  }

}


texts: Reviewing custom array List class of java

texts:
I am using JDK 12 and  I have developed the custom array list in java with a basic understanding Please let me know if there are any flaws in it that I can correct the same

First the POJO class

public class Employee {
    private String id;
    private String name;

    public Employee(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee[id=" + id + ", name=" + name + "] ";
    }

}

Then come the main logic class of ArrayList, which is the heart

class CustomArrayList<E> {

    private static final int INITIAL_CAPACITY = 10;
    private Object[] elementData;
    private int size = 0;

    public customArrayList() {
        elementData = new Object[INITIAL_CAPACITY];
    }

    private void ensureCapacity() {
        int newIncreasedCapacity = elementData.length * 2;
        elementData = Arrays.copyOf(elementData, newIncreasedCapacity);
    }

    public void add(E e) {
        if (size == elementData.length) {
            ensureCapacity();
        }
        elementData[size++] = e;
    }

    @SuppressWarnings("unchecked")
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
        }
        return (E) elementData[index];
    }

    public Object remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
        }

        Object removedElement = elementData[index];
        for (int i = index; i < size - 1; i++) {
            elementData[i] = elementData[i + 1];
        }
        size--;   //reduce size of ArrayListCustom after removal of element.
        return removedElement;
    }

    /**
     * method displays all the elements in list.
     */
    public void display() {
        System.out.print("Displaying list : ");
        for (int i = 0; i < size; i++) {
            System.out.print(elementData[i] + " ");
        }
    }

}

and finally, the test class to test the custom implementation of the ArrayList

public class ArrayListTest {

    public static void main(String... a) {
        CustomArrayList<Employee> list = new CustomArrayList<>();
        list.add(new Employee("1", "saral"));
        list.add(new Employee("2", "amit"));
        list.add(new Employee("3", "dinesh"));
        list.add(null);
        list.display();
        System.out.printf("\n element at index %d = %s%n", 1, list.get(1));
        System.out.printf("element removed from index %d = %s%n", 1, list.remove(1));

        System.out.println("\n" +
                "let's display list again after removal at index 1");
        list.display();

    }

}


texts: SQL connection in static class and wrapper

texts:
I need to make some calls to stored procedures in my SQL database from a .NET application, using C#.

I have something like this, and I put just one of the methods but the rest will be similar:

public static class ClientDataAccess
{
    public static void AddClient(Client client)
    {
        var connectionString = ConfigurationManager.ConnectionStrings["appDatabase"].ConnectionString;

        using (var connection = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand("Client_add", connection) { CommandType = System.Data.CommandType.StoredProcedure })

            // Add parameters

            connection.Open();
            command.ExecuteNonQuery();
        }
    }
}
}

When I needed to test the classes where it's used I had to create a wrapper to be able to mock it:

public class ClientDataAccessWrapper : IClientDataAccessWrapper
{
    public void AddClient(Client client)
    {
        ClientDataAccess.AddClient(client);
    }
}

Is this considered to be a good practice?


texts: Run loop for a text-based adventure game

texts:
I am programming a graphical text adventure using python. The game is playable, but I am not sure whether the code is well-suited for newcomers (code smells / quirks / general readability).

Here's the main script:

import time
import sys

import printer
from rooms import *
from _player import Player

VER = 0.01

SCENES = {0 : Lobby(),
          1 : LivingRoom(),
          2 : Bathroom()}

player = Player()

def run(start_at=None):
    """Starts the game"""

    if not start_at:
        scene = SCENES[0]
    else:
        scene = SCENES[start_at]
    scene.init_player(player)
    while 1:
        new_scene = scene.run()
        if new_scene != None:
            scene = SCENES[new_scene]
            scene.init_player(player)

if __name__ == "__main__":
    run()


texts:
This is a follow up question of Importing different type of files into Lists. Where the original lists are acquired.

In this script I am processing the obtained lists, and comparing them with each other to determine whether or not a used material has duplicate functions. This using their most commonly known traits, which are: Shader name, Color property and a texture property

I have the feeling my script is far from optimal, and currently takes roughly 120 seconds to compare 1200 materials. Making the rough iteration time per material 0.10 Where 200 of them are unique.

In the future this script will be expanded to process more different details besides the color/name/texture as well, so advice on how to to keep the process more 'open for change' is appreciated as well.

public void InitShaderSorting()
{
    //wipe data so it won't duplicate if button is pressed again
    unique = new List<Material>();
    broken = new List<Material>();
    duplicate = new List<Material>();
    dupof = new List<Material>();

    for (int i = 1; i < TotalMaterial; i++)
    {
        //Filter broken shaders out first so they can never be a unique one
        if (allMat[i].shader.name == "Hidden/InternalErrorShader")
            broken.Add(allMat[i]);
        //If no unique material has been assigned to compare with, assign one first
        else if (unique.Count == 0)
            unique.Add(allMat[i]);
        //If it aint broken, and there is a unique one. Go and compare the shader properties
        else
            CompareShader(allMat[i], allMat[i].shader.name, allMat[i].HasProperty("_Color"), allMat[i].HasProperty("_MainTex"));
    }
}

/// <param name="sn">Shader Name</param>
/// <param name="hc">Has Color Property</param>
/// <param name="ht">Has Texture Property</param>
void CompareShader(Material mat, string sn, bool hc, bool ht)
{
    bool finished = false;

    for (int i = 0; i < unique.Count; i++)
    {
        //Check if shader names are identical, if not continue as it can't be a duplicate
        if (sn != unique[i].shader.name)
        {
            if (i == unique.Count - 1)
            {
                finished = true;
                break;
            }
            else continue;
        }

        //Check if this material even uses a color
        if (hc)
        {
            //If the color is a match and there is no texture to compare, mark as duplicate
            if (unique[i].color == mat.color && !ht)
            {
                duplicate.Add(mat);
                dupof.Add(unique[i]);
                break;
            }
            else
            {
                if (i == unique.Count - 1)
                {
                    finished = true;
                    break;
                }
                else continue;
            }
        }

        if (ht)
        {
            //If the texture is a match, mark as duplicate
            if (unique[i].mainTexture == mat.mainTexture)
            {
                duplicate.Add(mat);
                dupof.Add(unique[i]);
                break;
            }
        }

        if (i == unique.Count - 1) finished = true;
    }

    //If we reached the end without a match, then this material is unique.
    if (finished) unique.Add(mat);
}


texts:
I'm wondering about the following code:

def ValidateGoto(placeToGo):
    conditions = {}
    conditions["not placeToGo"] = "Enter a positive integer in the text box"
    conditions[
              "int(placeToGo) <= 0"] = "I need a positive integer in the text box please"
    conditions[
           "not DataStore.DBFILENAME"] = "There is no data available in the table"
    for condition, errormessage in conditions.iteritems():
        try:
            if eval(condition):
                print errormessage
                return False
        except ValueError:
                return False
    return True

Should the eval statement be avoided?
Is this approach justified to reduce the number of if statements?