texts:
The game works, but I was wondering if anyone could help me with better structure for the code, simplification, or just any other improvements.

from random import randrange

# assigns the amount of turns and starts the program
def Main():
    print "~A game of Scissors, Paper, Rock!~"
    global turns
    turns = raw_input("How many times do you want to play? : ")
    # tests for int input and restarts if not an int
    try:
        turns = int(turns)
        print "\nYou will play", turns, "turn(s) against the computer! \n"
        play()
    except ValueError:
        print "That's not a valid input! Integers only, please! \n"
        Main()

#determines the player's choice and sets the computers choice
def play():
    global options
    options = {1: "Scissors", 2: "Paper", 3: "Rock"}
    global turns
# loops for different choices, and calls the comparison function
    while turns > 0:
        try:
            global pchoice
            pchoice = int(raw_input("Choose one! \n <1> Scissors \n <2> Paper \n <3> Rock \n"))
            global cchoice
            cchoice = randrange(1,4)
            comparison()
        except KeyError:
            print "an invalid input! Please try again. \n"
            play()
        turns -= 1

# compares player's choice with the computer's and returns a tie, win, or loss
def comparison():
    print "You chose:", options[pchoice], "and the computer chose:", options[cchoice]
    if int(pchoice) == cchoice:
        print "A tie! \n"
    elif pchoice == 1 and cchoice == 3 or pchoice == 2 and cchoice == 1 or pchoice == 3 and cchoice == 2:
        print "You lose! \n"
    else:
        print "You win! \n"

Main()


texts:
I'm new to PHP security and have made this login file:

<?php
header('Content-type: application/javascript');

$hostname_localhost = "";
$database_localhost = "";
$username_localhost = "";
$password_localhost = "";

$salt1 = "";
$salt2 = "";

$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$username = clean($_POST['username']);
$password = $_POST['password'];

$sha1_password = sha1($salt1.$password.$salt2);

$query_search = "select * from users where username = '".$username."' AND     password = '".$sha1_password. "'";

$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);

if($rows == 0) {
    echo "No Such User Found";
} else {
    $result = mysqli_query($localhost,"select * from users where username =     '".$username."'");

    while ($row = mysqli_fetch_array($result)) {
        echo $row['id'];
    }

}

function clean($string){
    if (get_magic_quotes_gpc()) $string = stripslashes($string);
    return mysql_real_escape_string($string);
}

?>

You'll probably all find a million things wrong with it but I need all the help I can get!


texts:
I have an input like this:

x = '415,252,428,233,428,214,394,207,383,205,390,195'

And I want to end up with this

y = [(415,252),(428,233),(428,214),(394,207),(383,205),(390,195)]

The closes I got is

tmp = [int(i) for i in x.split(',')]
y = zip(tmp[::2], tmp[1::2])

How do I get rid of the intermediate list? I need alternative to [::2] that could be used on a generator.


texts: Setting the default display name for my model

texts:
I have a method in my Ruby code that sets the default name for my model. Rubocop complains that Assignment Branch Condition Size is too high, 21.24/15. How can I improve this?

def set_default_display_name
   return unless display_name.blank?
   count = user.credentials.where(type: type).count
   if count == 0
     self.display_name = name
   elsif user.credentials.where(display_name: name).count == 0
     self.display_name = name
   else
     self.display_name = "#{name} #{count + 1}"
   end
end


texts: Multiple null Checks or try/catch NullPointerException

texts:
There is A LOT of information online stating that you should NEVER catch a NullPointerException.  Generally I agree, but I am wondering about this one case.

I have inherited code that requires me to access data that I need in the following way

context.getGrandParent().getParent().getChild().isRequired()

There is no guarantee that any of the objects in this hierarchy will not be null.
 I have to enter a block if isRequired() returns true.  First, and what I initially wrote, with null checks:

if(context != null
   && context.getGrandParent() != null
   && context.getGrandParent().getParent() != null
   && context.getGrandParent().getParent().getChild() != null
   && context.getGrandParent().getParent().getChild().isRequired()
){
   // continue with business logic
} else {
   LOG.error("Unable to determine if processing is required.");
}
// continue with other inherited code

Setting aside that I could refactor this, perhaps for readability, wouldn't it make more sense to do the following?

boolean isRequired = false;
try {
   isRequired = context.getGrandParent().getParent().getChild().isRequired();
} catch (NullPointerException npe) {
   LOG.error("Unable to determine if processing is required.");
}

if(isRequired){
   // continue with business logic
}
// continue with other inherited code


texts:
I have a list of posts. I need to generate it each one by one. For generation of each post, I need to know about other posts. However, I want to make the current post marked.

def generate(posts):
    print(posts) #faking generation

def marked_active_post(orig_posts, active_index):
    posts_view = orig_posts.copy()
    active_post = orig_posts[active_index]
    active_post = orig_posts[active_index].copy()
    active_post['active?'] = True
    posts_view[active_index] = active_post
    return posts_view

posts = [{'foo':'bar'}, {'aaa':'bbb'}]
for i in range(0, len(posts)):
    generate(marked_active_post(posts, i))

How can I do better?


texts: Calculating linux based octal file permission

texts:
I'm applying for a mid level devloper position.

In order to  progress to 2nd interview, you need to pass a technical test.
One of the questions was to write a function to work out linux based octal file permissions.

How would you guys improve it, and why?

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

public class ReadWriteExecute
{
    public static int CalculatePermissionSum(string permString)
    {
        int octalPerm = 0;

        foreach (char permission in permString.ToArray())
        {
            switch (permission)
            {
                case 'r':
                    octalPerm += 4;
                    break;
                case 'w':
                    octalPerm += 2;
                    break;
                case 'x':
                    octalPerm += 1;
                    break;
                case '-':
                    octalPerm += 0;
                    break;
            }
        }
        return octalPerm;
    }

    public static string SymbolicToOctal(string permString)
    {
        string octalPerm = string.Empty;
        for(int x=0; x<=6;x+=3)
        {

            octalPerm += CalculatePermissionSum(new string(permString.Skip(x).Take(3).ToArray())).ToString();
        }
        return octalPerm;
    }

    public static void Main(string[] args)
    {
        // Should write 752
        Console.WriteLine(ReadWriteExecute.SymbolicToOctal("rwx-x--r-"));
    }
}


texts:
As part of my training, I implemented a dataset class in C++ that allows me to create synthetic datasets to get more familiar with features that C++ offers such as object oriented programming.
This implementation uses a simple method to create two intertwined spirals as shown in the following image.

The output looks as follows:
x y label
-3.85616 -0.987058 0
1.16 4.6764 0
2.66279 2.13692 1
-0.643551 3.81989 0
-0.252046 -0.888411 0

Please be as hard as possible with this implementation and give me constructive feedback.
I would appreciate advice especially in the following areas:

Code style (readability, naming conventions, etc...)
Class design
Efficiency (how to avoid unnecessary complexity)
Reinventing the wheel (does the STL offer functionality that I should use?)

main.cpp
#include <iostream>
#include <vector>
#include "data.hpp"

int main() {
    unsigned int n_points = 3000;
    Data data (n_points);
    std::vector<Point> d;
    d = data.get();

    for (std::vector<Point>::iterator it = d.begin(); it != d.end(); ++it) {
        std::cout << it->x << " " << it->y << " " << it->label << std::endl;
    }
    return 0;
}

data.hpp
#ifndef DATA_H
#define DATA_H

#include <vector>
#include <cmath>
#include "util.hpp"

class Data {
    public:
        Data (unsigned int);
        unsigned int n_samples;
        unsigned int n_dims = 2;
        unsigned int n_classes = 2;
        std::vector<Point> get();

    private:
        Random random;
        std::vector<Point> data;
        std::vector<Point> generate_data();
};

Data::Data (unsigned int _n_samples) {
    n_samples = _n_samples;
}

std::vector<Point> Data::generate_data() {
    std::vector<Point> data(n_samples);
    std::vector<Point>::iterator it;

    double noise = 1.0;
    double spread = 4.0;
    for (it = data.begin(); it != data.end(); ++it) {
        double r = 3.14 * spread * random.rand();
        double r1 = -cos(r) * r + noise * random.rand();
        double r2 = sin(r) * r + noise * random.rand();
        if (random.rand() < 0.5) {
            it->x = r1;
            it->y = r2;
            it->label = 1;
        } else {
            it->x = -r1;
            it->y = -r2;
            it->label = 0;
        }
    }

    return data;
}

std::vector<Point> Data::get() {
    std::vector<Point> data(n_samples);
    std::vector<Point>::iterator it;
    data = generate_data();
    return data;
}

#endif /* DATA_H */

util.hpp
#ifndef UTIL_H
#define UTIL_H

#include <cstdlib>
#include <ctime>

struct Point {
    double x;
    double y;
    unsigned int label;
};

class Random {
    public:
        Random ();
        double rand();
};

Random::Random () {
    std::srand(static_cast<unsigned int>(std::time(nullptr)));
}

double Random::rand() {
    return static_cast<double> (std::rand()) / static_cast<double> (RAND_MAX + 1U);
}

#endif /* UTIL_H */


texts: Non-testable class wrapping Java Properties with basic logic

texts:
I have written a simple java.util.Properties wrapping class. Unfortunately, in my opinion, it isn't testable at the moment and I don't have any idea how to improve it. I could use PowerMockito to change properties after loading, or add a setter for them, or inject some class that provides properties, but I don't like any of that. I would like to avoid exposing properties by making it public or by getter/setter.

My application details:

Spring boot
my class is injected by @Bean mechanic
CONF_FILE_NAME contains key=value formatted properies with names same as in Keys subclass.

I would like to unit-test logic in this class (both public method) without relying on values in file.

PropertiesManager.java:

package pl.propertiesdemo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

public class PropertiesManager
{
    private final String secretToken = "SECRET";

    public final class Keys
    {
        public final static String KEY1 = "KEY1";
        public final static String KEY2 = "KEY2";
    }

    private final String CONF_FILE_NAME = "conf_file.conf";

    private Properties properties;

    public PropertiesManager() throws IOException
    {
        properties = new Properties();
        InputStream in = new FileInputStream(CONF_FILE_NAME);
        properties.load(in);
    }

    public String getProperty(String name)
    {
        String property = properties.getProperty(name);
        if (property == null) {
            System.out.println("Property " + name + " not found in properties file");
        }
        return property;
    }

    public HashMap<String, String> getAllPublicProperties()
    {
        HashMap<String, String> map = new HashMap<>();

        properties.keySet().stream().map(f -> (String)f).filter(f -> !f.contains(secretToken)).forEach(f -> map.put(f, properties.getProperty(f)));

        return map;
    }
}

PropertiesDemo.java: (main method and usage of both public methods)

package pl.propertiesdemo;

import java.io.IOException;

public class PropertiesDemo
{
    public static void main(String[] args) throws IOException
    {
        PropertiesManager manager = new PropertiesManager();
        System.out.println(manager.getProperty(PropertiesManager.Keys.KEY1));
        System.out.println(manager.getAllPublicProperties());
    }
}

conf_file_conf: (file loaded by PropertyManager)

KEY1=value_of_key1
KEY2=value_of_key2

PropertiesManager.java: (JUnit test I have so far)

package pl.propertiesdemo;

import java.io.IOException;
import java.util.HashMap;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class PropertiesManagerTest extends TestCase
{
    public PropertiesManagerTest(String testName)
    {
        super(testName);
    }

    public static Test suite()
    {
        return new TestSuite(PropertiesManagerTest.class);
    }

    private PropertiesManager getPropertiesManager()
    {
        PropertiesManager prop = null;
        try {
            prop = new PropertiesManager();
        } catch (IOException ioe) {
            fail();
        }
        return prop;
    }

    public void testGetProperty()
    {
        PropertiesManager prop = getPropertiesManager();
        String value = prop.getProperty(PropertiesManager.Keys.KEY1);
        assertEquals("value_of_key1", value);
    }

    public void testGetAllProperties()
    {
        PropertiesManager prop = getPropertiesManager();
        HashMap<String,String> values = prop.getAllPublicProperties();

        assertTrue(values.size() > 0);
        assertEquals(0, values.keySet().stream().filter(k -> k.contains("SECRET")).count());
    }
}

I don't like my tests, because right now they are dependant of value in real configuration file.


texts:
Can you please take a look at my code and improve it (if necessary)?

http://jsfiddle.net/U6R6E/

Javascript (with jQuery)

function random(min, max) {
    return min + parseInt(Math.random() * (max - min + 1), 10);
}
function generatePassword() {
    var length = parseInt($('#pwLength').val(), 10),
        charset = $('#pwChars').val(),
        password = "";
    while (length > 0) {
        length -= 1;
        console.log(length);
        password += charset[random(0, charset.length - 1)];
    }
    return password;
}
function getNewPassword() {
    $('#pwResult').html(generatePassword());
}
$(document).ready(function () {
    getNewPassword();
    $('#getNewPw').click(function () {
        getNewPassword();
        return false;
    });
});

HTML

    <input type="text" id="pwChars" value="AaBbCcDdEeFfGgHhiJjKkLMmNnoPpQqRrSsTtUuVvWwXxYyZz23456789!?$%#&@+-*=_.,:;()" />

<input type="text" id="pwLength" value="10" />

<button id="getNewPw">New</button>


texts: Output string length and classical Fibonacci sequence in a web page

texts:
I wrote a JavaScript and XHTML webpage. I think the format of the output is not better or the validation process is not as it is supposed to be. How can I improve the code? How can I make it more efficient?

There are two text boxes. First, it takes a sentence and returns the length. Second, it takes an integer and returns that number of classical Fibonacci numbers.

<!DOCTYPE html>

<titile></title>

<button id="lenClick" onclick="getStrLen()">String Length</button>
Enter a sentence or multiple ones: <input type="text" id="textbox1"></input>

Number of characters in this sentence is:

<input type="text" id="fibText"></input>
<button id="fibClick" onclick="outFib()">Generate Fibonacci Sequence</button>


texts: Using extdebug to display where a function was defined

texts:
I wrote a tool similar to which that would display the file and line number where a function was defined. Is there a way I can do the same for aliases? Also, any comments or critiques on the code?

function where() {
  cmd="$1"
  info=$(command -V "$cmd" | head -n 1)
  #rc="$PIPESTATUS[0]"

  case $info in
    *function*)
      shopt | grep -q extdebug
      extdebug=$?
      ! ((extdebug)) && shopt -s extdebug
      declare -F "$cmd"
      ! ((extdebug)) && shopt -u extdebug
      ;;
    *) echo "$info" ;;
  esac
}

Output looks like:

$ where ls ; where l ; where bad ; where where
ls is /bin/ls
l is aliased to `ls -Al --color=auto'
bash: command: bad: not found

where 6 /home/harleypig/projects/dotfiles/.bash_sources.d/tools

I realized, even though it was working, I was capturing the output of the shopt|grep command, not the exit status.


texts:
This program was inspired by a Code Golf challenge that I wanted to do properly. It simply converts oOo to Brainfuck and vice-versa.

The oOo language basically uses UPPER / lower case information in groups of 3 to encode a Brainfuck program. For further info see the Esolang wiki page of oOo.

The main problem with this code is that I feel like there is repetition in the encode / decode functions because they seem to contain similar type of information. I am also worried that I did not declare any types as Haskell is type-centric.

import qualified Data.Char as C
import qualified Data.List.Split as L
import qualified Test.QuickCheck as Q
import qualified Test.HUnit as T

oToBrain :: String -> String
oToBrain = map chunkToBrain . L.chunksOf 3 . filter isAlphabetic

brainToO :: String -> String
brainToO = concatMap singleCharToO

singleCharToO :: Char -> String
singleCharToO x = case x of
  '>' -> "ooo"
  '<' -> "ooO"
  '[' -> "oOo"
  ']' -> "oOO"
  '-' -> "Ooo"
  '+' -> "OoO"
  '.' -> "OOo"
  ',' -> "OOO"
  _ -> ""

isAlphabetic :: Char -> Bool
isAlphabetic = (`elem` ['a'..'z']) . C.toLower

chunkToBrain :: String -> Char
chunkToBrain [a, b, c] = case  (C.isUpper a, C.isUpper b, C.isUpper c) of
  (False, False, False) -> '>'
  (False, False, True ) -> '<'
  (False, True,  False) -> '['
  (False, True,  True ) -> ']'
  (True,  False, False) -> '-'
  (True,  False, True ) -> '+'
  (True,  True,  False) -> '.'
  (True,  True,  True ) -> ','
chunkToBrain _ = error "`oOo` chunks can only be 3 chars long"

brainChars :: Q.Gen String
brainChars = Q.listOf (Q.elements "<>[]+-.,")

doubleConversionIsId :: Q.Property
doubleConversionIsId = Q.forAll brainChars $ \x -> x == (oToBrain . brainToO) x

main = do
  T.assertEqual "Wiki example" ",[>,]<[.<]+" (oToBrain "PROgRam reVERsES giVeN iNPut sEqUENcE")
  Q.quickCheck doubleConversionIsId


texts: Modeling and computing intersection between continuous intervals

texts:
I created the class ContinuousDimensionInterval, to model an interval of a continuous dimension interval, presented below.

namespace Minotaur.Math.Dimensions {
    using System;

    public sealed class ContinuousDimensionInterval: IDimensionInterval {

        public int DimensionIndex { get; }
        public readonly DimensionBound Start;
        public readonly DimensionBound End;

        public ContinuousDimensionInterval(
            int dimensionIndex,
            DimensionBound start,
            DimensionBound end
            ) {
            if (dimensionIndex < 0)
                throw new ArgumentOutOfRangeException(nameof(dimensionIndex) + " must be >= 0.");

            DimensionIndex = dimensionIndex;
            Start = start;
            End = end;
        }

        public bool Contains(float value) {
            if (float.IsNaN(value))
                throw new ArgumentOutOfRangeException(nameof(value));

            if (value > Start.Value && value < End.Value)
                return true;
            if (Start.IsInclusive && value == Start.Value)
                return true;
            if (End.IsInclusive && value == End.Value)
                return true;

            return false;
        }
    }
}

I felt the need to create a struct, DimensionBound, to represent the bounds of an interval, since they may be inclusive or exclusive.

namespace Minotaur.Math.Dimensions {
    using System;

    public readonly struct DimensionBound {
        public readonly float Value;
        public readonly bool IsInclusive;

        public DimensionBound(float value, bool isInclusive) {
            if (float.IsNaN(value))
                throw new ArgumentOutOfRangeException(nameof(value) + " can't be NaN.");

            Value = value;
            IsInclusive = isInclusive;
        }
    }
}

I'd like to receive some feedback on the implementation of both classes.

Should I disallow the construction of DimensionBound with
value=infinity and inclusive=true?
Is my decision to make DimensionBound a struct reasonable? It feels struct-like to me...
Should DimensionBound implement IEquatable<DimensionBound>?
Am I over-engineering the whole thing by creating a class to represent the bounds of an interval?

Here an example of how the class is used:

private static bool IntersectsContinuous(ContinuousDimensionInterval lhs, ContinuousDimensionInterval rhs) {
    // @Improve performance?
    // @Verify correctness
    var aStart= lhs.Start;
    var aEnd = lhs.End;

    var bStart = rhs.Start;
    var bEnd = rhs.End;

    if (aStart.Value > bEnd.Value)
        return false;
    if (aStart.Value == bEnd.Value)
        return aStart.IsInclusive && bEnd.IsInclusive;

    if (bStart.Value > aEnd.Value)
        return false;
    if (bStart.Value == aEnd.Value)
        return bStart.IsInclusive && aEnd.IsInclusive;

    return true;
}


texts: Relative frequency of words in tree of documents

texts:
I have a tree structure where at every node there is a list of documents (document length can vary from 5 to 500), and each document contains a number of words.

I want to calculate relative frequency of each word at a particular node by taking the ratio between the percentage of time that word appears in all the documents at a given node to percentage of time it appears at its siblings documents combined.

I have written python code which runs for the entire node in that tree and calculates relative frequency of each word and stores it in the form of a dictionary ratio_dict at the same node. But the code is very slow. In total there are around 200 nodes in tree and it has taken 2 hours to run for only 2 nodes. I am not sure if there is a way to optimize this code. I don't think that python should take this long for this task but maybe it is a problem with python or my code.

Below is my code hopefully it is readable and any suggestions on how to make this faster is greatly appreciated:

def word_frequency(node):
    next_node = []
    wordSet = set()
    lis = []
    occurlist = []
    child_nodes = node.children
    for child in child_nodes:
        next_node.append(child)
        lis += child.documents
    wordSet = set([word for words in lis for word in words])
    occurDict = {word:0 for word in wordSet}
    for i, child in enumerate(child_nodes):
        occurlist.append(copy.deepcopy(occurDict))
        docs = []
        for sibs in child.siblings:
            docs += sibs.documents
        ratio_dict = {}
        for doc in child.documents:
            for word in wordSet:
                if word in doc:
                    occurlist[i][word]+=1
            for word in doc:
                X = occurlist[i][word]/float(len(child.documents))
                numerator = sum(map(lambda x: word in x, docs))
                Y = numerator/float(len(docs))
                if X==0:
                    ratio_dict[word] = 0
                elif Y==0:
                    ratio_dict[word] = 1000000*X
                elif X/float(Y) > 1:
                    ratio_dict[word] = X/float(Y)
                elif X/float(Y) < 1:
                    ratio_dict[word] = -1*Y/float(X)
        child.ratio_dict = ratio_dict
        print child.name
    if next_node:
        for nn in next_node:
            if nn.update is False:
                word_frequency(nn)

word_frequency(Finance)

Finance here is the root node.


texts: Reimplementation of Underscore _.throttle

texts:
I've built a function that mimics _.throttle (returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds).

I would like to know what you think about my code, especially if the code is clean and essential and if i'm managing arguments correctly.

function throttle(func, interval){
   var toExecute = true,
       queue = false;
   var result;
   return function doThrottle(){
       var args = Array.prototype.slice.call(arguments);

       if(toExecute){
           toExecute = false;
           queue = false;
           result = func.apply(null, args);
           startTimer(interval);
       } else {
           queue = true;
       }

       function startTimer(interval){
           setTimeout(function(){
               toExecute = true;
               if(queue){
                   result = func.apply(null, args);
               }
            }, interval);
       }

       return result;

   }
}


texts:
I implemented k-armed bandit problem in C#, MATLAB and Python. C# and Matlab code run fairly fast (With same settings of T = 2000 and nRun = 1000 the elapsed time is about 6sec). However, the Python version is ten times slower and takes about 60 seconds to complete. I am a beginner in Python but I guess it should be faster than this. I appreciate any tips to speed up this code.

import numpy as np
import matplotlib.pyplot as plt
import time

t1 = time.time()

plt.close('all')

nActions = 10
# np.random.seed(0)
sigma = np.ones(nActions)
mu = np.array([-0.4677,-0.1249,1.4790,-0.8608,0.7847,0.3086,-0.2339,-1.0570,-0.2841,-0.0867])

def Reward(action:int, mu:np.ndarray, sigma:np.ndarray):
  return mu[action] + sigma[action]*np.random.normal()

def EpsGreedyPolicy(Q,eps):
  p = np.random.rand()
  if p<eps:
    nAction = np.size(Q)
    return np.random.randint(nAction)
  else:
    return GreedyPolicy(Q)

def GreedyPolicy(Q):
   A = np.nonzero(Q == np.max(Q)) # A is a tuple
   n = np.size(A)
   if n == 1:
     return A[0]
   else:
     j = np.random.randint(n)
     return A[0][j] # Note A here is a tuple not array

# Reinforcement Learning

BestAction = np.argmax(mu)

T = 2000
nRun = 1000;

arrA = np.zeros((T,nRun))
arrR = np.zeros((T,nRun))

Q0 = 0 # Initial values

for j in range(nRun):
  TotalReward = np.zeros((nActions))
  Counter = np.zeros((nActions))

  for t in range(T):

    # Calculate action values
    Q = TotalReward/Counter
    Q[np.isnan(Q)] = Q0

    # Apply Policy
    a = EpsGreedyPolicy(Q,0.01)

    # Commit Action
    r = Reward(a, mu, sigma)

    # Update relevant stats
    Counter[a] += 1
    TotalReward[a] += r

    # Save results
    arrA[t][j] = a
    arrR[t][j] = r

  #print('End of Run ', j)

  print("end of run ",j)
  # end of main loop

# Plot Results
BestActionSelected = (arrA == BestAction)
BestActionSelectedMean = np.average(BestActionSelected, axis=1)

plt.figure(2,figsize=(10,10))

plt.subplot(2,1,1)
plot1 = plt.plot(BestActionSelectedMean)
plt.title('best action selection')

plt.subplot(2,1,2)
plot2 = plt.plot(np.average(arrR, axis=1))
plt.title('average reward')

plt.show()

t2 = time.time()

print(t2-t1)


texts: Sorting an assortment of strings and integers together, while keeping them separate

texts:
I put a solution to this coding problem together. The problem is this:

Create a function that takes an array, finds the most often repeated element(s) within it and returns it/them in an array. The function should work for both integers and strings mixed together within the input list (e.g. [1, 1, "a"]).
If there is a tie for highest occurrence, return both.
Separate integers and strings in the result.
If returning multiple elements, sort result alphabetically with numbers coming before strings.

This is the solution I came up with:
def highest_occurrence(arr)

  # Separate the unique values into individual sub-arrays
  x = rand(2**32).to_s(16)
  result = arr.sort do |a, b|
    a = a.to_s + x if a.is_a?(Numeric)
    b = b.to_s + x if b.is_a?(Numeric)
    a <=> b
  end.chunk_while {|a, b| a == b }.to_a

  # Get an array of all of the individual values with the max size,
  # Sort them by integers first, strings second
  result = result.select do |a2|
    a2.size == result.max_by(&:size).size
  end.map(&:uniq).flatten.sort_by { |v| v.class.to_s }

end

It passes these tests:
p highest_occurrence(["a","a","b","b"]) == ["a","b"]
p highest_occurrence([1,"a","b","b"]) == ["b"]
p highest_occurrence([1,2,2,3,3,3,4,4,4,4]) == [4]
p highest_occurrence(["ab","ab","b"]) == ["ab"]
p highest_occurrence(["ab","ab","b","bb","b"]) == ["ab","b"]
p highest_occurrence([3,3,3,4,4,4,4,2,3,6,7,6,7,6,7,6,"a","a","a","a"]) == [3,4,6,"a"]
p highest_occurrence([2,2,"2","2",4,4]) == [2,4,"2"]

I'd like to know whether there are better ways to solve some of the specific problems in this exercise. In particular, the requirement to sort strings and integers together without being able to convert the integers to strings in the sort block was an interesting one. I managed this by appending a random hex value (the same value) to each integer during the sort process. This seems a bit hackish, and I have the feeling it could be improved upon.
I would also appreciate any other suggestions for how to do a cleaner job.


texts: What should I change in my currency converter?

texts:
I wrote a simple currency converter in Python. Right now, my currency
  converter converts using the last available rate or converts using a
  specific date.

Looking for:

I'd appreciate any tips about how I can improve my little script.
What new features would be nice to add to my project?

Many thanks!

PS. I'm very sorry for my bad English, I'm not a native speaker.

from currency_converter import CurrencyConverter
from datetime import date
from colorama import Fore
import datetime

class CC():
    def __init__(self):
        self.features = ["1. Convert using the last available rate.", "2.
Convert using specific dates."]
        print("")
        print(Fore.GREEN + "-" * 76)
        print("")
        for x in self.features:
            print(x)
        print("")
        self.select = input("Select a feature: ")
        print("")
        print(Fore.GREEN + "-" * 76)
        print("")
        self.amount = input("Amount: ")
        self.c1 = input("Currency1: ")
        self.c2 = input("Currency2: ")
        self.c = CurrencyConverter()
        if self.select == "2":
            self.year = int(input("Year: "))
            self.month = int(input("Month: "))
            self.day = int(input("Day: "))

    def input_process(self):
        if self.select == "1":
            self.d = round(self.c.convert(self.amount, self.c1, self.c2), 2)
            self.x = datetime.datetime.now()
            print(f"{self.amount} {self.c1} is {self.d} {self.c2} on {self.x}")
        elif self.select == "2":
            self.d = round(self.c.convert(self.amount, self.c1, self.c2, date=date(self.year, self.month, self.day)))
            print(f"{self.amount} {self.c1} was {self.d} {self.c2} in {self.year}-{self.month}-{self.day}")

if __name__ == '__main__':
    currencies = ["USD", "SEK", "GBP", "EUR"]
    print(Fore.GREEN + f"This is a Currency converter, the main currencies is {', '.join(currencies)}")
    print("")
    print(Fore.GREEN + "-" * 76)
    print("")
    while True:
        test = CC()
        test.input_process()
        print("")
        print(Fore.GREEN + "-" * 76)
        print("")
        if input("Finished. Do another? (Y/N)\n").lower() != 'y':
            break


texts: Fluent NHibernate, Getting or Creating a new `Tag`

texts:
Edit

The rest of my code utilises the Command/Query seperation pattern. I'll probably move this out into a command and a query but for now I've written this directly in my MVC controller for brevity.

Original

I'm quite new to Fluent NHibernate and its various workings. This code is designed to receive an array of tag names, get those tags from the database and then create any tags that were in the array but not already in the database.

Here's the code I've just written:

private IEnumerable<Tag> GetOrCreateTags(IEnumerable<string> tagNames)
        {

            var tagCriteria = _nHibernateSession.CreateCriteria<Tag>();

            var or = Restrictions.Disjunction();

            foreach (var tagName in tagNames)
            {
                or.Add(Restrictions.Eq("Name", tagName));
            }
            tagCriteria.Add(or);

            var tagsFromTagNames = tagCriteria.List<Tag>();

            foreach (var newTagNeverSeen in tagNames.Except(tagsFromTagNames
                                                           .Select(x => x.Name)))
            {
                using (var transaction = _nHibernateSession.BeginTransaction())
                {
                    var newTag = new Tag
                                     {
                                         Name = newTagNeverSeen,
                                         Enabled = true,
                                         DateCreated = DateTime.Now
                                     };
                    _nHibernateSession.SaveOrUpdate(newTag);
                    tagsFromTagNames.Add(newTag);
                    transaction.Commit();
                }
            }
            return tagsFromTagNames;
        }

How would you improve this? I feel like I'm doing too much here already so I'll likely refactor this to split it out.


texts:
The active column in the database only contains a boolean. The country column contains ISO 3166 A2 codes (2 char). Do you have any advice on improving this class?

<?php
class WebShops {
    private $database;

    public function __construct() {
            $this->database = new Database();
    }

    public function fetchAll() {
            $this->database->query("SELECT * FROM web_shops");
            return $this->database->fetchAll();
    }

    public function fetchActive($option) {
            $this->database->query("SELECT * FROM web_shops WHERE active = :option");
            $this->database->bind(':option', $option);
            return $this->database->fetchAll();
    }

    public function fetchCountry($country) {
            $this->database->query("SELECT * FROM web_shops WHERE country = :country");
            $this->database->bind(':country', $country);
            return $this->database->fetchAll();
    }
}


texts: Calculate sum of digits from a given number using String's slice method

texts:
This is the "classic" algorithm for calculating the sum of digits uses the modulo-operator together with the division-operator. I had the idea of using the slice-method with a negative index for accomplishing the task.

/**
 * Calculates sum of digits from a given number.
 * @param { number } num
 * @return { number }
 * @throws { exception } Throws exception in
 *   case given parameter is not a number.
 * Usage example:
 *   var CheckSum = calcCheckSum(328); // Returns 13
 */
function calcCheckSum(num) {
  var ret = 0;
  var i;

  if (typeof num != 'number' || isNaN(num)) {
    throw new Error('Number expected. { ' +
      typeof num + ' } ' +
      num + ' found.');
  }

  num = num.toString();

  for (i = num.length; i > 0; i--) {
    ret += parseInt(num.slice(i - 1, i));
  }

  return ret;
}

// -- TESTS -----------
for (var i = 0; i < 10; i++) {
  var randomNumber =
    Math.floor(
      Math.random() * (100000 - 100)
    ) + 100;

  var spacer = new Array(6);

  spacer = spacer.join(' ');

  console.log('%s : %s => %s',
               ('0' + i).slice(-2),
               (spacer + randomNumber).slice(-5),
               calcCheckSum(randomNumber)
  );
}

try {
  console.log(calcCheckSum('abcdef'));
} catch (e) {
  console.error(e);
}

try {
  console.log(calcCheckSum(NaN));
} catch (e) {
  console.error(e);
}
// ------------------------------

It seems to work as expected. Nevertheless I would appreciate your opinions: shall I stay with the well-known algorithm or I can use my self-figured out solution?

Moreover, is my parameter validation and my documentation done well? Or do I have to improve something?


texts:
Given sample_size many arrays of length dim. For each index from 1 to dim, i want to give a list of indices, where no sample contained in both indexes 1s. The code is really slow and i want to improve the performance.

# Test set

dim = 10000
sample_size = 1000

from random import *

randBinList = lambda n: [randint(0,1) for b in range(1,n+1)]

samples = [randBinList(dim) for s in xrange(sample_size)]

# Find all variables that are not both 1 in one sample

node_neighbours = {}
for node in xrange(1,dim+1):
    node_neighbours[node] = []
    for node2 in xrange(1,dim+1):
        if node != node2:
            test_failed = False
            for s in samples:
                v1 = s[node-1]
                v2 = s[node2-1]
                if v1 == 1 and v2 == 1:
                    test_failed = True
                    break
            if not test_failed:
                node_neighbours[node].append(node2)
    #print node, ":", node_neighbours[node]


texts:
I would like to find the find the distance transform of a binary image in the fastest way possible without using the scipy function distance_transform_edt(). The image is 256 by 256. The reason I don't want to use scipy is because using it is difficult in Tensorflow. Every time I want to use this package I need to start a new session and this takes a lot of time. So I would like to make a custom function that only utilizes NumPy.

My approach is as follows: Find the coordinated for all the ones and all the zeros in the image. Find the euclidian distance between each of the zero pixels (a) and the one pixels (b) and then the value at each (a) position is the minimum distance to a (b) pixel. I do this for each 0 pixel. The resultant image has the same dimensions as the original binary map. My attempt at doing this is shown below.

I tried to do this as fast as possible using no loops and only vectorization. But my function still can't work as fast as the scipy package can. When I timed the code it looks like the assignment to the variable "a" is taking the longest time. But I do not know if there is a way to speed this up.

If anyone has any other suggestions for different algorithms to solve this problem of distance transforms or can direct me to other implementations in python, it would be very appreciated.

def get_dst_transform_img(og): #og is a numpy array of original image
   ones_loc = np.where(og == 1)
   ones = np.asarray(ones_loc).T # coords of all ones in og
   zeros_loc = np.where(og == 0)
   zeros = np.asarray(zeros_loc).T # coords of all zeros in og

   a = -2 * np.dot(zeros, ones.T)
   b = np.sum(np.square(ones), axis=1)
   c = np.sum(np.square(zeros), axis=1)[:,np.newaxis]
   dists = a + b + c
   dists = np.sqrt(dists.min(axis=1)) # min dist of each zero pixel to one pixel
   x = og.shape[0]
   y = og.shape[1]
   dist_transform = np.zeros((x,y))
   dist_transform[zeros[:,0], zeros[:,1]] = dists

   plt.figure()
   plt.imshow(dist_transform)


texts: Excluding resources from maven dependencies while exporting project to jar

texts:
I have two local maven projects A, and B. B is dependent on A.

A
|- resources/log4j2.xml

B
|- resources/META-INF/log4j.xml
|- Maven Dependencies
    |- A
    |- And other dependencies...

Both A, and B exports the log4j xmls to jar. However, as I only need the B/resources/META-INF/log4j.xml to my final B.jar, I tried to delete the log4j2.xml from A while packing B.jar.

To do the same, I used truezip:remove in B/pom.xml as follows:

<build>
...
<plugins>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>truezip-maven-plugin</artifactId>
        <version>1.1</version>
        <executions>
            <execution>
                <id>remove-a-file-in-sub-archive</id>
                <goals>
                    <goal>remove</goal>
                </goals>
                <phase>verify</phase>
                <configuration>
                    <fileset>
                        <directory>B-jar-with-dependencies.jar</directory>
                        <includes>
                            <include>log4j2.xml</include>
                        </includes>
                    </fileset>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>
...
</build>

Note that this is executed verify state (post packaging) of lifecycle.

Though it is working as expected, I am wondering whether there is any side-effect of this or not. Any light in this regard would be great.


texts:
I am playing with a sort of linked list using C++ classes. I have used a lot of C linked lists (struct based) during C programming course, but there was no behavior. Thus, I am a bit confused about the correct definition of a class containing a pointer to another object of the same class.
Here is the header:

#ifndef CONNECTEDPOINT_H
#define CONNECTEDPOINT_H

#include "vector3d.h"

class ConnectedPoint
{
  using Position = Vector3D<double>;

public:
  ConnectedPoint(unsigned index, const Position& pos);
  ~ConnectedPoint();
  ConnectedPoint(const ConnectedPoint& point);
  ConnectedPoint& operator=(const ConnectedPoint& point);

  void connectTo(const ConnectedPoint& point);

  unsigned index() const {return m_index;}
  const Position& position() const {return m_position;}
  Position& position() {return m_position;}
  ConnectedPoint* getNext() {return next;}

private:
  unsigned m_index;
  Position m_position;
  ConnectedPoint* next;
};
#endif // CONNECTEDPOINT_H

and the implementation file:

#include "connectedpoint.h"
ConnectedPoint::ConnectedPoint(unsigned index, const ConnectedPoint::Position& pos)
  : m_index(index)
  , m_position(pos)
  , next(nullptr)
{

}

ConnectedPoint::~ConnectedPoint()
{
  if(next != nullptr)
  {
    delete next;
    next = nullptr;
  }
}

ConnectedPoint::ConnectedPoint(const ConnectedPoint& point)
  : m_index(point.m_index)
  , m_position(point.m_position)
{
  if(point.next == nullptr)
  {
    this->next = nullptr;
  }
  else
  {
    next = new ConnectedPoint(*(point.next));
  }
}

ConnectedPoint& ConnectedPoint::operator=(const ConnectedPoint& point)
{
  if(this == &point)
  {
    return *this;
  }

  delete next;
  next = nullptr;

  m_index = point.m_index;
  m_position = point.m_position;

  if(point.next != nullptr)
  {
    next = new ConnectedPoint(*(point.next));
  }

  return *this;
}

void ConnectedPoint::connectTo(const ConnectedPoint& point)
{
  next = new ConnectedPoint(point.index(),point.position());
  *(next->next) = *(point.next);
}

Vector3D is just a class template which holds 3 coordinates and allows standard mathematical vector operations. Here its behaviors are not used.

Basically I would like to know:

Is this a proper implementation for such a class? Are there mistakes both in the approach and in the implementation?


texts:
I have this JS that has a lot of redundant functionality, and it works but looks unseemly.

I would love some assistance with making this more DRY (Don't Repeat Yourself):

// This provides character & word counter functionality

counter = function() {
    var body_value = $('#post_body').val();
    var title_value = $('#post_title').val();

    if (body_value.length == 0) {
        $('#wordCountBody').html(0);
        $('#totalCharsBody').html(0);
        return;
    }

    if (title_value.length == 0) {
        $('#wordCountTitle').html(0);
        return;
    }

    var regex = /\s+/gi;
    var wordCountBody = body_value.trim().replace(regex, ' ').split(' ').length;
    var totalCharsBody = body_value.length;
    var wordCountTitle = title_value.trim().replace(regex, ' ').split(' ').length;

    $('#wordCountBody').html(wordCountBody);
    $('#totalCharsBody').html(totalCharsBody);
    $('#wordCountTitle').html(wordCountTitle);
};

$(document).ready(function() {
    $('#count').click(counter);
    $('#post_body').change(counter);
    $('#post_body').keydown(counter);
    $('#post_body').keypress(counter);
    $('#post_body').keyup(counter);
    $('#post_body').blur(counter);
    $('#post_body').focus(counter);
    $('#post_title').change(counter);
    $('#post_title').keydown(counter);
    $('#post_title').keypress(counter);
    $('#post_title').keyup(counter);
    $('#post_title').blur(counter);
    $('#post_title').focus(counter);
});


texts:
I am brand new to dictionaries and coding  and am hoping to get some suggestions on how I should structure my dictionary.

I have a collector number which has meters connected to them. Each of the meters have a meter number and a ert number and would like to store both the meter and ert number. There will be a list of meter reading timestamps and values for each of the meters. Also, I would like to be able to select the values by either the ert number or meter number.  I have attached the current structure I have for the dictionary but was wondering if this was the best way to format the dictionary. Someone had suggested objects but I have never worked with objects before.

{
Dictionary<Int32, Dictionary<string, Meter>> dictionary = new Dictionary<int, Dictionary<string, Meter>>();

if (!dictionary.ContainsKey(objectID))
{
    dictionary.Add(objectID, new Dictionary<string, Meter>());
}

Meter meter = new Meter();
meter.ertNumber = "9480:1";
meter.meterNumber = "fsadfa";
meter.Reading = new Dictionary<Int32, double>();
meter.Reading.Add(0, 6);

dictionary[objectID].Add("Test", meter);
}

class Meter
{
    public String ertNumber { get; set; }
    public String meterNumber { get; set; }
    public Dictionary<Int32, double> Reading { get; set; }
}


texts: How to restrict a user to use only one plugin in WordPress

texts:
I want to restrict a specific user to use only one plugin. I don't want him to see any other pages on the WordPress admin dashboard like the Plugins page, Posts, or other pages. I want to show him just one link in the admin dashboard and let him to use just that page.
I want to do it programmatically and don't want to use a plugin for it.
I implemented the same functionality to restrict users by the code below but I want to know is there any better solution for it or not. It redirects the user to '/wp-admin/edit.php?post_type=product' if he doesn't visit the valid pages that I declared in the $pages array. I'm using WooCommerce, the post_type=product is for that.
Could you help me to achieve this, please? Thank you.
The code I wrote in functions.php file before to achieve this, the issue if I have to set all pages and plugins ID manually:
add_action('current_screen', 'checkUserPermissionsInThisScreen');

function checkUserPermissionsInThisScreen(){

    if (is_admin()){

      $a = get_current_screen();
      $currentUserName = wp_get_current_user()->user_login;

      if ($currentUserName === "testuser") {

         $pages = array(
          'dashboard',
          'toplevel_page_wpcf7',
          'contact_page_wpcf7-new',
          'contact_page_wpcf7-integration',
          'edit-shop_order',
          'edit-shop_coupon',
          'woocommerce_page_dgwt_wcas_settings',
          'woocommerce_page_wc-reports',
          'woocommerce_page_wc-settings',
          'woocommerce_page_wc-status',
          'woocommerce_page_wc-addons',
          'woocommerce_page_alg-wc-renumerate-orders-tools',
          'themes',
          'customize',
          'users',
          'tools',
          'import',
          'export',
          'site-health',
          'export-personal-data',
          'erase-personal-data',
          'tools_page_action-scheduler',
          'options-general',
          'options-writing',
          'options-reading',
          'options-discussion',
          'options-media',
          'options-permalink',
          'options-privacy',
          'toplevel_page_agilewc',
          'toplevel_page_smush',
          'shop_order'
        );

        remove_menu_page( 'themes.php' );
        remove_menu_page( 'woocommerce' );
        remove_menu_page( 'wpcf7' );
        remove_menu_page( 'index.php' );
        remove_menu_page( 'edit-comments.php' );
        remove_menu_page( 'users.php' );
        remove_menu_page( 'tools.php' );
        remove_menu_page( 'options-general.php' );
        remove_menu_page( 'smush' );

        //Remove the "WooCommerce Recent Reviews" widget.
        remove_meta_box('woocommerce_dashboard_recent_reviews', 'dashboard', 'normal');
        //Remove the "WooCommerce Status" widget.
        remove_meta_box('woocommerce_dashboard_status', 'dashboard', 'normal');
        //Hide the "Coupon data" meta box.
        remove_meta_box('woocommerce-coupon-data', $a->id, 'normal');
        //Hide the "Order data" meta box.
        remove_meta_box('woocommerce-order-data', $a->id, 'normal');
        //Hide the "Items" meta box.
        remove_meta_box('woocommerce-order-items', $a->id, 'normal');
        //Hide the "Downloadable product permissions" meta box.
        remove_meta_box('woocommerce-order-downloads', $a->id, 'normal');
        //Hide the "Order actions" meta box.
        remove_meta_box('woocommerce-order-actions', $a->id, 'side');
        //Hide the "Order notes" meta box.
        remove_meta_box('woocommerce-order-notes', $a->id, 'side');

      }

        global $pagenow;

        if ( ( ! in_array($a->id, $pages) || $pagenow === 'post-new.php' ) ) {
          wp_redirect(get_site_url() . "/wp-admin/edit.php?post_type=product");
          die;
        }

      }

    }
}


texts: Convert UTF8 string to UTF32 string in C

texts:
I'm doing some recreational programming in C (after spending some time in C++, but professionally using only PHP/JavaScript).
I wrote a UTF8 to UTF32 converter and just wanted to know if I made some obvious mistakes. (For example, is it a big no-no to malloc inside a function (because of possible memory leaks) – and if yes – how would you rather do it?)
#include <stdlib.h>
#include <stdint.h>

size_t utf8_strlen(uint8_t* text) {
    size_t i = 0;
    size_t num_chars = 0;

    while (text[i] != 0) {
        num_chars++;

        if ((text[i] & 0b10000000) == 0) {
            // 1 byte code point, ASCII
            i += 1;
        }
        else if ((text[i] & 0b11100000) == 0b11000000) {
            // 2 byte code point
            i += 2;
        }
        else if ((text[i] & 0b11110000) == 0b11100000) {
            // 3 byte code point
            i += 3;
        }
        else {
            // 4 byte code point
            i += 4;
        }
    }

    return num_chars;
}

uint32_t* utf8_to_utf32(uint8_t* text) {
    size_t num_chars = utf8_strlen(text);
    uint32_t* c = malloc(sizeof(uint32_t) * num_chars);
    size_t i = 0;

    for (size_t n = 0; n < num_chars; n++) {
        if ((text[i] & 0b10000000) == 0) {
            // 1 byte code point, ASCII
            c[n] = (text[i] & 0b01111111);
            i += 1;
        }
        else if ((text[i] & 0b11100000) == 0b11000000) {
            // 2 byte code point
            c[n] = (text[i] & 0b00011111) << 6 | (text[i + 1] & 0b00111111);
            i += 2;
        }
        else if ((text[i] & 0b11110000) == 0b11100000) {
            // 3 byte code point
            c[n] = (text[i] & 0b00001111) << 12 | (text[i + 1] & 0b00111111) << 6 | (text[i + 2] & 0b00111111);
            i += 3;
        }
        else {
            // 4 byte code point
            c[n] = (text[i] & 0b00000111) << 18 | (text[i + 1] & 0b00111111) << 12 | (text[i + 2] & 0b00111111) << 6 | (text[i + 3] & 0b00111111);
            i += 4;
        }
    }

    return c;
}

Edit:
I've posted an updated version of the code to GitHub for anyone that is interested: https://github.com/s22h/cutils/blob/master/src/unicode.h


texts: Reading the contents at three URLs using Promises

texts:
I'm learning promises and now I'm trying to figure out if something in this code can be improved. This code is expected 3 urls and then async parallel calls should be done. When all requests are finished thet just show each request's data.

const hyperquest = require('hyperquest');
const BufferList = require('bl');
const Promise = require('bluebird');

var tasks = [];
for (var i = 0; i < 3; i++) {
    new function(index) {
        tasks[index] = new Promise(function(resolve) {
            makeRequest(resolve, index);
        });
    }(i);
}

Promise.all(tasks).then(function(result) {
    result.forEach(function(item) {
        console.log(item.bl.toString());
    })
});

function makeRequest(resolve, step) {
    var bl = new BufferList();
    var req = hyperquest(process.argv[step + 2]);
    req.on('end', function() {
        resolve({data: bl});
    });
    req.pipe(bl);
}

The main question is it right usage of Promise.
Should I use this

tasks[index] = new Promise(function(resolve) { makeRequest(resolve, index); });

or it can be simplified?

Also req.on('end', function() { resolve({data: bl}); }); is a direct call of resolver callback but maybe it's possible without it?


texts:
I have implemented a basic object class in C++, and I want to make sure that I have implemented everything efficiently and safely, as I made a few mistakes while making it, which I corrected, but I could have left a few more mistakes behind:

class object
{
private:
    class dummy
    {
    public:
        dummy()
        {
        }
        virtual ~dummy()
        {
        }
        virtual const std::type_info &type() = 0;
        virtual dummy *duplicate() const = 0;
        virtual bool eq(object &) = 0;
    };

    template < typename _Ty > class data : public dummy
    {
    public:
        data()
        {
        }

        data(const _Ty &_Value)
            : __data(_Value)
        {
        }

        ~data()
        {
        }

        const std::type_info &type()
        {
            return typeid(_Ty);
        }

        data *duplicate() const
        {
            return new data<_Ty>(__data);
        }

        bool eq(object &_Obj)
        {
            return _Obj.cast<_Ty>() == __data;
        }

        _Ty __data;
    };

    dummy *d;
public:
    object()
    {
    }

    template < typename _Ty > object(const _Ty &_Value)
        : d(new data<_Ty>(_Value))
    {
    }

    object(const object &_Obj)
        : d(_Obj.d->duplicate())
    {
    }

    ~object()
    {
        if (!empty())
        {
            delete d;
        }
    }

    const std::type_info &type()
    {
        return (empty() ? typeid(void) : d->type());
    }

    object &operator=(object &_Rhs)
    {
        d = _Rhs.d->duplicate();
        return *this;
    }

    object &swap(object &_Rhs)
    {
        std::swap(*this, _Rhs);
        return *this;
    }

    template < typename _Ty > object &operator=(const _Ty &_Value)
    {
        d = new data<_Ty>(_Value);
        return *this;
    }

    template < typename _Ty > _Ty cast()
    {
        if (type() == typeid(_Ty))
        {
            return static_cast<data<_Ty> *>(d)->__data;
        }
        throw std::exception("Invalid cast type");
    }

    bool operator==(object &_Rhs)
    {
        return (type() == _Rhs.d->type() ? d->eq(_Rhs) : false);
    }

    template < typename _Ty > bool operator==(_Ty _Value)
    {
        return (type() == typeid(_Ty) ? cast<_Ty>() == _Value : false);
    }

    bool operator!=(object &_Rhs)
    {
        return !(*this == _Rhs);
    }

    template < typename _Ty > bool operator!=(const _Ty &_Value)
    {
        return !(*this == _Value);
    }

    bool empty()
    {
        return !d;
    }
};


texts:
I've written a singly linked list in C++. Would appreciate reviews on code efficiency and best practices.

#ifndef SLIST_HPP
#define SLIST_HPP

#include <stdexcept>
#include <iostream>

template <typename T> struct node{
    node(T data):data(data),next(nullptr){}
    T data;
    node<T> * next;
};

template< typename T> class slist{
    node<T>* head;
    int size;
public:
    slist(node<T>* head):head(head), size(0){}

    slist(const slist<T>& rhs){

     node<T>* temp = rhs.getHead();

    node<T>* current = new node<T>(temp->data);
    while(temp != nullptr){

        current->next = new node<T>(temp->next->data);
        temp = temp->next;
        current = current->next;
    }
}
    ~slist(){
        if(head == nullptr) return;

        while(head != nullptr){
            node<T>* current = head;
            head = head->next;
            delete(current);
        }
    }
    slist& operator= (const slist& rhs){

    node<T>* temp = rhs.getHead();
    try{
        if(temp == nullptr) throw std::runtime_error("Can't assign null");
    }catch(std::runtime_error& e){
        std::cout<<e.what()<<std::endl;
    }

    node<T>* current = head;
    while(temp != nullptr){

        temp = temp->next;
        current = current->next;
        current->next = new node<T>(temp->next->data);
    }

}
    node<T>* getHead()const {
        return head;
    }

    void add(node<T>* p, T item){
        if(p == nullptr) return;
        node<T>* current = new node<T>(item);
        node<T>* temp = p->next;
        p->next = current;
        current->next = temp;
        size++;

    }
    void insertFront(T item){
        node<T>* p = new node<T>(item);
        if(head == nullptr){
            p = head;
            size++;
            return;
        }
        p->next = head;
        head = p;
        size++;
    }

    void insertBack(T item){
        node<T>* p = new node<T>(item);
        node<T>* current = head;
        while(current->next != nullptr){
            current = current->next;
        }
        current->next = p;
        size++;
    }

    void remove(T item){
        bool check = false;

        node<T>* current = head;
        try {
            while(current != nullptr){
                if(current->data == item) check = true;
                current = current->next;
            }
            if(!check){
                throw std::runtime_error("Item not in list");

            }
        }catch(std::runtime_error& e){
            std::cout<<e.what()<<std::endl;
            exit(-1);
        }

        current = head;
        while(current != nullptr){
           if(current->next->data == item){
               node<T>* temp = current->next;
               current->next = current->next->next;
               delete(temp);
               break;
           }
            current = current->next;
        }
        size--;

    }
    int getSize () const {
        return size;
    }

    void printList(){
        node<T>* current = head;
        while(current != nullptr){
            if(current->next != nullptr){
                std::cout<<current->data<<"->";
            }else{
                std::cout<<current->data<<std::endl;
            }
            current = current->next;
        }
    }
};
#endif //SLIST_HPP


texts: Looping through list to create SQL Query

texts:
I have a list of variables which I need to convert to LIKE statements in SQL. The final query should look like the following:

...
WHERE ([TraceableItem].[IdentificationNo] LIKE N'%015558'
       OR [TraceableItem].[IdentificationNo] LIKE N'%123456'
       OR [TraceableItem].[IdentificationNo] LIKE N'%654321')
...

Below is my code to do it, but I feel it is fairly inefficient / redundant. Especially features like having a bool for firstLoop, and constantly checking for items already existing. I would be very grateful for a code review and tips on how to improve - I'm fairly rusty on C#

string queryInsertString = "([TraceableItem].[IdentificationNo] LIKE ";
string lastBatchNo = batchnos.Last();
List<string> alreadyAdded = new List<string>();
bool firstLoop = true;
foreach(string item in batchnos)
            {
    string splitItem = item.Split('/')[1];
    if (!alreadyAdded.Contains(item)){
        if (!firstLoop)
        {
            queryInsertString += " OR [TraceableItem].[IdentificationNo] LIKE N'%" + splitItem + "'";
        } else
        {
            queryInsertString += "N'%" + splitItem + "'";
            firstLoop = false;
        }
        alreadyAdded.Add(item);
    }
}


texts:
Below is my solution for the LeetCode Jump Game

Given an array of non-negative integers, you are initially positioned
at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true

This is my solution. It is correct but timed out the LeetCode code-checker for an array of 25000 elements.
Please can someone help me improve this code.
It seems to have a time complexity of O(N^2) and a space complexity of O(N). I cannot work out a method faster than O(N^2).
def function(nums):
    if len(nums) == 1:
        return True
    output = [0] * len(nums)
    last_index = len(nums) - 1
    output[0] = 1

    for index, number in enumerate(nums):
        if output[index] == 0:
            continue
        if output[index] == 1:
            stop_at = min(last_index, index + number)
            for i in range(index, stop_at + 1):
                output[i] = 1
        if output[last_index] == 1:
            return True
    return False

if __name__ == "__main__":
    nums = [3,2,1,0,4]
    output = function(nums)
    print(output)


texts: Extending UITableViewCell to preserve UIView background color when selecting the cell

texts:
When a UITableViewCell has subviews with background color set, when setSelected(_: animated:) gets called, all the views are made transparent.

This issue is also discussed here

I'm trying to solve this issue by extending UITableViewCell

extension UITableViewCell {
    private func backgroundColors(views: [UIView]) -> [UIColor?] {
        var colors = [UIColor?]()
        for view in views {
            colors.append(view.backgroundColor)
        }
        return colors
    }

    private func resetBackgroundColors(views: [UIView], colors: [UIColor?]) {
        for (index, view) in views.enumerate() {
            view.backgroundColor = colors[index]
        }
    }

    func preserveBackgroundColors(views: [UIView], @noescape f: () -> Void) {
        let colors = backgroundColors(views)
        f()
        resetBackgroundColors(views, colors: colors)
    }
}

class MyCell: UITableViewCell {
    override func setSelected(selected: Bool, animated: Bool) {
        preserveBackgroundColors([/* some views */]) {
            super.setSelected(selected, animated: animated)
            /* rest of method implementation */
        }
    }
}

I'm trying to avoid having this functionality in a class hierarchy.

Is this a good implementation?


texts:
I created a user defined literal _c to convert an "integer" literal into an std::integral_constant. Basically, the goal is to allow users to write std::integral_constant instances without the usual boilerplate. Here is the implementation:

#include <type_traits>

template<typename T, typename U>
constexpr auto pow_helper(T acc, T value, U times)
    -> T
{
    return (times > 1) ?
        pow_helper(acc*value, value, times-1) :
            acc;
}

// Compile-time pow function, only works with
// an unsigned integer exponent
template<typename T, typename U>
constexpr auto pow(T value, U exponent)
    -> T
{
    return (exponent == 0) ? 1 :
        (exponent > 0) ? pow_helper(value, value, exponent) :
            1 / pow_helper(value, value, -exponent);
}

// Structure to parse an integer literal
template<typename Integral, char C, char... Digits>
struct parse
{
    static constexpr Integral value =
        parse<Integral, C>::value * pow(10u, sizeof...(Digits))
        + parse<Integral, Digits...>::value;
};

// Specialization of parse to parse a single
// decimal digit
template<typename Integral, char C>
struct parse<Integral, C>
{
    static_assert(C >= '0' && C <= '9',
                  "only characters in range 0..9 are accepted");

    static constexpr Integral value = C - '0';
};

// User defined literal for std::integral_constant
template<char... Digits>
constexpr auto operator"" _c()
    -> std::integral_constant<int, parse<int, Digits...>::value>
{
    return {};
}

With this literal, wirting 42_c generates an instance of std::integral_constant<int, 42>. Here is a small working example:

int main()
{
    std::cout << 45_c << '\n';   // prints 45
    std::cout << -23_c << '\n';  // prints -23

    static_assert(std::is_same<decltype(58_c), std::integral_constant<int, 58>>::value, "");
}

To generate other integral constants, I plan to add the user defined literals _cl, _cll, _cu, _cul and _cull whoe implementation is exactly the same, only the resulting type differs.

Is there a way to improve this code and/or make it cleaner or more idiomatic? Have I missed some potential flaws?


texts:
Following is my solution to Knapsack problem using all combinations of the sent list of items (in Racket programming language). Although it is very short, I am sure it can be improved in many ways.

(define (maxI L)  (- (length L) (length (member (apply max L) L))))
(define (knapsack maxwt itemL)
  (let* ((combL (filter (λ (x) (<= (apply + (map second x)) maxwt))
                        (combinations itemL)))
         (totalvalueL (map (λ (x) (apply + (map third x))) combL))
         (maxvalindex (maxI totalvalueL)))
    (list-ref combL maxvalindex)))

Following is code with comments to explain different steps:

; support fn to find index of largest number in a list:
(define (maxI L)  (- (length L) (length (member (apply max L) L))))

; Main fn - only 4 statements:
(define (knapsack maxwt itemL)
  (let* ((combL (filter (λ (x) (<= (apply + (map second x)) maxwt)) ; Get all combinations and filter out
                        (combinations itemL)))                      ; those where total wt is upto maxwt;
         ; Other filters can be added here, e.g. if both wt and volume are limiting;
         (totalvalueL (map (λ (x) (apply + (map third x))) combL))  ; Get total values in each combination;
         (maxvalindex (maxI totalvalueL)))   ; Find index of maximum value;
    ;(printf "Total value = ~a~n" (list-ref totalvalueL maxvalindex))  ; uncomment to print total value;
    ;(printf "Total wt = ~a~n" (apply + (map second (list-ref combL maxvalindex))))  ; uncomment to print total wt;
    (list-ref combL maxvalindex)))           ; return combination at this index;

Usage:

(define Itemslist '((a 20 100)      ; (name wt value) ;
                    (b 10 20)
                    (c 30 130)))
(define MaxWtAllowed 30)
(knapsack MaxWtAllowed Itemslist)

Output:

Total value = 130
Total wt = 30
'((c 30 130))

Another test:

(set! Itemslist '((a 3 50)      ; (name wt value) ;
                  (b 6 30)
                  (c 4 40)
                  (d 5 10)))
(set! MaxWtAllowed 10)
(knapsack MaxWtAllowed Itemslist)

Output:

Total value = 90
Total wt = 7
'((a 3 50) (c 4 40))

I find that it gets stuck with large lists (as one used on https://rosettacode.org/wiki/Knapsack_problem/0-1#Racket - see its example run).

(knapsack 400
          '((map 9 150) ; 9 is weight, 150 is value
            (compass 13 35) (water 153 200) (sandwich 50 160)
            (glucose 15 60) (tin 68 45)(banana 27 60) (apple 39 40)
            (cheese 23 30) (beer 52 10) (cream 11 70) (camera 32 30)
            (T-shirt 24 15) (trousers 48 10) (umbrella 73 40)
            (trousers 42 70) (overclothes 43 75) (notecase 22 80)
            (glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10)))

I get "Interaction disabled" message most of the time (on DrRacket IDE). Sometimes it runs and then it give correct answer (same as on rosettacode page):

Total value = 1030
Total wt = 396
'((map 9 150)
  (compass 13 35)
  (water 153 200)
  (sandwich 50 160)
  (glucose 15 60)
  (banana 27 60)
  (cream 11 70)
  (trousers 42 70)
  (overclothes 43 75)
  (notecase 22 80)
  (glasses 7 20)
  (socks 4 50))

Any suggestions will be appreciated.


texts: Using standard library to simplify pairwise iteration of container values

texts:
I came up with this code whilst answering this question.

Is there a simpler way of doing this using standard library?

I want to iterate over every object and do something with every other object.

For example, 4 values 1, 2, 3, 4 would pair like:

(1, 2), (1, 3), (1, 4)
(2, 3), (2, 4)
(3, 4)

Each value combines with every other value. None combine with themselves, and symmetric pairings are considered the same.

This might be useful in a collision system where you want to check every solid with every other.

template<typename Iter, typename Func>
void pair_wise(Iter it, Iter last, Func func) {
    while(it != last) {
        Iter other = it;
        ++other;
        while(other != last) {
            func(*it, *other);
            ++other;
        }
        ++it;
    }
}

Usage:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values = {1, 2, 3, 4};

    pair_wise(values.begin(), values.end(),
              [](int& lhs, int& rhs) {
                  std::cout << "(" << lhs << ", " << rhs << ")\n";
              });
}

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)


texts:
I'm currently toying around with some Computer Vision algorithms and always wanted to learn more about templates, so I came up with the idea to build a templated Image Processing Pipeline.

I want the pipeline to be built of several task blocks which I want to plug into each other sequentially. For a specific block, its input and output types are fixed. I ultimately want to be able to inherently control for a block to only accept the next block if the output type of the current is identical to the input type of the next.

         Block_N                 Block_N+1
     _______________         _________________
int |               |  str  |                 | float
--->| str = f1(int) |------>| float = f2(str) |------->
    |_______________|       |_________________|

Consequently, Block_N+2 would have to accept float as input and may have an arbitrary output type.

This is what I was able to come up with:

Abstract base classes:

template<class I>
class AbstractInput {

public:
    virtual ~AbstractInput() { }

    virtual void call( I _input ) = 0;
};

template<class I, class O>
class AbstractPipelineTask : public AbstractInput<I> {

public:
    typedef AbstractInput<O>* Ptr;

    AbstractPipelineTask( AbstractInput<O>* _nextTask = NULL)
        : m_nextTask ( _nextTask ) { }

    virtual void call( I _input ) {

        m_input = _input;
        m_output = executeTask( m_input );

        if ( m_nextTask )
            m_nextTask->call( m_output );
    }

    virtual O executeTask( I& _input ) = 0;

protected:
    AbstractInput<O>* m_nextTask;

    I m_input;
    O m_output;
};

Example implementation:

class Str2IntPipelineTask : public AbstractPipelineTask< std::string, int > {

public:
    Str2IntPipelineTask( AbstractInput<int>* _nextTask = NULL )
        : AbstractPipelineTask( _nextTask ) { }
    virtual ~Str2IntPipelineTask() { }

    virtual int executeTask( std::string& _input ) {

        return atoi( _input.c_str() );
    }
};

class Int2IntPipelineTask : public AbstractPipelineTask< int, int> {

public:
    Int2IntPipelineTask( AbstractInput<int>* _nextTask = NULL )
        : AbstractPipelineTask( _nextTask ) { }
    virtual ~Int2IntPipelineTask() { }

    virtual int executeTask( int& _input ) {

        return ( _input * _input );
    }
};

class Int2FloatPipelineTask : public AbstractPipelineTask< int, float > {

public:
    Int2FloatPipelineTask( AbstractInput<float>* _nextTask = NULL )
        : AbstractPipelineTask( _nextTask ) { }
    virtual ~Int2FloatPipelineTask() { }

    virtual float executeTask( int& _input ) {

        return ( static_cast<float>( _input ) / 42.f );
    }
};

Examples:

int _tmain(int argc, _TCHAR* argv[])
{

    Int2FloatPipelineTask* pipeTask2    = new Int2FloatPipelineTask( );
    Int2IntPipelineTask* pipeTask1      = new Int2IntPipelineTask( pipeTask2 );
    Str2IntPipelineTask* pipeTask0      = new Str2IntPipelineTask( pipeTask1 );

    pipeTask0->call( "42" );

    return 0;
}

What I would really like to know besides some general advice is:

How can I get rid of the raw pointers AbstractInput<O>* m_nextTask? I tried changing the typedef of Ptr to std::shared_ptr<AbstractInput<O>> but that broke the derived classes constructors.
Is it possible to get rid of AbstractInput?


texts:
I have this array const idArray = ["12", "231", "73", "4"] and an object

const blueprints = {
  12: {color: red, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
  231: {color: white, views: [{name: "front}, {name: "back}]},
  73: {color: black, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
  4: {color: silver, views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]},
}

How can I return an array of the following objects that have all front, back, top, and bottom using ES6 map/filter/some and etc?:

result =[
    {colorId: "12", views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]}
    {colorId: "73", views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]}
    {colorId: "4", views: [{name: "front}, {name: "back}, {name: "top}, {name: "bottom}]}
]

I did it here but I feel like it is too messy and hard to read. Anybody could recommend on how to shorten it and make it easier to read using the ES6 functions (map, filter ...)?

const result = idArray.map(id => {
      const bluePrint = bluePrints[id];
      const exists = bluePrint.views.some(view => view.name === 'top' || view.name === 'bottom');

      if (exists) {
        return {
          colorId: id,
          views: bluePrint.views
        }
      }
    }).filter(bluePrint => bluePrint);


texts: Timer convenience class to time code execution for user output

texts:
I implemented a convenience class to time code execution and print it to the user. This is part of a bigger project that will be distributed to external users. The timer however is only called by other procedures, not by the user directly. I was interested in implementing this myself, so I'm not looking for an external module or similiar. Docstrings are omitted here, the functions are rather straightforward.
from time import perf_counter

class Timer:
    def __init__(self, default_round_digits: int = 5):
        self.default_digits = default_round_digits
        self.start_timer()

    def start_timer(self) -> None:
        self.start_time = perf_counter()
        self.pause_start_time = None
        self.pause_length = 0

    def pause_timer(self) -> None:
        self.pause_start_time = perf_counter()

    def resume_timer(self) -> None:
        if self.pause_start_time is not None:
            self.pause_length += perf_counter() - self.pause_start_time
            self.pause_start_time = None

    @property
    def elapsed_seconds(self) -> float:
        # If timer is paused only consider time up to self.pause_start_time instead of now
        if self.pause_start_time is not None:
            return self.pause_start_time - self.start_time - self.pause_length
        else:
            return perf_counter() - self.start_time - self.pause_length

    def get_timer(self, round_digits: int = None, print_text: str = None, restart: bool = False) -> float:

        if round_digits is None:
            round_digits = self.default_digits

        elapsed_seconds = round(self.elapsed_seconds, ndigits=round_digits)

        if print_text is not None:
            print(f"{print_text}{elapsed_seconds} seconds")

        if restart:
            self.start_timer()

        return elapsed_seconds

    def __str__(self) -> str:
        state = "Running" if self.pause_start_time is None else "Paused"
        return f"{state} Timer at {self.get_timer()} seconds"

I'm still unsure about initializing attributes outside of __init__. I know it's not recommended, but copying start_timer into __init__ seemed like the worse option to me.


texts: Saving WPF DataGrid changes to Entity Framework

texts:
I feel like I had to invent a whole new way to do this because I couldn't find anything that did this the way I wanted to...

The basic process involves reading changes to cells and capturing information about those changes as they relate to the actual Entities in question and then persisting them to the database.

Here's the XAML. I didn't use databinding because I don't quite understand it yet and I'm on a  bit of a deadline for this one so that's item number 1 on my to do list when I get a break.

Note that this project has been my first every foray into WPF. I've dabbled a bit in the past but I've really pushed myself to do things properly here... As properly as I know how anyway.

<DataGrid Name="dgUsers" Height="150"
    CellEditEnding="dgUsers_CellEditEnding">
</DataGrid>

<StackPanel Name="spActions" Background="#2d2d30" Width="500" Height="50" Orientation="Horizontal" FlowDirection="RightToLeft">
    <Button Name="btnCancel" Click="btnClose_Click" Content="Cancel" Style="{StaticResource CancelButton}" Height="30" Width="66" Margin="5,3,5,5"></Button>
    <Button Name="btnSave" Click="btnSave_Click" Content="Save" Style="{StaticResource RoundedButtonGreen}" Height="30" Width="66" Margin="5,3,5,5"></Button>
    <Label Name="lblResult"></Label>
</StackPanel>

Here's the C# codebehind:

Generate an entity from the changes that were made:

private List<User> UpdatedUsers { get; set; }
/// <summary>
/// Maintains a list of all changes made to all entities on the datagrid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgUsers_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (UpdatedUsers == null) UpdatedUsers= new List<User>();

    var _User = (User)e.Row.Item;
    var Element = (TextBox)e.EditingElement;
    if (String.Equals((string)e.Column.Header, "EmailAddress"))
    {
        User.EmailAddress = Element.Text;
    }
    else if (String.Equals((string)e.Column.Header, "Password"))
    {
        User.Password = Element.Text;
    }

    UpdatedUsers.Add(User);
}

From here the user clicks on a save button which loops through the changes captured in this list and updates the relevant records in the database:

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    try
    {
        ApplicationDbContext Context = new ApplicationDbContext();
        var Users = Context.Users.Where(x => x.CompanyId == (int)cmbCompanies.SelectedValue).ToList();

        foreach (User User in Users)
        {
            foreach (User U in UpdatedUsers)
            {
                if (U.Id == User.Id)
                {
                    User.EmailAddress = U.EmailAddress;
                    User.Password = U.Password;
                }
                Context.SaveChanges();
            }
        }
    }
    catch (Exception ex)
    {
        lblResult.Content = ex.Message;
    }
}


texts:
I'm trying to create an if-else statement that pops up a modal with output in the body, and if there is no input detected then an alert pops up.

    //fizzbuzz
$("#btnfb").click(function () {
var numfiz = $("#fizz").val();
var numbuz = $("#buzz").val();
var outputarray = [];
for (var loop = 1; loop <= 100; loop++) {
if (loop % numfiz === 0 & loop % numbuz === 0) {
outputarray.push("Fizzbuzz");
}
else if (loop % numfiz === 0) {
outputarray.push("Fizz");
}
else if (loop % numbuz === 0) {
outputarray.push("Buzz");
}
else {
outputarray.push(loop);
}
$("fzbzout").html(outputarray.join(", "));
$('#myModel5').modal('show');
});


texts:
I need to be able to store results of a game in a file with names and high scores where I will eventually want to review the file and sort it alphabetically, etc.  I'm unsure if I have the correct way of storing the results to be able to do this.

class_number = input('Please enter your class number: ')

from datetime import datetime
now = datetime.now()
time = ('%s/%s/%s %s:%s' % (now.day, now.month, now.year, now.hour, now.minute))

userscore = (user_name, ' ', str(total_score),' ', time, '  ')

if(int(class_number) == 1):
    with open('class1.txt', 'a') as myFile:
        myFile.writelines(userscore)
        myFile.close()

elif(int(class_number) == 2):
    with open('class2.txt', 'a') as myFile:
        myFile.writelines(userscore)
        myFile.close()

elif(int(class_number) == 3):
    with open('class3.txt', 'a') as myFile:
        myFile.writelines(userscore)
        myFile.close()


texts:
The complete problem definition can be summarized as "find the largest sum of for paths from the top to the bottom of a triangle of integers".  I decided to read the triangle in from a file which can be found here.

My solution

#!/usr/bin/python
"""chicks' answer to Euler Project problem #18"""

import sys
import string
import re
import pprint

# read command line
argcount = len(sys.argv)
if argcount <= 1:
    raise ValueError("missing filename on command line")
triangle_filename = sys.argv[1]
print str(argcount) + " arguments: " + triangle_filename

# read file
with open(triangle_filename, "r") as triangle_file:
    lines = triangle_file.readlines()
    print str(len(lines)) + " lines read"

triangle = []
for y in lines:
    y = string.strip(y)
    fields = re.split(r'\s+', y)
    int_fields = []
    for f in fields:
        int_fields.append(int(f))
    triangle.insert(0, int_fields)
    c = len(fields)

pretty = pprint.PrettyPrinter(indent=4)
#pretty.pprint(triangle)

rows = len(triangle) - 1
for z in range(0, rows):
    row = triangle[z]
    pretty.pprint(row)

    entries = len(row) - 1
    for y in range(0, entries):
        a = row[y]
        b = row[y + 1]
        #print "comparing " + str(a) + " and " + str(b)
        adder = 0
        if a >= b:
            adder = a
        else:
            adder = b

        triangle[z + 1][y] += adder

answer = str(triangle[rows][0])
print "ANSWER:" + answer

Desired Focus

I left performance out because I'm more interested in having pythonicly correct and maintainable code than squeezing out a few ms.  I have run this through pylint and fixed everything it suggested.  I am still a beginner at python so I'm presuming there are more pythonic ways to do some of this.


texts:
In Rust, I want to take an array of u32 values, convert each to four bytes in big endian, and concatenate them to yield a Vec<u8> result. Example:
let input: [u32; 5] = [
    0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];

(... Do some data conversion work ...)

let output: Vec<u8> = vec![
    0x67, 0x45, 0x23, 0x01,
    0xEF, 0xCD, 0xAB, 0x89,
    0x98, 0xBA, 0xDC, 0xFE,
    0x10, 0x32, 0x54, 0x76,
    0xC3, 0xD2, 0xE1, 0xF0,
];

I have several pieces of working code that all give the same answer.
Algorithm A (for-loop):
let mut output = Vec::<u8>::new();
for val in &input{
    output.extend_from_slice(&val.to_be_bytes());
}

Algorithm B (for-each):
let mut output = Vec::<u8>::new();
input.iter().for_each(|val| output.extend_from_slice(&val.to_be_bytes()));

Algorithm C (fold-append):
let output = input.iter().fold(Vec::<u8>::new(),
    |mut acc, val| {acc.extend_from_slice(&val.to_be_bytes()); acc});

Algorithm D (flat-map):
let output: Vec<u8> = input.iter().flat_map(|val| val.to_be_bytes().to_vec()).collect();

Is there an even shorter, clearer way to accomplish the task? Maybe algorithm D's to_vec() could be avoided somehow?
Speed is not a concern because this code only executes a few times, and the input array length is fixed at 5.


texts:
I have implemented linked list data structure in c.

linkedlist.h

#ifndef LINKED_LIST
#define LINKED_LIST

#include <stdbool.h>

struct linkedlist {
    int key;
    struct linkedlist* next;
    struct linkedlist* prev;
};

bool list_insert(struct linkedlist** p,int k);
struct linkedlist* list_search(struct linkedlist* p,int k);
bool list_delete(struct linkedlist** p,int k);
void list_show(struct linkedlist* p);
void memory_map(struct linkedlist* p);

#endif

list.c

#include "linkedlist.h"
#include <stdio.h>
#include <stdlib.h>

bool list_insert(struct linkedlist** p,int k) {
    struct linkedlist* x = malloc(sizeof (struct linkedlist));
    if(!x)
    {
        return false;
    }
    x->key = k;
    x->prev = NULL;
    x->next = *p;

    if(*p)
    {
        (*p)->prev = x;
    }
    *p = x;
    return true;
}

struct linkedlist* list_search(struct linkedlist* p,int k) {
    if(!p)
    {
        return NULL;
    }

    while(p != NULL)
    {
        if(p->key == k)
        {
            return p;
        }
        p = p->next;
    }
    return NULL;
}

bool list_delete(struct linkedlist** p,int k) {
    struct linkedlist* x = list_search(*p,k);
    if(!x)
    {
        return false;
    }
    if(x->prev)
    {
        x->prev->next = x->next;
    }
    if(x->next)
    {
        x->next->prev = x->prev;
    }

    free(x);
    return true;
}

void list_show(struct linkedlist* p) {
    printf("\n[linkedlist][");
    while(p)
    {
        printf("%d ",p->key);
        p = p->next;
    }
    printf("]");
}
void memory_map(struct linkedlist* p) {
        printf("\n[memory map for linkedlist]");
        while(p)
        {
                printf("\n%d : [%p]", p->key,p);
                p = p->next;
        }
}

main.c

#include <stdio.h>
#include "linkedlist.h"

int main()
{
    struct  linkedlist* head = NULL;
    int i;
    for(i = 0; i < 5; i++)
    {
        if(!list_insert(&head,i+1))
            printf("list_insert operation fails");
    }
    list_show(head);
    memory_map(head);
    list_delete(&head,2);
    list_delete(&head,1);
    list_delete(&head,3);
    list_insert(&head,18);
    list_show(head);
    memory_map(head);
    return 0;
}


texts: Inserting new Node in a Binary Search Tree

texts:
I wrote this method to recursively insert a new node at the proper position in a BST. Is it good enough? Can it be improved? It went through a couple of revisions and I still am not very confident in this version.
Making the new node root when no nodes are present is taken care of in a separate wrapper function.

public void insertNode(Node<Integer> currentParent, Node<Integer> newNode) {
    if (newNode.getNodeData() < currentParent.getNodeData()) {
        if(currentParent.getLeftChild() == null)
            currentParent.setLeftChild(newNode);
        else
            insertNode(currentParent.getLeftChild(), newNode);

    } else {
        if(currentParent.getRightChild() == null)
            currentParent.setRightChild(newNode);
        else
            insertNode(currentParent.getRightChild(), newNode);
    }
}


texts: Determine if a point is inside or ouside of an irregular shape on a bitmap

texts:
So this is my task:

You are given an irregular shape on a bitmap. How do you determine if
a point is inside or ousdie of the shape?

We are allowed to assume that helper functions are already available for us and we don't need to write them as well.
So I decided that I can use a function that returns me the status of a given bit on that bitmap.
int IsBitIsOn(bitmap_ty *bitmap, size_t x, size_t y);

We also can assume that the given point won't be a point on the outline of the shape. Which means the given X,Y coordinates must be either inside or outside the shape and not on one of the outlines.
And here is my full code of the task,
I wrote it as a bitmap that every ON(==1) bit tells me that I'm on an outline, while 0 bit tells me i'm either inside or outside the shape.
int IsInTheShape(bitmap_ty *bitmap, size_t x, size_t y)
{
    int IsIn = 0; /* flag of whether the given point is inside the shape    */

    int ComeFromAbove = 0;

    int start_sequal = 1;

    size_t curr_row = y;
    size_t curr_column = 0;

    while (x != curr_column)
    {
        if (IsBitIsOn(bitmap, curr_column, curr_row))
        {
            IsIn = !IsIn;

            /* starts a sequal of bits that are ON  */
            while (IsBitIsOn(bitmap, curr_column + 1, curr_row))
            {
                /* checks the source direction of the first bit in the sequal */
                if (start_sequal &&
                    IsBitOn(bitmap, curr_column, curr_row - 1) ||
                    isBitOn(bitmap, curr_column - 1, curr_row - 1) ||
                    isBitOn(bitmap, curr_column + 1, curr_row - 1))
                {
                    ComeFromAbove = 1;
                    start_sequal = 0;
                }
                ++curr_column;
            }
            /*  checks the source direction of the last bit in the sequal,
                so if it cuts the direction of the first bit, it means
                the next points are out of the shape    */
            if (ComeFromAbove)
            {
                if (!IsBitOn(bitmap, curr_column, curr_row + 1) &&
                    !isBitOn(bitmap, curr_column - 1, curr_row + 1) &&
                    !isBitOn(bitmap, curr_column + 1, curr_row + 1))
                {
                    ComeFromAbove = 0;
                    IsIn = !IsIn;
                }
            }
        }
        ++curr_column;
    }

    return (IsIn);
}

I draw the following shapes find the problematic points and shapes:


texts: Fisher-Yates shuffle Java implementation

texts:
This is my attempt at an implementation of the modern Fisher-Yates shuffle in Java. I'm not sure if it can be made more efficient, but I did my best to make it as simple as possible, and I learned how to use generics specifically for this, so If I did something wrong in that regard, let me know.

package com.kestrel.test;

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

public class ShuffleTest
{
    public static <T> ArrayList<T> shuffle(ArrayList<T> a)
    {
        Random rand = new Random();

        for(int n = a.size() - 1; n > 0; n--)
        {
            int index = rand.nextInt(n + 1);
            T temp = a.get(index);

            a.set(index, a.get(n));
            a.set(n, temp);
        }
        return a;
    }

    public static <T> T[] shuffle(T[] a)
    {
        Random rand = new Random();

        for(int n = a.length - 1; n > 0; n--)
        {
            int index = rand.nextInt(n + 1);
            T temp = a[index];

            a[index] = a[n];
            a[n] = temp;
        }
        return a;
    }
}

I know that I would have to implement methods for all of the primitive array types separately, but I'm short on time, and I don't think autoboxing will slow down my code all that much.


texts:
Here are my class library code which create credit card.
public abstract class CreditCard
{
    public CardType CardType { get; protected set; }
    public decimal CreditLimit { get; protected set; }
    public decimal AnnualCharge { get; protected set; }
}

public class GoldCreditCard : CreditCard
{
    private GoldCreditCard(decimal creditLimit, decimal annualCharge)
    {
        CardType = CardType.Gold;
        CreditLimit = creditLimit;
        AnnualCharge = annualCharge;
    }

    /// <summary>
    /// Factory pattern
    /// </summary>
    /// <returns></returns>
    public static CreditCard Create()
    {
        return new GoldCreditCard(creditLimit: 15000, annualCharge: 100);
    }
}

public class TitaniumCreditCard : CreditCard
{
    private TitaniumCreditCard(decimal creditLimit, decimal annualCharge)
    {
        CardType = CardType.Titanium;
        CreditLimit = creditLimit;
        AnnualCharge = annualCharge;
    }

    /// <summary>
    /// Factory pattern
    /// </summary>
    /// <returns></returns>
    public static CreditCard Create()
    {
        return new TitaniumCreditCard(creditLimit: 30000, annualCharge: 250);
    }
}

and the ui will be:
    static void Main(string[] args)
    {
        CreditCard card;

        System.Console.WriteLine("Select your card type");
        System.Console.WriteLine("1. Gold Credit Card");
        System.Console.WriteLine("2. Titanium Credit Card");
        var option = System.Console.ReadLine();
        switch (option)
        {

            case "1":
                card = GoldCreditCard.Create();
                PrintCard(card);
                break;
            case "2":
                card = TitaniumCreditCard.Create();
                PrintCard(card);
                break;
            default:
                break;
        }

    }

    static void PrintCard(CreditCard card)
    {
        System.Console.WriteLine($"Your credit card has been successfully created.");
        System.Console.WriteLine($"The credit card type is {card.CardType}.");
        System.Console.WriteLine($"The credit card limit is {card.CreditLimit:C}.");
        System.Console.WriteLine($"The credit card annual fee is {card.AnnualCharge:C}.");
    }

Is this implementation of factory design pattern in C#?


texts: Project Euler #12 - highly divisible triangular number

texts:
The following is a solution to Project Euler problem number 12: which is to find the first triangular number with more than 500 divisors.

The code takes far too long to complete (over 10 minutes). Is there any way to optimize the run-time and to make it more elegant?

#include <iostream>
#include <chrono>
#include <ctime>

inline void triangle(int &num, int &interval)
{
    num = ((interval * interval) + interval ) / 2;
}

int main()
{
    long int input;
    int num = 1, interval = 1, divisor = 1, no_divisor = 0;

    std::cout << "Enter factor limit for Triangle number: ";
    std::cin >> input;

    auto start = std::chrono::steady_clock::now();

    for (;;)
    {
        while (divisor <= num)
        {
            if (0 == num % divisor) //check factor;
            {
                std::cout << "factor: " << divisor << "\n";
                no_divisor++;
                if (no_divisor > input) //divisor count over input number, jump to exit;
                {
                    goto exit;
                }
            }
            divisor++;
        }
        std::cout << "\n";
        interval++;
        triangle(num, interval);
        divisor = 1; //reset divisor back to 1;
        no_divisor = 0; //reset divisor count back to 0;
    }
    exit: std::cout << "the first Triangle number to have over " << input << " divisors : " << num << "\n";

    auto end = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    std::cout << "\nIt took me " << elapsed.count() << " milliseconds." << "\n";

    return 0;
}

Optimization I've done:

using std::cout << "\n" instead of std::cout << endl to prevent flushing output buffers. Source: this
using inline void triangle(int &num, int &interval) speed up 10% time
using n(n+1)/2 according to this

Speculation:

I figured if the question asked for over 500 factors, which for example:
Triangular number 28 has over 5 factors:

So I only need to iterate up to half of the limit. But how can I implement that into my code to only iterate up to half as many factor?


texts: Codility: MaxZeroProduct - complexity issues

texts:
My solution scored 100% correctness, but 0% Performance.
I just can't figure out how to minimize complexity time.

Problem:

Write a function:

int solution(int A[], int N);

that, given an array of N positive integers, returns the maximum number of trailing zeros of the number obtained by multiplying three different elements from the array. Numbers are considered different if they are at different positions in the array.

For example, given A = [7, 15, 6, 20, 5, 10], the function should return 3 (you can obtain three trailing zeros by taking the product of numbers 15, 20 and 10 or 20, 5 and 10).

For another example, given A = [25, 10, 25, 10, 32], the function should return 4 (you can obtain four trailing zeros by taking the product of numbers 25, 25 and 32).

Assume that:

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

Complexity:

expected worst-case time complexity is \$O(N*log(max(A)))\$;
expected worst-case space complexity is \$O(N)\$ (not counting the storage required for input arguments).

Solution:

the idea:

factorize each element into pairs of 5's and 2's
sum each 3 pairs into one pair - this costs \$O(N³)\$
find the pair who's minimum coordinate value is the biggest
return that minimun coordinate value

the code:

int solution(int A[], int N) {
    int fives = 0, twos = 0, max_zeros = 0;
    int(*factors)[2] = calloc(N, sizeof(int[2])); //each item (x,y) represents the amount of 5's and 2's of the corresponding item in A

    for (int i = 0; i< N; i++) {
        factorize(A[i], &fives, &twos);
        factors[i][0] = fives;
        factors[i][1] = twos;
    }

    //O(N^3)
    for (int i = 0; i<N; i++) {
        for (int j = i + 1; j<N; j++) {
            for (int k = j + 1; k<N; k++) {
                int x = factors[i][0] + factors[j][0] + factors[k][0];
                int y = factors[i][1] + factors[j][1] + factors[k][1];
                max_zeros = max(max_zeros, min(x, y));
            }
        }
    }
    return max_zeros;
}

void factorize(int val, int* fives, int* twos) {
    int tmp = val;
    *fives = 0, *twos = 0;

    if (val == 0) return;
    while (val % 5 == 0) { //factors of 5
        val /= 5;
        (*fives)++;
    }
    while (val % 2 == 0) { //factors of 2
        val /= 2;
        (*twos)++;
    }
}

I can't figure out how else i can iterate over the N-sized array in order to find the optimal 3 items in time \$O(N*log(max(A)))\$.