texts: Game server auth: cookie key generate&check

texts:
UPD: Haskell version, please check it too.

gameKey(long id) is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls gameKey() and returns it as JSON to player via API. When a friend establishes connection, he sends the game id and his key, server calls gameKey(id), where id is user data, and then checks user's key.

Algorithm is:

use current time and internal counter to generate id if it's not provided, or use provided id
make fast crypto hash using Blake2 function of id and secret(Yes, I know about HMAC and using as key, but in this case it doesn't matter)
split 64-bit hash to four 16-bit values, one hash for one user
make JSON object from id and keys and return it

I want to make stable code: exploit-free, no memory leaks and high speed (for high load and DDOS prevention). I'm experimenting now, so the algorithm was first written in JavaScript, because I'm skilled in JS coding. Then I rewrote JS code in C++ to increase execution speed. You can see C++ and JS code below. The C++ code is 3x faster than JS: 34s vs 10s, per 1M keys

Please review the C++ code; I think it can be significantly improved (I'm bad in C++). Code compiles and works same as JS. Also please advise me, which programming language is better for this: JS, C++ , Haskell or Go?

Here's the C++ code; it requires libb2-dev and libjsoncpp-dev (run sudo apt install libb2-dev libjsoncpp-dev to install it on Ubuntu):

//"g++"  "main.cpp" -o "main" -lb2 -ljsoncpp
#include <sstream>
#include <string>
#include <iostream>
#include <ctime>
#include <blake2.h>//libb2-dev
#include <jsoncpp/json/json.h>//libjsoncpp-dev
#include <iomanip>

char TOPSECRET[] = "TOPSECRET";
long dateCounter = 0;

std::string gameKey(long id2=-1){

  long long id = std::time(0)*1000+dateCounter;
  if(id2!=-1){
    id = id2;
  }
  dateCounter++;

  std::stringstream inStream;
  inStream << id << "|keys|" << TOPSECRET;
  const std::string inString = inStream.str();
  const char* in = inString.c_str();

  size_t outlen=64;
  uint8_t* out = new uint8_t[outlen];
  char key[] = "";
  blake2b(out,in,&key,outlen,inString.length(),0);

  std::stringstream a,b,c,d;
  for(int i=0;i<16;i++){
    a << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
  }
  for(int i=16;i<16*2;i++){
    b << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
  }
  for(int i=16*2;i<16*3;i++){
    c << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
  }
  for(int i=16*3;i<16*4;i++){
    d << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(out[i]);
  }

  Json::Value obj(Json::objectValue);
  obj["id"] = id;

  Json::Value arr(Json::arrayValue);
  arr.append(a.str());
  arr.append(b.str());
  arr.append(c.str());
  arr.append(d.str());
  obj["keys"] = arr;

  Json::Writer* writer = new Json::FastWriter();
  std::string jsonOut = writer->write(obj);

  delete writer;
  //delete in;//comment=memory leak, uncomment=segfault when gameKey() is called more than once
  delete out;

  return jsonOut;
}

int main(){
  std::cout << gameKey();
  std::cout << gameKey();
}

Here's the node.js version; it needs blakejs (run npm i blakejs to install it):

const TOPSECRET = "TOPSECRET", blake = require("blakejs").blake2bHex;
let dateCounter = 0;

function gameKey(checkId){
  let id = checkId || (Date.now()/1000>>0)*1000+(dateCounter++%1000),
    keys = blake(`${id}|keys|${TOPSECRET}`).match(/.{32}/g);
  return {id, keys};
}
console.log(gameKey());


texts: Determine children within edge and return a list of tuple pairs

texts:
I've been studying hard and asking a lot of questions - I finally came a cross an exercise in LYAH that looked like it was easy enough but a perfect candidate for practicing.

The below program has a bunch of helper funcs in there, but the one of interest is neighbors/3.  It takes a Pair type and Edge number, and a BiMorph type. It then determines all of the children within that edge and returns it as a list of tuple pairs.

I would like a more experienced Haskeller to come in and tear it apart or to give me constructive criticism.

import Control.Monad
import Control.Applicative

data Pair a    = Pair a a deriving (Show, Eq)
data BiMorph a = BiMorph Func Func

type Neighbors = [(Int, Int)]
type Matrix    = [[Int]]
type Func      = (Int -> Int -> Int)

instance Functor Pair where
   fmap f (Pair a b) = Pair (f a) (f b)

instance Applicative Pair where
   pure a = Pair a a
   (Pair fa fb) <*> (Pair a b) = Pair (fa a) (fb b)

matrix :: Int -> Int -> Matrix
matrix xl yl = replicate yl $ [1..xl]

cartesianPairs :: Func -> Pair Int -> [Pair Int]
cartesianPairs f p =
    [(f <$> (Pair x y) <*> p) | x <- [1,0], y <- [0,1], (x,y) /= (0,0)]

cartesianDoubles :: Func -> Func -> Pair Int -> [Pair Int]
cartesianDoubles f g (Pair x y) = [Pair (f x 1) (g y 1), Pair (g x 1) (f y 1)]

dropP :: Pair Int -> (Int, Int)
dropP (Pair x y) = (abs x, abs y)

liftP :: (Int, Int) -> Pair Int
liftP (x, y) = Pair x y

neighbors :: Pair Int -> Int -> BiMorph Int -> Neighbors
neighbors p e (BiMorph f g) =
    map dropP $ concat [(cartesianPairs f p), (cartesianPairs g p), (cartesianDoubles f g p)]
        >>= (\(Pair x' y') -> guard (x' <= e && y' <= e)
            >> return (Pair x' y'))


texts: Python code for serving k customers with bounded time window

texts:
As I asked a question here, I want to write a python code for the following problem:
A person provides a service and he/she can serve \$k\$ clients each minute. Now, client number \$i\$ comes at the beginning of minute \$ a_{i} \$ and waits \$w_{i}\$ minutes to receive the service and if they don't receive the service in the interval \$[a_{i}, a_{i} + w_{i}]\$, they leave. If we have \$n\$ clients, can the person serve all them or not?
Now, by the answer stated there, I wrote the following code.
intervals = [] # Some intervals like [[1, 2], [1, 100], [1, 1], [5, 20]]

intervals = sorted(intervals)

start = intervals[0][0]
end = intervals[-1][1]

i = start
while i < end:
    if not intervals:
        break
    else:
        for j in range(k):
            try:
                if intervals[0][0] <= i <= intervals[0][1]:
                    del intervals[0]
                else:
                    break
            except:
                pass
    i += 1

if not intervals:
    print('YES')
else:
    print('NO')

My question: Is my code right? Can it become more efficient?


texts: Calculate course module credits from individual assessment scores

texts:
I'm currently working on a grade calculator for a university (professionally), and I am wondering if anyone can suggest an improvement to the following query? Here is my database:

The query returns the following table:

SELECT
        `course`.`title` AS `course_title`,
        `yearGroup`.`id` AS `year_group_id`,
        `yearGroupLookup`.`yearGroup` AS `year_group`,
        `yearGroup`.`max_credits`,
    TRUNCATE
        (
            COALESCE(
                SUM(
                    `assessment`.`percentage_achieved` *(
                        `assessment`.`percentage_weighting` / 100
                    ) /(
                    SELECT
                        COUNT(*)
                    FROM
                        `module`
                    WHERE
                        `yearGroup`.`id` = `module`.`year_group_id`
                )
                ),
                0
            ),
            2
        ) AS `grade`,
    TRUNCATE
        (
            COALESCE(
                SUM(
                    `assessment`.`percentage_achieved` *(
                        `assessment`.`percentage_weighting` / 100
                    ) /(
                    SELECT
                        COUNT(*)
                    FROM
                        `module`
                    WHERE
                        `yearGroup`.`id` = `module`.`year_group_id`
                )
                ),
                0
            ) / 100 * `yearGroup`.`max_credits`,
            2
        ) AS `credit_achieved`
    FROM
        `assessment`
    RIGHT JOIN `module` ON `module`.`id` = `assessment`.`module_id`
    RIGHT JOIN `yearGroup` ON `yearGroup`.`id` = `module`.`year_group_id`
    RIGHT JOIN `course` ON `course`.`id` = `yearGroup`.`course_id`
    RIGHT JOIN `yearGroupLookup` ON `yearGroup`.`yearLookup_id` = `yearGroupLookup`.`id`
    WHERE
        `yearGroup`.`course_id` = 1
    GROUP BY
        `yearGroup`.`id`


texts: Applying Scikit-Learn Linear Kernel with a generator for low memory pressure

texts:
matrix = # a sparse matrix of TFIDF vectors - 28458x3218988

My aim was to create a similarity matrix comparing all documents to all documents using sklearn.metrics.pairwise.cosine_similarity but the doc notes indicated that with normalized values, such as TFIDF vectors, that `linear_kernel' was equivalent with better performance.

I tried linear_kernel(matrix,matrix) which I believe is valid but was clearly going to take a long time and was resulting in high memory pressure. My solution which uses a generator and writing to disk to alleviate memory pressure, functions, but I wondered if there was any way to speed it up.

def cos_compare(corpus_matrix):
    for i in range(0, corpus_matrix.shape[0]):
        x = linear_kernel(corpus_matrix[i],corpus_matrix)
        yield i,x

My generator cos_compare iterates through the matrix row by row, yielding the index  and the result of applying linear kernel to measure the similarity between document at index i and all documents.

try:
    with open('cosine_data.csv','a') as f:
        for i,x in cos_compare(matrix):
            if i%100 == 0:
                print('Saving Row {} of {}:'.format(i, matrix.shape[0]))
            pd.DataFrame(x).to_csv(f, header=False,index=False,mode='a')

finally:
    cosine_data = pd.read_csv('cosine_data.csv', header=None)
    print(cosine_data.head())

The script opens 'cosine_data.csv' for appending and then initializes cos_compare() generator. The single row array that the generator yields as x is then converted to a pandas DataFrame for convenience when writing a line to disk (np.savetxt() was throwing format errors).

Currently works fine but am I overlooking any optimizations from numpy,pandas or scikit that I could use?


texts:
I have created a simple event manager and I want it to work properly in a multithreaded environment:

public enum EventType {
    EVENT_TYPE_A,
    EVENT_TYPE_B,
    EVENT_TYPE_C;
}

public interface Observer {
    void onEvent(EventType eventType);
}

public class ObserverManager {
    private Set<Observer> m_weakReferencedObservers;

    public ObserverManager() {
        m_weakReferencedObservers = Collections.newSetFromMap(new WeakHashMap<Observer,Boolean>()); // allows a set of weak references
    }

    public void add(Observer observer){
        if (observer != null) {
            m_weakReferencedObservers.add(observer);
        }
    }

    public void remove(Observer observer){
        m_weakReferencedObservers.remove(observer);
    }

    public void callEvent(EventType eventType){
        m_weakReferencedObservers.stream()
                .filter(Objects::nonNull)
                .forEach(observer -> observer.onEvent(eventType));

        m_weakReferencedObservers.remove(null);
    }
}

public class EventManager {
    private Map<EventType,ObserverManager> m_observerManagers = new HashMap<>();

    public void registerObserver(EventType eventType,Observer observer){
        synchronized (m_observerManagers){
            if (!m_observerManagers.containsKey(eventType)){
                m_observerManagers.put(eventType,new ObserverManager());
            }

            ObserverManager observerManager = m_observerManagers.get(eventType);
            observerManager.add(observer);
        }
    }

    public void unregisterObserver(EventType eventType,Observer observer){
        synchronized (m_observerManagers) {
            if (!m_observerManagers.containsKey(eventType)) {
                return;
            }

            ObserverManager observerManager = m_observerManagers.get(eventType);
            observerManager.remove(observer);
        }
    }

    public void callEvent(EventType eventType){
        if (!m_observerManagers.containsKey(eventType)){
            return;
        }

        ObserverManager observerManager = m_observerManagers.get(eventType);
        observerManager.callEvent(eventType);
    }
}

A few points:

Is my use of weak references appropriate here?
Is my use of the synchronized keyword appropriate here?
In general, is there a better way to implement this?
If I want my event manager to be able to send many more different onEvent methods (with different prototypes), what's the best way to do it? So, instead of only having onEvent(EventType eventType), I could also easily use onEvent(EventType eventType, MyClass myClass). I mean, in general, how can I let the user of this class create his own onEvent() prototype?


texts:
I've tried to improve my code: separate HTML/PHP, much clear, next time change will be easier.  After doing research on MVC/OOP, I've made the below code to learn.

I understand this is not the MVC pattern now.  Can anybody help me fix it to become actual MVC?

get the result from db (list all)
get the result from db (list search)

index.php

require_once 'grant.php';
require_once 'controller.php';
$controller = new controller();
$controller -> temp_index();

controller.php

require_once 'model.php';
class controller{
    public $model;
    public function __construct(){
        $this -> model = new model();
    }

    public function temp_index(){
        require 'temp_index.php';
        if($_REQUEST['submit'] == 'get_all'){
            $result = $this -> model -> get_all();
            require 'get_all.php';
        }
        else if($_REQUEST['submit'] == 'get_search'){
            $result = $this -> model -> get_search();
            require 'get_search.php';
        }
    }
}

model.php // please ignore not use PDO

class model{
    public function get_all(){
        $sql = "select * from tb order by id desc";
            $query = mysql_query($sql) or die(mysql_error());
            $result = array();
    while($list = mysql_fetch_array($query)){
                $result[] = $list;
            }
            return $result;
    }
    public function get_search(){
        $search = mysql_real_escape_string($_POST['search']);
        $search = trim($search);
        if($search !== ''){
            $sql = "select * from tb where ac_email like '%$search%'";
            $query = mysql_query($sql) or die(mysql_error());
            if(mysql_num_rows($query) > 0){
                $result = array();
                while($list = mysql_fetch_array($query)){
                    $result['result'][] = $list;
                }
                return $result;
            }
            else{
                $result['statu'] = 'can\'t find search';
                return $result;
            }
        }else{
            $result['statu'] = 'can\'t find search plz input text';
            return $result;
        }
    }
}

get_search.php // view

<?php foreach ($result['result'] as $list) : ?>

<?php print"$list[ac_id]";?>

<?php print"$list[ac_email]";?>

<?php endforeach; ?>

<?php print"$result[statu]";?>

temp_index.php // view

<form action="" method="POST">
    <input type="submit" name="submit" value="get_all">
</form>
<form action="" method="POST">
    <input type="text" name="search">
    <input type="submit" name="submit" value="get_search">
</form>


texts: Calculating the count of integer partitions of a number (uses stateful vectors internally)

texts:
I've written a Haskell function to count the number of partitions of an integer - it's basically an implementation of the same algorithm as this one, using Euler's Pentagonal Number Theorem:

$$P(n) = \sum_{k=1}^n (-1)^{k+1} \left[ P\left( n - \frac{k\left(3k-1\right)}{2} \right) + P\left( n - \frac{k\left(3k+1\right)}{2} \right) \right]$$

To get it to complete on large-ish inputs (say, 60,000 or so) on a reasonable time , I used a mutable vector, internally. (This cut the time by about half from using an immutable vector, and by a ... very large amount, I forget how much, from using "pure" memoization.) It now calculates \$p(60000)\$ in about 8 seconds or so on my machine, which is reasonable for my purposes. (Though three times slower than a C++ equivalent.)

I wondered if anyone had any suggestions for getting similar performance, but without using mutable state?

Gist

{-# LANGUAGE BangPatterns #-}

import Control.Monad (when, forM_, forM)

import Data.STRef
import Control.Monad.ST

import qualified Data.Vector.Generic.Mutable as GM
import Data.Vector.Generic.Mutable ( write )
import qualified Data.Vector.Mutable as VM

main :: IO ()
main = do
  print $ part 60000

fint :: (Num b, Integral a) => a -> b
fint = fromIntegral

part :: Int -> Integer
part n = runST $ do
  vec <- VM.replicate (n+1) (-3)
  write vec 0 1
  result <- newSTRef (-1)
  forM_ [1..n] $ \i' -> do
      let i = ((fromIntegral i') :: Integer)
      !sR <- newSTRef 0
      let -- loop :: Integer -> ST s ()
          loop k = do
              let f = (fint (i - k * (3 * k - 1) `div` 2))
              when (not (f < 0)) $ do
                   if k `mod` 2 /= 0
                      then do vec_f <- GM.read vec f
                              modifySTRef' sR (\s -> s + vec_f)
                      else do vec_f <- GM.read vec f
                              modifySTRef' sR (\s -> s - vec_f)
                   let f = (fint (i - k * (3 * k + 1) `div` 2))
                   let xx = f :: Int
                   when (not (f < 0)) $ do
                        if k `mod` 2 /= 0
                          then do vec_f <- GM.read vec f
                                  modifySTRef' sR (\s -> s + vec_f )
                          else do vec_f <- GM.read vec f
                                  modifySTRef' sR (\s -> s - vec_f)
                        loop (k + 1)
      loop 1 -- k starts at 1
      !s <- readSTRef sR
      write vec i' s
      when (i' == n) $
        writeSTRef result s
  readSTRef result


texts: Algorithm for building a string by appending and cloning substrings

texts:
I have a problem where I need to construct a given string from scratch for a minimum cost by either:

Appending a new character for a cost A

Appending a substring of my existing string for a cost B

E.g. for a string "abcabc" with a cost of A = 10, B = 11

a 10
ab 20
abc 30
abcabc 41

First I tried a greedy algorithm but it didn't give the optimal answer for this problem. I had the idea to use the dijkstra algorithm and a priority queue, so for each popped node I calculated the possibilities for A and B and pushed the new nodes back onto the queue. Since you can't change keys on the priority queue I use an int array ("visited") to keep track of the visited nodes.

However my solution isn't fast enough to finish 30000 char strings in 2 seconds so I wanted to ask for some pointers on how I could optimise/change my approach.

typedef pair<int, int> iPair;
int solve(string &s, int a, int b) {
    priority_queue<iPair, iPair<Node>, greater<iPair>> pq;
    int visited[s.size()];
    for (int i = 0; i < s.size(); ++i)
        visited[i] = -1;
    pq.push(make_pair(a, 0));
    iPair p;
    while (!pq.empty()) {
        p = pq.top();
        pq.pop();
        if (visited[p.second] == -1)
            visited[p.second] = 1;
        else
            continue;
        if (p.second == s.size() - 1)
            break;

        // Handle append costs
        pq.push(make_pair(p.first + a, p.second + 1));

        // Handle clone costs
        int j;
        int i = p.second;

        if (s.size()  > 2*i + 2)
            j = 2*i + 1;
        else
            j = s.size() - 1;

        for (; j > i + 1; --j) {
            if(s.substr(0, i+1).find(s.substr(i+1, j-i)) != string::npos) {
        pq.push(make_pair(p.first + b, j));
                break;
                }
        }
    }
    return p.current_cost;
}

As I say I'm looking for how I'm out of ideas how how to optimise this code and I'm not sure Dijkstra is even the right approach.  I read up how A* search can speed up Dijkstra but I couldn't come up with an easy heuristic function.


texts:
After a little bit of troubleshoots, I've finished this simple users registration and login class. It uses PDO to connect to a mysql database, I've tried also to manage the session when an user do the login or logout. The main objective of this code form me was to make an exercise for using correctly the PDO and related functions, and to start improving my coding skills to manage account creations and login using PHP OOP.

<?php
reqiure_once 'config.php';
class User{

private $db = null;
private $email;
private $username;
private $password;
private $uid;
private $sessioncode;

public function __construct(\PDO $db){

    $this->db = $db;
}

public function createUser($email,$username,$password){

    if($this->checkEmail($email)){
        echo 'Email address already exsist.';
    } elseif($this->checkUsername($username)){
        echo 'Username already exsist.';
    } else {
        $this->password = password_hash($password,PASSWORD_BCRYPT);
        $stmt = $this->db->prepare('INSERT INTO users (email,username,password) VALUES (?, ?, ? )');
        if($stmt->execute(array($email,$username,$this->password))){
        echo 'Account successful created';
        }
    }
}

public function loginUser($username,$password){

    $stmt = $this->db->prepare('SELECT id,username,password FROM users WHERE username = ?');
        $stmt->execute(array($username));
            if($stmt->rowCount() > 0){
                $result = $stmt->fetch(PDO::FETCH_OBJ);
                if(password_verify($password, $result->password)){
                $this->setSession($result->username,$result->id);

            } else {
                echo 'wrong password';
                }
            } else {
                echo 'Username or email does not exist in the database.';
            }
}

public function logoutUser($uid){

    $this->unsetSession($uid);
}

private function checkEmail($email){

    $stmt = $this->db->prepare('SELECT email FROM users WHERE email = ?');
        $stmt->execute(array($email));
        if($stmt->rowCount() > 0){
        return true;
        } else {
        return false;
        }
}

private function checkUsername($username){

    $stmt = $this->db->prepare('SELECT username FROM users WHERE username = ?');
        $stmt->execute(array($username));
        if($stmt->rowCount() > 0){
        return true;
        } else {
        return false;
        }
}

private function setSession($username,$uid){

    $this->sessioncode = bin2hex(rand());
    $_SESSION['id'] = $uid;
    $_SESSION['username'] = $username;
    $_SESSION['session_code'] = $this->sessioncode;
        $stmt = $this->db->prepare('UPDATE users SET session_code = ? WHERE id = ?');
        if($stmt->execute(array($this->sessioncode,$uid))){
        header('Location: u/dashboard.php');
    }
}

private function unsetSession($uid){

    $this->uid = $uid;
    $this->sessioncode = '';
    $stmt = $this->db->prepare('UPDATE users SET session_code = ? WHERE id = ?');
        if($stmt->execute(array($this->sessioncode,$this->uid))){
        session_unset();
        session_destroy();
        header('Location: ../index.php');
    }
}

}
?>


texts: Java builder for user contact information, with optionals

texts:
I have this simple builder here:

public class User {

    private final String name;
    private final String lastname;
    private final String phone;

    private User(Builder builder) {
        this.name = builder.name;
        this.lastname = builder.lastname;
        this.phone = builder.phone;
    }

    public String getName() {
        return name;
    }

    public String getLastname() {
        return lastname;
    }

    public String getPhone() {
        return phone;
    }

    public static class Builder {
        private String name;
        private String lastname;
        private String phone = "";

        public Builder(String name, String lastname) {
            name(name);
            lastname(lastname);
        }

        private Builder name(String name) {
            this.name = Optional.ofNullable(name).orElseThrow(() -> new IllegalArgumentException("Name must not be null"));
            return this;
        }

        private Builder lastname(String lastname) {
            this.lastname = Optional.ofNullable(lastname).orElseThrow(() -> new IllegalArgumentException("Last name must not be null"));
            return this;
        }

        public Builder phone(String phone) {
            this.phone = Optional.ofNullable(phone).orElse("");
            return this;
        }

        public User build() {
            return new User(this);
        }

    }
}

This code works as expected but I have some doubts. My question is about private methods in builder (name and lastname). Is it allowed in a world of a clean code? And also about this Optionals, are they well written? I just started using this functionality so I don't know for sure if I am right here.


texts: normal distribution line does not show up when plotting

texts:
I am plotting a distribution of 10,000 samples of sum of 100 poisson variables, and overlaying that distribution of the approximate normal distribution. However, the normal distribution line does not show up. I also plotted with sum of 4 variables, in which case it worked. So what is the difference here that makes normal distribution disappear?
Here is my code in the sum of 4 variables case
final = c()
for (i in 1:10000){

sum = sum(rpois(4,2))
final = c(final,sum)
}

dens_final = density(final)
aprox_norm <- dnorm(min(final):max(final), 8,sqrt(8))
plot(dens_final)
lines(aprox_norm, col='red')

and here is my code of sum of 100 variables
final = c()
for (i in 1:10000){

sum = sum(rpois(100,2))
final = c(final,sum)
}

dens_final = density(final)
aprox_norm <- dnorm(min(final):max(final), 200,sqrt(200))
plot(dens_final)
lines(aprox_norm, col='red')

I have also attached images of the 2 plots as reference


texts:
I am building this program in Python to generate 10 random arithmetic questions of either multiplication, addition or subtraction and then saves users scores to a .txt file. I just wanted some help condensing the code as I'm really stuck as of what to do with it.

How can I combine the function (e.g. multiplication, addition and subtraction) into one?

import random
import time
import sys

ans = 0   #variable to hold question answer
question = 0   #question number
user_score = 0  #user's score
userInput = int()   #where user enters the answer
lastName = str()   #holds last name
firstName = str()   #holds first name
form = str()    #holds user's form

def function(score,name):   #writes user's information to a .txt file
    sumOfStudent = (name + ' scored ' + str(user_score))
    classNameTxt = (className, '.txt.')
    f = open(className, 'a')
    f.write(sumOfStudent + form + '\n')
    f.close()

def multiplication():   #creates a multiplication question
    global ans
    numberOne, numberTwo  = random.randint(0,20), random.randint(0,20)
    print("What is" , numberOne , "*" , numberTwo)
    ans = (numberOne * numberTwo)

def subtraction():   #creates a subtraction question
    global ans
    numberOne, numberTwo  = random.randint(0,20), random.randint(0,20)
    print("What is" , numberOne , "-" , numberTwo)
    ans = (numberOne - numberTwo)

def addition():   #creates a addition question
    global ans
    numberOne, numberTwo  = random.randint(0,20), random.randint(0,20)
    print("What is" , numberOne , "+" , numberTwo)
    ans = (numberOne + numberTwo)

operation = [multiplication,subtraction,addition]   #holds all of the opperators
randOperation = random.choice(operation)    #chooses a random operator

lastName = input("Please enter your surname: ").title()
firstName = input("Please enter your first name: ").title()
className = input("Please enter your form: ").title()
print()

def main():   #main game loop - ask questions and checks it against answer, stops are a give amount of questions
    question = 0
    user_score = 0
    randOperation = random.choice(operation)

    while True:
        try:
            randOperation()
            randOperation = random.choice(operation)
            if question >= 10:
                break
            userInput = int(input("Enter the answer: "))
            if userInput == ans:
                print("Correct!" + "\n")
                user_score += 1
                question += 1
            else:
                print("Incorrect!" + "\n")
                question += 1
        except ValueError:
            print("I'm sorry that's invalid")
            question += 1

main()    #initializes the function

print(firstName, lastName , "you scored" , user_score , "out of 10")   #shows the user's score and name

user_name = firstName + ' ' + lastName
function(user_score,user_name)

def endMenu():
    while True:
        try:
            options = int(input('''Press '1' to view users' scores,
            press '2' to restart the test,
            press '3' to exit the game,

            Enter option here: '''))
        except ValueError:
            print("I'm sorry that was invalid...")

        if options == 3:  #exits the game...
            sys.exit()

        elif options == 2:   #starts the game loop again because it's in a function
            main()

        elif options == 1:   #displays everything on the .txt file
            f = open('userScore.txt', 'r')
            print(f.read())
            print()
            endMenu()

        else:
            print("Sorry, I don't understand. Please try again...")
            print()
            endMenu()

endMenu()


texts:
The purpose of this is to prevent a re-entrant function call in a single thread, e.g. prevent the situation where func() calls bar() which calls func().

This is currently not used in any multithreaded code (and does not plan to be).

struct TranLock
{
static int count;
    bool failed;
    TranLock() { failed = count; if (!failed) ++count; }
    ~TranLock() { if (!failed) --count; }
};
int TranLock::count = 0;

Usage:

void func()
{
    TranLock lock;
    if ( lock.failed )
        return;   // or take other action

    // the function's logic here
}

Is there a better idiom for this, e.g. involving std::shared_ptr ? C++11 features OK.

Update: As pointed out by Greg Hewgill, if multiple functions use TranLock they will all have a shared lockout. Currently I only use it in one function, although it would be nice to see two different possible implementations:

Lock which can be shared amongst functions
Individual lock per function

(perhaps this could be controlled with a template parameter or something).


texts:
Following this SO post and this Wikipedia article, I wrote a Python script to simulate physics of 2D elastic balls.

I define the physical behaviour of each ball in the Ball class. Then the function solve_step enables to compute position and velocity of every ball for one time step.

The balls are moving inside a square. Two balls rebound elastically from each other (see compute_coll function). When a ball hits one edge of the square, it bounces off elastically (see compute_refl function).

Note that I'm using 2 functions step1 and step2 for solve_step because that makes the program faster.

Moreover I provide a main to run an example of simulation.

Here I don't show the code used to display the simulation in a window because I think this is another issue.

Any ideas on optimizing and simplifying this code?

import numpy as np

Ball class

class Ball:
    """Define physics of elastic collision."""

    def __init__(self, mass, radius, position, velocity):
        """Initialize a Ball object

        mass the mass of ball
        radius the radius of ball
        position the position vector of ball
        velocity the velocity vector of ball
        """
        self._mass = mass
        self._radius = radius
        self._position = position
        self._velocity = velocity
        self._vafter = np.copy(velocity) # temp storage for velocity of next step

    def compute_step(self, step):
        """Compute position of next step."""
        self._position += step * self._velocity

    def new_velocity(self):
        """Store velocity of next step."""
        self._velocity = self._vafter

    def compute_coll(self, ball, step):
        """Compute velocity after elastic collision with another ball."""
        m1 = self._mass
        m2 = ball._mass
        r1 = self._radius
        r2 = ball._radius
        v1 = self._velocity
        v2 = ball._velocity
        x1 = self._position
        x2 = ball._position
        di = x2-x1
        norm = np.linalg.norm(di)
        if norm-r1-r2 < step*abs(np.dot(v1-v2,di))/norm:
            self._vafter = v1 - 2.*m2/(m1+m2) * np.dot(v1-v2,di)/(np.linalg.norm(di)**2.) * di

    def compute_refl(self, step, size):
        """Compute velocity after hitting an edge.

        step the step of computation
        size the size of a square edge
        """
        r = self._radius
        v = self._velocity
        x = self._position
        projx = step*abs(np.dot(v,np.array([1.,0.])))
        projy = step*abs(np.dot(v,np.array([0.,1.])))
        if abs(x[0])-r < projx or abs(size-x[0])-r < projx:
            self._vafter[0] *= -1
        if abs(x[1])-r < projy or abs(size-x[1])-r < projy:
            self._vafter[1] *= -1.

Solver

def step1(ball_list, step, size):
    """Detect reflection and collision of every ball."""
    index_list = range(len(ball_list))
    for i in index_list:
        ball_list[i].compute_refl(step,size)
        for j in index_list:
            if i!=j:
                ball_list[i].compute_coll(ball_list[j],step)
    return ball_list

def step2(ball_list, step):
    """Compute position of every ball."""
    index_list = range(len(ball_list))
    for i in index_list:
        ball_list[i].new_velocity()
        ball_list[i].compute_step(step)
    return ball_list

def solve_step(ball_list, step, size):
    """Solve a step for every ball."""
    ball_list = step1(ball_list, step, size)
    ball_list = step2(ball_list, step)
    return ball_list

Main

def init_list(N):
    """Generate N Ball objects in a list."""
    ball_list = []
    r = 10.
    for i in range(N):
        v = 10.*np.array([(-1.)**i,1.])
        pos = 400./float(N+1)*np.array([float(i+1),float(i+1)])
        ball_list.append(Ball(r, r, pos, v))
    return ball_list

if __name__ == "__main__":
    ball_list = init_list(10)
    size = 400.
    step = 0.05
    for i in range(5000):
        solve_step(ball_list, step, size)


texts:
I have 3 nested NSEnumeration loops, which are used to get the textfields of a custom cell, in a custom table in a custom view in a controller.

How can I make this code more readable and more optimizated?

- (void) textfieldsOperations:(APOperation)op
{
  __block int Valid = 0;
  __block NSArray *sub = _Table.subviews;
  __block MyCell *cell = nil;
  __block UIView *view = nil;
  __block NSMutableArray *ret = [NSMutableArray arrayWithCapacity:5];

  [sub enumerateObjectsUsingBlock:^(id c, NSUInteger index, BOOL *stop)
  {
    if ( [c isKindOfClass:[MyCell class]] ) {
      cell = c;
      [cell.subviews enumerateObjectsUsingBlock:^(id v, NSUInteger index, BOOL *stop)
      {
        if ( [v isKindOfClass:[UIView class]] ) {
          view = v;
          [view.subviews enumerateObjectsUsingBlock:^(id t, NSUInteger index, BOOL *stop)
          {
            if ( [t isKindOfClass:[MyTextField class]] )
            {
              MyTextField *txt = t;
              switch ( op )
              {
                case APOperationClear:
                  // something with "txt"
                  break;
                case APOperationEnableSearch:
                  // something with "valid"
                  break;
                case APOperationGetText:
                  // something with "txt"
                  break;
                case APOperationPos: {
                  // something with "txt"
                  break;
                }
              }
            }
          }];
        }
      }];
    }
  }];
  //[...]
}


texts: Get value from a dictionary contained in a dictionary

texts:
I have an API that returns a dictionary of dictionaries.

I currently have this code to access the value of the dictionary, but it looks like a code smell. Is there a better way to structure this?

// Dictionary<string, Dictionary<DateTime, string>> CountryCode();

var response = api.CountryCode();

string GB2001;
if (response.ContainsKey("GB") && response["GB"].ContainsKey(new DateTime(2001, 04, 01)))
{
    GB2001 = response["GB"][new DateTime(2001, 04, 01)];

    // Use the result of GB2001 here
}


texts: Doubly circular linked list implementation

texts:
I made this C++ doubly circular linked list implementation and it seems to work right, handle everything well, and not have any errors. However, I've been working with it for a while and would like some fresh eyes to take a look and see if I am missing anything large or if my code contains any 'gotchas'.

Side note: I ran valgrind on several tests of this implementation and never got any memory leaks so I suspect it is handling that end of this correctly.

CLL.h

#ifndef CLL
#define CLL

class CircularLinkedNode {
public:
    int info;
    CircularLinkedNode *next, *prev;

    CircularLinkedNode() {
        next = prev = this;
    }

    CircularLinkedNode(int num) {
        info = num;
        next = prev = this;
    }

    CircularLinkedNode(int nu, CircularLinkedNode *ne, CircularLinkedNode *pre) {
        info = nu;
        //auto put new node in the middle of next and previous
        next = ne;
        prev = pre;
        prev->next = this;
        next->prev = this;
    }

    ~CircularLinkedNode() {
        //when deleted, seal the gap
        //prev->next = next;
        //next->prev = prev;
    }
};

class CircularLinkedList {
private:
    CircularLinkedNode *head, *tail;
public:
    CircularLinkedList() {
        head = tail = 0;
    }

    ~CircularLinkedList();

    bool isEmpty() const {
        return head == 0;
    }

    void addToHead(int);
    void addToTail(int);
    int removeFromHead();
    int removeFromTail();
    void remove(int);
    bool isInList(int) const;

};

#endif

CLL.cpp

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

CircularLinkedList::~CircularLinkedList() {
if (isEmpty()) {
    return;
}
if(head == tail) {
    delete head;
    head = tail = 0;
    return;
}

    CircularLinkedNode *tmp = head->next;
    delete head;
    while(tmp != tail) {
        head = tmp;
        tmp = tmp->next;
        delete head;
    }
    delete tail;

}

void CircularLinkedList::addToHead(int n) {
    isEmpty() ? head = tail = new CircularLinkedNode(n) : head = new     CircularLinkedNode(n, head, tail);
}

void CircularLinkedList::addToTail(int n) {
    isEmpty() ? tail = head = new CircularLinkedNode(n) : tail = new CircularLinkedNode(n, head, tail);
}

int CircularLinkedList::removeFromHead() {
    if(isEmpty()) {
        return 0;
    }

    int el = head->info;
    if(head == tail) {
        delete head;
        head = 0;
        return el;
    }

    CircularLinkedNode *tmp = head;
    head->prev->next = head->next;
    head->next->prev = head->prev;
    head = head->next;
    std::cout << "delete" << std::endl;
    delete tmp;
    return el;
}

int CircularLinkedList::removeFromTail() {
    if(isEmpty()) {
        return 0;
    }

    int el = tail->info;
    if(head == tail) {
        delete tail;
        tail = 0;
        return el;
    }
    CircularLinkedNode *tmp = tail;
    tail->prev->next = tail->next;
    tail->next->prev = tail->prev;
    tail = tail->prev;
    std::cout << "delete" << std::endl;
    delete tmp;
    return el;
}

void CircularLinkedList::remove(int n) {
    if (!isEmpty()) {
        if (head->info == n) {
            removeFromHead();
            return;
        } else if (tail->info == n) {
            removeFromTail();
            return;
        } else {
            CircularLinkedNode *tmp;
            for (tmp = head; tmp != tail && !(tmp->info == n); tmp = tmp->next);
            if(tmp != tail) {
                tmp->prev->next = tmp->next;
                tmp->next->prev = tmp->prev;
                delete tmp;
            }
        }

    }
}

bool CircularLinkedList::isInList(int el) const {
    CircularLinkedNode *tmp;
    for (tmp = head; tmp != tail && !(tmp->info == el); tmp = tmp->next);
    return (tmp->info == el);
}


texts: Find the longest string without repeating a letter

texts:
I've written some code to scan large files and search for long strings that you can write without repeating a letter. I'm self-taught in python and I'm wondering what I've missed.

import sys
letters ={} #letters is a dictionary
currentResult=""
ideas=[]
with open(sys.argv[1]) as f:
  while True:
    c = f.read(1)
    if not c:
      print "End of file"
      break
    if c in letters:
        letters={}
        temp=currentResult.rsplit(' ',1)[0]
        ideas.append(temp.rstrip('?:!.,;'))
        currentResult=""
    currentResult+=c
    if not c.isspace():
        letters[c]=True
ideas=sorted(set(ideas))
ideas.sort(lambda x,y: cmp(len(x), len(y)))
for x in ideas:
    print x.strip()


texts: Laravel session handler for Phpbb sessions

texts:
Ok, so I am developing a Laravel 5.5 app that needs to interface with an existing phpBB forum.  Specifically, if you log into the phpBB forum, you must also be logged into the Laravel app.  Otherwise, users will have to log into both separately, and I feel that would be terrible user experience for my site.  The forums exist already and have a database of users as well as extensive functionality for user creation, logging in, administration, roles & permissions, etc, so rather than build all that, I'd like phpBB to handle most of the heavy lifting.

That's why I implemented this hacky custom session handler in Laravel (which works):

class PhpbbSessionHandler implements SessionHandlerInterface
{
    private function getPhpbbSessionId() {
        $key = config('session.phpbb_cookie');
        return isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
    }

    protected function getLaravelSessionQuery($id) {
        return DB::table( config('session.table') )->where('laravel_session_id', $id);
    }

    protected function getBBSessionQuery() {
        return DB::table( config('session.table') )
                ->where( 'session_id', $this->getPhpbbSessionId() )
                ->where( 'session_user_id', '!=', config('session.phpbb_anonymous') );
    }

    // Needed for interface
    public function open($savePath, $sessionName) {}
    public function close() {}

    /**
     * Look for existing session in Laravel, then phpBB
     */
    public function read($sessionId) {
        $session = $this->getLaravelSessionQuery($sessionId)->first();

        if($session) {
            // We are logged in, set the authenticated user
            $user = User::find($session->session_user_id);
            Auth::setUser($user);

            return ($session->payload) ? base64_decode($session->payload) : null;
        }
        else {
            // The forum is logged in, but Laravel is not. Let's log them in.
            $bb_user_id = $this->getBBSessionQuery()->value('session_user_id');

            if($bb_user_id) {
                Auth::loginUsingId($bb_user_id);
            }

            return;
        }
    }

    /**
     * Update session data
     */
    public function write($sessionId, $data) {
        $update['payload'] = base64_encode($data);

        if( $this->getLaravelSessionQuery($sessionId)->exists() ) {
            return $this->getLaravelSessionQuery($sessionId)->update($update);
        }
        else {
            $update['laravel_session_id'] = $sessionId;
            return $this->getBBSessionQuery()->update($update);
        }
    }

    public function destroy($sessionId) {
        return $this->getLaravelSessionQuery($sessionId)->delete();
    }

    /**
     * Clear out expired session records
     */
    public function gc($lifetime) {
        return DB::table( config('session.table') )->where('session_time', '<', $lifetime)->delete();
    }
}

The part I'd really like feedback on is the read method. It definitely is vulnerable to session hijacking, but without messing around deep in the lowest levels of phpBB source code, or implementing encryption that both apps can handle exactly the same, I'm not sure what to do.  This is already deeper into Laravel than I usually go, so any constructive feedback would be appreciated.


texts: Rendering and re-rendering a Mustache template

texts:
I want to ask whether my following implementation is good in the view of good practice and performance. I have an app where I have to show another page or template html in an iframe. I get that template html via ajax and render it in the iframe. Iframe must be used because the template must be isolated.I am now storing that template html in a javscript variable

var tmp;
$.get('/template/1', function(data){  tmp = $(data); });
// tmp = '<html><body>....etc...</body></html'; holds whole template

and then I have my div container in that template where I use mustache for changing content.

var render = tmp.find('#container').html();
var rendered = Mustache.to_html(render, some_data);
//then
tmp.find('#container').html(rendered);
// and add tmp to iframe

I am storing whole html in tmp so that it can be used later also and when my some_data change I again process tmp and re-render template in iframe. I may need re-render template many times later so I am storing in in variable. Is it good to store whole template html in javascript variable like that or it's better use other ways...if there are other ways what are they...


texts: Winsock chat server and client application

texts:
I have made a C++ command line chat with server and clients as a hobby project.

Here is the GitHub link.

#include <iostream>

#include <winsock2.h>

#include <windows.h>

#include "Class_Logger.hpp"

using namespace std;

SOCKET ServerCom = INVALID_SOCKET;

int ClientAddressSize;

SOCKADDR_IN ClientAddress;

 char lftxt[40] = "../Logs/ClientNetworkInitLogs";

 logfile lf(lftxt);

 class ClientNetworkInit

{

    private:

     WSAData ClientNetworkData;

 char message[512];

  public:

  ClientNetworkInit(char sIP[],u_short sPORT)

   {

    lf.writeLog(sIP);

   cout<<"Intializing Winsock API";

        strcpy(lftxt,"Initializing Winsock API");

        lf.writeLog(lftxt);

     for(int i=0;i<15;i++)

     {

         cout<<".";

         Sleep(100);

     }

     if(!WSAStartup(MAKEWORD(2,1),(WSAData*)&ClientNetworkData))

     {

        cout<<"done"<<endl;

        strcpy(lftxt,"done");

         lf.writeLog(lftxt);

        }

        else

        {

            cout<<"Error starting Winsock API"<<endl;

            strcpy(lftxt,"Error starting Winsock API");

         lf.writeLog(lftxt);

         cout<<"Shutting down the server"<<endl;

         strcpy(lftxt,"Error starting Winsock API");

         lf.writeLog(lftxt);

            lf.~logfile();

            closesocket(ServerCom);

 WSACleanup();

 exit(0);

        }

   ClientAddress.sin_addr.s_addr = inet_addr(sIP);

     ClientAddress.sin_port = htons(sPORT);

     ClientAddress.sin_family = AF_INET;

     ClientAddressSize = sizeof(ClientAddress);

     ServerCom = socket(AF_INET,SOCK_STREAM,0);

     if(ServerCom == INVALID_SOCKET)

     {

     cout<<"Error initialising socket"<<endl;

     strcpy(lftxt,"Error starting socket");

         lf.writeLog(lftxt);

         lf.~logfile();

            closesocket(ServerCom);

 WSACleanup();

 exit(0);

        }

        else

        {

            cout<<"Socket Intialised"<<endl;

            strcpy(lftxt,"Socket Intialised");

         lf.writeLog(lftxt);

        }

    }

 void ConnectServer()

 {

 int val;

 val = connect(ServerCom,     (SOCKADDR*)&ClientAddress,ClientAddressSize);

 if(!val)

 {

    cout<<"Connected to server"<<endl;

     strcpy(lftxt,"Connected to server");

         lf.writeLog(lftxt);

        }

     else

     {

     cout<<"Unable to connect to the server"<<endl;

     strcpy(lftxt,"Unable to connect to the server");

         lf.writeLog(lftxt);

     cout<<"Closing chat client"<<endl;

     strcpy(lftxt,"Closing chat client");

         lf.writeLog(lftxt);

         lf.~logfile();

     WSACleanup();

     exit(0);

     }

 }

  };

I am a grade 12 student. The C++ syllabus doesn't even include vectors, but I still pulled this project off on my own. Please take this fact into consideration.


texts:
I have a simple encryption module that is used to "encrypt" a text file because it contains some passwords. I only need to encrypt it because I need those passwords in my program (they are used to send an automated bug-report email), but I don't want the end-user to be able to see them.

My "encryption" function is VERY simple and straightforward: it replaces each character in the file with a two-character sequence (either two numbers, two letters, or a number and a letter - these are mapped using a dictionary). The "decryption" function simply reverses the dictionary ({v: k for k, v in _encrypt_key.items()}), then reads the file two-characters at a time and replaces each pair with the corresponding letter. All of this works fine. The file just looks like a bunch of random numbers and letters, so it can't be "read" without the decryption algorithm by any normal end-user.

I used Cython to convert my encryption module (which is a basic Python, .py file), to a .pyd file, so the module itself cannot be read by a normal text-editor.

The problem occurs if the end-user has any Python experience.

For example, it is a very basic task to open the Python console, import the module, open the text file, and decrypt it using the module's "decrypt" function. To prevent this, I used the __main__ module:

import __main__ as main
if hasattr(main, '__file__'):
    # define functions here

Now, it cannot be used interactively in a Python console, because the functions simply won't be defined if it is not being imported from an actual Python program.

To "secure" the key, I made the encryption key local to both functions (both the "encrypt" and "decrypt" functions have a copy of a different variable with the same data). Thus, the user cannot view the key directly.

Finally, I made sure that only certain modules can import it:

import __main__ as main
if hasattr(main, '__file__'):
    path = os.path.basename(main.__file__)
    if path in # tuple of specific files:
        # define functions here

The only loophole I can think of is if the main program itself is edited - other than the encryption module (which is packaged as a .pyd, so I'm not considering it as "open-source"), everything is open-source. If the end-user knows any Python, (s)he can simply open the main program and add a single line, which would show the passwords: print(EXTRA_DATA).

I thought of one way to prevent this:

from __future__ import print_function
print = lambda *args: None # prevent any printing, since my program itself doesn't require it

Of course, the user could always remove this, so it doesn't really fix it.

So, my overall questions are: Can I make this any more secure (make the data and module inaccessible by end-users), and can I prevent any way to print variables in my main program? I want to keep it as open-source if possible.


texts:
I am building a highlight feature for search results on my website and need to escape the user's input so that I could highlight the matching string within the original text.

The function

function sanitize_for_regex(s){
    var escaped = '';
    for(var i = 0; i < s.length; ++i){
        switch(s[i]){
            case '{':
            case '}':
            case '[':
            case ']':
            case '-':
            case '/':
            case '\\':
            case '(':
            case ')':
            case '*':
            case '+':
            case '?':
            case '.':
            case '^':
            case '$':
            case '|':
                escaped+= '\\';
            default:
                escaped+= s[i];
        }
    }
    return escaped;
}

How it's used

var input_from_user = 'Hey + wi$ll th<is \'" { tex|t / \\ mess w?>ith you?';

var highlighted_text = original_text.replace(new RegExp('('+sanitize_for_regex(input_from_user)+')', 'gi'), '$1');

My test cases show that it's working quite well but I would like to get some feedback from other professionals.

Does this function look like it will escape all injection "attempts"? (I quoted attempts because the user is usually not aware of attempting to break anything)

Could the performance be improved?


texts: Shell script that verifies checksums when moving between filesystems

texts:
I coded this because it seemed like a fun project, would be awesome if someone reviewed this.

Thanks!

#! /bin/sh

#function that checks if dependencies are installed
check_software() {
    #check if md5sum is installed

    if [ $(command -v md5sum) > /dev/null 2>&1 ]; then
        echo 'md5sum'

    #check if md5 is installed
    elif [ $(command -v md5) > /dev/null 2>&1 ]; then
        echo 'md5'

    #if neither are installed, quit
    else
        echo "Neither md5sum nor md5 are installed. Quitting." 1>&2
        exit 1
    fi
}

#function to check if we're moving to same filesystem type
check_filesystem() {
    #df gives us detailed information about the file, use awk to get only the disk
    DISK1=$(df "$SOURCE" | tail -1 | head -1 | awk '{print $1}')

    #run dirname to remove the last bit of the path as the file does not exist yet
    DISK2=$(df $(dirname "$DESTINATION") | tail -1 | head -1 | awk '{print $1}')

    if [ "$DISK1" == "$DISK2" ]; then
        echo 1
    else
        echo 0
    fi
}

main() {
     CHECKSOFT=$(check_software)

     #if file is being moved on the same filesystem
     if [ "$(check_filesystem)" == "1" ]; then
        #move normally
        if [ "$FLAGS" != '' ]; then
            mv "-""$FLAGS" "$SOURCE" "$DESTINATION"
        else
            mv "$SOURCE" "$DESTINATION"
        fi
     else
        echo "Starting bettermv"
        #copy the file
        cp -p "$SOURCE" "$DESTINATION"

        #this bit of code extracts only the hashes from the output produced
        if [ "$CHECKSOFT" = "md5sum" ]; then
            CHECKSUMSOURCE="$($CHECKSOFT "$SOURCE" | awk '{print $1}')"
            CHECKSUMDEST="$($CHECKSOFT "$DESTINATION" | awk '{print $1}')"
        else
            CHECKSUMSOURCE="$($CHECKSOFT "$SOURCE" | awk '{print $4}')"
            CHECKSUMDEST="$($CHECKSOFT "$DEST" | awk '{print $4}')"
        fi

        #compare checksums and if they match up
        if [ "$CHECKSUMSOURCE" == "$CHECKSUMDEST" ]; then
            #remove original and exit
            rm "$SOURCE"
            echo "Move completed successfuly"
            return 0
        #if they don't match up
        else
            #display error message and quit
            echo "Checksums did not match, please try again" 1>&2
            rm "$DESTINATION"
            exit 1
        fi
    fi
}

FLAGS=''
#get all the move flags and store them in a variable
while getopts "finv" opt; do
    case $opt in
        f)
        FLAGS="$FLAGS""f"
        ;;
        i)
        FLAGS="$FLAGS""i"
        ;;
        n)
        FLAGS="$FLAGS""n"
        ;;
        v)
        FLAGS="$FLAGS""v"
        ;;
        \?)
        echo "Invalid argument $OPTARG"
        ;;
    esac
done

#shift optindex past the flags
shift $(( OPTIND-1 ))

#iterate through files to move and move them to the destination (last argument supplied)
for i in $@; do
    if [ $i != ${BASH_ARGV[0]} ]; then
        SOURCE=$i
        DESTINATION="${BASH_ARGV[0]}""$(basename $SOURCE)"
        main

    fi
done
exit 0


texts: Insert missing records in a list with LINQ

texts:
We have a table with periods, and other child tables with these periods and values for combinations of product + location.

Based on selected periods, I would like to add any missing rows in the child tables. I have come up with the following code, which seems to work just fine. But I would like to know if there is a simpler or more efficient way of doing this, since I have to repeat this for a number of tables.

public static void SeedActivityData(int startPeriod, double endPeriod, IList<DAL.OMS_StockStatus> stockStatus)
{
    DAL.EFDbContext dbFilter = new DAL.EFDbContext(0, stockStatus.FirstOrDefault().Product, startPeriod, endPeriod);
    var period = dbFilter.Periods.Select(b => b.PeriodID);
    foreach (var item in stockStatus)
    {
        IEnumerable<int> missingFAF = period.Except(dbFilter.OMS_Forecast_Adjustment.Where(a => a.SiteID == item.SiteID).Select(b => b.PeriodID));

        var modelFAF = db.OMS_Forecast_Adjustment;
        foreach (int periodID in missingFAF)
        {
            var modelItem = new OMS_Forecast_Adjustment { PeriodID = periodID, Product = item.Product, SiteID = item.SiteID, Value = 0 };
            modelFAF.Add(modelItem);
        }

        IEnumerable<int> missingRAF = period.Except(dbFilter.OMS_Receipts_Adjustment.Where(a => a.SiteID == item.SiteID).Select(b => b.PeriodID));

        var modelRAF = db.OMS_Receipts_Adjustment;
        foreach (int periodID in missingRAF)
        {
            var modelItem = new OMS_Receipts_Adjustment { PeriodID = periodID, Product = item.Product, SiteID = item.SiteID, Value = 0 };
            modelRAF.Add(modelItem);
        }

        db.SaveChanges();
    }
}


texts:
I would like some help condensing this code down to size. I am trying to utilize Qt's container classes as efficiently as possible. I do not believe this code reflects my objective.

#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QVector<int> vect;

    vect.append(0);
    vect.append(0);
    vect.append(0);
    vect.append(0);
    vect.append(1);
    vect.append(1);
    vect.append(2);
    vect.append(1);

    QVectorIterator<int> ivect(vect);

    double median = 0;
    if(vect.count() % 2 == 0){

        median =
        static_cast<double>((vect[vect.count() / 2 - 1] + vect[vect.count() / 2])) / 2;
    }
    else{

        median = vect[vect.count() / 2];
    }

    int sum = 0;
    while(ivect.hasNext()){

        sum += ivect.next();
    }

    double mean = static_cast<double>(sum) / vect.count();

    QSet<int> set;

    ivect.toFront();
    while(ivect.hasNext())
    {
        set << ivect.next();
    }

    QMap<int, int> map;

    QSetIterator<int> iset(set);

    ivect.toFront();
    while(iset.hasNext())
    {
        int count = 0;
        while(ivect.hasNext())
        {
            if(iset.peekNext() == ivect.next())
            {
                count++;
            }
        }
        ivect.toFront();
        map.insert(iset.next(), count);
    }

    QMapIterator<int, int> imap(map);

    int maxValue = 0;
    QString mode;
    while(imap.hasNext())
    {
        imap.next();
        if(imap.value() > maxValue)
        {
           maxValue = imap.value();
           mode = QString::number(imap.key());
        }
        else if(imap.value() == maxValue)
        {
            mode = "NULL";
        }
    }

    qDebug() << set;
    qDebug() << map;
    qDebug() << "Mean:" << mean;
    qDebug() << "Median:" << median;
    qDebug() << "Mode frequency:" << maxValue;
    qDebug() << "Mode:" << mode;

    return a.exec();
}


texts:
What I'm basically wondering is if there's anything that is possible to improve in this C++ code:

#include <cstddef>
#include <string>

bool is_palindromic(std::string s)
{
    std::size_t i = 0;
    std::size_t j = s.length() - 1;
    while (i < j) {
        if (s[i++] != s[j--]) {
            return false;
        }
    }
    return true;
}


texts:
I would like a code review to make this code better, clear, and concise.

The problem it's solving is as follows:

  Given a matrix, print the circumference of each of the items. For example:

1 2 3
4 5 6
7 8 9

  should result in

1 : 2 4 5
2 : 1 4 5 6 3
3 : 2 5 6
etc.

Also, am I correct in saying the time complexity is O(n4)?

public final class PrintCircumference {

    private PrintCircumference() {
    }

    public static void printCircumference(int[][] m) {

        if (m == null) {
            throw new NullPointerException("The input matrix cannot be null");
        }
        int row = m.length;
        int col = m[0].length;

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                System.out.print(m[i][j] + " --> ");

                for (int i1 = Math.max(0, i -1); i1 < Math.min(row, i + 2); i1++) {
                    for (int j1 = Math.max(0, j -1); j1 < Math.min(col, j + 2); j1++) {
                        if (i1 != i || j1 != j)
                            System.out.print(m[i1][j1]);
                    }
                }
                System.out.println();
            }
        }
    }

    public static void main(String[] args) {

        int[][] m = { {1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9}, };

        printCircumference(m);
    }
}


texts: Counting number of nodes between two nodes

texts:
This code counts the number of nodes between any given two nodes in a circular linked list. Any feedback is appreciated:

public class CountNodesBetweenTwoNodes {
  Node first;
  Node fifth;

  private class Node<Item> {
    Item item;
    Node next;
  }

  public static void main(String[] args) {
    CountNodesBetweenTwoNodes countNodes = new CountNodesBetweenTwoNodes();
    countNodes.buildCircularList();
    int noOfNodes = countNodes.countNodesBetweenTwoNodes(countNodes.getFirst(), countNodes.getFifth());
    System.out.println("Number of Nodes is: "+noOfNodes);
  }

  private Node buildCircularList() {
    first = new Node();
    first.item = "First";

    Node second = new Node();
    second.item = "Second";

    Node third = new Node();
    third.item = "Third";

    Node forth = new Node();
    forth.item = "Forth";

    fifth = new Node();
    fifth.item = "Fifth";

    first.next = second;
    second.next = third;
    third.next = forth;
    forth.next = fifth;

    fifth.next = first;

    return first;
  }

  private int countNodesBetweenTwoNodes(Node firstNode, Node secondNode) {
    int count = 0;

    while(firstNode.next != secondNode) {
        count++;
        firstNode = firstNode.next;
    }

    return count;
  }

  public Node getFirst() {
    return first;
  }

  public Node getFifth() {
    return fifth;
  }
}


texts:
I'm pretty new to C so I decided to implement SRFI-1 (linked-list library) to help me learn.

What I have so far is working, but only handles integers.

typedef struct pair {
  int car;
  struct pair *cdr;
} pair;

From what I've read I can use a void * for the car:

typedef struct pair {
  void *car;
  struct pair *cdr;
} pair;

This works but I get lots of these...

llist.c:262:3: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘void *’
llist.c:27:7: note: expected ‘void *’ but argument is of type ‘int’

I've found some workarounds but before diving in and fixing everything I want to be sure this is the appropriate way to go.

The only other way I can think of is using some sort of generic object type:

typedef struct object {
  union {
    int fixnum;
    double flonum;
  }
}

typedef struct pair {
  object *car;
  struct pair *cdr;
} pair;

Or something similar.

Is there a best practice for generic functions/data types?

The full source is here.


texts: Processing requests using the user's time zone

texts:
I have an application in Ruby on Rails (3.2) and I want all the requests to take into account the currently logged in user's time zone. Also, I want to have a helper that will let me display date time fields using user's time zone.

I follow this approach:

Inside ApplicationController I hook an around_filter like this:

around_filter :user_time_zone, if: :current_user

The implementation of user_time_zone is:

def user_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

In ApplicationController as well, I have a helper method like so:

helper_method :datetime_users_time_zone

with implementation:

def datetime_users_time_zone(datetime, user = nil)
  time_zone = user.present? ? user.time_zone : Time.zone_default
  datetime.in_time_zone(time_zone)
end

Is this good practice and implementation? What might be the gotchas? If I were to implement this for Rails 4, what changes should I make?


texts:
There is the implementation of flood game on my GitHub.

The app.coffee is the main part of project:

class Square
  colors = [
    'orange',
    'green',
    'red',
    'blue',
    'violet',
    'yellow',
  ]
  constructor: (@game, @node)->
    @node.on 'click', =>
      @game.flood(@color)

  reset: ->
    @controlled = false
    color = colors[Math.floor(Math.random() * colors.length)]
    @setColor(color)

  setColor: (color)->
    @node.removeClass(@color)
    @color = color
    @node.addClass(@color)

class Game
  DIMENSION = 14
  SIZE = DIMENSION * DIMENSION
  constructor: ($tbody)->
    @limit = 25
    @grid = []
    for i in [0...DIMENSION]
      $tr = $ '<tr/>'
      $tbody.append $tr
      @grid.push []
      for j in [0...DIMENSION]
        $td = $('<td/>').html('&nbsp;')
        $tr.append $td
        @grid[i].push(new Square(@, $td))
    @top = @grid[0][0]
    @reset()

  reset: ->
    for i in [0...DIMENSION]
      for j in [0...DIMENSION]
        @grid[i][j].reset()
    @top = @grid[0][0]
    @top.controlled = true
    @flood(@top.color)
    @setTurnCounter(0)

  setTurnCounter: (counter)->
    $counter = $ '#count'
    @turn = counter
    $counter.toggleClass 'bad', @turn > @limit
    $('#counter-used').text(@turn)

  flood: (color)->
    if @top.color is color
      return
    @setTurnCounter(@turn + 1)
    @_flood(0, 0, color, [])
    if @hasWon()
      setTimeout(
        =>
          @decreaseLimit()
          @reset()
        2000
      )
  decreaseLimit: ()->
    @expected--

  _flood: (i, j, color, checked)->
    if i < 0 or j < 0 or i == DIMENSION or j == DIMENSION
      return
    cur = @grid[i][j]
    if cur.controlled or cur.color is color
      if cur in checked
        return
      cur.setColor(color)
      cur.controlled = true
      checked.push cur
      @_flood(i-1, j, color, checked)
      @_flood(i+1, j, color, checked)
      @_flood(i, j-1, color, checked)
      @_flood(i, j+1, color, checked)

  hasWon: ->
    for i in [0...DIMENSION]
      for j in [0...DIMENSION]
        if not @grid[i][j].controlled
          return false
    return true

(($, Game)->
  tbody = $('tbody')
  game = new Game(tbody)
  btnRestart = $('#btn-restart')
  btnRestart.on 'click', (e)->
    e.preventDefault()
    game.reset()

)(jQuery, Game)

I build assets with Grunt and use grunt-serve as a simple HTTP server.

P.S.: I use styles from another implementation of this game but based on Knockout.js.


texts:
I am learning the basics about managing an SQLite database by using Python and, mainly for practice purposes, I have then defined an interface class in order to let operations on database as clear as possible. That said, I would like to ask you for some feedback about the following code:

import sqlite3, os

class DbInterface:
  def __init__(self, file):
    self.dbfile = file

  def open(self):
    try:
      assert os.path.exists(self.dbfile)
      assert os.path.isfile(self.dbfile)
      self._dbconn = sqlite3.connect(self.dbfile)
      return 0
    except sqlite3.Error as e:
      print(e)
    except AssertionError as e:
      print('ERROR: database file not found.')
    return -1

  def close(self):
    if hasattr(self, '_dbconn'):
      self._dbconn.close()
      return 0
    return -1

  def write(self, query, *args):
    try:
      assert any(map(lambda s: query.upper().strip().startswith(s), ('CREATE TABLE', 'ALTER TABLE', 'INSERT', 'UPDATE', 'DELETE')))
      assert query.count('?') == len(args)
      c = self._dbconn.cursor()
      c.execute(query, args)
      self._dbconn.commit()
      return 0
    except AssertionError:
      print('ERROR: inconsistent query arguments.')
    except sqlite3.Error as e:
      self._dbconn.rollback()
      print('SQL ERROR:', e)
    return -1

  def read(self, query, *args):
    try:
      assert query.count('?') == len(args)
      assert query.upper().strip().startswith('SELECT')
      c = self._dbconn.cursor()
      c.execute(query, args)
      rows = c.fetchall()
      return 0, rows;
    except AssertionError:
      print('ERROR: inconsistent query arguments.')
    except sqlite3.Error as e:
      print('SQL ERROR:', e)
    return -1, ()

Here is a test function I am using for code validation:

def test(path):
  db = DbInterface(path)
  res = db.open()
  q = """
    CREATE TABLE IF NOT EXISTS example(
      id integer PRIMARY KEY,
      sometext text NOT NULL
    );
  """
  res = db.write(q)
  q = 'INSERT INTO example(sometext) VALUES(?);'
  res = db.write(q, 'a')
  q = 'INSERT INTO example(sometext) VALUES(?, ?);'
  res = db.write(q, 'b')
  q = 'INSERT INTO example(sometext) VALUES(?);'
  res = db.write(q)
  q = 'INSERT INTO example(sometext) VALUES(?, ?);'
  res = db.write(q, 'c', 'd')
  q = 'SELECT * FROM example;'
  res, data = db.read(q)
  q = 'SELECT somevalue FROM example;'
  res, data = db.read(q)
  q = 'SELECT * FROM example WHERE sometext = ?;'
  res, data = db.read(q, 'a')
  q = 'SELECT * FROM example WHERE sometext = ?;'
  res, data = db.read(q)
  res = db.close()

if __name__ == '__main__':
  test('testdb.db')


texts: UIScrollView Category utility function for auto sizing contentSize

texts:
I wanted a utility function on UIScrollView to automatically size the contentSize based on the content inside the scrollView. How is this?

#import "UIScrollView+UIScrollViewUtilities.h"
#import <objc/runtime.h>

static const int BOTTOM_CONTENT_OFFSET = 75;

@implementation UIScrollView (UIScrollViewUtilities)

- (void)setRecursiveSubviews:(NSMutableArray *)recursiveSubviews {
    objc_setAssociatedObject(self, @selector(recursiveSubviews), recursiveSubviews, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSMutableArray *)recursiveSubviews {
    NSMutableArray *array = objc_getAssociatedObject(self, @selector(recursiveSubviews));
    if (array == nil) {
        array = [[NSMutableArray alloc] init];
        [self setRecursiveSubviews:array];
    }
    return array;
}

- (void)autoAdjustContentSize {
    [self autoAdjustContentSize:self];
}

/*
 * This method is used to dynamically set the contentSize
 * of a UIScrollView based on its content.
 */
- (void)autoAdjustContentSize:(UIView *)view {

    // For all subviews of view passed in, add them to our
    // recursiveSubviews array and call this method recursively
    // to ensure we add all subviews (even grandchildren subviews)
    for (UIView *subView in [view subviews]) {
        NSMutableArray *array = [self recursiveSubviews];
        [array addObject:subView];
        [self setRecursiveSubviews:array];

        [self autoAdjustContentSize:subView];
    }

    // Of all of our subviews found, figure out which one
    // is the bottom-most element, and remember its y val
    CGFloat currentBottomValue = 0;
    for (UIView *subView in [self recursiveSubviews]) {
        CGFloat thisElementsBottomValue = subView.frame.origin.y + subView.frame.size.height;

        // Ignore UIViews because they are just blank space by themselves
        if (![subView isMemberOfClass:[UIView class]] && thisElementsBottomValue > currentBottomValue) {
            currentBottomValue = thisElementsBottomValue;
        }
    }

    // Finally, update the contentSize of the scrollView based on the bottom most element found on screen
    [self setContentSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width, currentBottomValue + BOTTOM_CONTENT_OFFSET)];
}

@end


texts: Find kth element from tail of singly linked list in one pass

texts:
I have tried the below program to find (Kth element from tail) of a singly linked list. I have tried to utilize the length field which I am incrementing whenever an item is added into the list or vice versa.

public Node<T> findKthFromTail(int kthElem) {
    // length has the size of the list
    int kthPos = length - kthElem;

    if (kthPos < 0) {
        return null;
    }

    Node<T> node = head;
    int start = 0;
    while (node != null) {
        if (start == kthPos) {
            // found the node
            break;
        }

        node = node.getNext();
        start++;
    }

    return node;
}


texts:
I've just stumbled upon something today that seemed "unethical" in PHP. What I originally thought as malpractice, turned out to work just fine. Basically what I was wondering is if pushing an instantiated class in an array was considered proper?

Example:

$array = array();

array_push($array, new myClass());

foreach($array as $i => $class)
{
    $class->doSomething();
}

Although this example is quite vague, the idea is there. Any input or alternatives on this matter would be great.


texts:
I have incoming data from an absolute rotary encoder. It is 24 bits wide. 12 bits are the number of turns and 12 bits are the angle.

I'm reading the data with an Arduino and sending it to the computer over a serial port. The most natural thing to do would be to combine all of the bits and send it as 3 bytes.

Splitting up the 3 bytes into 12 bits/12 bits at the computer in Python 3 feels unpythonic to me. Here is what I have so far:

import struct

# fake message, H is header last 3 bytes are data
msg = b'H\x90\xfc\xf9'
header, bytes3 = struct.unpack('>c3s', msg)
print('bytes3 ', bytes3)
val = int.from_bytes(bytes3, 'big')
print('val ', val)
print('bin(val) ', bin(val))

upper12 = val >> 12
print('bin(upper12)', bin(upper12))
lower12 = val & 0b000000000000111111111111
print('bin(lower12)', bin(lower12))

which gives console output of

bytes3  b'\x90\xfc\xf9'
val  9501945
bin(val)  0b100100001111110011111001
bin(upper12) 0b100100001111
bin(lower12) 0b110011111001

This code seems to work fine, but bitshifting (val >> 12) and bitwise anding (val & 0b000...) are a little wonky. Also it feels funny to specify Big Endian twice: first in the struct.unpack format string and second in int.from_bytes.

Is there a more elegant way to achieve this?

Update: timing

I'm still on the fence on which technique is most Pythonic. But I did time 3 techniques:

original technique above
technique by AlexV with overlapping unsigned 16 bit integers
change comms protocol to send a padded 4 byte unsigned integer that struct can convert directly to integer

import  struct
import time
import random
import timeit

def gen_random_msg(nbyte = 3):
    # make a n byte message with header 'H' prepended
    data = random.randint(0, 2**12-1)
    data = data.to_bytes(nbyte, 'big')
    msg = b'H' + data
    return msg

def original_recipe():
    msg = gen_random_msg(3)
    header, bytes3 = struct.unpack('>c3s', msg)
    val = int.from_bytes(bytes3, 'big')

    upper12 = val >> 12
    lower12 = val & 4095 # 4095 = 2**12-1

def overlap16bits():
    msg = gen_random_msg(3)
    header, val = struct.unpack('>cH', msg[0:-1])
    upper12 = val >> 4
    lower12 = struct.unpack('>H', msg[2:])[0] & 0xfff

def fourbyte():
    msg = gen_random_msg(4)
    header, val = struct.unpack('>cI', msg)
    upper12 = val >> 12
    lower12 = val & 4095 # 4095 = 2**12-1

niter = int(1e6)
t0 = time.time()
for i in range(niter): gen_random_msg(3)
t1 = time.time()
for i in range(niter): gen_random_msg(4)
t2 = time.time()
for i in range(niter): original_recipe()
t3 = time.time()
for i in range(niter): overlap16bits()
t4 = time.time()
for i in range(niter): fourbyte()
t5 = time.time()

gentime3 = t1-t0
gentime4 = t2-t1
original_time = t3-t2
overlap_time = t4-t3
fourbyte_time = t5-t4

print('gentime3: ', gentime3, '. gentime4: ', gentime4)
print ('original recipe: ', original_time - gentime3)
print ('overlap 16 bits: ', overlap_time - gentime3)
print ('four bytes: ', fourbyte_time - gentime4)

this has console output:

gentime3:  3.478888988494873 . gentime4:  3.4476888179779053
original recipe:  1.3416340351104736
overlap 16 bits:  1.435237169265747
four bytes:  0.7956202030181885

It takes more time to generate 1M dummy msg than it does to process the bytes. The fastest technique was to change the comms spec and pad the 3 bytes to make a 4 byte unsigned integer. The speed up was good (approx 2x) for "fourbytes", but requires changing the communications specification. At this point I think it comes down to personal preference as to which algorithm is the best.


texts: Looking For a More Efficient/Elegant Way To Write a MySQL Query

texts:
I'm querying a MySQL database and displaying the info in order of timestamp (DESC). Essentially, I'm grabbing the last record in the database, displaying it's date and year as the header of it's section and then going backwards from there. I've put together these if and else if statements to display the appropriate month name according to the timestamp. It works fine but I know I could probably do this with an array or some sort of other loop. I'm still learning this type of coding so I was wondering if someone could help me find a way to make this code more efficient. Thanks!

$sql = "SELECT * FROM user ORDER BY timestamp DESC LIMIT 1";
$result = $mysqli->query($sql);
$row_lastone = mysqli_fetch_array($result);
$timestamp_lastone = date_parse($row_lastone['timestamp']);
$month_lastone = $timestamp_lastone['month'];
$year_lastone = $timestamp_lastone['year'];
if ($month_lastone==1){
$lastone_month = "January";
}
else if ($month_lastone==2){
$lastone_month = "February";
}
else if ($month_lastone==3){
$lastone_month = "March";
}
else if ($month_lastone==4){
$lastone_month = "April";
}
else if ($month_lastone==5){
$lastone_month = "May";
}
else if ($month_lastone==6){
$lastone_month = "June";
}
else if ($month_lastone==7){
$lastone_month = "July";
}
else if ($month_lastone==8){
$lastone_month = "August";
}
else if ($month_lastone==9){
$lastone_month = "September";
}
else if ($month_lastone==10){
$lastone_month = "October";
}
else if ($month_lastone==11){
$lastone_month = "November";
}
else if ($month_lastone==12){
$lastone_month = "December";
}
echo "<h1>".$lastone_month." ".$year_lastone."</h1>";

Thanks for the help!


texts: Speed up simple Python function that uses list comprehension

texts:
I'm extracting 4 columns from an imported CSV file (~500MB) to be used for fitting a scikit-learn regression model.

It seems that this function used to do the extraction is extremely slow. I just learnt python today, any suggestions on how the function can be sped up?

Can multithreading/core be used? My system has 4 cores.

def splitData(jobs):
    salaries = [jobs[i]['salaryNormalized'] for i, v in enumerate(jobs)]
    descriptions = [jobs[i]['description'] + jobs[i]['normalizedLocation'] + jobs[i]['category'] for i, v in enumerate(jobs)]
    titles = [jobs[i]['title'] for i, v in enumerate(jobs)]

    return salaries, descriptions, titles

Full Code

def loadData(filePath):
    reader = csv.reader( open(filePath) )
    rows = []

    for i, row in enumerate(reader):
        categories = ["id", "title", "description", "rawLocation", "normalizedLocation",
                        "contractType", "contractTime", "company", "category",
                        "salaryRaw", "salaryNormalized","sourceName"]

        # Skip header row
        if i != 0:
            rows.append( dict(zip(categories, row)) )

    return rows

def splitData(jobs):
    salaries = []
    descriptions = []
    titles = []

    for i in xrange(len(jobs)):
        salaries.append( jobs[i]['salaryNormalized'] )
        descriptions.append( jobs[i]['description'] + jobs[i]['normalizedLocation'] + jobs[i]['category'] )
        titles.append( jobs[i]['title'] )

    return salaries, descriptions, titles

def fit(salaries, descriptions, titles):
    #Vectorize
    vect = TfidfVectorizer()
    vect2 = TfidfVectorizer()
    descriptions = vect.fit_transform(descriptions)
    titles = vect2.fit_transform(titles)

    #Fit
    X = hstack((descriptions, titles))
    y = [ np.log(float(salaries[i])) for i, v in enumerate(salaries) ]

    rr = Ridge(alpha=0.035)
    rr.fit(X, y)

    return vect, vect2, rr, X, y

jobs = loadData( paths['train_data_path'] )
salaries, descriptions, titles = splitData(jobs)
vect, vect2, rr, X_train, y_train = fit(salaries, descriptions, titles)


texts:
I use this code in a GAS (Google Apps Script) to automate my project budgets.

Since every project has its own spreadsheet but all functions are in the same script file, being called as a library, I can't use them directly. I need to call libraryName.functionName, but it can't serve any arguments unless I do this:

function funcoesOrcamento( funcao, args ){
  if(args)
    args = args.split("\!|");
  else
    args = [];

  switch( args.length ){
    case 0:
      return FuncoesOrcamentoV2[ funcao ]();
    case 1:
      return FuncoesOrcamentoV2[ funcao ]( args[0] );
    case 2:
      return FuncoesOrcamentoV2[ funcao ]( args[0], args[1] );
    case 3:
      return FuncoesOrcamentoV2[ funcao ]( args[0], args[1], args[2] );
    case 4:
      return FuncoesOrcamentoV2[ funcao ]( args[0], args[1], args[2], args[3] );
    case 5:
      return FuncoesOrcamentoV2[ funcao ]( args[0], args[1], args[2], args[3], args[4] );
  }
}

Is there any way to make this more elegant and accept any number of args?


texts:
An AJAX request gives me an object, containing dates and values:

"Values":{"2017-05-01T23:59:27":100.0,"2017-05-02T23:59:27":100.0,"2017-05-03T23:59:27":41.25,"2017-05-04T23:59:27":100.0,...}

The aim is to split this array by year, get all values of a same year together.

The current code is:

var dataPerYear = [];
function addToData(array, nameOfObject, dataToInsert) {
    //Check if the year is already in the array
    var object = $.grep(array, function (e, i) {
        return e.name == nameOfObject;
    });
    // If so, add new data to the correct object
    if (object.length > 0) {
        object[0].values.push(dataToInsert)
    } else
    // If not, create a new object, and add it to the array.
    {
        array.push({name: nameOfObject, values: [dataToInsert]})
    }
}

$(document).ready(function () {
        $.post("myEndPoint", function (data) {
            $.each(data,function (key, val) {
                    addToData(dataPerYear, new Date(key).getFullYear(), val);
            });
        });
});

How can I improve this code, with regards to readability / maintenability first, performance then (not a lot of data, so not a big concern)?


texts:
The purpose of the method is to add a list of items after every nth step (5 for example) where the input items are repeated if needed. I'm looking for an overall review and possible how to remove the use of the while and replace it with a for.

public static List<string> AddEveryNthStep(List<string> items, List<string> itemsToAdd, int nthStep)
{
    List<string> output = new List<string>();

    int itemIndex = 0;
    int itemsToAddIndex = 0;
    int index = 1;

    while (itemsToAddIndex < itemsToAdd.Count)
    {
        output.Add(items[itemIndex++]);

        if (itemIndex == items.Count)
        {
            itemIndex = 0;
        }

        // We are at at point where we want to add a item
        if (index % nthStep == 0)
        {
            output.Add(itemsToAdd[itemsToAddIndex++]);
        }

        index++;
    }

    return output;
}

Usage:

List<string> items = new List<string> { "Item 1", "Item 2", "Item 3", "Item 4" };
List<string> itemsToAdd = new List<string> { "Item to add 1", "Item to add 2", "Item to add 3" };

Console.WriteLine(String.Join(Environment.NewLine, AddEveryNthStep(items, itemsToAdd, 5)));

Output:


texts: Updating an item's status in MS SQL Server using ODBC

texts:
Is the following query is vulnerable in terms of $itemstatus? I want to be sure about it. $yesorno is a user input which is sanitized and it's fine, however, $itemstatus is a not user input but is included in the query. Can $itemstatus be manipulated or overall if it's vulnerable?

    $username = $this->site->SanitizeIt($_POST['username'], 20);
    $yesorno = $this->site->SanitizeIt($_POST['yesorno'], 1);

    if (intval($yesorno) == 1)
    {
    $itemstatus = '1';
    }
    else if (intval($yesorno) == 2)
    {
    $itemstatus = '2';
    }
    else
    {
        $this->content = Template::Load('error', array('error_message' => Template::GetLangVar('INVALID_STATUS')));
        return;
    }

    $this->database[DBB]->doQuery('UPDATE INFO SET ItemStatus = ? WHERE UserName = ?', $itemstatus, $username);
    $this->content = Template::Load('error', array('error_message' => Template::GetLangVar('ITEM_STATUS_SUCCESS')));
}

And if you wanna look at the SanitizeIt .. (It's NOT required since I ask for $itemstatus but however let me include it as well) here it is: (BTW: I am using MSSQL Server 2005)

function SanitizeIt($intext, $lenght = 20)
{
    return substr(preg_replace("/[^a-zA-Z0-9_]/", "", htmlspecialchars(htmlentities(strip_tags($intext)))), 0, $lenght);
}

Here is my doQuery() which is part of my ODBC.class file:

function doQuery($query)
{
    if (!parent::isConnected())
    {
        if (!$this->doConnect())
            return -1;
    }

    if ($this->result)
        @odbc_free_result($this->result);

    $parameters = func_get_args();
    array_shift($parameters);

    parent::Query();
    if (sizeof($parameters) > 0)
    {
        $this->result = @odbc_prepare($this->conn, $query);
        if (!$this->result)
            return -1;

        $result = @odbc_execute($this->result, $parameters);
        if (!$result)
            return -1;
    }
    else
    {
        $this->result = @odbc_exec($this->conn, $query);
        if (!$this->result)
            return -1;
    }
    parent::Success();
    return @odbc_num_rows($this->result);
}


texts: Python3 conditionally moving files and string formatting

texts:
I have written the below code while helping one of the colleague over the SO and this code working as desired, but I feel there may be some improvement specially on the string formatting syntax's which can be better reviewed by experts here.
Code snippet:
#!/python3/bin/python
import pandas as pd
pd.set_option('expand_frame_repr', True)
########################################################################################
## Importing SMTP for the e-mail distribution                                        ###
########################################################################################
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from smtplib import SMTP
import requests
import time
import glob
import os
from os import path
import shutil

# Set the timestamp for file based on the timestamp_src and timestamp_dst
timestamp_src = time.strftime("%Y%m%d")
timestamp_dst = time.strftime("%Y%m%d-%H:%M:%S")
# Set the Destination file Variable
src = "/home/user2/.working_scripts/hpe_out/"
dst = "/home/user2/script_logs/"
file_name = "hpeCriticalAlert"
outfile = (f"{src}/{file_name}.{timestamp_src}.csv")

csv_files = [f_extn for f_extn in os.listdir(src) if f_extn.endswith(".csv") and path.isfile(path.join(src, f_extn))]
for file in csv_files:
    shutil.move(path.join(f"{src}/{file}"), f"{dst}/{file}-{timestamp_dst}.log")

session = requests.Session()
url = "https://synergy.example.com/rest/login-sessions"
credentials = {"userName": "administrator", "password": "myPass"}
headers = {"accept": "application/json",
           "content-type": "application/json",
           "x-api-version": "120",
          }
response = session.post(url, headers=headers, json=credentials, verify=False)
session_id = response.json()["sessionID"]
#############################################################################################
url = "https://synergy.example.com/rest/resource-alerts"
headers = {"accept": "application/json",
           "content-type": "text/csv",
           "x-api-version": "2",
           "auth": session_id,
          }
# stream=True on the request avoids reading the content at once into memory for large responses.
response = session.get(url, headers=headers, verify=False, stream=True)
with open(outfile, 'wb') as f:
    for chunk in response.iter_content(chunk_size=1024):
        f.write(chunk)
#################################################################################################
for file in glob.glob(f"{outfile}"):
#for file in glob.glob(f"{src}/{file_name}.*.csv"):
   df = pd.read_csv(file)
##################################################################################################
recipients = ['karn.kumar@example.com']
mail_receivers = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = "HTML OneView"
msg['From'] = 'hpe-dashboard@example.com'
#########################################################################
html = """\

     Dear Team,

     Please Find the Report!

     {0}

    Kind regards.

    Synergy Global Dashboard.

  """.format(df.to_html(index=False))

part1 = MIMEText(html, 'html')
msg.attach(part1)
server = smtplib.SMTP('smtp.example.com')
server.sendmail(msg['From'], mail_receivers, msg.as_string())


texts: Ensuring images will look as best as possible on any size using object-fit and a container class

texts:
This is a snippet from my codebase. Here's how I write markup for my images. In order to make sure that, no matter the specs of the image, it will look as best as possible most of the time:

I am giving a class to my image in case I have more images within the container, for easy selection.

.container-class {
    width: 200px;
    height: 300px;
    overflow: hidden;
    ..
    /* do everything related to the container, floats, etc. */
}

.image-class,
.class img /* If there's no other image */ {
    position: relative;
    width: 100%; height: 100%;
    object-fit: cover;
}

My goals are:

Make sure that no matter what the size of the image that's provided (the images will be dynamic, user input, big, small, weird sized, everything), they will look somewhat good, hence object-fit: cover;.
Be able to affect the main class-container with changes on height / width and the image should adapt to them. Additionally, at times, I might want my images to look in some weird ways, but they'll never go over the container-class, no matter what I do. Hence, if my container-class has some weird positioning rules, they won't get ruined by by image-class' rules. Such, I am free to do whatever with the container.
Be able to add position: absolute elements on the image, as such the container serves this purpose. Think... a "play" button for your image, which is a youtube-preview. Unfortunately, the hidden: overflow; doesn't affect the position: absolute;; be careful.
Be able to insert more content on the image-class and use float: left/right; on the container-class to position it on the flow of the page.

Additional things one can do where the same rules apply:

Things to watch out for:

WordPress sometimes, due to plugins / options, gives an inline styling to the image, making sure there are no conflicts.

Will update as soon as I discover more.


texts:
I've written this program that, renders a circle in the middle of the screen. It's been written in a very elementary way.

Any suggestions on principles or techniques? Or any more optimal or efficient ways of drawing circles in C?

I'm using SDL2 (Simple Direct Media Library) and GCC to compile.

#include "SDL.h"
#include <math.h>
#include <stdio.h>

#define PI  3.14159
#define SCR_WDT  1280
#define SCR_HGT  960

const int SCR_CEN_X = SCR_WDT / 2;
const int SCR_CEN_Y = SCR_HGT / 2;

struct Circle
{
    int radius;
    int h; // The X access of the center of the circle.
    int k; // The Y access of the center of the circle.
    int new_x;
    int new_y;
    int old_x;
    int old_y;
    float step;
};

int main ( int argc, char *argv[] )
{
    SDL_Init ( SDL_INIT_VIDEO );
    SDL_Window *window = SDL_CreateWindow ( "Drawing a Circle",       SDL_WINDOWPOS_UNDEFINED,
                                             SDL_WINDOWPOS_UNDEFINED, SCR_WDT, SCR_HGT, 0 );
    SDL_Renderer *renderer = SDL_CreateRenderer ( window, -1, SDL_RENDERER_SOFTWARE );

    Circle circle;
    circle.radius = 200;
    circle.h = SCR_CEN_X;
    circle.k = SCR_CEN_Y;
    circle.new_x = 0;
    circle.new_y = 0;
    circle.old_x = 0;
    circle.old_y = 0;
    circle.step = (PI * 2) / 50;

    bool is_running = true;
    while ( is_running )
    {
        SDL_Event event;
        if ( SDL_PollEvent( &event ))
        {
            if ( event.type == SDL_QUIT )
            {
                is_running = false;
            }
        }

        SDL_RenderClear ( renderer );

        SDL_SetRenderDrawColor ( renderer, 255, 255, 255, 255 );

        for ( float theta = 0; theta < (PI * 2); theta += circle.step )
        {
            circle.new_x = circle.h + (circle.radius * cos ( theta ));
            circle.new_y = circle.k - (circle.radius * sin ( theta ));

            SDL_RenderDrawLine ( renderer, circle.old_x, circle.old_y,
                                 circle.new_x, circle.new_y );

            circle.old_x = circle.new_x;
            circle.old_y = circle.new_y;

        }

        SDL_SetRenderDrawColor ( renderer, 0, 0, 0, 255 );
        SDL_RenderPresent ( renderer );
    }

    SDL_Quit ();

return 0;
}


texts: Dynamic programming to solve two printers with different speeds

texts:
I solved this problem using a Class, but thought I might try to figure out this memoization thing.

Problem
There are two printers that print pages at different speeds (X, Y).
What is the minimum amount of time it takes to print (N) pages?
Input Data First line contains the number of test cases Each test case
is on a new line in the form of X Y N
Output The minimum printing time for each test case separated by spaces

e.g.

input data:
2
1 1 5
3 5 4

output:
3 9

The math here is trickier than it appears, so make the assumption that my math is correct (it is).
Code
Option Explicit On
Option Strict On
Option Infer On
Option Compare Text

Module Module1

    <STAThread>
    Sub Main()
        Const inputPath As String = "C:\Temp\printers.txt"
        Dim delimiters As String = " " & System.Environment.NewLine
        Dim data() As Integer = System.IO.File.ReadAllText(inputPath).Split(delimiters.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) _
                                .Select(Function(i) Integer.Parse(i)).ToArray
        Dim result As String

        For i As Integer = 0 To data(0) - 1
            result = result & BestTime(data(i * 3 + 1), data(i * 3 + 2), data(i * 3 + 3)) & " "
        Next

        result = result.Trim()
        System.IO.File.AppendAllText(inputPath, Environment.NewLine & result)
    End Sub

    Public Function BestTime(ByVal X As Double, ByVal Y As Double, ByVal N As Integer) As Double
        Dim myTimes(1) As Double
        For nextpage As Integer = N To 1 Step -1
            If myTimes(0) + X <= myTimes(1) + Y Then
                myTimes(0) = myTimes(0) + X
            Else
                myTimes(1) = myTimes(1) + Y
            End If
        Next
        Return myTimes.Max
    End Function

End Module

For some reason I couldn't get the delimiters to work as a constant. I'm using doubles because I kept getting overflow.

Additional test data
Input
16
206 120 2925144
5680 2268 173606
443 144 2231807
1336 1966 235314
251936 215499 755
1 1 610653060
27229864 68593621 7
13 11 58925803
25 13 39786943
936 301 970391
6811369 9145334 90
3070457 3923385 93
111 126 4757640
16350510 10897861 9
171127 91014 3379
2 2 373415582

Output
221808480 281383956 242540784 187180894 87708093 305326530 137187242
351099580 340283073 221013936 354191188 160858785 280761012 65387166
200776884 373415582