texts:
Here is my function I want to test:
template<typename T>
void free_items(std::vector<T*>& items)
{
    std::for_each(items.begin(), items.end(), [](T* (&item)){delete item; item = nullptr; });
}

I expect the each pointer in my result vector will be freed and be set null correctly. So I write down the following test code.
This is my mock class:
struct FreeItemMock
{
    FreeItemMock(bool& destroyed):m_destroyed (destroyed) {}
    ~FreeItemMock(){ m_destroyed = true;}
    bool& m_destroyed ;
};

Here is my test code:
BOOST_AUTO_TEST_CASE(test_free_items)
{
    bool destroyed[3] = {};
    std::vector<FreeItemMock*> mocks;

    mocks.push_back(new FreeItemMock(destroyed[0]));
    mocks.push_back(new FreeItemMock(destroyed[1]));
    mocks.push_back(new FreeItemMock(destroyed[2]));

    BOOST_CHECK_EQUAL(destroyed[0], false);
    BOOST_CHECK_EQUAL(destroyed[1], false);
    BOOST_CHECK_EQUAL(destroyed[2], false);

    free_items(mocks);

    BOOST_CHECK_EQUAL(destroyed[0], true);
    BOOST_CHECK_EQUAL(destroyed[1], true);
    BOOST_CHECK_EQUAL(destroyed[2], true);

    BOOST_CHECK(mocks[0] == nullptr);
    BOOST_CHECK(mocks[1] == nullptr);
    BOOST_CHECK(mocks[2] == nullptr);
}

The following are my questions:

Is the my so-called FreeItemMock a mock or a stub? I am not sure whether I pick the right name on my testee-class. According to the book The art of unit testing with examples in C#. A mock is used to test whether the interaction with other classed happened. I use my FreeItemMock to test its destructor is called, but after invoke the free_item my FreeItemMock actually does not exist anymore. It looks the destroyed[3] array variable is more like a mock.

The function I want to test is doing job on a vector, so I need to prepare a array of data to test. Is it correct to hand write a serious of fixture like data[0], data[1], data[2] and assert the result? Because the books also says a unit test should not have "logic" (like while, for-loop, if) to increase its complexity.
Or should I make a testing utility to help me produce the array data, and make another test for the utility?

Is it necessary to check the pre-test value of destroyed? Is it clearer to tell the reader that this function would make destroyed from 0 to 1? Or It is just too tedious?


texts: Add a set of querystring params to a URL

texts:
Example cases:

Need to add x=1, y=2 and querystring variables to the following URLs:

http://www.foo.com/blah/blah?test=1&abc=2
http://www.foo.com/blah

//-- usage
get_link(array('x' => 1, 'y' => 2, 'z' => 'string'));

function get_link( $my_params )
{
    $param_querystring = "";
    $http_host = $_SERVER['HTTP_HOST'];

    //-- get the part of the url before the querystring, if applicable
    $url = explode( '?', $_SERVER['REQUEST_URI'] );

    $request_uri = $url[0];
    $querystring = $url[1];

    foreach ( $my_params as $param_key => $param_value )
    {
        $param_querystring .= $param_key . '=' . $param_value;
    }

    if ( empty( $querystring ) )
    {
        //-- generates foo.com/blah?x=1&y=2&z=string if no
        //-- querystring was present
        $link = $request_uri . '?' . $param_querystring;
    }
    else
    {

        //-- generates foo.com/blah?a=1&b=2&x=1&y=2&z=string if a=1&b=2
        //-- querystring was already present.
        $link = $request_uri . $querystring . '&' . $param_querystring;
    }

    return $link;
}


texts: Finding minimum steps required to traverse from source to terminal

texts:
Hello everyone this is my first post here so please do critique my post if there's anything.
I have made a program intended to pass a programming challenge on open.kattis.com, here.
It should do as title says, but with the conditions that each traversal follows the rules of a "Knight" from chess, that being plus/minus two columns/rows and plus/minus one column/row.

_read method:
I attempted to solve this making a Node class and passing coordinate and char data into each instance of a Node object for each coordinate.

_adjacencify method:
Thereafter, I found adjacencies (neighbours) of all Node objects, with the aforementioned condition of a chess Knight.

_jump method:
Lastly, I used a BFS implementation in order to find the shortest path from the source (root) to the terminal (here represented as 'K').

find_path:
Wraps everything up.

Here's the code I ended up with:
class Nite
  #attr_accessor :char, :col, :row
  class Node
    attr_accessor :char, :col, :row, :disc, :parent
    attr_reader :adjies
    def initialize(char, col, row)
      @char = char
      @col = col
      @row = row
      @adjies = [] # adjacencies
      @disc = false
      @parent = nil
    end
    def add(value)
      @adjies << value
    end
  end

  def _read
    # assign each coord. to a Node-object
    n = gets.to_i
    nodes = Array.new
    n.times do |x|
      temp = gets.strip.to_s
      temp.size.times do |y|
        node = Node.new(temp[y], x, y)
        nodes << node
      end
    end

    nodes
  end

  def _adjacencify(nodes)

    nodes.each do |x|
      nodes.each do |y|
        if y.col == x.col && y.row == x.row || y.char == '#'
          next
        end

        # logic

        if x.row == (y.row - 1) # y.row + 1

          if x.col == (y.col - 2) # y.col + 2
            x.add(y) # (col+2, row+1)
          elsif x.col == (y.col + 2) # y.col - 2
            x.add(y) # (col-2, row+1)
          end

        elsif x.row == (y.row + 1) # y.row - 1

          if x.col == (y.col - 2) # y.col + 2
            x.add(y) # (col+2, row-1)
          elsif x.col == (y.col + 2) # y.col - 2)
            x.add(y) # (col-2, row-1)
          end

        end

        if x.row == (y.row - 2) # y.row + 2

          if x.col == (y.col - 1) # y.col + 1
            x.add(y) # (col+1, row+2)
          elsif x.col == (y.col + 1) # y.col - 1
            x.add(y) # (col-1, row+2)
          end

        elsif x.row == (y.row + 2) # y.row - 2

          if x.col == (y.col - 1) # y.col + 1
            x.add(y) # (col+1, row-2)
          elsif x.col == (y.col + 1) # y.col - 1
            x.add(y) # (col-1, row-2)
          end

        end

      end
    end

    nodes
  end

  def _jump(nodes)

    nodes = _adjacencify(nodes)

    q = Queue.new
    root = nodes[0]
    root.disc = true
    q << root

    while !q.empty? do
      v = q.pop
      if v.char == 'K'
        steps = 0
        until v.parent == nil do
          if !v.nil?
          end
          steps += 1
          v.parent = v.parent.parent
        end
        return steps
      end
      v.adjies.each do |w|
        if w.disc == false
          w.parent = v
          w.disc = true
          q << w
        end
      end
    end
    return -1

  end

  def find_path
    _jump(_read)
  end

end

nite = Nite.new
puts nite.find_path

I suspect of course that the _adjacencify method is super time consuming, and that some loops are way too time consuming.
I failed the <1.00s time requirement in order to pass the challenge.
I want all types of criticism on my code, and I want tips and also, if anyone wants, different implementations that perform better.
Especially Ruby convention is something I want critique on, considering I am coming from a Java and Python background and I'm fairly fresh in Ruby.
Please tell me if I should edit anything in this post to make anything clearer.


texts: Getting all the dates in a month that do not coincide with a project's dates

texts:
I'm creating an array of dates that won't be selectable in a calendar. The following works, although the way I've gone about it is quite long-winded.

I was wondering if there is a more elegant way of getting all the dates in a month, where dates don't fall on various days a project does run on. It's probably more clear from the example...

$project_days_this_month = [];
$month_array = [];

$month = date('n');
$year = date('Y');

$project_days = [1, 6]; // days of week the project runs on
$days_in_month = cal_days_in_month(CAL_GREGORIAN, $month, $year);

// create an array of days in month
for ($day = 1; $day <= $days_in_month; $day++) {
  $date = $year.'-'.$month.'-'.$day; //format date
  $month_array[] = $date;
}

// get project days in month
foreach ($project_days as $pd) {
  //loop through all days
  for ($day = 1; $day <= $days_in_month; $day++) {

    $date = $year.'-'.$month.'-'.$day; //format date
    $day_number_of_week = date('N', strtotime($date));

    // add project days to array
    if($day_number_of_week == $pd){
        $project_days_this_month[] = $date;
    }

  }
}

// get the difference - these will be non project days
$non_project_days = array_diff($month_array, $project_days_this_month);
print_r($non_project_days);

Are there any PHP functions that can be used here that would might make this code more concise?


texts: Find Element in Tree Given a List of Directions

texts:
Looking at Learn You a Haskell, I implemented a function that, given a binary tree, i.e. left and right branches, give a list of Directions and give the element at that location.

Here's the Tree:

data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)

And then the functions:

elemAt :: Directions -> Tree a -> a
elemAt []     (Node x _ _) = x
elemAt (R:ds) (Node _ _ r) = elemAt ds r
elemAt (L:ds) (Node _ l _) = elemAt ds l

But, I re-wrote it to be safe (maybe not)

maybeElemAt :: Directions -> Tree a -> Maybe a
maybeElemAt []     (Node x _ _)     = Just x
maybeElemAt (R:ds) (Node _ _ Empty) = Nothing
maybeElemAt (R:ds) (Node _ _ r)     = maybeElemAt ds r
maybeElemAt (L:ds) (Node _ Empty _) = Nothing
maybeElemAt (L:ds) (Node _ l _)     = maybeElemAt ds l

Testing

anotherTree :: Tree Char
anotherTree = Node 'A' (Node 'B' Empty Empty) Empty

ghci> maybeElemAt [R,R,R] anotherTree
Nothing
ghci> maybeElemAt [R] anotherTree
Nothing
ghci> maybeElemAt [L] anotherTree
Just 'B'

Please critique my implementations of either function.


texts: jQuery function to create a container div with some content

texts:
I just recently started with Javascript and jQuery. My background is in Python. I would be more than happy to get some feedback if this coding style of mine is optimal, or if in JS people generally write things differently.

The current task is to build different elements in a website that are always hosted in the same container. I have written a container creation function like this:

  function create_container(type, counter) {
      var ret = $('<div />').attr({
          class: 'container-box',
      }).data({
          type: type,
          counter: counter,
      }).append(
          $('<span />').attr({
              class: 'remove'
          }).append('&times;')
      );
      return ret
  }

  var b = create_container('text', 0);
  console.log(create_container('text', 0));

This function will then be reused in different objects to create the same containing container. Type and counter will be set when the object will be initiated.


texts: GET multiple data frames using external module's function that uses requests

texts:
Purpose

The point of this mini project is to quickly gather data from a website's API and combine the collected DataFrames into a "master" DataFrame with all of the stocks I am interested in looking at. I do this using the iexfinance module. If needed, here is the code behind iexfinance.

Improvements?

While this module does a great job of dealing with the API, I'm not sure my code is as fast as it could be.  Because the iexfinance module uses requests to make GET requests, I believe there should be a faster way to asynchronously send GET requests instead of having to use multiprocessing. Below is my code:

import pandas as pd
import numpy as np
from iexfinance import Stock
from multiprocessing import Pool
import os

def iex_get_stat(batch):
    """
    :param batch: batch is a list of stock tickers (ex: ["AAPL", "MSFT", "TSLA"]
    Gets and returns DataFrames of stats on a list of stocks
    """
    frame = Stock(batch, output_format="pandas").get_key_stats().T
    return frame

def get_stats(symbols):
    """
    :param symbols: List of symbols (can only send 100 at a time,
    so these may need to be broken up)
    :return: Pandas DataFrame with stats
    """
    symbols = [symbols[i : i + 99] for i in range(0, len(symbols), 99)]
    frames = []
    pool = Pool(processes=os.cpu_count())
    frames.append(pool.starmap(iex_get_stat, [[batch] for batch in symbols]))
    pool.close()
    pool.join()
    stats = pd.concat(frames[0])
    return stats

if __name__ == "__main__":
    symbols = ["AAPL", "TSLA", "MSFT"]
    stats = get_stats(symbols)
    print(stats)


texts: Inheriting from Dictionary class with tuple as value

texts:
I have a class that inherits from Dictionary<Tkey, TValue>.
I need my Value part of the KeyValue pair to be a a Tuple (int, bool )
public class IssueRowValidationDictionary :
        Dictionary<string, (int, bool)>
    {
        public IssueRowValidationDictionary() : base() { }

        internal void Add(string issueReference, int rawRowNumber, bool v)
        {
            Add(issueReference, (rawRowNumber, v));
        }
    }

In my code there are cases where I need to get the int Value part of the dictionary Element
             var intValue = issueRowValidationDictionary['keyRef'].Item1;

Is there a more elegant way for Example to create a specific property that will only return the int part of the value. Any suggestions for improvement of my code are welcomed


texts:
I'm trying to get familiar with database handling.  Can you point out my errors and what I should change?

I want to learn new methods, but just don't want to learn it the wrong way.

I do realize these things below, yet I wanted to make the code more clear:

I need to bind values for insert()
Use try/catch for error handling
Password hashing (did not use it to make example simpler)

<?php

class Query
{
    private $_sql;
    private $_sth;
    private $_db;

    public function __construct()
    {
        $this->_db = new PDO('mysql:host=localhost;dbname=mvc;', 'root', '');
        $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->_db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    }

    public function select($arg)
    {
        $this->_sql .= "SELECT {$arg}";
        return $this;
    }

    public function from($arg)
    {
        $this->_sql .= " FROM {$arg}";
        return $this;
    }

    public function insert($arg)
    {
        $this->_sql .= "INSERT INTO {$arg}";
        return $this;
    }

    public function columns($arg)
    {
        $this->_sql .= " ({$arg})";
        return $this;
    }

    public function values($arg)
    {
        $this->_sql .= " VALUES ({$arg})";
        return $this;
    }

    public function execute($data = null)
    {
        $this->_sth = $this->_db->prepare($this->_sql);
        $this->_sth->execute($data);
        $this->_sql = null;
        return $this;
    }

    public function fetch()
    {
        return $this->_sth->fetchAll();
    }

    public function getSql()
    {
        return $this->_sql;
    }
}

$query = new Query;

// inserts into database
$query->insert('users')
        ->columns('`username`,`password`')
        ->values('"test","tester"')
        ->execute();

// returns array of users
$query->select('username')
        ->from('users')
        ->execute()
        ->fetch()

?>


texts:
I'm looking for a better alternative to replace insert + gsub.

hobbies = "Hobbies: \nsports (basketball, gym), foods (hamburger, steak, pasta), reading, movie, justfortesting((test1, test2), test3)"
print "\n\nBefore: \n\n" + hobbies
counter = 0
for i in 0...hobbies.length do
    case hobbies[i]
    when '('; counter += 1
    when ')'; counter -= 1
    when ','; hobbies.insert i + 1, "\n" if counter == 0
    end
end
counter = nil
hobbies.gsub!(",\n", "\n")
hobbies.gsub!("\n ", "\n")
print "\n\nAfter: \n\n" + hobbies

Output:

Before:

Hobbies:
sports (basketball, gym), foods (hamburger, steak, pasta), reading, movie, justfortesting((test1, test2), test3)

After:

Hobbies:
sports (basketball, gym)
foods (hamburger, steak, pasta)
reading
movie
justfortesting((test1, test2), test3)


texts:
I have MySQL data that I am rendering in an HTML table using PHP. This is the full code of my table and PHP. It does output fine and looks how I would expect but I am wondering if there is a better way to write this code. Also, the 'Delete' button specifically, is there a better way to output the button itself as right now, I noticed especially on a mobile device, I will see a text cursor indicator when tapping the button as if I am trying to select the text on the button itself.

                    Description

                    Date Created

                    Created By

                    Edit - Delete

        <?php

        $noLists = "
You have no lists. Why dont you create one?
";

        if ($db->connect_error) {
            die("Connection failed: " . $db->connect_error);
        }

        $sql = "SELECT DISTINCT lists.id, lists.listdescription, lists.createdon, lists.createdby, lists.sharedlist FROM lists INNER JOIN users ON users.fname = '$displayname' AND users.fname = lists.createdby";
        $result = $db->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {

                $listID = $row["id"];
                $listDescription = $row["listdescription"];
                $createdOn = $row["createdon"];
                $createdBy = $row["createdby"];

                echo "<form>";
                echo "
";
                echo "$listDescription	";
                echo "$createdOn	";
                echo "$createdBy	";
                echo "";
                echo "<form action='account.php' method='post'>";
                echo "<input class=\"btn btn-success\" type=\"submit\" name=\"\" value=\"Edit\">";

                echo "<input class=\"btn btn-danger\" value=Delete style=\"width: 85px;\">

                	";

            }
        } else {
            echo "
";
            echo "
";

            echo "
";
            echo "
";
            echo "
 $noLists
";
        }
        $db->close();

        ?>


texts: Conversion between enum and string in C++ class header

texts:
I have the following redundant-feeling design to convert between enums and strings regarding a class that stores enums. The approach doesn't scale if there are more enums and in any event, less-redundant code is also better.

Questions

If there will be more enums, would it be possible to avoid defining two explicit conversion functions per enum type and device a system where the caller sees just one (i.e. convert) or two different function names (i.e. convertto/convertfrom for all the enums, not just per enum type)? Perhaps using some kind deduction magic with auto and decltype? It looks like ambiguity sets in since only the return value can be used to separate the different functions overloads (even if done with function templates).
Is the following design of separating the conversion functions and putting them to an anonymous namespace good design (I've thought about putting the conversion functions to a file, say conversions.incl and including it)?

The idea would be make the multiple (i.e. more enums than the one presented here) conversions as implicit as possible

The conversions would be used like this:

random.cpp

string token_string = "none"; //In reality this will be externally, user, generated.
some_class_instance->set_type(enum_conversion(token_string));
token_string = enum_conversion(some_class_instance->get_type());

And to present one enum and related conversions (but there could be more):

some_class.h

class some_class
{
    public:
         enum class enum_type
         {
             none   = 0,
             type1  = 1,
             type2  = 2
         }

     void set_type(enum_type);
     enum_type get_type() const;

   private:
       enum_type type_;
};

namespace
{
    std::array<std::pair<std::string, some_class::enume_type>, 3> type_map;

    bool initialize_map()
    {
       type_map[0] = std::make_pair("none", some_class::enum_type::none);
       type_map[1] = std::make_pair("type1", some_class::enum_type::type1);
       type_map[2] = std::make_pair("type2", some_class::enum_type::type2);
    }

    bool initialization_result = initialize_map();

    some_class::enum_type enum_conversion(std::string const& enum_type)
    {
        for(auto val: type_map)
        {
            if(val.first == enum_type)
            {
                return val.second;
            }
        }

        return type_map[0].second;
    }

    std::string enum_conversion(some_class::enum_type enum_type)
    {
        for(auto val: type_map)
        {
            if(val.second == enum_type)
            {
                return val.first;
            }
        }

        return type_parameter_map[0].first;
    }
}


texts:
Project Euler Problem 12 asks to find the value of the first triangular number to have over 500 divisors, where the \$n\$th triangular number is \$\sum_{i=1}^{n} i\$.

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be \$1 + 2 + 3 + 4 + 5 + 6 + 7 = 28\$. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five
  divisors.

I have the following code written in C#. I never had the patience to wait for the program to finish but the code shows the right answer because I tried  the example on their website. My code has a very long runtime and I don't know what to do to optimize it. I've waited for like 5-6 minutes on a AMD 4x cores 3.10 GHz and nothing...

static void Main(string[] args) {

        Stopwatch time = new Stopwatch();
        time.Start();

        int trianglenumber = 0;
        int divizori = 0;

            for (int i = 1; i < Int32.MaxValue; i++) {
                int tempnumber = 0;
                for (int j = 1; j < i; j++) {
                    tempnumber += j;
                }
                for (int k = 1; k < tempnumber+1; k++) {
                    if (tempnumber % k == 0) {
                        divizori++;
                    }
                }
                if (5 < divizori) {
                    trianglenumber = tempnumber;
                    break;
                }
                divizori = 0;
            }

            time.Stop();

            double timp = time.ElapsedMilliseconds ;

            Console.WriteLine(trianglenumber);
            Console.Write("Runtime: " + timp/1000+ " seconds");
            Console.ReadKey();

    }


texts: Handling SIGINT signal for a server program

texts:
I have created a small server program that encrypts text using a named pipe:

#define UNICODE
#define WIN32_WINNT 0x0500
#include <stdio.h>
#include <windows.h>
#include <signal.h>

HANDLE hPipe;
DWORD WINAPI ServerProc(LPVOID lpVoid)
{

    hPipe = CreateNamedPipe(L"\\\\.\\pipe\\testpipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |PIPE_WAIT, 1, 256, 256, 0, NULL);
    if(!hPipe)
        return wprintf(L"ERROR : Cannot create pipe.\n");

    while(ConnectNamedPipe(hPipe, NULL))
    {
        WCHAR szText[80] = {0};
        DWORD dwSize;
        INT i;

        ReadFile(hPipe, szText, 158, &dwSize, NULL);

        for(i = 0; i < dwSize; i++)
            szText[i] ^= '#';

        WriteFile(hPipe, szText, 158, &dwSize, NULL);
        FlushFileBuffers(hPipe);
            DisconnectNamedPipe(hPipe);
    }

    CloseHandle(hPipe);

    return 0;
}

void SignalHandler(int signal)
{
    DisconnectNamedPipe(hPipe);
    CloseHandle(hPipe);
    printf("Application closing...\n");
    exit(0);
}

int wmain(void)
{
    HANDLE hThread;

    signal(SIGINT, SignalHandler);

    hThread = CreateThread(NULL, 0, ServerProc, NULL, 0, NULL);

    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(hThread);
}

In this code I have created a hPipe handle as global because my program thread and the signal handler both need the handle.

Is this a correct way to handle signals?


texts: Embed MD5 digest in a directory path name

texts:
My boss needs me to embed the MD5 digest in a file path, but the problem is MD5 contains escape characters.

I've already taught about a uc%duc%d... format, but it also makes lengthy file names. In Linux it's not a problem since the Linux kernel could handle them.

char * uc_encode_md5(const char * password)
{
  char digest_output[1024];
  MD5_CTX md5_ctx ;
  MD5_Init(&md5_ctx);
  MD5_Update(&md5_ctx,password,strlen(password));
  MD5_Final((unsigned char*) digest_output,&md5_ctx);
  char* ret = (char*) malloc(500);
  int len=0;
  int i ;
  for(i=0;i<16;i++)
  {
   len+= sprintf(&ret[len],"uc%d",(unsigned char)digest_output[i]);
  }

  return ret;
}

Any better way than this? Since my just boss shared what to do, but not how to do it: what's the best practice here?

How about #ifdef's?  I could suggest more formats on here and let him choose when I get back to him later tonight.

For example:

char * uc_encode_md5(const char * password)
{
#ifdef _UC_PATH_ENCODE_
  char digest_output[1024];
  MD5_CTX md5_ctx ;
  MD5_Init(&md5_ctx);
  MD5_Update(&md5_ctx,password,strlen(password));
  MD5_Final((unsigned char*) digest_output,&md5_ctx);
  char* ret = (char*) malloc(500);
  int len=0;
  int i ;
  for(i=0;i<16;i++)
  {
   len+= sprintf(&ret[len],"uc%d",(unsigned char)digest_output[i]);
  }
#endif /* endif _UC_PATH_ENCODE_ */
  return ret;
}


texts: Why is this code so much faster (relatively) in IE7?

texts:
Here's some code that I ran through jsperf to assess its performance. The first test (named EvalLengthBefore++ in the images below) is the way I would consider normally looping through the elements of an array:

var arr = [];
for (var x = 0; x < 1000; x++) {
  arr.push(Math.random());
}

var len = arr.length;
for (var y = 0; y < len; y++) {
  //do some maths
  var el = arr[y];
  el++; //meaningless operation
}

The second test (named InfiniteLoopWithBreak in the images below) is the method I found in some code that is supposed to to be run in IE7 (it's part of a CSS fallback):

var arr = [];
for (var x = 0; x < 1000; x++) {
  arr.push(Math.random());
}

for (var y = 0;; y += 1) {
  //do some maths
  var el = arr[y];
  if (!el) {
    break;
  }
  el++;
}

In modern browsers, the second method is much slower, which is kind of what I expected. However in IE7 it is just as fast, occasionally faster, in the jsperf tests:

Test results in Chrome:

Test results in IE7

Here are the jsperf tests if you want to run them yourselves.

Why is the second code snippet faster than the rest in IE7?


texts: Reading and printing a text file in Java

texts:
I am trying to read lines from a text file in Java, but there is a lot going on. Is this the best way to do this? I am especially concerned with resource leaks.

import java.io.*;

public class Filing {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        FileReader fr = new FileReader("/Users/thomaspovinelli/Desktop/apps.txt");
        BufferedReader br = new BufferedReader(fr);
        String buffer;
        String fulltext="";
        while ((buffer = br.readLine()) != null) {
            System.out.println(buffer);
            fulltext += buffer;
        }
        br.close();
        fr.close();
    }
}


texts:
I am trying to learn some basic Python and am trying to find tricks to write speedy code:

import sys
if len(sys.argv) < 3:
    print("You left out the arguments")
    sys.exit()
gcf = 0

numbers = []
collections = []
unique = False

for i in range(1,len(sys.argv)):
    numbers.append(int(sys.argv[i]))
for x in range(0,len(numbers)):
    collections.append([])
    for s in range(1,numbers[x] + 1):
        if numbers[x] % s == 0:
            collections[x].append(s)
    print str(numbers[x]) + ": ",
    print ','.join(map(str,collections[x]))
for i in collections[0]:
        for x in collections:
            if i in x:
                unique = True
            else:
                unique = False
        if unique:
            gcf = i
print "gcf is: "+str(gcf)


texts:
I wrote below piece of code generating dummy data loaded to MongoDB.
2 issues :
1.customer class has subscriber class so it nested with one level customer--> subsciber.
I think i'm not doing right:
self.subscriber = Subscriber().returnJson()

it does working ,
but what if need to add another class under subscriber? it will become messy.
2.Peroformance - very bad:
10 documents:

real    0m20.371s
user    0m2.691s
sys     0m0.736s

for 1000 documents - very bad:
real    5m8.299s
user    1m40.819s
sys     0m44.380s

The generating of documents is the bottleneck - not the actual load.
Surely multiprocessing didn't work well , as performance is really bad.
second ,I collect all document in a list (see mongo_doc[]) and at the end use insert_many
i think it right , but it doesn't show meaningful improvement compare to insert_one.
Would appreciate any help
from faker import Faker
import json

from multiprocessing.pool import ThreadPool as Pool

import concurrent.futures
import random

from motor.motor_asyncio import AsyncIOMotorClient
from config.config import DB, CONF,trace_request,redis_client

pool_size = 10
mongo_docs = []

customer_type_options = ['Individual', 'Organization']
customer_status_options = ['Active', 'Cancelled','Suspened','Collection']

class Subscriber():

    def __init__(self):
        fake = Faker()
        self.subscriber_no= random.randint(10000000, 99999999)
    def returnJson(self):
        return dict (subscriber_no= self.subscriber_no)

class Customer():

    def __init__(self):
        fake = Faker()
        self.customer_no = random.randint(10000000, 99999999)
        self.customer_type = random.choice(customer_type_options)
        self.customer_status = random.choice(customer_status_options)
        self.address = fake.address()
        self.subscriber = Subscriber().returnJson()

    def returnJson(self):
        return {'customer_no': self.customer_no,
                'customer_type': self.customer_type,
                'customer_status': self.customer_status,
                'address': self.address,
            'subscriber': self.subscriber
        }

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj,'returnJson'):
            return obj.returnJson()
        else:
            return json.JSONEncoder.default(self, obj)

def LoadOToMongo(Customer):
    mongo_docs.append(Customer.returnJson())

if __name__ == "__main__":
    no_of_input = 2
    pool = Pool(pool_size)
    jobs =[]
    for i in range(0, no_of_input):
       customer = Customer()
       pool.apply_async(LoadOToMongo, (customer,))

    pool.close()
    pool.join()
#bulk insert
    DB.customer.insert_many(mongo_docs)

```


texts:
This is the solution for a simple challenge from Hackerrank.I am just trying to solve Sorting: Bubble Sort Problem on HackerRank.

We are asked to count the number of swaps performed during a bubble sort and to print the first and last item of the ordered vector.

Sample input

3
3 2 1

First line is the number of elements in the vector, the second line is the vector

Expected output

Array is sorted in 3 swaps.
First Element: 1
Last Element: 3

Code

I've implemented my solution in C++ and would love to hear what your feedback and what could I have done cleaner

#include <iostream>
#include <vector>
#include <algorithm>

using big_int = long long;

struct answer {
    std::size_t count;
    big_int first_element;
    big_int last_element;
};

template<class T>
answer bubble_sort(std::vector<T> &v) {
    std::size_t swap_count = 0;
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v.size() - 1; j++) {
            if (v[j] > v[j + 1]) {
                std::swap(v[j], v[j + 1]);
                swap_count++;
            }
        }
    }
    return answer{swap_count, v[0], v[v.size()-1]};
}

int main(int argc, char** argv) {
    int n;
    std::cin >> n;
    std::vector<big_int> v(n);
    for (int i=0; i<n; i++) {
        std::cin >> v[i];
    }

    auto answer = bubble_sort(v);
    std::cout << "Array is sorted in " << answer.count         << " swaps.\n"
              << "First Element: "     << answer.first_element << "\n"
              << "Last Element: "      << answer.last_element;

}


texts: Finding a pair of words from two files with a particular MD5

texts:
I have two txt files. Both contain 60k+ words in a list. I put together some code to loop through each file and concatenate the strings

import hashlib
with open('1.txt') as f:
    a= [line.rstrip() for line in f]
with open('2.txt') as f:
    b= [line.rstrip() for line in f]

for y in a:
    for z in b:
        if hashlib.md5(y+z).hexdigest()=='XXXTHEXXXHASHXXX':
            print y+z
            break

So line 1 in file 1 gets concatenated with line 1 in file 2, then line 2 etc. Line 2 in file  gets.... you get where this is going...

Is there a cleaner way to do this? Not only that but how can I edit the script to use more cores?


texts: ffmpeg shell script to squeeze videos for Twitter

texts:
Here's a pretty rookie attempt at creating a shell script to squeeze videos into Twitter's 140s limitation:

for f in "$@"
do
    /Applications/ffmpeg -i $f -filter_complex "[0:v]setpts=140 / \
  $(/Applications/ffprobe -i $f -show_entries format=duration -v quiet -of csv="p=0") \
  * PTS[v];[0:a]atempo= \
  $(/Applications/ffprobe -i $f -show_entries format=duration -v quiet -of csv="p=0") \
  / 140[a]" -map "[v]" -map "[a]"  "${f%.*}_twitter.mp4"
done

It works, but it's pretty badly written. Can you help me improve it?

How can I run ffprobe only once?
Do I need ffprobe at all, or does ffmpeg have the duration of the input amongst its arguments?
Will it encode faster with other settings (e.g. HW acceleration)?


texts: SIMD Finding the maximum Euclidean distance to origin (c++)

texts:
I am trying to find the longest Euclidean distance to the origin for each point. Their positions are stored in two float arrays, denoting each point's position on the Cartesian plane. I tried to speed up the function using SIMD (WITHOUT SVML, so no _mm256_hypot_ps), however it still seemed a little bit slow. The code loop through the array by a chunk size of 8, on each iteration updates the maximum squared Euclidean distance and finally returns the sqrt of the maximum element.
#include <immintrin.h>
#include <math.h>
#include <stdio.h>
float dist(const float* x, const float* y, unsigned int len) {
  if (len < 16) {
    float d = 0.0f, a;
    unsigned i = 0;
    for (i = 0; i < len; i++) {
      a = x[i] * x[i] + y[i] * y[i];
      if (a > d) d = a;
    }
    return sqrt(d);
  }
  __m256 a = _mm256_loadu_ps(x), b = _mm256_loadu_ps(y);
  a = _mm256_mul_ps(a, a);
  b = _mm256_mul_ps(b, b);
  __m256 max = _mm256_add_ps(a, b);  // x[i]*x[i] + y[i]*y[i]
  unsigned i;
  for (i = 8; i + 8 < len; i += 8) {
    a = _mm256_loadu_ps(x + i);
    a = _mm256_mul_ps(a, a);
    b = _mm256_loadu_ps(y + i);
    b = _mm256_mul_ps(b, b);
    max = _mm256_max_ps(
        max, _mm256_add_ps(a, b));  // max(max[i], x[i]*x[i] + y[i]*y[i])
  }
  float d = 0.0f, t;
  for (; i < len; ++i) {
    t = x[i] * x[i] + y[i] * y[i];
    if (t > d) d = t;
  }
  const __m128 hiQuad = _mm256_extractf128_ps(max, 1); // high 128 bits in max
  const __m128 loQuad = _mm256_castps256_ps128(max); // low 128 bits in max
  const __m128 maxQuad = _mm_max_ps(loQuad, hiQuad);
  const __m128 hiDual = _mm_movehl_ps(maxQuad, maxQuad);
  const __m128 loDual = maxQuad;
  const __m128 maxDual = _mm_max_ps(loDual, hiDual);
  const __m128 lo = maxDual;
  const __m128 hi = _mm_shuffle_ps(maxDual, maxDual, 0x1);
  const __m128 res = _mm_max_ss(lo, hi);
  t = _mm_cvtss_f32(res);
  if (t > d) d = t;
  return sqrt(d);
}

The function will be called many times. I would like to speed it up further.


texts: Populate an ArrayList of different instances of a class

texts:
First of all, here is an overview of my application. I want to create a multiple-choice app, on android, using data stored on a remote MySQL database. The DB has 100 questions that will appear in random order.

My php script returns a JSON array with the following results

[
 {
    "id": 1,
    "Question": " blahblahblahblahblah?"
},
{
    "id": 2,
    "Question": "blehblehblehblehblehblehblehblehbleh?"
},
]

Since the Question table on my database has integers and strings I thought that it would be a better approach to copy the information of the JSON Objects to different instances of a Class Question. I want the JSONArray to be created once in order to avoid multiple requests to the server.That's why I wrote the following code:

public class Question {
    int question_id;
    String question_txt ;
    JSONArray json ;

public int setQuestion_id(int i) {
    try {this.question_id = this.json.getJSONObject(i).getInt("id");}
    catch (JSONException e) {e.printStackTrace();}

    return question_id;
}

public String setQuestion_txt(int i) {
    try {this.question_txt=this.json.getJSONObject(i).getString("Question");}
    catch (JSONException e) {e.printStackTrace();}

    return question_txt;
}

public JSONArray setJson()throws JSONException, IOException {
    java.net.HttpURLConnection connection = null;
    URL url = new URL("url_to_my.php");
    connection = (java.net.HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Content-length", "0");
    connection.setUseCaches(false);
    connection.setConnectTimeout(0);
    connection.setReadTimeout(0);
    connection.connect();
    int status = connection.getResponseCode();
    JSONArray json = null;

    switch (status) {
        case 200:
        case 201:

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            this.json = new JSONArray(sb.toString());
            br.close();
    }
    return this.json;

}

}

What I tried doing is creating an ArrayList questionnaire and add to it different instances of the Class Question with different values.

ArrayList<Question> questionnaire = new ArrayList<Question>();
Question q = new Question();

for(int i=0; i< q.setJson().length() ;i++){
    Question newQuestion = new Question();
             newQuestion.json = q.json;
             newQuestion.setQuestion_id(i);
             newQuestion.setQuestion_txt(i);
             questionnaire.add(newQuestion);}

Everything seems to work fine, at least for now. Later on, I want the JSON result to return more information like the possible answers and which is the correct one.


texts: Writing a generic performance efficient isEmpty method which can check for null or emptiness

texts:
I am writing a utility method which can check for empty and null string, or collection or an object or any general types -

public static boolean isEmpty(Object obj) {
    if (obj == null)
        return true;
    if (obj instanceof Collection)
        return ((Collection<?>) obj).size() == 0;

    // is below line expensive?
    final String s = String.valueOf(obj).trim();

    return s.length() == 0 || s.equalsIgnoreCase("null");
}

How can I make my above method efficient, since above isEmpty method will be called multiple times from the application which is very performance critical?

I am suspecting below line will be expensive because of heavy toString methods and it will create temporary garbage as well that might cause GC and slow down the performance?

final String s = String.valueOf(obj).trim();

If I need to check for map null or empty, should I keep both collection isEmpty and Map isEmpty method both or Collection isEmpty method will be fine for that?

public static void main(String[] args) {

    Map<String, String> hello = new HashMap<String, String>();
    System.out.println(isEmpty(hello));

    Map<String, HashMap<Integer, String>> primary = new HashMap<String, HashMap<Integer, String>>();
    System.out.println(isEmpty(primary));

}

public static boolean isEmpty(Collection<?> value) {
    return value == null || value.isEmpty();
}

public static boolean isEmpty(Map<?, ?> value) {
    return value == null || value.isEmpty();
}


texts: bullet-proof way to generate a list of object attributes (if object has them)

texts:
Background

I wrote a a couple functions that make it possible to generate a list of attributes for any given object that has them. I use the list that is objectWalker generates in other functions mostly centered around pandas DataFrame analysis. Please tear this code apart I'd like to hear whatever you have to say.

Code

def inspectObject(obj):
    """Return list of object attributes and their types.

    Parameters
    ----------
    obj: :obj:
        Any kind of object that is not a builtin.

    Returns
    -------
    obj_ids: list
        A list of lists to be specific.
    """
    obj_ids = []
    # Make list of builtins
    # bi_list = dir(__builtins__)
    # Try to make a list of the types of things inside obj.
    try:
        # Make list all things inside of an object
        for name, thing in obj.__dict__.items():
            obj_ids.append([name, type(thing).__name__, thing])

        return obj_ids

    except Exception:
        pass

def objectWalker(obj, desired_type=None, att_list=None):
    """Recursively walks through an object an genrates a list of its attributes.

    Parameters
    ----------
    obj: :obj:

    desired_type: str

    Returns
    -------
    att_list: list

    """
    # Create an attributes list if none has been asigned.
    if att_list is None:
        att_list = []

    # Create list of types that we do not want yo serch through
    no_list = dir(__builtins__)
    no_list.append("DataFrame")
    # desired_type = desired_type or "DataFrame"

    obj_inspect = inspectObject(obj)

    for i in obj_inspect:

        # Test if object attribute is desired_type.
        if re.search(desired_type, i[1], re.I) is not None:

            att_list.append(i)

        # If the object attribute is not the desired_type then...
        elif i[1] not in no_list:
            # Try to use recursively objectWalker on the object.
            try:
                objectWalker(obj.__dict__[i[0]], desired_type, att_list)
            except Exception:
                pass
    return att_list

UPDATE

So I guess this is the best way to do it.


texts:
Here is my class to read a csv file and I was wondering if there is any improvements that I should do. I feel there are some performance improvements or in exception handling because I just took IO exceptions.

package com.mypackage.utils;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.enums.CSVReaderNullFieldIndicator;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;

public class FileReader {

    private String path;
    private CSVReader reader;
    private List<String> linesList;
    private Set<List<String>> splitLinesSet;

    public FileReader(String path) {
        this.path = path;
    }

    public boolean readFile() {

        this.splitLinesSet = new HashSet<>();

        try {
            File file = Paths.get(path).toFile();
            reader = new CSVReaderBuilder(new java.io.FileReader(file))
                    .withCSVParser(new CSVParserBuilder()
                            .withSeparator('|')
                            .withFieldAsNull(CSVReaderNullFieldIndicator.NEITHER).build())
                    .build();
            read();
            reader.close();
        } catch (IOException e) {
            System.err.println("Error in reading CSV: " + e.getMessage());
            return false;
        }

        return true;
    }

    public Set<List<String>> getSplitLinesSet() {
        return splitLinesSet;
    }

    private void read() throws IOException {
        String[] lines;
        while ((lines = reader.readNext()) != null) {
            linesList = new ArrayList<>();
            Collections.addAll(linesList, lines);
            splitLinesSet.add(linesList);
        }
    }
}


texts: Printing text based on divisibility of number

texts:
The following piece of code will print a text based on the divisibility of number.
If the number is not divisible by 3, 5 and 7, then the number gets printed.

Does making use of a f-string make the type cast of integers to string implicit?

def convert(number):
    result = ""
    if (number % 3 == 0):
        result += "Pling"
    if (number % 5 == 0):
        result += "Plang"
    if (number % 7 == 0):
        result += "Plong"
    if(number % 7 != 0 and number % 5 != 0 and number%3 != 0):
        result = f{'number'}
    return result


texts: Determine if one string is a rotation of the other Python

texts:
After thinking for a long hard time, learning about algorithms to find substrings, and coming to really long and tedious code I decided against my solution and to look for help. The solution was much simpler and elegant. After determining that my code was too much for a simple task I came across an explanation of a simple way to find if one string was a rotation of the other. Man I feel dumb for falling down a long rabbit hole however I learned much about many different things and also how to keep it simple stupid. Previous post of this problem here.

#rotated list

def is_rotated(lst1, lst2):
    ''' Is lst2 a rotation of lst1'''
    str1, str2 = ''.join(map(str,lst1)), ''.join(map(str,lst2))
    if not len(str1) == len(str2):
        raise ValueError("Lengths not equal")

    if str2 in (str1 + str1):
        return True
    return False

# rotation
lst1, lst2 = [1,2,3,4,6,4,7], [6,4,7,1,2,3,4]
assert is_rotated(lst1, lst2)

# rotation with repeated numbers
lst1, lst2 = [1,2,3,4,6,4,7,1], [6,4,7,1,1,2,3,4]
assert is_rotated(lst1, lst2)

# different set
lst1, lst2 = [1,2,3,4,6,4,6], [6,4,7,1,2,3,4]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1,2,3,4,6,4,7], [6,4,6,1,2,3,4]
assert not is_rotated(lst1, lst2)

# equal
lst2 = lst1
assert is_rotated(lst1, lst2)

# empty
lst1, lst2 = [], []
assert is_rotated(lst1, lst2)

# 1 empty, 1 not empty
lst1, lst2 = [], [1]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1], []
assert not is_rotated(lst1, lst2)


texts: Find occurrences of strings in view B in column from table A

texts:
I'm trying to find the occurrences of strings in view B in a string in table A. However, the performance is horrendous (takes about 17 minutes to run) and I was wondering if anyone had any suggestions to improve it.

view B has 3570 records and has one column of type varchar named MISubCode

Table A has 160081 records and has the schema in the attached image.

There's also a third table, (Table C) which is largely used to filter the results of table A since I don't need to find occurrences in any of those records.

My rational to solve this was as follows:

Count the number of characters in the string in the desired search column in table A, producing one row for each character
Filter the unneeded rows using view C
Run each row generated in result set from 2. and use the Number column to find the occurrences from view B in the string in column from Table A until the end of the string in column from table A.

Code:

 SELECT *
FROM
(
SELECT Number, A.StatusInputPoint_DESC, A.StatusInputPoint_CODE, A.StatusInputPoint_CORE_ID
FROM
(
SELECT Number, A.StatusInputPoint_DESC, A.StatusInputPoint_CODE,  A.StatusInputPoint_CORE_ID
FROM
tblStatusInputPoints_CORE A
CROSS JOIN
(
    SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
    FROM sys.all_objects
) AS n(Number)
WHERE Number >= 1 AND Number <= CAST(LEN(A.StatusInputPoint_DESC) AS INT) AND System_ID = 1
) AS A
LEFT JOIN
vwAlarmLibrary_MI_StatusPoint_Mask_Match_NoWildCards C
ON
A.StatusInputPoint_CORE_ID = C.StatusInputPoint_CORE_ID
WHERE C.StatusInputPoint_CORE_ID IS NULL
) AS RemainingStatusPoints
LEFT JOIN
dbo.vwAlarmLibrary_MI_Substation_Abbreviations B
ON
SUBSTRING(RemainingStatusPoints.StatusInputPoint_DESC, Number, LEN(B.MISubCode)) = B.MISubCode
WHERE B.MISubCode IS NOT NULL

I'm at a loss as to how to make this faster. I tried several different methods and join combinations and I can't seem to get it to perform well. I'm not an expert in SQL Server so I don't know all the features.

I'm currently using SQL Server 2016

EXAMPLE:

For clarity, lets say I have these strings in view B

 ABC
 EFGH
 IJ

And I have these strings in table A

 123 ABC 45 IJ
 IJ
 IJ EFGH 22

The result should be this:

 Pos   String          Occurrence
 5   | 123 ABC 45 IJ | ABC
 12  | 123 ABC 45 IJ | IJ
 1   | IJ            | IJ
 1   | IJ EFGH 22    | IJ
 4   | IJ EFGH 22    | EFGH


texts: Web scraping JSON-data from API put into Dataframe

texts:
The web-scraping process currently takes quite a bit of time, and I wonder if I can structure the code otherwise or improve it in any way.

Code looks like this:

import numpy as np
import pandas as pd
import requests
import json
from sklearn import preprocessing
from sklearn.preprocessing import OneHotEncoder

results_2017 = []
results_2018 = []
for game_id in range(2017020001, 2017021271, 1):
    url = 'https://statsapi.web.nhl.com/api/v1/game/{}/boxscore'.format(game_id)
    r_2017 = requests.get(url)
    game_data_2017 = r_2017.json()

    for homeaway in ['home','away']:

        game_dict_2017 = game_data_2017.get('teams').get(homeaway).get('teamStats').get('teamSkaterStats')
        game_dict_2017['team'] = game_data_2017.get('teams').get(homeaway).get('team').get('name')
        game_dict_2017['homeaway'] = homeaway
        game_dict_2017['game_id'] = game_id
        results_2017.append(game_dict_2017)

df_2017 = pd.DataFrame(results_2017)

for game_id in range(2018020001, 2018020667, 1):
    url = 'https://statsapi.web.nhl.com/api/v1/game/{}/boxscore'.format(game_id)
    r_2018 = requests.get(url)
    game_data_2018 = r_2018.json()

    for homeaway in ['home','away']:

        game_dict_2018 = game_data_2018.get('teams').get(homeaway).get('teamStats').get('teamSkaterStats')
        game_dict_2018['team'] = game_data_2018.get('teams').get(homeaway).get('team').get('name')
        game_dict_2018['homeaway'] = homeaway
        game_dict_2018['game_id'] = game_id
        results_2018.append(game_dict_2018)

df_2018 = pd.DataFrame(results_2018)

df = df_2017.append(df_2018)


texts: Create a binary tree, code review request

texts:
Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple. ( Generics would be added a bit later).

public class CreateABinaryTree {
    private TreeNode root;

    public CreateABinaryTree() {
    }

    /**
     * Constructs a binary tree in order of elements in an array.
     * After the number of nodes in the level have maxed, the next
     * element in the array would be a child of leftmost node.
     *
     * http://codereview.stackexchange.com/questions/31334/least-common-ancestor-for-binary-search-tree/31394?noredirect=1#comment51044_31394
     */
    public CreateABinaryTree(List<Integer> items) {
        this();
        create(items);
    }

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

        TreeNode(TreeNode left, int element, TreeNode right) {
            this.left = left;
            this.element = element;
            this.right = right;
        }
    }

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

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

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

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

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


texts:
How can I rework the code up that ema(x, 5) returns the data now in emaout? I'm trying to enclose everything in one def.

Right now its in a for loop and a def.

x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21]

def ema(series, period, prevma):
    smoothing = 2.0 / (period + 1.0)
    return prevma + smoothing * (series[bar] - prevma)

prevema = x[0]
emaout =[]

for bar, close in enumerate(x):
    curema = ema(x, 5, prevema)
    prevema = curema
    emaout.append(curema)

print
print emaout

x could be a NumPy array.


texts: Functional Programming approach to a REST API example

texts:
I would like to know if there are any things I could improve with the following code regarding writing it in a FP style:

server.js:

const express = require('express');
const app = express();
const person = require('./person');

app.get('/create-person/:name', (req, res) => {
    person.addPerson(req.params.name);
    res.sendStatus(201);
});

app.get('/get-person/:name', function (req, res) {
    res.json(person.getPerson(req.params.name));
})

app.listen(3000);

person.js:

// Impure
let personList = [];
// Impure
function set(newPersonList) {
    personList = newPersonList;
    console.log(personList);
}
// Pure
function createPerson(name) {
    return {
        name
    };
}
// Pure
function addPerson(name, createPersonArg = createPerson, personListArg = personList, setArg = set) {
    return setArg([...personListArg, createPersonArg(name)]);
}
// Pure
function getPerson(name, personListArg = personList) {
    return personListArg.find((person) => {
        return name === person.name
    });
}

module.exports = {
    addPerson,
    getPerson
}

I'm using default parameters. I'm also wondering if this is the correct way of using them in FP.

I am aware I am creating a resource with GET. So ignore that, it is for being able to use the browser quickly to create a resource in this example.


texts:
I have a exercise where I have to write a Stack class with the push and pop methods. The code compiles and works as it should. Are there better practices to use in my code? Is there something I should avoid doing?

public class Stack {

    private final int INCREMENTSIZE = 1024;
    Integer position = 0;

    int[] list = null;

    public Stack(){
        list = new int[INCREMENTSIZE];
    }

    public void push(Integer i) {
        if(position == list.length) {
            list = Arrays.copyOf(list, list.length + INCREMENTSIZE);
        }
        list[position++] = i;
    }

    public Integer pop(){
        return list[--position];
    }
}


texts:
My C program uses the Monte Carlo method to approximate the mathematical constant π, the ratio of a circle's circumference to its diameter (and, importantly for this code, 4 times the ratio of a circle's area to that of its bounding square).

This estimation executes more slowly when parallelised using OpenMP than it does when executed in a single thread.

I think that my random generator function is not thread safe, and that may be the cause of the slowdown.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>

#define DART 1000000    // Number of darts each player throws
                        // Number of random dots in the square[-1,+1]

#define MAXPLAYER 8     // Maximume number of participant players
                    // Number of threads
/**
Generates a random number between two params given

@param: random number scope
@return: desired random number
*/
long double fRand(long double fMin, long double fMax)
{
    long double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

/**
    Generates random dots on the board

    @param: playerDarts, total number of darts to throw
    @return: score, number of darts thrown in the circle
*/
int player(int playersDarts)
{
    srand(time(NULL));
    long double pi, x, y;
    int score = 0;

    for (int i = 0; i < playersDarts; i++)
    {
        x = fRand(-1.0, 1.0);
        y = fRand(-1.0, 1.0);

        if (x*x + y*y < 1.0)
            score++;
    }
    return score;
}

void main()
{
long double pi;
long const double REAL_PI = 3.141592653589;
int score = 0, playersDarts;

////////////////////////////////////////////////////
//  Parallel                                      //
////////////////////////////////////////////////////

// devide the total number of DARTS between players
playersDarts = DART / MAXPLAYER;
double beginParallel = omp_get_wtime();

#pragma omp parallel for
for (int i = 1; i <= MAXPLAYER; i++)
    score += player(playersDarts);

double endParallel = omp_get_wtime();
pi = 4.0 * ((long double)score / (long double)DART);

double time_spent_parallel = endParallel - beginParallel;
printf("\n\t Calculated pi : %.12Lf\n", pi);
printf(  "\t       Real pi : %.12Lf\n", REAL_PI);
printf("\n\t Parallel Execution Time: %f\n", time_spent_parallel);

////////////////////////////////////////////////////
//  Serial                                        //
////////////////////////////////////////////////////

double beginSerial = omp_get_wtime();
pi = 4.0 * ((long double) player(DART) / (long double)DART);
double endSerial = omp_get_wtime();

double time_spent_serial = endSerial - beginSerial;

printf("\n\t Calculated pi : %.12Lf\n", pi);
printf(  "\t       Real pi : %.12Lf\n", REAL_PI);
printf("\n\t Serial Execution Time: %f\n", time_spent_serial);
}


texts: Bash pass multiple commands to SSH and make readable

texts:
I have a script that sends multiple commands after logging in a remote machine via SSH.

Problem is, it's barely readable. I've tried quoting everything with "", but it's terrible (everything appears in pink), and here documents are just as bad (everything appears in gray). I'm using Gedit as an editor, but I tried Emacs as well.

Can I make the editor parse the remotely executed code as code?

#!/bin/bash

function remoteExec()
{
    echo "remote execution starting"
    ssh -n "$1" << 'EOF'
#the following code is _not_ highlighted by real editors
currIt=\"$2\" #I hope this parameter is passed correctly
while [ "$currIt" -lt 5 ]; do
    echo "hello"
    currIt=$(($currIt + 1))
done
EOF
}

I'd rather not create a separate script just for these lines, because then I'd have to copy it on the remote machine, or pipe it, and I have arguments too.

EDIT: as Glenn noticed, as far as highlighting goes, there isn't much to do. I'm open to solutions putting the code in a separate script. I need to transfer the code to the remote host then, and pass it the necessary arguments.


texts: Mongoose / MongoDB schemas for blog posts and authors

texts:
I'm programming a model for a blog with authors and posts. I was following this doc: Mongoose Query Population

My concern is that the createPost function is inefficient.
Another option is to nest the posts in the Author, but how I will get all posts? Should I use MySQL? Am I doing it right? (Take a look at the functions as well)

Some more details:

Pastebin

let mongoose = require("mongoose");
let Schema = mongoose.Schema;

let PostSchema = Schema({
    title: {type: String},
    body: {type: String},
    date: {type: Date},
    tags:[{type: String}],
    _author: {type: Schema.Types.ObjectId, ref: 'author'}
});

let AuthorSchema = Schema({
    name: {type: String},
    photo: {type: String},
    bio: {type: String},
    username: {type: String, index: true},
    posts:[{type: Schema.Types.ObjectId, ref: 'post'}],
    password: {type: String}
});

let Author = mongoose.model('author', AuthorSchema);
let Post = mongoose.model('post', PostSchema);

module.exports = Author;
module.exports = Post;

module.exports.createAuthor = (newAuthor, callback)=>{
    newAuthor.save(callback)
};

module.exports.createPost = (username, newPost, callback)=>{
        Author.findOne({username:username}).then((author)=>{
            newPost._author = author._id
            author.posts.push(newPost);
            newPost.save().then(err, auth)=>{
                author.save(callback);
            };
        },(err)=>{
            if(err)
            throw err;
        });
};

module.exports.getAuthorByPostTitle = (postTitle, callback)=>{
        Post.findOne({title:postTitle}).populate('_author').exec((err, post)=>{
            if(err)
                throw err;
            else
                return post._author;
        });
};

module.exports.getPostsByAuthorId = (authorId, callback)=>{
        Post.find({_author:authorId}).exec((err, posts)=>{
            if(err)
                throw err;
            else
                return posts;
        });
};


texts:
Is this the best way to implement this pattern in C#?

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    public static Singleton Instance { get { return instance; } }

    static Singleton() {}
    private Singleton() {}
}


texts: Find the Nth number divisible by only 2,3,5, or 7

texts:
I recently participated in a small friendly competition and this was one of the questions:

  A number whose only prime factors are 2, 3, 5 or 7 is called a humble
  number. The first 20 humble numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9,
  10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ...

  Given n, find the nth humble number.

  Example

  n = 1: 1; n = 11: 12; n = 22: 30

  [input] integer: positive integer n

  [output] integer: The nth humble number.

  There should be a O(N) solution!

Here's my solution:

def humbleNumber(n):
    curr = 0
    i = 0
    dp = {}
    while i < n:
        curr += 1
        if ishumble(curr, dp):
            dp[curr] = True
            i += 1
        else:
            dp[curr] = False
    return curr

def ishumble(x,dp):
    if x == 1:
        return True
    acc = [2,3,5,7]
    for i in acc:
        if x % i == 0:
            if (x/i) in dp:
                return dp[x/i]
            return ishumble(x / i) #i don't believe this ever get's called
    return False

I believe that this solution is \$O(N)\$. I am iterating up to \$n\$, and at each step, I am calling a constant-time helper function. The helper function ishumble(x, dp) will check if the current number x is a humble number. We are able to do this in constant time because we are guaranteed that if x % i == 0, then (x/i) is in dp! So I believe that the return ishumble(x / i) line is actually never called.

Therefore, this solution is in \$O(N)\$. Is my analysis correct? Is there a better solution?


texts: How secure is my PHP registration script?

texts:
I coded a registration form and was wondering if anyone could give me feedback on whether I'm lacking any major security mechanisms. I've done loads of reading around the topic and feel it should be secure but expert feedback would be great.
Registration script
<?php

// User/pass only used locally
$host = 'localhost';
$db   = 'new_db';
$user = 'root';
$pass = '';

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$host;dbname=$db";
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

$errors = [];
if ( $_POST )
{

    // Get form field values
    $fname              = filter_input(INPUT_POST, 'fname', FILTER_SANITIZE_STRING);
    $email              = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $pwd                = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
    $pwd_confirm        = filter_input(INPUT_POST, 'confirm-password', FILTER_SANITIZE_STRING);

    // Generate activation key
    $activation_key     = md5(uniqid(mt_rand(), true));
    $activation_link    = 'https://www.example.com/activate?id='.$activation_key.'&name='.$fname;

    // Check if passwords match
    if ($pwd !== $pwd_confirm) {
        $errors[] = "Passwords don't match";
    }

    // Check if password is secure
    if (strlen($pwd) < 8) {
        $errors[] = "Password not long enough! Must be at least 8 characters long";
    }

    // Check if username equals password
    if ($fname === $pwd) {
        $errors[] = "Your name cannot be your password!";
    }

    // Check if email address exists in database
    $email_query = $pdo->prepare("SELECT * FROM users WHERE email = :email");
    $email_query->bindParam(':email', $email);
    $email_query->execute();
    $email_found = $email_query->fetchColumn();
    if ($email_found) {
        $errors[] = "Your email address is associated with another account.";
    }

    // If no errors, continue with user account creation
    if (!$errors)
    {
        // Hash password
        $hashed_password = password_hash($pwd, PASSWORD_DEFAULT);

        // Create database entry
        $create_account = $pdo->prepare("INSERT INTO users (first_name,email,password, activation_key) VALUES (:fname, :email, :password, :activation_key)");
        $create_account->bindParam(':fname', $fname);
        $create_account->bindParam(':email', $email);
        $create_account->bindParam(':password', $hashed_password);
        $create_account->bindParam(':activation_key', $activation_key);
        $create_account->execute();

        // Send out activation email
        $to=$email;
        $subject="Activate your account";
        $from = 'no-reply@example.com';
        $body='Thank you for creating your account, '.$fname.'. Please click on the following link to activate your account: '.$activation_link.'';
        $headers = "From:".$from;
        mail($to,$subject,$body,$headers);

        // Redirect user to the dashboard
        header("Location: /dashboard.php");
        exit;
    }

}

?>

I do want to use it on a live site at one point, so the end result should not just be a registration form that's somewhat secure but could actually be used in production.
EDIT
I did some more thinking and I guess before redirecting the newly registered user, I have to start a session to detect on the dashboard page whether the user is logged in. Is the following sufficient and secure to to add after I sent out the activation email?
session_start();

$_SESSION["loggedin"] = true;
$_SESSION["email"] = $email;

// Redirect user to the dashboard
header("Location: /dashboard.php");
exit;


texts: Tiny Lua library to get char pointer from string

texts:
Background

I'm using Lua with luaglut to do some OpenGL stuff. The luaglut API is almost identical to the gl/glut C APIs. Sometimes, gl functions want a pointer to some data, for example:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
    GL_UNSIGNED_BYTE, oh_crap_a_pointer)

In these cases, the luaglut bindings take a light userdata containing the pointer. In the luaglut demos, a small example library called memarray does the work of setting up a C array and returning a pointer to it as a light userdata.

You might use "memarray" something like this:

require 'memarray'
function loadTexture(filename)
  local file = assert(io.open(filename, 'rb'))
  local data = file:read('*a')
  file:close()
  local array = memarray('uchar', #data)
  array:from_str(data)

  return array
end

-- ... later

local texture = loadTexture('whatever.rgba')
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA,
    GL_UNSIGNED_BYTE, texture:ptr())

That got me thinking, why do we need memarray at all? Lua strings should be binary safe; all we really need is to get a pointer to the string returned from
file:read('*a') as a light userdata. It would look something like this:

function loadTexture(filename)
  local file = assert(io.open(filename, 'rb'))
  local data = file:read('*a')
  file:close()

  return data
end

-- ... later

local stringpointer = require 'stringpointer'
local texture = loadTexture('whatever.rgba')
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0, GL_RGBA,
    GL_UNSIGNED_BYTE, stringpointer.get(texture))

Of course we pass the string around instead of the pointer, because the GC could free the memory the string was in if there are no more references to it, invalidating the pointer. Internally Lua strings are immutable and passed by reference anyway, so this is no big deal.

Code

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int get_pointer(lua_State *L)
{
    luaL_checktype(L, 1, LUA_TSTRING);
    lua_pushlightuserdata(L, (void *)lua_tostring(L, 1));
    return 1;
}

int luaopen_stringpointer(lua_State *L)
{
    const luaL_Reg api[] = {
        {"get", get_pointer},
        {NULL, NULL}
    };

#if LUA_VERSION_NUM == 501
    luaL_register(L, "stringpointer", api);
#else
    luaL_newlib(L, api);
#endif

    return 1;
}

It's really tiny, but my C is rusty so maybe I did something stupid. It seems to work fine so far. Any input is welcome.


texts:
I am given 8 positive 32-bit integer numbers. The task is to write program to count all X-bits.

X-bits are groups of 9 bits (3 rows x 3 columns) forming the letter "X". task is to count all X-bits and print their count on the console. Valid X-bits consist of 3 numbers where their corresponding bit indexes are exactly {"101", "010", "101"}. All valid X-bits can be part of multiple X-bits (with overlapping).

Expected input and output:

Bellow is my solution, for any of the inputs it prints out the correct value, and it passes every test in our judge system, which makes me think that it's a valid solution to the problem.
The idea of my approach is simple, the array is treated as if it was a 2d array and each group of 9 bits across 3 ints of the array is compared to the required pattern.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        int xCount = 0;
        int nums[] = new int[8];
        for(int i = 0; i < nums.length; i++) {
            nums[i] = Integer.parseInt(stdin.nextLine());
        }
        for (int i = 0; i < nums.length - 2; i++) { // nums.length - 2 because in validX(...) we have index (passed as i) + 2
            for (int j = 0; j < 29; j++) {              // 31 (index of the leftmost bit) - 2 because we have startingPosition + 2
                if(validX(nums, i, j) == true) {
                    xCount++;
                }
            }
        }
        System.out.println(xCount);
    }

    public static int get_bit(int num, int pos) {
        return ((num >> pos) & 1);
    }
    public static boolean validX(int nums[], int index, int startingPosition) {
        if(get_bit(nums[index], startingPosition) == 1 && get_bit(nums[index], startingPosition + 1) == 0
        && get_bit(nums[index], startingPosition + 2) == 1 &&
                get_bit(nums[index + 1], startingPosition) == 0 && get_bit(nums[index + 1], startingPosition + 1) == 1
                && get_bit(nums[index + 1], startingPosition + 2) == 0 &&
        get_bit(nums[index + 2], startingPosition) == 1 && get_bit(nums[index + 2], startingPosition + 1) == 0 &&
        get_bit(nums[index + 2], startingPosition + 2) == 1) {
            return true;
        }
        return false;
    }
    /*
     * in actuality what this function is doing is getting each individual bit and comparing it to the pattern
     * we need, which is:
     * {"101",
     *  "010",
     *  "101"}
     */
}

The issue I have with this code is that it's ugly. Truth be told I'm slightly ashamed of my validX(...) method, but I can't think of a quicker way or one that would take even less memory. The idea of my approach is simple, the array is treated as if it was a 2d array and each group of 9 bits is compared to the required pattern.

And just to get a few things out of the way, nobody assigned me this problem, I'm doing it to get better in Java. Whatever code I receive (if any at all) won't be submitted anywhere. Quite frankly I'm interested to know if there's a more elegant, readable solution which avoids hardcoded values. The reason I'm not happy with the default solution is because I don't think 0.2 s allowed runtime and 16 MB allowed memory is adequate for a problem like this.


texts: A Python decorator for an "observable property", that notifies observers when the data is changed

texts:
I have classes that have some data, and whenever this data changes, it should notify observers of that data change. There also should be a method to add new observers.
My first approach was to use a property with a custom setter. This means that whenever the = operator was used on the data it would call the custom setter, which would notify the observers.
Like so:
# (1)
from typing import Callable

class Foo:

    def __init__(self):
        self.__bar = 0
        self.__bar_observers = []

    @property
    def bar(self):
        return self.__bar

    @bar.setter
    def bar(self, value):
        self.__bar = value
        #notify observers
        for obs in self.__bar_observers:
            obs(value)

    def add_bar_observer(self, observer : Callable[[int], None]):
        self.__bar_observers.append(observer)

f = Foo()
f.add_bar_observer(lambda newval : print(f'new bar val {newval}'))
f.bar = 8

But this is a lot of boilerplate and is many lines of code just for one property. If Foo had 10 observable properties instead of just one, this class would be quite large.
It would be good if this pattern could be created automatically with a decorator.
Here is my attempt at that:
# (2)
def observable_property(initial_value):

    class _observable_property:

        def __init__(self, fget):
            pass

        # We don't know if __set__, __get__, or add_observer will be called first, so we need to call this at the start of all 3.
        def __init(self, obj):
            #On first time called, create the data
            if not hasattr(obj, f'__{self.name}'):
                setattr(obj, f'__{self.name}', initial_value)
            if not hasattr(obj, f'__{self.name}_observers'):
                setattr(obj, f'__{self.name}_observers', [])

        def __get__(self, obj, objtype=None):
            self.__init(obj)
            return getattr(obj, f'__{self.name}')

        def __set__(self, obj, value):
            self.__init(obj)
            setattr(obj, f'__{self.name}', value)
            #Notify all of the observers
            for obs in getattr(obj, f'__{self.name}_observers'):
                obs(value)

        def __set_name__(self, owner: type, name : str):
            self.name = name
            #Add a function to the owner to add new observers
            def add_observer(obj, observer):
                self.__init(obj)
                getattr(obj, f'__{name}_observers').append(observer)

            setattr(owner, f'add_{name}_observer', add_observer)

    return _observable_property

And then a test:
# (3)
Meters = NewType('Meters', float)
Kelvin = NewType('Kelvin', float)

class Axis:

    @observable_property(initial_value=Meters(0.0))
    def position(self):
        pass

    @observable_property(initial_value=Kelvin(0.0))
    def temperature(self):
        pass

a = Axis()
a.add_position_observer(lambda newval : print(f'New position for a: {newval}'))
a.add_temperature_observer(lambda newval : print(f'New temperature for a: {newval}'))
a.position = Meters(5.0)
a.temperature = Kelvin(300.0)

This works, but two downsides I can see are that the add_{}_observer functions do not appear in an IDE IntelliSense autocomplete, and it also loses its type hints.
What do you think? Would you use this in production code?
I would also prefer it if the initial_value was set in the constructor of the class, instead of as a decorator parameter, and then the function to be decorated returns that, as is the case with the standard @property decorator.
i.e
# (4)
class Axis:

    def __init__(self):
        self.__position=Meters(0.0)

    @observable_property
    def position(self):
        return self.__position

But I cannot do this as I can't mutate the self.__position from the __set__ descriptor. Is there any way to get the style of # (4), with the functionality of # (3)?
Thanks.


texts: Function/method to get selective columns

texts:
Is it possible to simplify getRows() or it is fine as it is now?

protected $container;
public function __construct(ContainerInterface $container) {
    $this->container = $container;
    $this->em = $this->getDoctrine()->getManager();
}

/*
* @param    $ntt              name of the entity to fetch
* @param    $cols             columns to fetch
* @param    $where            array of data to be matched (for example array('id'=>1))
* @param    $result_type      type of result required. (object|array)
*/
public function getRows($ntt,$cols=array(),$where=array(),$result_type=null){
    $data = 'nulllllll';
    if($ntt && $where && is_array($where)){
        $i = 1;
        $filter = '';
        foreach ($where as $key => $value) {
            if(is_array($value)){
                $filter = $filter.($filter ? ' AND ' : '')."tm.$key in (:v$i)";
            }else{
                $filter = $filter.($filter ? ' AND ' : '')."tm.$key = :v$i";
            }
            $param['v'.$i] = $value;
            $i++;
        }

        $select = 'tm';
        if($cols){
            $select = '';
            foreach ($cols as $col) {
                $select = $select.($select ? ', ' : '')."tm.$col";
            }
        }

        $ntt = 'AppBundle:'.$ntt;
        $data = $this->em->getRepository($ntt)->createQueryBuilder('tm')
        ->select($select)
        ->where($filter)
        ->setParameters($param)
        ->getQuery();
        if($result_type == 'array'){
            $data = $data->getArrayResult();
        }else{
            $data = $data->getResult();
        }
    }
    return $data;
}

Calling:

getRows('My_user',array('lName','llname'),array('id'=>array(1,4,50)),'array')

Where My_user is my entity name and lName and llname are the columns I want to fetch.

Will output:

Array
(
    [0] => Array
        (
            [lName] => Abc
            [llname] => Sha
        )

    [1] => Array
        (
            [lName] => And
            [llname] => Bainbri
        )

    [2] => Array
        (
            [lName] => Ken
            [llname] => Lee
        )

)


texts:
My program inspects filenames which are delimited via underscores. So an example may be:

  This_is_an_example_of_my_filename.tif

A counter example may be:

  This_is_a_very_bad_document.tif

The filename should always consist of 7 distinct values within the filename. Those values are used to create an instance of a class object which allows me to further validate data based on segment location in the filename.

The program should only consider *.tif files in the directory, and ignore all others.

If the filename is invalid (too few/too many fields, or field data is improperly formatted) we move it to an error bin. If it is good, I upload the data to a database and move the file on it's merry way.

The code that pulls these filenames apart looks like:

foreach(string file in Directory.GetFiles(path))
{
    FileInfo fi = new FileInfo(file)
    if(fi.Extension == ".tif")
    {
        MyDocumentObject do = new MyDocumentObject();
        string filename = fi.Name;
        string[] filenameAsArray = filename.split('_');
        string lastIndexNoExtension = (filenameAsArray[filnameAsArray.Length -1].Split('.'))[0];
        filenameAsArray.SetValue(lastIndexNoExtension, (filenameAsArray.Length - 1));
        if(filenameAsArray.Length == 6)
        {
            for(int x=0;x<=(filenameAsArray.Length - 1);x++)
            {
                switch(x)
                {
                    case 0:
                        string part1 = filenameAsArray[x];
                        do.part1 = part1;
                        break;

                    //so on for 1-6
                }
            }
        }
        bool validationResults = do.ValidateFields();
        if(validationResults)
        {
            File.Move(fi.FullName, "path\to\destination");
        }
        else
        {
            File.Move(fi.FullName, "path\to\errorbin");
        }
    }
}

My main point of focus for this review is on the method of pulling apart the filename into an array of text segments and then assigning that data to an instance object and operating on it.

In practice I'm pretty happy - it does the job and is zippy about it. But looking at it... just bugs me.

EDIT: I forgot to mention the reason I use my method of splitting to remove the file extension is due to issues that arise when a file in the directory is named something like:

  this_is_a_trick.txt.tif


texts: A game called Bocce played on a Cartesian grid

texts:
You may know Bocce, so you should know that I've tweaked the rules a little. Three types of balls are thrown: a red type, a blue type, and single black ball called the jack.

These are all on the Cartesian coordinate system. The coordinates of the jack are given, and also distances of an equal amount of red and blue balls from the origins of the system (0, 0). If a ball's distance is larger than the distance of the jack, and if the distance of this ball is larger than the distance of its peer, it's a score. The team with the highest score wins.

Here's the code:

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <cmath>
#include <array>
#include <algorithm>

typedef std::map<std::string, std::vector<int>> bocce_balls;
typedef std::vector<int> int_vec;
typedef std::array<int, 2> int_arr;

std::string bocce(bocce_balls balls, int_arr jack)
{
    auto distance = std::sqrt(std::pow(jack[0], 2)+std::pow(jack[1], 2));
    int red_count = 0;
    int blue_count = 0;

    int_vec red = balls["red"];
    int_vec blue = balls["blue"];

    if (blue.size() != red.size())
    {
        std::cerr << "Balls were different numbers!" << std::endl;
        return "Fail!";
    }

    std::sort(blue.begin(), blue.end());
    std::sort(red.begin(), red.end());

    for (int i = 0; i < blue.size(); ++i)
    {
        if (red[i] > distance && red[i] > blue[i])
            ++red_count;
        else if (blue[i] > distance && blue[i] > red[i])
            ++blue_count;
    }

    if (red_count > blue_count)
        return "Red Wins!";
    else if (blue_count > red_count)
        return "Blue Wins!";
    else
        return "Draw!";

}

int main() {

    bocce_balls insert;
    insert["blue"] = {2, 9, 3, 4, 5, 1, 10, 2};
    insert["red"] = {20, 11, 3, 4, 3, 1, 2, 3};
    int_arr dist = {2, 2};

    std::cout << bocce(insert, dist) << std::endl;
    return 0;
}


texts: Program to find unique chars in a String (and also to find number of occurences of chars in a String)

texts:
I am new to Java and learning about Strings in Java. So I wrote a program which counts the number of times a character repeats in a String and also identifies unique characters(chars not repeated more than once) in a String.

Is this an efficient way to do this?

public static String uniqueValues(String str){
char[] arr = str.toCharArray();
int[] result = NumberOfOccurences.numberOfOccurencesOfLetters(arr);
StringBuilder sb = new StringBuilder();
for(int i=0;i<result.length;i++){
    if(result[i]==1){
        sb.append((char)(i+97));
        sb.append(" ");
        }
    }
return sb.toString();
}

//in the other class i wrote this method
public static int[] numberOfOccurencesOfLetters(char[] arr){
int[] result = new int[26];
int num;
for(int i=0;i<arr.length;i++){
    num =(arr[i]-97);
    result[num]++;
    }
return result;
}


texts:
This is my first attempt at trying to write a "monitor" class to determine if a UNC path is available. I need the monitor to not block the main thread and to also event when the UNC is toggled UP/DOWN so that I can respond to that event.

I'm looking for:

Best practice suggestions
Am I doing this properly? Is there a more efficient way?
Will there be threads left alive? will I eat into the pool until it starves?
Other comments suggestions related to this code or programming context

public class NetworkPathMonitor
{
    public event EventHandler<PathAvailabilityChangedArgs> PathAvailabilityChanged;
    public event EventHandler Started;
    public event EventHandler Stopping;
    public event EventHandler Stopped;
    public event EventHandler CheckingStatus;

    protected virtual void OnStopping(object sender, EventArgs e)
    {
        EventHandler handler = Stopping;
        if (handler != null)
            handler(sender, e);
    }
    protected virtual void OnCheckingStatus(object sender, EventArgs e)
    {
        EventHandler handler = CheckingStatus;
        if (handler != null)
            handler(sender, e);
    }
    protected virtual void OnStopped(object sender, EventArgs e)
    {
        EventHandler handler = Stopped;
        if (handler != null)
            handler(sender, e);
    }
    protected virtual void OnStarted(object sender, EventArgs e)
    {
        EventHandler handler = Started;
        if (handler != null)
            handler(sender, e);
    }
    protected virtual void OnPathAvailabilityChanged(object sender, PathAvailabilityChangedArgs e)
    {
        EventHandler<PathAvailabilityChangedArgs> handler = PathAvailabilityChanged;
        if (handler != null)
            handler(sender, e);
    }

    private PathState CurrentState { get; set; }

    private CancellationTokenSource TokenSource { get; set; }

    private AutoResetEvent IsStopping { get; set; }

    public string PathToMonitor { get; set; }

    public int Interval { get; set; }

    public NetworkPathMonitor(string pathToMonitor, int interval, PathState expectedState = PathState.Up)
    {
        this.CurrentState = expectedState;
        this.Interval = interval;
        this.PathToMonitor = pathToMonitor;
    }

    public void Stop()
    {
        OnStopping(this, EventArgs.Empty);
        TokenSource.Cancel();
    }

    public void Start()
    {

        IsStopping = new AutoResetEvent(false);
        TokenSource = new CancellationTokenSource();

        var t = Task.Factory.StartNew(() =>
        {
            OnStarted(this, EventArgs.Empty);
            TimeSpan waitInterval = TimeSpan.FromMilliseconds(Interval);
            while (!IsStopping.WaitOne(waitInterval))
            {
                if (this.TokenSource.IsCancellationRequested)
                {
                    //Is this how to properly stop the signal?
                    IsStopping.Set();
                    IsStopping.Dispose();
                    OnStopped(this, EventArgs.Empty);
                    break;
                }

                OnCheckingStatus(this, EventArgs.Empty);
                CheckPathStatus();
            }
        }, TokenSource.Token);

    }

    private void CheckPathStatus()
    {
        //this is synchronous. We just have to wait for it to timeout.
        var currentState = Directory.Exists(PathToMonitor) ? PathState.Up : PathState.Down;

        var shouldEvent = currentState != CurrentState;
        CurrentState = currentState;

        if (shouldEvent)
        {
            OnPathAvailabilityChanged(this, new PathAvailabilityChangedArgs() { Path = PathToMonitor, PathState = CurrentState });
        }

    }
}

public enum PathState
{
    Up,
    Down
}
public class PathAvailabilityChangedArgs : EventArgs
{
    public string Path { get; set; }
    public PathState PathState { get; set; }
    public PathAvailabilityChangedArgs() { }
    public PathAvailabilityChangedArgs(string path)
    {
        Path = path;
    }
}


texts:
So this is my first time going over a pretty big nested object, was posting this up to see how I can possibly cut this down. (Some fears I have would be, I currently know the extent of the nesting (4) but could be more in the future. Which I'm not accounting for. )

The code below sits within a function:

if (itemLi.items) {

var ul = new Element('ul').inject(el)
for (var i = 0; i < itemLi.items.length; i++) {
    var li = new Element('li').inject(ul);
    lastPgNum = itemLi.items[i].page;
    //subItem = new Element('a', {'href': itemLi.items[i].href,'html': itemLi.items[i].title}).inject(li);
    if (itemLi.items[i].items) {

        subItem = new Element('span', {
            'html': itemLi.items[i].title,
            'class': 'pgTitle'
        }).inject(li);
        var ulsub = new Element('ul', {
            'class': 'here1'
        }).inject(ul)

        for (var b = 0; b < itemLi.items[i].items.length; b++) {
            var liSub = new Element('li').inject(ulsub);
            lastPgNum = itemLi.items[i].items[b].page;
            countSubSubs++;

            if (itemLi.items[i].items[b].items) {
                subItem = new Element('span', {
                    'html': itemLi.items[i].items[b].title,
                    'class': 'pgTitle'
                }).inject(liSub);
                var ulsubTwo = new Element('ul', {
                    'class': 'here2'
                }).inject(ulsub)
                for (var c = 0; c < itemLi.items[i].items[b].items.length; c++) {
                    var li = new Element('li').inject(ulsubTwo);
                    lastPgNum = itemLi.items[i].items[b].items[c].page;
                    countSubSubsSub++;
                    subSubItem = new Element('a', {
                        'href': itemLi.items[i].items[b].items[c].href,
                        'html': itemLi.items[i].items[b].items[c].title
                    }).inject(li);
                };
                var startPgSub = new Element('span', {
                    'class': 'pgNumbers',
                    'html': 'pg ' + (lastPgNum - (countSubSubs + countSubSubs + i + 1)) + '-' + lastPgNum
                }).inject(name);
            } else {

                var startPgSub = new Element('span', {
                    'class': 'pgNumbers',
                    'html': 'pg ' + (lastPgNum - (countSubSubs)) + '-' + lastPgNum
                }).inject(name);
                subItem = new Element('a', {
                    'href': itemLi.items[i].items[b].href,
                    'html': itemLi.items[i].items[b].title
                }).inject(liSub);
            }

        };
    } else {

        subItem = new Element('a', {
            'href': itemLi.items[i].href,
            'html': itemLi.items[i].title
        }).inject(li);

        if ((lastPgNum - i) == lastPgNum) {
            startPg = new Element('span', {
                'class': 'pgNumbers',
                'html': 'pg ' + lastPgNum
            }).inject(name);
        } else {
            startPg = new Element('span', {
                'class': 'pgNumbers',
                'html': 'pg ' + (lastPgNum - i) + '-' + lastPgNum
            }).inject(name);
        }

    }
};

};


texts:
I want to refactor my code but I can't find and much simplier one. Can you please suggest on how to refactor the code below without using a loop? maybe using only array functions? TIA

<?php
$week_no = array(2,3,4);
$days = array('TU', 'WE', 'TH');

foreach ($week_no as $n) {
  foreach ($days as $d) {
   $out[] = $n . $d;
  }
}

var_dump($out); // array('2TU', '2WE', '2TH','3TU', '3WE', '3TH, '4TU', '4WE', '4TH)
?>


texts:
The following code simply prompts the user to choose from a menu, and then it displays the choice made by that user.
It only accepts input consisting of a single digit between 1 and 6, inclusive.  Anything else will be considered as being invalid.
Questions

While it considers Ctrl-D as an invalid choice, should it be handled differently?  If so, how?

It takes user input as an int.  Would you suggest taking it as a string instead, and then use either stoi or stringstream to convert it to an int?

Can it be re-written in a more elegant and concise way?

Do you see any potential issues?

Any comments?

Source Code
#include <iostream>
#include <limits>

int getChoice()
{
    std::cout << "Main Menu\n"
        << "-------------------\n"
        << "1. Add record\n"
        << "2. Edit record\n"
        << "3. Delete record\n"
        << "4. View record\n"
        << "5. View all records\n"
        << "6. Exit\n";

    bool isValid;
    int choice;

    do
    {
        isValid = true;
        std::cout << "Enter choice: ";
        std::cin >> choice;

        if (std::cin.fail())
        {
            if (std::cin.eof())
            {
                std::cin.clear();
            }
            else
            {
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
            isValid = false;
        }
        else
        {
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            if (std::cin.gcount() > 1)
            {
                isValid = false;
            }
            else if (choice < 1 || choice > 6)
            {
                isValid = false;
            }
        }
        if (!isValid)
        {
            std::cout << "Invalid choice\n";
        }
    } while (!isValid);

    return choice;
}

int main()
{
    int choice;
    choice = getChoice();

    std::cout << "User chose option " << choice << std::endl;

    return 0;
}

Input and Results
Main Menu
-------------------
1. Add record
2. Edit record
3. Delete record
4. View record
5. View all records
6. Exit
Enter choice: x
Invalid choice
Enter choice: 8
Invalid choice
Enter choice: 2x
Invalid choice
Enter choice: x2
Invalid choice
Enter choice: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Invalid choice
Enter choice: 888888888888888888888888888888888888888888888888888888888888888888888888888
Invalid choice
Enter choice: Invalid choice // Ctrl-D entered here
Enter choice: ^Z
[1]+  Stopped                 ./getchoice_cpp


texts: Evaluation function for minimax/alphabeta algorithm for Tic Tac Toe AI

texts:
I am trying to develop an optimal evaluation function to use in minimax/alpha-beta algorithm for developing tic-tac-toe AI.

I am counting number of circles/crosses in a row/column/diagonal with empty space behind it (with three-in-a-row, there is no empty space). Based on number of symbols in such line, I multiply the separate scores with \$10^{\text{counter} - 1}\$, which results in \$1,10 \text{ or } 100\$ points. I am sure much can be improved, because optimal solution is rarely found and I am having problems using this function in alphabeta algorithm
My question is - How can this function be improved? Small pieces of code and suggestions appreciated.
My code:

private int h(int[][] field, int depth, int player) //final score of the node
        {
            if (win(field, 1)) //if human won
                return -1000; //very bad for MAX=computer
            if (win(field, 0)) //if computer won
                return 1000;

            int heuristics = individualScore(field, 0) - individualScore(field, 1);
            return heuristics;
        }

private int individualScore(int[][] field, int player)
        {

            int sum = 0;
            int otherPlayer = -1;
            if (player == 0) //if computer is the current player
                otherPlayer = 1; //other player is human
            else
                otherPlayer = 0;//Vice versa
            for (int i = 0; i < 3; i++) // rows
            {
                int counter = 0;
                bool rowAvailable = true;
                for (int l = 0; l < 3; l++)
                {
                    if (field[i][l] == player)
                        counter++;
                    if (field[i][l] == otherPlayer)
                    {
                        rowAvailable = false;
                        break;
                    }
                }
                if (rowAvailable && counter > 0)
                    sum += (int)Math.Pow(10, counter - 1);
            }

            for (int i = 0; i < 3; i++) // columns
            {
                int counter = 0;
                bool columnAvailable = true;
                for (int k = 0; k < 3; k++)
                {
                    if (field[k][i] == player)
                        counter++;
                    if (field[k][i] == otherPlayer)
                    {
                        columnAvailable = false;
                        break;
                    }
                }
                if (columnAvailable && counter > 0)
                    sum += (int)Math.Pow(10, counter - 1);
            }
            int counterD = 0;
            bool diagonalAvailable = true;
            for (int i = 0; i < 3; i++) //diagonals
            {
                if (field[i][i] == player)
                    counterD++;
                if (field[i][i] == otherPlayer)
                {
                    diagonalAvailable = false;
                    break;
                }
            }
            if (diagonalAvailable && counterD > 0)
                sum += (int)Math.Pow(10, counterD - 1);
            counterD = 0;
            diagonalAvailable = true;
            int j = 0;
            for (int i = 2; i >= 0; i--)
            {
                if (field[i][j] == player)
                    counterD++;
                if (field[i][j] == otherPlayer)
                {
                    diagonalAvailable = false;
                    break;
                }
            }
            if (diagonalAvailable && counterD > 0)
                sum += (int)Math.Pow(10, counterD - 1);

            return sum;
        }