texts:
I have built a super simple tip calculator to help me try and get a hold of the javascript knowledge I've gained. I just wanted to see if there was any feedback I could get for it...
Basic functionality is:
If a letter or incorrect character is input in either the bill or the number of persons input, a message should appear at the bottom advising this.
Otherwise if everything is okay, the tip per person is shown at the bottom, followed by the total cost per person!
Here is the JS:
const button = document.querySelector('button'),
    bill = document.querySelector('#amount'),
    serviceRating = document.querySelector('#service'),
    numberPersons = document.querySelector('#people'),
    pTip = document.querySelector('.tip'),
    pTotal = document.querySelector('.total'),
    p = document.querySelectorAll('p'),
    regex = /(^0|[a-zA-Z]+)/i;

let tipAmount = 0,
    totalCostPP = 0;

button.addEventListener('click', () => {
    if (regex.test(bill.value)) {
        pTip.textContent = 'Please give a valid bill value'
    } else if (regex.test(numberPersons.value)) {
        pTip.textContent = 'Please enter how many people were there'
    } else {
        tipAmountPP = tipPP(bill.value, serviceRating.value, numberPersons.value);
        totalCostPP = totalPP(tipAmountPP, bill.value, numberPersons.value);
        for (paragraph of p) {
            paragraph.classList.toggle('hidden');
        }
        pTip.textContent = `Tip per person: $${tipAmountPP.toFixed(2)}`;
        pTotal.textContent = `Total per person: $${totalCostPP.toFixed(2)}`;
    }
});

const tipPP = (bill, service, people) => {
    let tip = (bill / 100) * service;
    return (tip / people);
}

const totalPP = (tip, bill, people) => {
    return (bill / people + tip);
}

I haven't included the HTML and CSS as I didn't see it necessary as everything is functioning with each other just now.
Anyway, appreciate any help you can give, little or large!


texts: Running a shell command and getting output

texts:
This is the code I'm currently using to run a shell command on the current machine, intended for use only with GNU/Linux at the moment:

std::string getCmdOutput(const std::string& mStr)
{
    std::string result, file;
    FILE* pipe{popen(mStr.c_str(), "r")};
    char buffer[256];

    while(fgets(buffer, sizeof(buffer), pipe) != NULL)
    {
        file = buffer;
        result += file.substr(0, file.size() - 1);
    }

    pclose(pipe);
    return result;
}

Example use:

getCmdOutput(R"( sudo pacman -Syyuu )");
auto output(getCmdOutput(R"( echo /etc/pacman.conf )"));

I use this when making simple script-like C++ programs (mostly for personal use).

Is this the "correct" way of doing it? What can be improved?


texts: MySQL PDO query to search by name and role

texts:
I'm new to this PDO PHP and I have coded this spaghetti style. I hope you can give me idea how to improve using prepared statements.  I'm not a lazy person, but I really need your help to improve my coding style.

            try {
        $select = "SELECT users.id, users.users_id, username, firstname, lastname, password, position";
        $from = " FROM users
                  INNER JOIN users_role
                  ON users.id=users_role.users_id
                  INNER JOIN role
                  ON users_role.users_role=role.id";
        $where = " WHERE";
        $placeholders = array();
        if ($category !=''){
            if ($category == 'admin'){
                $where .= " position='admin'";
                if ($character_match !=''){
                    $where .= " AND ";
                }

            }
            else if($category == 'instructor'){
                $where .= " position='Instructor'";
                if ($character_match !=''){
                    $where .= " AND ";
                }
            }
            else if ($category=='student'){
                $where .= " position='student'";
                if ($character_match !=''){
                    $where .= " AND ";
                }
            }
            elseif ($category == 'Unverified'){
                $where .= " position='Unverified'";
            }
            else if ($category == 'view_all') {
                $where = "";
                if ($character_match != ''){
                    $where = " WHERE ";
                }
            }
            if($character_match !=''){
                $where .= "(username LIKE '" . $character_match . "%'"
                        . " OR firstname LIKE '"  . $character_match . "%'"
                        . " OR lastname LIKE '"  . $character_match . "%')";
                $placeholders[] = $character_match;
            }
            $where .= " ORDER BY position ASC";

            $sql = $select . $from . $where;
            $q = $this->db->prepare($sql);
            $q->execute($placeholders);
        }
    }
    catch(PDOException $e){
            $e->getMessage();
        }
       $rows = array();

       while($row = $q->fetch(PDO:: FETCH_ASSOC)){
           $rows[] = $row;
       }


texts:
I'd just like to get some pointers on my newbie-ish C here. The intention is to have an environment variable provide the "prefix" for any paths this app needs.

For example, APP_PREFIX could be /opt/app, a path the app wanted to get could be /etc/app.conf, and so app_path("/etc/app.conf") should return /opt/app/etc/app.conf.

I realise this is currently sensitive to leading/trailing slashes; I just wanted to make sure I'm on the right track with this basic stuff. Be as pedantic as you like – from outright bugs down to style and convention.

It compiles with no warnings on Mac OS X with gcc -Wall -pedantic ..., and does what I expect it to. On Linux, I had to compile with libbsd, and #include <bsd/string.h> for strlcpy() and strlcat().

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

#define APP_PREFIX_ENV_VAR "APP_PREFIX"

const char * app_path_prefix() {
    char * env_prefix = getenv(APP_PREFIX_ENV_VAR);
    if (env_prefix == NULL) {
        return "";
    } else {
        return env_prefix;
    }
}

char * app_path(char * in_path) {
    const char * prefix = app_path_prefix();
    size_t prefix_len = strlen(prefix);
    size_t out_size = prefix_len + strlen(in_path) + 1;
    char * out = malloc(out_size);

    strlcpy(out, prefix, prefix_len + 1);
    strlcat(out, in_path, out_size);
    return out;
}

int main(int argc, char ** argv) {
    char * path = app_path(argv[1]);
    printf("result: '%s'\n", path);
    free(path);
    return EXIT_SUCCESS;
}


texts:
Please review my answer for this interview question:

#include <iostream>
#include <vector>

std::vector<int> merge2Sorted ( std::vector<int> left, std::vector<int> right )
{
  //finger matching algo

  auto itLeft = left.begin();
  auto itRight = right.begin();

  auto itLeftEnd = left.end();
  auto itRightEnd = right.end();

  std::vector<int> result;
  result.reserve(std::max(left.size(),right.size()));

  while ( itLeft != itLeftEnd &&
          itRight != itRightEnd )
  {
    if ( *itLeft < *itRight )
      result.push_back( *itLeft++ );
    else
      result.push_back( *itRight++ );
  }

  // copy rest of left array
  while ( itLeft != itLeftEnd )
    result.push_back(*itLeft++);

  // copy rest of right array
  while ( itRight != itRightEnd )
    result.push_back(*itRight++);

  return result;
}

int main ()
{
  std::vector<int> v1 = { 1,2,3,4,5,6,7,8,9,10 };
  std::vector<int> v2 = { -1,-2,0,3,7,9,11,12 };

  std::vector<int> v3 ( merge2Sorted ( v1, v2 ) );

  for ( auto& i: v3 )
    std::cout << i << std::endl;
}


texts: Makefile and main header file for a shell

texts:
My main.c includes this header file. Please let me know how I can improve it. I did my best but I don't know much about code conventions in C (I come from Java and Python).

#define _XOPEN_SOURCE 500

#ifndef OPENSHELL_OPENSHELL_H
#define OPENSHELL_OPENSHELL_H
#define    CMD_LEN        1024
#define    EXPAND_ALLOC    1024
#define    PATH_LEN    1024
#define    isBlank(ch)    (((ch) == ' ') || ((ch) == '\t'))
#define    isDecimal(ch)    (((ch) >= '0') && ((ch) <= '9'))
#define    MAX_SOURCE    10
#define    isWildCard(ch)    (((ch) == '*') || ((ch) == '?') || ((ch) == '['))
#define    CHUNK_INIT_SIZE    4
#define    DEBUG TRUE
#ifndef VERSION
#define VERSION2 "v0.1a"
#endif

#include <string.h>
#include <dirent.h>
#include <utime.h>
#include <stdbool.h>
#include <getopt.h>

/*
 * A chunk of data.
 * Chunks contain data which is allocated as needed, but which is
 * not freed until all of the data needs freeing, such as at
 * the beginning of the next command.
 */
typedef struct chunk CHUNK;

struct chunk {
    CHUNK *next;
    char data[CHUNK_INIT_SIZE];    /* actually of varying length */
};
/*
 * One entry of the command table.
 */
typedef struct {
    const char *name;

    int        (*func)(int argc, const char **argv);

    int minArgs;
    int maxArgs;
    const char *description;
    const char *usage;
} CommandEntry;

typedef int Pipe[2];

static struct option options[] = {
        {"with_param", 1, 0, 'p'},
        {"version",    0, 0, 'v'},
        {"help",       0, 0, 'h'},
        {0,            0, 0, 0}
};
struct command {
    char *const *argv;
};
extern void freeChunks(void);

extern char **str_split(char *a[], char *a_str, const char a_delim);

extern int do_checkenv(int argc, const char **argv);

extern int do_cd(int argc, const char **argv);

extern int do_add2path(int argc, const char **argv);

extern int do_exit(int argc, const char **argv);

extern int do_help(int argc, const char **argv);

extern int do_kill(int argc, const char **argv);

int spawn_proc(int in, int out, struct command *cmd);

void fork_pipes(int n, struct command *cmd);

int file_exist(char *filename);

extern bool makeArgs(const char *cmd, int *argcPtr, const char ***argvPtr, bool pipe, int g, int h);

#endif
#define VERSION "v0.160429-21-g54bb-dirty"

The above file is versioned at github. You can also review the project's Makefile:

CC = gcc
GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
CFLAGS := $(CFLAGS) -L/usr/local/include/ -L/usr/include -pedantic -std=c99 -Wall -O3 -g -DVERSION=\"$(GIT_VERSION)\" -ledit -lncurses

LDIRS = -L/usr/local/lib -L/usr/lib
LIBS =su -lcurses

shell: main.o
    $(CC) -o shell main.o errors.c util.c pipeline.c -ledit -lncurses -lcurses

main.o: main.c errors.c util.c
USERNAME := $(shell whoami >> username.txt)
GIT:= $(shell head -n -1 openshell.h > temp.txt ; mv temp.txt openshell.h;git describe --abbrev=4 --dirty --always --tags > VERSION; echo "\#define VERSION \"$(GIT_VERSION)\"" >> openshell.h)

.PHONY: clean
clean:
    rm -f *.o

As seen in the Makefile, I'm writing the git version number to the header file with a shell instruction. Maybe I should do this before I compile to be able to get a "clean" version, otherwise I will always differ from a tag just by writing the new tag.


texts: Python algorithm that converts array-like data into MathJax

texts:
I frequently use MathJax, and often I need to write matrices. Since writing matrices using MathJax is very tiresome task, I decided to automate it.

Code:

import numpy as np
import pyperclip

class Conversion():

    def __init__(self, matrix, n = None, m = None):
        if matrix == None:
            self.matrix = np.random.randint(-10,10, size = [n,m])
        else:
            '''If variable "matrix", for example, contains [1,2,3,4], instead of [[1,2,3,4]], functions below
            will throw error, hence we need to make sure that the data type is correct.'''
            if type(matrix[0]) in (str,int,float):
                self.matrix = np.array([matrix,])
            else:
                self.matrix = np.array(matrix)

        self.rows = len(self.matrix)
        self.cols = len(self.matrix[0])

    def single(self, choosen_brackets = ')'):
        available_brackets = {' ' : 'matrix',
                              ')' : 'pmatrix',
                              ']' : 'bmatrix',
                              '}' : 'Bmatrix',
                              '|' : 'vmatrix',
                              '||': 'Vmatrix'  }
        choosen_brackets = available_brackets[choosen_brackets]
        body = '$$\\begin {} \n'.format('{' + choosen_brackets + '}')
        for row in self.matrix:
            row = [str(x) for x in row]
            body += ' & '.join(row) + '\\\\' + '\n'
        body +='\end {} $$'.format('{' + choosen_brackets + '}')
        print(body)
        pyperclip.copy(body)

    def augmented(self, choosen_brackets = '[]'):
        '''We are assuming that the last column of the given matrix is a vector.'''

        pos_of_the_verticar_bar = '{' + 'c'*(self.cols-1) + '|' + 'c' + '}'
        body = '$$\\left [ \\begin {array} %s \n' % (pos_of_the_verticar_bar)
        for row in self.matrix:
            row = [str(x) for x in row]
            body += ' & '.join(row) + '\\\\' + '\n'
        body +='\end {array} \\right ]$$'
        print(body)
        pyperclip.copy(body)

Notes:

Since function augmented is quite similar to single, I could've merged  them into one. However, I think that keeping them separate makes the code a little bit more readable.
On MSE, mathjax equations are enclosed with $$ instead of \$
"single" is a bad name for a function, I admit. I haven't found any better options. Feel free to offer suggestions.

What can be improved?

Written for Python 3.6.5.


texts:
After reviewing autoloader functions on the site, I didn't see anything like this, and I was wonder what may be wrong with this?

function findNloader($classFile){
    $file = exec("find ./ -name ".$classFile.".php");
    if(file_exists($file)){
        return require $file;
    } else {
        return false;
    }
}

The shell command returns false if somebody were to ever manage to inject something like:

../../../../sudoers  or the like...

And of course, it could be used with
spl_autoload_register() -- and if the file path were configured properly, it could find anything without chaining down autoload functions.  I understand that if it were pointed at a very large project, it might be resource intensive -- but with a direct enough focus, is there anything else wrong with this?

It could then be shortened into:

public function findnload($class) {
    return (file_exists($st = exec("find ./ -name ".$class.".php")) ?
    require $st : false);
}

And that looks quite elegant, to me.
Or if you want to be safe:

public function findnload($class) {
    return (file_exists($st = exec("find ./ -name ".$class.".php")) &&
           (length($class) < $thirtyTwoOrSo) || ($someOtherSafetyCriteria)
           ?
    require $st : false);
}

Any thoughts ?


texts: Readability in creation of a long output string

texts:
Below is a function from a driver that I wrote for and I2C temperature sensor.
The function takes as input the name of the bus and the device's bus address, reads it's status register, and then reports the status verbosely. (It also returns a values of interest, but that's not important now).

I have two questions about this:

I'm using lots of comment text {}'.format('this' if Condition else 'that'). I gather this is frowned upon, but in this case I think readability is optimal. The alternative would be

statusthing = 'this' if Condition else 'that'
'comment text {}'.format(statusthing)

or, worse (as in 'much more lines and no better readability'):

if Condition:
    statusthing = 'this'
else:
    statusthing = 'that'

Rpt += 'comment text %s' % statusthing

Same for using this way of constructing the output string. I see people get upset when you do this:

Rpt = 'eggs, bacon, sausage \n'
.
.
Rpt += 'sausage'

But in this case, it's concise, I think it's readable, it works. I don't see anything wrong with it. Is there?

Here's the full function.

def read_config(bus, sensor):
    Conf = bus.read_byte_data(sensor, ACCESS_CONFIG)

    TH = decode_DS(bus.read_word_data(sensor, ACCESS_TH))
    TL = decode_DS(bus.read_word_data(sensor, ACCESS_TL))

    Rpt = '\nStatus of DS1621 at address {}:\n'.format(sensor)

    Rpt += '\tConversion is {}\n'.format(
            'done' if Conf & DONE else 'in process')

    Rpt += '\t{} measured {} degrees Celsius or more\n'.format(
            'HAVE' if Conf & TH_BIT else 'have NOT', str(TH))

    Rpt += '\t{} measured below {} degrees Celsius\n'.format(
            'HAVE' if Conf & TL_BIT else 'have NOT', str(TL))

    Rpt += '\tNon-volatile memory is {}\n'.format(
            'BUSY' if Conf & NVB else 'not busy')

    if Conf & POL_HI:
        level, device = 'HIGH', 'cooler'
    else:
        level, device = 'LOW', 'heater'

    Rpt += '\tThermostat output is Active {} (1 turns the {} on)\n'.format(
            level, device)

    Rpt += '\tDevice is measuring {}\n'.format(
            'in One Shot mode' if Conf & ONE_SHOT else 'continuously')

    print Rpt

    return Conf, TH, TL

My aim is for this to be as usable, readable and understandable as possible.


texts: Header file that includes all standard C library headers

texts:
The Standard C Library consists of various headers files.  Often only a few select ones are needed for given code.

Other times it is simply convenient coding to include them all in a .c file, even if that make the compilation time a bit slower.

Including all standard <*.h> is useful to help detect naming collisions of a .c file with an existing standard function, object, type, macro, etc.

Review Goal

How well does std.h accomplish the goal of including all standard header files via one .h file given that the set varies amongst C versions and implementations?

/*
 * std.h
 *  Created on: Mar 16, 2019, Author: chux
 */

#ifndef STD_H_
#define STD_H_

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#if defined __STDC__ && defined __STDC_VERSION__

#if __STDC_VERSION__ >= 199409
#include <iso646.h>
#include <wchar.h>
#include <wctype.h>
#endif

#if __STDC_VERSION__ >= 199901
#ifndef __STDC_NO_COMPLEX__
#include <complex.h>
#endif
#include <fenv.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <tgmath.h>
#endif

#if __STDC_VERSION__ >= 201112
#include <stdalign.h>
#ifndef __STDC_NO_ATOMICS__
#include <stdatomic.h>
#endif
#include <stdnoreturn.h>
#ifndef __STDC_NO_THREADS__
#include <threads.h>
#endif
#include <uchar.h>
#endif

#if __STDC_VERSION__ >= 201710
/* None added */
#endif

#endif

#endif /* STD_H_ */

In making a set of functions and types called say foo, I do not recommend including all header files in a foo.h, yet perhaps in foo.c.

Sample usage

// foo.h  (no std.h here)
#ifndef FOO_H_
#define FOO_H_

#include <stdint.h>
#include <time.h>

typedef struct {
    time_t t;
    uint32_t u32;
} foo;

void foo_this(foo *f);
void foo_that(foo *f);

#endif /* FOO_H_ */

foo.c or main.c

#include "foo.h"
#include "std.h"

int main(void) {
  foo f;
  foo_this(&f);
  foo_that(&f);
  printf("Hello World!\n");
  return 0;
}

The alternative spellings afforded in <iso646.h> seem to be a solution to a regional character set problem of years ago.  I reluctantly included <iso646.h> here but do see that a good candidate to exclude.  It defines macros for and, or, xor and others.


texts:
This question is a small subset of the problem I am trying to solve.
I am trying to learn to break problems into better abstractions.

The original problem I am trying to solve is:

  Write a JS library which allows an user to select an Image and then divide the image into square tiles. Calculate the average color of each tile and render the equivalent number of svg elements from top to bottom and left to right direction. The request for each svg element should be an XHR request.

I decided to create two abstractions for now:

Grid
Tile

here is the code:

class Tile {
  constructor(shape='', width = Tile.Width, height = Tile.Height) {
    this.shape = shape;
    this.width = width;
    this.height = height;
  }

  render() {
    return this.shape;
  }
}
Tile.Width = 50;
Tile.Height = 50;

class Grid {
  constructor(rows, cols) {
    this.cells = [];
    this.R = rows;
    this.C = cols;
    for (let row = 0; row < rows; row++) {
      const cells = [];
      for (let col = 0; col < cols; col++) {
        cells.push({
          x: col * Tile.Width,
          y: row * Tile.Height,
          tile: new Tile()
        });
      }
      this.cells.push(cells);
    }
  }

  setTile(shape, {row, col}) {
    if (row < 0 || row >= this.R || col < 0 || col >= this.C) {
      throw new Error("Invalid tile position");
    }
    this.cells[row][col] = {
      x: col * Tile.Width,
      y: row * Tile.Height,
      tile: new Tile(shape)
    };
  }

  render() {
    let output = [];
    this.cells.forEach(row => {
      output.push(this.renderRow(row));
    });
    console.log(output.join('\n'));
  }

  renderRow(cells) {
    let output = [];
    cells.forEach(cell => {
      output.push(cell.tile.render());
    });
    return output.join(' ');
  }
}

const grid = new Grid(2, 2);
grid.setTile('', {row: 0, col: 1});
grid.setTile('', {row: 1, col: 0});
grid.setTile('', {row: 0, col: 1});
grid.setTile('', {row: 1, col: 1});
console.log(grid.render());

Here is the live example.

Question

Does the design of the grid system is compatible with the requirement so far? I want it to be used in the canvas or some other rendering platform so is this a good design?


texts: Infix to postfix notation in Haskell (Shunting-yard algorithm)

texts:
I've written an infix to postfix converter in Haskell using the Shunting-yard algorithm. Example of how it works:

$ ./in2post
2 + 2
2 2 +
$ ./in2post
1 + 2 * 3
1 2 3 * +
$ ./in2post
  (5 - 4) * 3+1005/(12-6*(12   -8)  )
5 4 - 3 * 1005 12 6 12 8 - * - / +
$ ./in2post
(2 + 45
2 45 + ERROR

And the source code:

Main.hs

module Main (main) where

import System.IO
import InToPost

main :: IO ()
main = do
    line <- getLine
    let tokens  = tokenise line
        newexpr = shuntYard [] [] tokens
    putStrLn $ untokenise newexpr

InToPost.hs

module InToPost
    ( Token(TNum, TOp)
    , Operator
    , splitTok
    , tokenise
    , untokenise
    , shuntYard
    ) where

import Data.Char (isSpace, isDigit)
import Data.List (groupBy)

data Token = TNum Int
           | TOp Operator
           deriving (Show)
data Operator = Add
              | Sub
              | Mult
              | Div
              | LBrace
              | RBrace
              deriving (Show, Eq)

splitTok :: String -> [String]
splitTok = groupBy (\x y -> isDigit x && isDigit y) . filter (not . isSpace)

str2tok :: String -> Either String Token
str2tok tkn@(c:_)
    | isDigit c = Right $ TNum $ read tkn
    | otherwise = case tkn of
        "+" -> Right $ TOp Add
        "-" -> Right $ TOp Sub
        "*" -> Right $ TOp Mult
        "/" -> Right $ TOp Div
        "(" -> Right $ TOp LBrace
        ")" -> Right $ TOp RBrace
        _   -> Left  $ "No such operator: \"" ++ tkn ++ "\""

tok2str :: Token -> String
tok2str (TNum t) = show t
tok2str (TOp t) = case t of
    Add  -> "+"
    Sub  -> "-"
    Mult -> "*"
    Div  -> "/"
    _    -> "ERROR"

precedence :: Operator -> Int
precedence Add    = 1
precedence Sub    = 1
precedence Mult   = 2
precedence Div    = 2
precedence LBrace = 3
precedence RBrace = 3

-- shuntYard (Operator stack) (Token Queue) (Token Buffer) = new Token Queue
shuntYard :: [Operator] -> [Token] -> [Either String Token] -> Either String [Token]
shuntYard _ _ (Left s:_) = Left s
shuntYard stack queue [] = Right $ queue ++ map TOp stack
shuntYard stack queue (Right (TNum t):ts) = shuntYard stack (queue ++ [TNum t]) ts
shuntYard stack queue (Right (TOp t):ts) =
    shuntYard ustack uqueue ts
  where
    (ustack, uqueue) = case t of
        LBrace -> (t : stack, queue)
        RBrace -> (stail srest, queue ++ map TOp sstart)
        _      -> (t : ssend, queue ++ map TOp ssops)
    (sstart, srest) = break (==LBrace) stack
    currprec = precedence t
    (ssops, ssend) = span (\op -> precedence op > currprec && op /= LBrace) stack
    stail :: [a] -> [a]
    stail (x:xs) = xs
    stail [] = []

tokenise :: String -> [Either String Token]
tokenise = map str2tok . splitTok

untokenise :: Either String [Token] -> String
untokenise (Left s) = s
untokenise (Right ts) = unwords . map tok2str $ ts

Please tell me, what are my bad practices here? For example, the use of Either felt really awkward and I'm sure it can be done better. Also, the case expression in str2tok is quite ugly.


texts:
Bulls and Cows is a simple code-breaking game sometimes better known as "Mastermind." The rules are explained here: https://en.wikipedia.org/wiki/Bulls_and_Cows

I would appreciate some feedback on the following implementation in terms of overall code quality, layout and logic. It's meant to be at a fairly basic level so I don't want to over complicate things, but want to avoid any obviously bad choices. Suggestions for improvements very welcome.

import random

SECRET_NUMBER_SIZE = 2
MAX_GUESSES = 5

# Generate secret number with SECRET_NUMBER_SIZE digits and no duplicates
secret_number = ""
while len(secret_number) < SECRET_NUMBER_SIZE:
    new_digit = str(random.randint(0, 9))
    if new_digit not in secret_number:
        secret_number += new_digit

# print(f"For testing. Secret number is: {secret_number}")

print(f"Guess my number. It contains {SECRET_NUMBER_SIZE}\
unique digits from 0-9")

remaining_turns = MAX_GUESSES

while remaining_turns <= MAX_GUESSES:

    # Get user guess and validate length
    player_guess = input("Please enter your guess: ")
    if len(player_guess) != SECRET_NUMBER_SIZE:
        print(f"Your guess must be {SECRET_NUMBER_SIZE} digits long.")
        continue

    # Main game logic
    if player_guess == secret_number:
        print("Yay, you guessed it!")
        break
    else:
        bulls = 0
        cows = 0
        for i in range(SECRET_NUMBER_SIZE):
            if player_guess[i] == secret_number[i]:
                bulls += 1
        for j in range(SECRET_NUMBER_SIZE):
            if player_guess[j] in secret_number and \
              player_guess[j] != secret_number[j]:
                cows += 1
        print(f"Bulls: {bulls}")
        print(f"Cows: {cows}")
        remaining_turns -= 1
        if remaining_turns < 1:
            print("You lost the game.")
            break


texts: Scraping with asyncio/aiohttp and retrying the request on error

texts:
I am doing some practicing with back-connect proxies and asyncio/aiohttp. The IP changes on every request to the proxy and I am allowed up to 1500 threads. The big issue with back-connect proxies, is you do not always get a proxy that works. This forces me to keep requesting the URL until there are no errors so I can return the HTML.

I am mainly asking for a code review to see if using a while loop is the best option to keep retrying the request. And how I can speed up the script overall? I have been looking into different HTML parsers, using multiprocessing, etc... but just not sure what direction to go in. The code below does work fine, and it processes 12,000 URLs in about 30 minutes. I really appreciate you looking at my code and let me know if you have any questions! Thank you for your time.

import asyncio
import aiohttp

from bs4 import BeautifulSoup
from datetime import datetime
from aiohttp.resolver import AsyncResolver

class Proxy:
    def __init__(self, headers, proxy):
        self.headers = headers
        self.proxy = proxy

    async def build(self, urls):
        tasks = []
        resolver = AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"])
        connector = aiohttp.TCPConnector(limit=1500, limit_per_host=0, resolver=resolver, use_dns_cache=False)
        async with aiohttp.ClientSession(connector=connector) as session:
            for url in urls:
                task = self.fetch(session, url)
                tasks.append(task)
            r = await asyncio.gather(*tasks)
            return r

    async def fetch(self, session, url):
        while True:
            try:
                async with session.get(url, headers=self.headers, proxy=self.proxy) as resp:
                    assert resp.status == 200
                    r = await resp.read()
                    soup = BeautifulSoup(r, 'lxml')
                    html_title = soup.title.string
                    print (html_title)
                    return html_title
            except Exception as e:
                print (e)

if __name__ == '__main__':
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
    proxy = 'XXX.XX.X.XXX:XXXXX'
    proxy = "http://{}".format(proxy)

    px = Proxy(headers, proxy)

    urls= []
    with open('urls.txt') as f:
        for line in f:
            urls.append(line.strip())

    startTime = datetime.now()
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    future = asyncio.ensure_future(px.build(urls))
    html_title = loop.run_until_complete(future)
    loop.close()
    print (datetime.now() - startTime)


texts: Optimization code for checking if a list contains any element ID of another list

texts:
I have the following code:

var sessionsWithError = SessionsFilteredByDate
    .Where(i => i.TrackerId > 0 && i.StatusId == 0)
    .Select(i => i.SessionId);
var sessionsWithErrorFixed = BusinessClient.Instance.Tracker
    .GetAllTrackerAttempts()
    .Select(i => i.SessionId);
var sessionsWithErrorIntersection = sessionsWithError.Intersect(sessionsWithErrorFixed);
var sessionsWithErrorsNotFixed = sessionsWithError.Except(sessionsWithErrorIntersection);

Then I have to create a IEnumerable where I put all the SessionsFilteredByDate where the sessionID is included in sessionsWithErrorsNotFixed, but this operation, since I am using the Any operator, it's slow, apparently \$O(m*n)\$.

How can I achieve this operation with a lower complexity?

SessionsFilteredByDateAndErrors = SessionsFilteredByDate
    .Where(i => sessionsWithErrorsNotFixed.Any(y => y == i.SessionId));


texts:
I have made a simple concurrent program. It represents a battle between a hero and a monster. I am beginner in concurrency so I just want to hear your opinion. What are bad and good sides of my code and how can I improve it?

Interface Attack

public interface Attack {
public void attack(Object s, int dmg);
}

Main class

public class Main {
public static void main(String[] args) {
    Monster monster = new Monster(50, "monster");
    Hero hero = new Hero (50, "hero");
    ThreadFight tf = new ThreadFight(hero, monster);

    Thread t1 = new Thread (new Runnable() {
        @Override
        public void run() {
            tf.hitHero();
        }
    });

    Thread t2 = new Thread (new Runnable() {
        @Override
        public void run() {
            tf.hitMonster();
        }
    });

    t1.start();
    t2.start();
}
}

Class Hero

public class Hero implements Attack{
private int hp;
private String name;
private Monster monster;

public Hero (int hp, String name) {
    this.hp = hp;
    this.name = name;
}

public int getHp() {
    return this.hp;
}

public String getName() {
    return this.name;
}

public void decreaseHp(int dmg) {
    this.hp = getHp() - dmg;
}

public void setMonster(Monster monster) {
    this.monster = monster;
}

@Override
public void attack(Object s, int dmg) {
    if (s instanceof Monster) {
        Monster m = (Monster) s;
        System.out.println("Monster hp: " + m.getHp());
        System.out.println("Hero dealt " + dmg + " damage");
        m.decreaseHp(dmg);
        System.out.println("Monster hp is now: " + m.getHp());
        System.out.println("--------------------------");
    }
}
}

Class Monster

public class Monster implements Attack{
private int hp;
private String name;
Hero hero;

public Monster (int hp, String name) {
    this.hp = hp;
    this.name = name;
}

public int getHp() {
    return this.hp;
}

public String getName() {
    return this.name;
}

public void decreaseHp(int dmg) {
    this.hp = getHp() - dmg;
}

public void setHero(Hero hero) {
    this.hero = hero;
}

@Override
public void attack(Object s, int dmg) {
    if (s instanceof Hero) {
        Hero h = (Hero) s;
        System.out.println("Hero hp: " + h.getHp());
        System.out.println("monster dealt " + dmg + " damage");
        h.decreaseHp(dmg);
        System.out.println("Hero hp is now: " + h.getHp());
        System.out.println("--------------------------");
    }
}
}

Class ThreadFight

public class ThreadFight{
Hero hero;
Monster monster;
Random random = new Random();
Object lock = new Object();

public ThreadFight(Hero hero, Monster monster) {
    this.hero = hero;
    this.monster = monster;
}

public void hitMonster() {

    while (monster.getHp() > 0 && hero.getHp() > 0) {
        synchronized (lock) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            hero.attack(monster, random.nextInt(20));

        }
        if (monster.getHp() < 0) {
            System.out.println("Hero won.");
        }
    }
}

public void hitHero() {

    while (hero.getHp() > 0 && monster.getHp() > 0) {
        synchronized (lock) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            monster.attack(hero, random.nextInt(20));

        }
        if (hero.getHp() < 0) {
            System.out.println("Monster won.");
        }
    }
}
}


texts: Dynamically create javascript object (Backbone View)

texts:
The context here is Backbone but it's a general question about dynamically creating javascript objects.

I would like to pass the name of a View ('ViewX') to be created, to a function which can then create the new ViewX()

How could I do this?

In my Backbone View I want to create a subView, the type of which depends on the Model I have used for the current View.
At the moment I have an if-else structure (See Approach #1 in the example) which works, but is clunky and will be more clunky in future when I have more Model types.

I have tried some alternatives, including evaluation via the Function constructor (Approach #2), which gives 'string is not a function' error.
In Approach #3, the View module I am passing as a parameter is not available in the current View's this namespace (I am using requirejs).

renderContentList: function() {

    var self = this;

    // Approach #1
    var setSidebarListCollectionView = function(type) {
       if (type === 'tags') {
           self.sidebarListCollectionView = new TagSidebarListCollectionView({
               collection: self.collection,
               tagCollection: self.tagCollection
           });
       } else {
           self.sidebarListCollectionView = new CardSidebarListCollectionView({
               collection: self.collection,
               tagCollection: self.tagCollection
           });
       }
    };
    /*
    // Approach #2
    var setSidebarListCollectionView = new Function('type', 'coll', 'tagColl', 'return new type({collection: coll, tagCollection: tagColl});');

    // Approach #3
    var setSidebarListCollectionView = function(type) {
        return new self[type]({
                        collection: self.collection,
                        tagCollection: self.tagCollection
                    });
    };
    */
    // reset it every time
    if (this.sidebarListCollectionView) {
        this.sidebarListCollectionView.remove();
    }
    if (this.model.get('activeSubTab') === 'tags') {
        // Approach #1
        setSidebarListCollectionView('tags');
        // Approach #2
        // this.sidebarListCollectionView = setSidebarListCollectionView('TagSidebarListCollectionView', this.collection, this.tagCollection);
        // Approach #3
        // this.sidebarListCollectionView = setSidebarListCollectionView('TagSidebarListCollectionView');
    } else {
        // Approach #1
        setSidebarListCollectionView('cards');
        // Approach #2
        // this.sidebarListCollectionView = setSidebarListCollectionView('CardSidebarListCollectionView', this.collection, this.tagCollection);
        // Approach #3
        // this.sidebarListCollectionView = setSidebarListCollectionView('CardSidebarListCollectionView');
    }

    // render the list of content title links.
    this.$el.find('#content-manager-list-content').append(this.sidebarListCollectionView.render().el);
},


texts: Immutable binary search tree using Scala

texts:
I have written a sample immutable binary search tree using Scala. However, I am not sure whether or not I was doing it the proper way since I am not an expert at functional programming. Is there a better or more efficient way of, say, traversing the tree or adding an item to it using a purely functional approach?

The add (+) method:

def +(data: T): Bst = {
  def insert(optTree: OptBst): Bst = optTree match {
    case None => BST(data)(comparison)
    case Some(tree) => comparison(data, tree.data) match {
      case cmp if cmp < 0 => tree(left = Some(insert(tree.left)))
      case cmp if cmp > 0 => tree(right = Some(insert(tree.right)))
      case _ => tree
    }
  }
  insert(Some(this))
}

Delete (-) method:

def -(data: T): OptBst = {
  def remove(optTree: OptBst): OptBst = optTree match {
    case None => None
    case Some(tree) => comparison(data, tree.data) match {
      case cmp if cmp > 0 => Some(tree(right = remove(tree.right)))
      case cmp if cmp < 0 => Some(tree(left = remove(tree.left)))
      case _ => (tree.hasLeft, tree.hasRight) match {
        case (false, false) => None
        case (true, false) => tree.left
        case (false, true) => tree.right
        case (true, true) =>
          val rightMinData = tree.rightMin.get.data
          Some(tree(data = rightMinData, right = tree.right.get - rightMinData))
      }
    }
  }
  remove(Option(this))
}

Search method:

  def search(data: T) = {
    @tailrec
    def search(optTree: OptBst): OptBst = optTree match {
      case None => None
      case Some(tree) => comparison(data, tree.data) match {
        case cmp if cmp < 0 => search(tree.left)
        case cmp if cmp > 0 => search(tree.right)
        case _ => optTree
      }
    }
    search(Some(this))
  }


texts: Finding the distance between every indices in an array that contain odd numbers

texts:
I'm doing this HackerRank problem which basically boils down to what I've written in the title. We have to find out the distance between all the odd values in the array. I've written this code below which passes all the test cases but I think I can do better, namely, I don't have to make a separate array (oddindices) to contain the odd values' indices.

def min_bread(N, breads):
    oddcount = 0
    oddindices = []
    for idx in xrange(N):
        if breads[idx]%2:
            oddcount += 1
            oddindices.append(idx)
    if oddcount%2: # Odd number of odd loaves make it impossible to distribute
        return "NO"
    if oddcount==N or oddcount == 0: # All are odd (return that number) or even (return 0)
        return oddcount
    loaves = 0
    for idx in xrange(0, oddcount, 2):
        loaves += (oddindices[idx+1] - oddindices[idx])*2
    return loaves

if __name__ == '__main__':
    N = int(raw_input())
    breads = map(int, raw_input().split())
    print min_bread(N, breads)

But I can't figure out how to do it without having a separate array. The way I'm thinking is, if I encounter an odd value, I make the loop skip to AFTER the next odd value. I could do this easily with oddindices, but how do I do it without that extra array?


texts: Game of Rock paper and scissors against a random bot

texts:
I have to do a project on a game of rock, paper, and scissors, and the code I have so far is a complete code for the game, but my professor does not like it since it is too redundant. Is there anyway to shorten it or make it more simple?

import random

while True:
   bot = random.choice(["Rock", "Paper", "Scissors"]).lower()

   user_choice = input("Choose between Rock, Paper, and Scissors or -1 to exit: \n ").lower()
   if user_choice == bot:
      print("We tied! I chose", bot," and you chose", user_choice)
   elif user_choice == "rock":
      if bot == "paper":
         print("You lose! I chose", bot," and you chose", user_choice , ", Paper beats rock!")
      elif bot == "scissors":
       print("You win! I chose", bot," and you chose", user_choice , ", Rock beat scissors!")
   elif user_choice == "paper":
      if bot == "rock":
         print("You win! I chose",bot," and you chose", user_choice , ", Paper beats rock!")
      elif bot == "scissors:":
         print("You lose! I chose", bot," and you chose", user_choice , ", Scissors beats paper")
   elif user_choice == "scissors":
      if bot == "paper":
         print("You win! I chose", bot," and you chose",user_choice, ", Scissors beats paper")
      elif bot == "rock":
         print("You Lose! I chose", bot," and you chose", user_choice , ", Rock beats scissors")
   else:
      print("Invalid Entry, you typed:", user_choice, ", Please try again: ")

   if user_choice == '-1':
      print("You selected -1 to exit, Goodbye!")
exit()


texts:
I am trying to calculate the time required to tag one sentence/file by one trained NLTK HMM Tagger.
To do this I am writing the following code, please suggest if I need to revise anything here.

import nltk
from nltk.corpus.reader import TaggedCorpusReader
import time
#HMM
reader = TaggedCorpusReader('/python27/', r'.*\.pos')
f1=reader.fileids()
print f1
sents=reader.tagged_sents()
ls=len(sents)
print "Total No of Sentences:",ls
train_sents=sents[0:40]
test_sents=sents[41:46]
#TRAINING & TESTING
hmm_tagger=nltk.HiddenMarkovModelTagger.train(train_sents)
test=hmm_tagger.test(test_sents)
appli_sent1=reader.sents(fileids='minicv.pos')[0]
print "SAMPLE INPUT:",appli_sent1
start_time = time.clock()
application=hmm_tagger.tag(appli_sent1) #I MAY REPLACE WITH ONE DOCUMENT
print "ENTITY RECOGNIZED",application
print "Time Taken Is:",time.clock() - start_time, "seconds"

NB: This is a toy kind example and I did not follow much of training/testing size parameters.


texts:
I needed a monadic version of partition today. I settled on the following version:

partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM p xs = bimap (map fst) (map fst) . partition snd . zip xs <$> mapM p xs

Then I realized it's already implemented here:

partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM f [] = return ([], [])
partitionM f (x:xs) = do
    res <- f x
    (as,bs) <- partitionM f xs
    return ([x | res]++as, [x | not res]++bs)

This second version doesn't have to pull in extra packages and doesn't create intermediate lists, but mine is shorter and doesn't have explicit recursion. What do you think of my solution in comparison with the library's implementation?


texts: Determine if points are within a rotated rectangle

texts:
Using only Python 2.7 and the standard library (no imports):
Determine if a point is inside the rotated rectangle.
Test point 1: 670831  4867989
Test point 2: 675097  4869543

Rectangle:

Vertex 1:     670273   4879507
Vertex 2:     677241   4859302
Vertex 3:     670388   4856938
Vertex 4:     663420   4877144

Can the following code be improved?
vertices = [(670273, 4879507), (677241, 4859302), (670388, 4856938), (663420, 4877144)]

def dot_pdt(point1, point2, pointT):
    return ((point2[0] - point1[0]) * (pointT[0] - point1[0])) + ((point2[1] - point1[1]) * (pointT[1] - point1[1]))

def check_point(pointT):
    for i in range(len(vertices)):
        k = dot_pdt(vertices[i], vertices[(i + 1) % len(vertices)], pointT)
        if k <= 0:
            return False

    return True

point1 = (676455.270, 4861545.437)

print(check_point(point1))


texts: Parallelized web crawler using goroutines and channels

texts:
As part of the "a tour of Go" section on golang.org, I was trying to make a (formerly singlethreaded) web crawler parallelized using goroutines. I got it working but it doesn't seem to "flow" right; there's a bunch of duplicated code. Looking for advice as to how it can seem a bit more Go-literate.
package main

import (
    "fmt"
    "sync"
)

type Fetcher interface {
    // Fetch returns the body of URL and
    // a slice of URLs found on that page.
    Fetch(url string) (body string, urls []string, err error)
}

type safeMap = struct {
    seen map[string]bool
    mu sync.Mutex
    remaining int
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.

func gci(url string, depth int, fetcher Fetcher, m *safeMap, fc chan string) {
    go crawl_int(url, depth, fetcher, m, fc)
}

func crawl_int(url string, depth int, fetcher Fetcher, m* safeMap, fc chan string) {
    if depth > 0 {
        body, urls, err := fetcher.Fetch(url)
        //fc <- fmt.Sprintf("Crawling %s\n", url)
        m.mu.Lock()
        defer m.mu.Unlock()

        if err != nil {
            fc <- fmt.Sprintf("%v\n",err)
        } else {
            fc <- fmt.Sprintf("found: %s %q %d\n", url, body, len(urls))
            for _, u := range urls {
                _, found := m.seen[u]
                if !found {
                    m.remaining += 1
                    m.seen[u] = true
                    defer gci(u, depth-1, fetcher, m, fc)
                }
            }
        }
    } else {
        m.mu.Lock()
        defer m.mu.Unlock()
    }
    m.remaining -= 1
    //fc <- fmt.Sprintf("finished %s remaining to %d\n", url, m.remaining)
    if (m.remaining == 0) {
        //fc <- fmt.Sprintf("closing")
        close(fc)
    }
}

func Crawl(url string, depth int, fetcher Fetcher, ch chan string) {
    // Fetches URLs in parallel.
    // Doesn't fetch the same URL twice.
    c := safeMap{seen: make(map[string]bool), remaining: 1}

    go crawl_int(url, depth, fetcher, &c, ch)
}

func main() {
    ch := make(chan string,5)
    Crawl("https://golang.org/", 4, fetcher, ch)
    for u := range ch {
        fmt.Print(u)
    }
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
    body string
    urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string, error) {
    if res, ok := f[url]; ok {
        return res.body, res.urls, nil
    }
    return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
    "https://golang.org/": &fakeResult{
        "The Go Programming Language",
        []string{
            "https://golang.org/pkg/",
            "https://golang.org/cmd/",
        },
    },
    "https://golang.org/pkg/": &fakeResult{
        "Packages",
        []string{
            "https://golang.org/",
            "https://golang.org/cmd/",
            "https://golang.org/pkg/fmt/",
            "https://golang.org/pkg/os/",
        },
    },
    "https://golang.org/pkg/fmt/": &fakeResult{
        "Package fmt",
        []string{
            "https://golang.org/",
            "https://golang.org/pkg/",
        },
    },
    "https://golang.org/pkg/os/": &fakeResult{
        "Package os",
        []string{
            "https://golang.org/",
            "https://golang.org/pkg/",
        },
    },
}


texts: Print out a table that displays how far a cannon can shoot an object at incremental speeds and angles

texts:
Does the way I am storing and printing out the data make any sense? or am I going about it all wrong. the code works great, but I'm not entirely sure it was the best way to go about it. Also, I think I can ditch the arrayList and use an array, but I'm not sure if I should.

import java.util.ArrayList;
public class CatapultTester
{
    public static void main (String[] args)
    {
        ArrayList<Catapult> cat = new ArrayList<Catapult>();

        int angleIntervals = 5;
        int speedIntervals = 5;

        int startAngle = 25;
        int startSpeed = 20;

        int NumAngles = 6;
        int NumSpeeds = 7;

        // you can add rows/columns just by changing the two ints above. (you can also change the starting points and the intervals in which they increase)

        // it should also be relatively easy to make the header adjust itself to added/removed columns, but I'll do that later.

        for(int x = 0; x < NumSpeeds; x++)
        {
            for(int y = 0; y < NumAngles; y++)
            {
                cat.add(new Catapult((y * angleIntervals) + startAngle, (x * speedIntervals) + startSpeed));
            }
        }

        // just calculates distance for every angle/speed combo.
        for(int i = 0; i < cat.size(); i++)
        {
            cat.get(i).calcDist();
        }

        System.out.println("       |                    Projectile Distance (ft.)                    ");
        System.out.println("*************************************************************************");
        System.out.println("  MPH  |  25 Deg     30 Deg     35 Deg     40 Deg     45 Deg     50 Deg  ");
        System.out.println("*************************************************************************");

        for(int x = 0, i = 0; x < NumSpeeds; x++)
        {
            double mph = cat.get(i).getMilesPerHour();

            System.out.printf("  %-8.0f", mph);

            for(int y = 0; y < NumAngles; y++, i++)
            {
                double dist = cat.get(i).getDist();

                System.out.printf("%-10.2f ", dist);
            }

            System.out.print("\n");
        }

        System.out.println("*************************************************************************");
    }
}

Here is the Catapult class

public class Catapult
{
    private double launchAngle;
    private double milesPerHour;
    private double distance;

    /**
     * Constructor for objects of class Catapult
     *
     * @param angle The angle at whitch the projectile is launched.
     *
     * @param mph The speed at whitch the projectile is launched.
     */
    public Catapult(int angle, int mph)
    {
        launchAngle = angle;
        milesPerHour = mph;
    }

    /**
     * Calulates how far the projectile travels
     */
    public void calcDist()
    {
        distance = (Math.pow(milesPerHour, 2) * Math.sin( 2 * Math.toRadians(launchAngle)) / 9.8);
    }

    /**
     * @return Returns distance.
     */
    public double getDist()
    {
        return distance;
    }

    //not used, but I added it anyway. it could be used to make a dynamic header for the output.
    /**
     * @return Returns launchAngle.
     */
    public double getLaunchAngle()
    {
        return launchAngle;
    }

    /**
     * @return Returns milesPerHour.
     */
    public double getMilesPerHour()
    {
        return milesPerHour;
    }
}

Also, sorry about the messy code.


texts:
This produces recursive directory listings(it's intended to do other things, so there will be something else instead of echo, but it isn't important), yet it isn't very intuitive. How can I improve it?

#! /bin/bash
deploy ()
{
    for file in $(ls $1); do
        if [ ! -d "$2$file" ]; then
            echo ${2}${file}
        else
            deploy $2$file "$2$file/"
        fi
    done;
}

deploy .

Output example:

tmp/kdecache-z/http/ba9c27404980248a61dcdadd35f5f52395b8bdde
tmp/kdecache-z/http/scoreboard
tmp/kdecache-z/icon-cache.kcache
tmp/kdecache-z/ksycoca4
tmp/kdecache-z/ksycoca4stamp
tmp/kdecache-z/plasma-svgelements-.customized1
tmp/kdecache-z/plasma-svgelements-internal-system-colors
tmp/kdecache-z/plasma_theme_.customized1.kcache
tmp/kdecache-z/plasma_theme_internal-system-colors.kcache
tmp/kdecache-z/Активные
tmp/kdecache-z/напоминанияrc
tmp/kdecache-z/Устаревшие
tmp/kdecache-z/напоминанияrc
tmp/kdecache-z/Шаблоны
tmp/kdecache-z/напоминанийrc
tmp/kde-z/xauth-1000-_0
tmp/ksocket-z/kdeinit4__0
tmp/ksocket-z/kio_http_cache_cleaner
tmp/ksocket-z/klauncherhX2255.slave-socket
tmp/ksocket-z/KSMserver__0
tmp/pulse-PKdhtXMmr18n/native
tmp/pulse-PKdhtXMmr18n/pid
tmp/qtsingleapp-homezS-8560-3e8
tmp/qtsingleapp-homezS-8560-3e8-lockfile
tmp/skype-2664/DbTemp./temp-KXp68f252Xx0kBMtqNdj7NFo
tmp/skype-2664/DbTemp./temp-NAailvY24hLGYNrZiJ99QIgH
tmp/sni-qt_skype_2664-v6Xyna/icons/hicolor/24x24/apps/skype_2664_2d1ee5482260fd9cd180b32787792683.png
tmp/sni-qt_skype_2664-v6Xyna/icons/hicolor/24x24/apps/skype_2664_37e170fc54e7355d9d298917e74f9ea9.png
tmp/sni-qt_skype_2664-v6Xyna/icons/hicolor/24x24/apps/skype_2664_602c84fa0f4d61c64f770495a500279e.png
tmp/sni-qt_skype_2664-v6Xyna/icons/hicolor/24x24/apps/skype_2664_f2fc4a539a7b9553f5b35241d1154e84.png
tmp/z.socket

P.S. It is working perfectly for me so I just want to make it more beautiful.


texts:
I tried implementing visitor patter and have questions about my usage of is and as keywords. Is there a big performance hit when using them?

 class Program
{
    static void Main(string[] args)
    {
        List<IVisitor> visitors = new List<IVisitor>();
        visitors.AddRange(new List<IVisitor>()
        {
            new PersonVisitor(),
            new AnimalVisitor()
        });

        List<Creature> creatures = new List<Creature>();
        creatures.AddRange(new List<Creature>()
        {
            new Person() { Name = "Frank" },
            new Person() { Name = "Tony" },
            new Person() { Name = "Amy" },
            new Animal() { Name = "Bubbles" },
            new Animal() { Name = "Max" }
        });

        CreatureProcessor creatureProcessor = new CreatureProcessor(creatures, visitors);
        creatureProcessor.Process();

        Console.ReadKey();
    }
}

interface IVisitor
{
    void Visit(IElement element);
}

interface IElement
{
    void Accept(IVisitor visitor);
}

class PersonVisitor : IVisitor
{
    public void Visit(IElement element)
    {
        if (element is Person)
        {
            Creature creature = element as Person;

            Console.WriteLine("{0} is a good {1}", creature.Name, "Person");
        }
    }
}

class AnimalVisitor : IVisitor
{
    public void Visit(IElement element)
    {
        if (element is Animal)
        {
            Creature creature = element as Animal;

            Console.WriteLine("{0} is a good {1}", creature.Name, "Animal");
        }
    }
}

class Person : Creature
{

}

class Animal : Creature
{

}

abstract class Creature : IElement
{
    public string Name { get; set; }

    public void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}

class CreatureProcessor
{
    private readonly List<IVisitor> visitors;
    private readonly List<Creature> creatures;

    public CreatureProcessor(List<Creature> creatures, List<IVisitor> visitors)
    {
        this.creatures = creatures;
        this.visitors = visitors;
    }

    public void Process()
    {
        foreach (IVisitor visitor in visitors)
        {
            foreach (Creature creature in creatures)
            {
                creature.Accept(visitor);
            }
        }
    }
}

It works, the way it should I think, so would anyone care to critique it?


texts: Getting the current timestamp and compute the timestamp difference in minutes

texts:
I have this code to get the current Timestamp and compute the last timestamp's difference with the current timestamp in minutes. I'm wondering if this can be optimized further for production.

public static Timestamp getTimestamp() {
    java.util.Date date= new java.util.Date();
    long time = date.getTime();
    java.sql.Timestamp ts = new java.sql.Timestamp(time);
    return ts;
}

public static long getLastTimestampElapse(java.sql.Timestamp oldTime){
  long milliseconds1 = oldTime.getTime();
  long milliseconds2 = getTimestamp().getTime();
  long diff = milliseconds2 - milliseconds1;
  long diffMinutes = diff / (60 * 1000);
  return diffMinutes;
}


texts:
This is a simple C++ program I had to write for class. It prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. How do I improve this?

For example:

Input: 3456
Output:
3 4 5 6
Sum of all digits: 19

Input: 1234
Output:
1 2 3 4
Sum of all digits: 10

#include <iostream>
#include <iomanip>

using namespace std;
int main()
{
    int base;
    int first;
    int second;
    int third;
    int fourth;
    int sum;

    cout << " Please enter a whole number." << endl;
    cin >> base ;

    first = base / 1000;
    second = base / 100 % 10;
    third =  base / 10 % 10;
    fourth = base % 10;

    sum = first + second + third + fourth;

    cout << first << " " << second << " " << third<<  " " << fourth <<  " " << endl;
    cout << "Sum of the digits: " << sum << endl;

    return 0;
}


texts: wrapper class for random access iterator to hide template method implementation from header file

texts:
I have a set of template functions that have itrator types as template parameters, so can be used with any kind of iterators. std::find can be a good example.
Also I have a class that uses this function in its implementation and I don't want to expose my algorithms' header. Regarding the template function, inside my class I expect the iterators to be of random access type. So I wrote a wrapper class which can be constructed from any iterator Type that has the same pointer type and std::random_access_iterator_tag
template <typename IterR, typename IterL>
using iter_same_value_type = std::is_same<
        typename std::iterator_traits<IterR>::value_type,
        typename std::iterator_traits<IterL>::value_type>;

template <typename IterR, typename IterL>
using iter_same_category = std::is_same<
        typename std::iterator_traits<IterR>::iterator_category,
        typename std::iterator_traits<IterL>::iterator_category>;

template <typename T>
class WrapperRandomAccessIterator
{
    using this_type = WrapperRandomAccessIterator<T>;
public:

    using difference_type = std::ptrdiff_t;
    using value_type = T;
    using pointer = T*;
    using reference = T&;
    using iterator_category = std::random_access_iterator_tag;

    template <typename RandomAccessIter, typename  = typename
            std::enable_if<iter_same_category<this_type, RandomAccessIter>() &&
                    iter_same_value_type<this_type, RandomAccessIter>()>::type>
    constexpr explicit WrapperRandomAccessIterator(RandomAccessIter iter)
        : ptr_(&*iter)
    {}

    reference operator*()
    {
        return *ptr_;
    }

    // Warning says "const has no effect on type reference"
    const T& /*reference*/ operator*() const
    {
        return *ptr_;
    }

    const this_type& operator++()
    {
        ptr_ = std::next(ptr_);
        return *this;
    }

    this_type operator++(int)&
    {
        auto res = *this;
        ++(*this);
        return res;
    }

private:
    T *ptr_;
};

Here I have clang-tidy complaining about operator++(int)& that it returns non-const object.
It also says that for const reference operator*() that `const qualifier have no effect.

How can it be improved?
Do I have to use the rule of 3 or 5 in such case?
Does it make sense to create a generic iterator wrapper class and a specialization for each iterator type? (I know, this question probably belongs with engineering stack exchange).


texts:
Every call to the web service goes through a custom queuing system. This has a limit that is set to 1. Every call that enters the same time with another call is purged and not handled. Not sure if this is completely thread safe.

public void QueueForExecution(T value)
{
    lock (_queueLock)
    {
        if (_entryCount < _queueLimit)
        {
            Interlocked.Increment(ref _entryCount);
            Logger.Trace(String.Format("Running task queue item for {0}.", _methodName));

            Task.Run(() => RunTask(value));
        }
        else
        {
            lock (_queueItemLock)
            {
                _queuedExecutionValue = value;
            }
            Logger.Trace(String.Format("Task queue limit reached for {0} - queued request - overriding any previous queued items.", _methodName));
        }
    }
}


texts:
This code to solve Problem 23 in Project Euler gives the correct answer. But, running the last expression takes around 40 seconds. I welcome advice on how to improve performance here.

(defn sum-div [num]
  (->> (range 2 (+ 1 (int (Math/ceil (Math/sqrt num)))))
       (filter #(= (mod num %) 0))
       (map (fn [x]
              (let [d (/ num x)]
                (if (= x d)
                  x
                  [x d]))))
       flatten
       distinct
       (reduce +)
       (+ 1)))

(def abundants
  (->> (range 12 28123)
       (map #(vector % (sum-div %)))
       (filter #(> (second %) (first %)))
       (map first)
       set))

(defn is-sum-of-two-abundants?
  [num]
  (let [sub-ab (->> abundants
                    (filter #(< % num))
                    set)]
    (some (fn [ab]
            (sub-ab (- num ab)))
          sub-ab)))

(->> (range 28124)
     (filter (complement is-sum-of-two-abundants?))
     (reduce +))


texts:
Exercise: Write a method that returns the gcd of an unspecified number of integers.

What I did:

Created a for loop that stores integers in an array. The array length is increased every time the else statement is reached. The loop will break upon receiving '0'.
Created a method to find the gcd. This method sorts the array using Arrays.sort. The first element of the array will be 0. The lowest integer (index 1) is assigned to the variable min.
To compute the gcd, I created a for loop that assigns min to i. I decrement this variable until the modulo operation for count % numbers.length - 1 equals 0. This indicates that a gcd has been found for all integers and will break out of the main for loop. The variable count will increment when an integer in the array is divisible by the current divisor.

I would really appreciate any feedback you can give me.

public class Exercise_07_14 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter numbers: ");
        int[] numbers = new int[1];

        for (int i = 0; i < numbers.length; i++) {
            int number = input.nextInt();

            if (number == 0)
                break;
            else
                numbers[i] = number;

            numbers = incrementArraySize(numbers);
        }

        int gcd = getGCD(numbers);

        String output = "";

        for (int i = 1; i < numbers.length; i++) {
            if (i == numbers.length - 1)
                output += numbers[i];
            else
                output += numbers[i] + ", ";
        }

        System.out.println("The GCD of [" + output + "] is: " + gcd);
    }

    public static int getGCD(int... numbers) {
        Arrays.sort(numbers);

        int min = numbers[1];
        int gcd = 1;

        for (int i = min; i > 1; i--) {
            int count = 0;

            for (int k = 1; k < numbers.length; k++) {
                if (numbers[k] % i != 0)
                    break;
                else
                    count++;
            }

            if (count == (numbers.length - 1)) {
                gcd = i;
                break;
            }
        }

        return gcd;
    }

    public static int[] incrementArraySize(int[] array) {
        int[] tempArray = array;
        array = new int[tempArray.length + 1];

        System.arraycopy(tempArray, 0, array, 0, tempArray.length);

        return array;
    }
}


texts: Capitalize string except for conjunction words

texts:
I am using the code below to capitalize words in a string. I do not want conjunction words capitalized, but always want the first character in the string to be capitalized no matter what the word is. Is this the most optimized way of accomplishing this? How could this be improved?

xText = queryForHeading
xTextSplit = split(xText, " ")

for each item in xTextSplit
    xWord = item
    if lcase(item) = "a" or lcase(item) = "an" or lcase(item) = "and" or lcase(item) = "as" or lcase(item) = "at" or lcase(item) = "but" or lcase(item) = "by" or lcase(item) = "en" or lcase(item) = "for" or lcase(item) = "if" or lcase(item) = "in" or lcase(item) = "is" or lcase(item) = "nor" or lcase(item) = "of" or lcase(item) = "on" or lcase(item) = "or" or lcase(item) = "per" or lcase(item) = "the" or lcase(item) = "this" or lcase(item) = "to" or lcase(item) = "it" or lcase(item) = "vs." then
        xWord = lcase(item)
    elseif lcase(item) = "ii" or lcase(item) = "iii" or lcase(item) = "iv" or lcase(item) = "vi" or lcase(item) = "vii" or lcase(item) = "viii" or lcase(item) = "ix" then
        xWord = ucase(item)
    end if
    xCompleteWord = xCompleteWord & " " & xWord
next

queryForHeading = xCompleteWord
queryForHeading = Mid(queryForHeading, 2)
queryForHeading = UCase(Mid(queryForHeading, 1, 1)) & Mid(queryForHeading, 2)


texts: Program that removes comments from C and C++ programs

texts:
I have downloaded the latest version of the Linux kernel and I want to perform thorough analysis on it. I want to start by eliminating comments from all the source and header files that belong to it. I am using a code I wrote sometime ago and I want to use it recursively. In the past I tested it on my code and it worked fine, but since I want to use it on a wide scale, I want to know if the code is consistent and successful in all cases.

Can you help me determine if it has bugs that do not deal with removing comments and create mess in certain cases?

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

int RemoveComments(const char *filename, const char *Output);

int main(void)
{
    RemoveComments("file.cpp", "output.cpp");
    return 0;
}

int RemoveComments(const char *filename, const char *Output)
{
#define NOT_COMMENT (!DOUBLESLASH_Comment && !ASTERISK_SLASH_Comment)

    clock_t t1 = clock();
    FILE *input, *output;
    if (fopen_s(&input, filename, "r"))
    {
        perror(filename);
        exit(1);
    }
    if (fopen_s(&output, Output, "w"))
    {
        perror(Output);
        exit(1);
    }
    int c, d;

    bool DOUBLESLASH_Comment = 0, ASTERISK_SLASH_Comment = 0, flag = 0;

    int s_QUOTED = 0, d_QUOTED = 0;
    while ((c = getc(input)) != EOF)
    {
        switch (c)
        {
        case '\\':
        {
            if (NOT_COMMENT)
            {
                if (flag == 1)
                    flag = 0;
                else
                    flag = 1;
            }
        }break;
        case '\'':
        {
            if (NOT_COMMENT && !d_QUOTED)
            {
                if (!flag)
                {
                    s_QUOTED++;
                }
            }
        }break;
        case '"':
        {
            if (NOT_COMMENT && !flag)
            {
                if (!s_QUOTED)
                {
                    d_QUOTED++;
                }
            }
        }break;
        case '/':
        {
            if (NOT_COMMENT && !d_QUOTED)
            {
                if ((d = getc(input)) == '*')
                {
                    ASTERISK_SLASH_Comment = 1;
                }
                else if (d == '/')
                {
                    DOUBLESLASH_Comment = 1;
                }
                else
                {
                    if (d != EOF)
                    {
                        ungetc(d, input);
                    }
                }
            }
        }break;
        case '*':
        {
            if (ASTERISK_SLASH_Comment)
            {
                if ((d = getc(input)) == '/')
                {
                    if ((c = getc(input)) == EOF)
                        return 0;
                    ASTERISK_SLASH_Comment = 0;
                }
                else
                {
                    if (d != EOF)
                    {
                        ungetc(d, input);
                    }
                }
            }
        }break;
        case '\n':
        {
            if (DOUBLESLASH_Comment)
            {
                DOUBLESLASH_Comment = 0;
            }
        }break;
        }
        if (NOT_COMMENT && c != '\\') flag = 0;
        if (d_QUOTED == 2) d_QUOTED = 0;
        if (s_QUOTED == 2) s_QUOTED = 0;
        if (NOT_COMMENT)
        {
            putc(c, output);
        }
    }
    fclose(input);
    fclose(output);
    clock_t t2 = clock();
    double elapsed = (double)(t2 - t1) / CLOCKS_PER_SEC;
    printf("time elapsed : %.4f\n", elapsed);
    return 0;
}


texts: Simple authentication and registration of users

texts:
I have created a simple authentication script in python that can add users and
provides a login function. I've tried to thow as much security into this as possible, which probably wasn't the best idea.
To my knowledge, the code works fine and withstands as much invalid input as I can find (although I haven't written any proper tests). I can see straight away that I've repeated myself quite a lot, but I'm not entirely sure how to cut it down.
Usage:

login(username, password)
Checks if this username/password combination is valid.
Returns bool
add_user(username, password)
Adds a user to the password file.
Returns bool

import hashlib, random, string

USERNAME_CHARACTERS=string.digits+string.ascii_letters
PASSWORD_CHARACTERS=string.digits+string.ascii_letters+string.punctuation

SALT_CHARACTERS="0123456789abcdefghijklmnopqrstuv"
SALT_CHARACTER_BITS=5
SALT_LENGTH=16
PEPPER_LENGTH=1

FILE_PATH="./shad"
FILE_SEPERATOR=":"

def int_to_string(num):
    string=""
    while num!=0:
        c=num%(2**SALT_CHARACTER_BITS)
        string+=SALT_CHARACTERS[c]
        num-=c
        num//=2**SALT_CHARACTER_BITS
    return string

def generate_new_salt():
     return int_to_string(random.getrandbits(SALT_CHARACTER_BITS*SALT_LENGTH))
def generate_new_pepper():
    return int_to_string(random.getrandbits(SALT_CHARACTER_BITS*PEPPER_LENGTH))
def generate_all_peppers():
    for i in range(1,SALT_CHARACTER_BITS*PEPPER_LENGTH):
        yield int_to_string(i)

def do_hash(string):
    return hashlib.sha3_256(string.encode()).hexdigest()

def get_user_data(username):
    with open(FILE_PATH) as h:
        data=h.read()
    for line in data.split("\n"):
        l=line.split(FILE_SEPERATOR)
        if l[0]==username:
            return {"user":l[0],
                    "pass":l[1],
                    "salt":l[2]}
    raise ValueError("Username not found: "+username)

def is_valid_username(username):
    for i in username:
        if not(i in USERNAME_CHARACTERS):
            return False
    return True

def is_valid_password(username):
    for i in username:
        if not(i in PASSWORD_CHARACTERS):
            return False
    return True

def add_user(username, password):
    if not(is_valid_username(username)):
        print("Invalid username")
        return False
    elif not(is_valid_password(password)):
        print("Invalid password")
        return False
    with open(FILE_PATH) as h:
        data=h.read()
    for line in data.split("\n"):
        l=line.split(FILE_SEPERATOR)
        if l[0]==username:
            print("Username already exists")
            return False

    salt=generate_new_salt()
    data=FILE_SEPERATOR.join([username, do_hash(generate_new_pepper()+salt+password), salt])+"\n"
    with open(FILE_PATH, "a") as h:
        h.write(data)
    return True

def login(username, password):
    if not(is_valid_username(username)):
        print("Invalid username")
        return False
    elif not(is_valid_password(password)):
        print("Invalid password")
        return False
    data=get_user_data(username)
    for pepper in generate_all_peppers():
        if do_hash(pepper+data["salt"]+password)==data["pass"]:
            return True
    return False


texts:
I'd created a C# class to connect to a MySQL database (Connection.cs) and a separate class for the user validation (User.cs).

Connection.cs

public static MySqlConnection GetConnection()
{
    try
    {
        var connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        _connection = new MySqlConnection(connectionString);
        _connection.Open();
    }
    catch (MySqlException ex) {

        switch (ex.Number)
        {
            //0: Cannot connect to server.
            case 0:
                MessageBox.Show("Cannot connect to server.  Contact administrator");
                break;
            //1045: Invalid user name and/or password.
            case 1045:
                MessageBox.Show("Invalid username/password, please try again");
                break;
        }

    }

    return _connection;
}

User.cs

public bool AuthenticateUser()
{
    string query = "SELECT * FROM users WHERE user_name = @userName LIMIT 1";
    bool password = false;
    try
    {
        Console.Write("connection");
        using (MySqlConnection connection = Connection.GetConnection())
        {
            Console.Write("Cmd");
            using (var cmd = new MySqlCommand(query, connection))
            {
                cmd.Parameters.AddWithValue("@userName", this.UserName);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        password = BCrypt.Net.BCrypt.Verify(this._password + reader["salt"].ToString(), reader["password"].ToString());
                        this._user_id = int.Parse(reader["id"].ToString());
                    }
                }
            }
        }
    }
    catch (MySqlException ex)
    {
        throw new ArgumentException(ex.Message);
    }
    catch (Exception ex) {
        throw new ArgumentException(ex.Message);
    }

    return password;

}

I didn't created a method to dispose/close the connection anymore, since as far as I know, the using statement automatically disposes the type of IDisposable. I was looking for a suggestion before I continue coding for more functionalities.


texts: Printing doubles using string manipulation

texts:
Having mostly used Qt and its classes like QString, I wrote a little exercise with plain C++11. I'm looking for two kinds of input: generally improving the code and/or doing it better in an entirely different way (still standard C++11 or C++14, no Boost or anything).

The code is for printing doubles with given number of significant digits, by first producing a string using scientific notation, and then manipulating that string to move the dot and pad it with zeros.

#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <stdexcept>

template <typename T>
std::string number_to_sci_string(T number, int precision) {
    std::stringstream ss;
    ss << std::scientific << std::setprecision(precision-1) << number;
    return ss.str();
}

std::string sci_string_to_normal(const std::string &s) {
    auto dot_pos = s.find('.');
    auto e_pos = s.find('e');
    if (dot_pos == std::string::npos || // dot required
        dot_pos < 1 ||  // part1 below must not be empty
        e_pos == std::string::npos || // e required
        e_pos >= s.length()-1 || // must not be last
        e_pos - dot_pos < 2) { // part2 below must not be empty
        throw std::invalid_argument(s);
    }

    auto exponent = std::stoi(s.substr(e_pos + 1), nullptr, 10);
    if (exponent == 0) {
        return s.substr(0, e_pos);
    }
    else {
        auto part1 = s.substr(0, dot_pos);
        auto part2 = s.substr(dot_pos + 1, e_pos - dot_pos - 1);
        auto part2length = static_cast<ssize_t>(part2.length());
        if (exponent >= part2length) {
            auto fill = std::string(exponent - part2length, '0');
            return part1 + part2 + fill;
        }
        else if (exponent < 0) {
            auto fill = "0." + std::string(-1 - exponent, '0');
            // this is the only case where sign matters
            auto sign = (s[0] == '-' || s[0] == '+')
                        ? std::string(1, s[0])
                        : std::string();
            return sign + fill + part1.substr(sign.length()) + part2;
        }
        else { // 0 < exponent < part2.length()
            return part1 + part2.substr(0,  exponent) + "." + part2.substr(exponent);
        }
    }
}

using namespace std;

int main(void)
{
    vector<double> nums{ -2000.0005, -1.2345234, -0.000011345, 0, 0.0000001, 0.1342134, 1.1234, 10000 };
    for_each(nums.begin(), nums.end(), [](double &n) {
        string sci = number_to_sci_string(n, 5);
        string nor = sci_string_to_normal(sci);
        cout << n << ": " << sci << " == " << nor << endl;
    });
}


texts:
I had a logging function…

@task
def log_request(label, target, request_as_dict):
    # Detect flood

    # In general this task do not process misuse. But it can send
    # an alarm to another celery task if something strange happened.
    if incr_with_ttl(INDICATOR_KEY, INDICATOR_TTL) >= INDICATOR_THRESHOLD:
        process_misuse.apply_async()
        redis.delete(INDICATOR_KEY)

    # Save entry
    fields = request_as_dict['fields']
    fields.update({
        "label": label,
        "type": 1 if target else 2, # 1: target, 2: extra

        "suspicion": suspicion_rating(request_as_dict),
        "raw_request": request_as_dict
    })
    RequestEntry.objects.create(**fields)

… that I rewrote using two inner functions for readability.

@task
def log_request(label, target, request_as_dict):

    def detect_flood():
        '''
        In general this task do not process misuse. But it can send
        an alarm to another celery task if something strange happened.
        '''
        if incr_with_ttl(INDICATOR_KEY, INDICATOR_TTL) >= INDICATOR_THRESHOLD:
            process_misuse.apply_async()
            redis.delete(INDICATOR_KEY)

    def save_entry():
        fields = request_as_dict['fields']
        fields.update({
            "label": label,
            "type": 1 if target else 2, # 1: target, 2: extra

            "suspicion": suspicion_rating(request_as_dict),
            "raw_request": request_as_dict
        })
        RequestEntry.objects.create(**fields)

    save_entry()
    detect_flood()

Is the rewrite an improvement?


texts:
I am sort of new to programming.  I would like to understand the code areas that are garbage and could be better written keeping the exact (if possible) behavior the code has now.

from random import randint
import time
from collections import OrderedDict

cast_again = 'r'
statistics = OrderedDict()
casts = 0
menu_options = """
> Options:
>    R - to cast again;
>    S - view stats;
>    E - exit the programme.
> """

def rollDice(dice):
    input('> Press Enter to cast dice!')
    time.sleep(1)
    cast_result = []
    for a_cast in range(0,dice):
        cast_result.append(randint(1,6))
    return cast_result

def atLeastALetterInput(text_to_display):
    cast_again = 'x'
    try:
        cast_again = input(text_to_display)[0].lower()
        return cast_again
    except IndexError:
        print('> Please make sure input is valid before pressing enter...')

while 1:
    try:
        num_dice = int(input('> Enter the number of dice you would like to cast! (max 10):'))
        if num_dice not in range(0,11):
            print('> Please enter a value between 1 and 10! ')
            continue
        break
    except ValueError:
        print('> Non-numerical characters detected. Try again!')

while 1:
    if cast_again not in ('r', 's', 'e'):
        print('> Ups! Available options R(new cast), S(statistics) and E(exit).')
        cast_again = atLeastALetterInput(menu_options)
        continue
    if cast_again == 'r':
        next_cast = casts + 1
        print('> Here comes cast number {}'.format(next_cast))
        casts +=1
        cast_results_to_stats = rollDice(num_dice)
        statistics[casts] = cast_results_to_stats
        print('> Here is your result: {}'.format(cast_results_to_stats))
        cast_again = atLeastALetterInput(menu_options)
    elif cast_again == 's':
        for key in statistics:
            print('> *** Cast {} resulted in {}'.format(key, statistics[key]))
        cast_again = atLeastALetterInput(menu_options)
    elif cast_again == 'e':
        print('> The game finished after {} casts.'.format(casts))
        break

print('> Good bye! ')
input()


texts:
It's a common occurrence nowadays to have different refresh rates across different devices. That's why it's very important to keep track of the device's frame rate to keep the game time consistent across different refresh rates.

Is this an efficient way to go about this?

var timeBetween;
var timeLast;

function gameLoop() {
  var timeNow = window.performance.now();
  timeBetween = timeNow - timeLast;
  timeLast = timeNow;

  gameLogic(timeBetween); // Send time to game logic to calculate e.g. game speed etc.
  gameDraw();

  requestAnimationFrame(gameLoop);
}


texts:
I am asking for an experienced person to review my basic shell script. I do not write them at work, but I am a software developer. I am using this for my personal project that I am working on. Later, it will be integrated with Docker and a CI server maybe Jenkins/Travis CI.

I am just looking for someone to tell me if I am not following best practices
or conventions, or if certain parts need to be changed/revised.

#!/bin/bash
PATH=$PATH:$(npm bin)
set -x
webapp="/Users/earzate/Development/Career/profile-page-app"
serverapp="/Users/earzate/Development/Career/profile-server-ws/app-server"

#build profile-page-app
cd $webapp
echo "Building ng page app"
ng build --prod
echo "ng page app build complete"

#build app-server
echo "Cleaning static sources"

#clean old static web files
cd "$serverapp/src/main/resources"
echo "Deletic static web resources"
rm -r static

#make new static directory
echo "Creating static directory"
mkdir static

#copy web resources from webapp into serverapp static directory
echo "Copying static resources into directory"
cp -r "$webapp/dist/."  "$serverapp/src/main/resources/static"

#copy secured objects from secured directory
#secured objects not versioned in git
cp "$serverapp/secured/name/private-key.p12" "$serverapp/src/main/resources"

echo "Building jar"
cd "$serverapp"
./gradlew build

echo "Deploying app"
java -jar build/libs/app-server-0.0.1-SNAPSHOT.jar


texts: Advent of code 2017 Day 1 (1) in Functional Programming


texts: Reducing nested while statements for building a grid?

texts:
I have the following grid shape:

 __ __ __
|__|__|__|
|__|__|__|

I have the following 3 types of shapes to fill it (they cannot rotate):

 __
|__|    __
|__|   |__|   (6x6 one above, or full size)

I have also 3 "shape lists" that need to fill it in priority, as in:

ShapeList1 = all types
ShapeList2 = all types
ShapeList3 = only single type

The lists are actually stacks, and I cannot have any empty spaces. I also need to pop the the first shape off each stack, if it does not fill it, go to the next type. ShapeList3 will always be able to complete the grid as it only has the 1x1 type. If it gets to the end of ShapeList3 I try the shapes in order again, trying to fill the grid, until the shape is filled.

I have this working but I have a lot of while loops, including a nested loop. This is a code smell and I feel as if I could do this better. Here's my current building code in pseudo-C#:

    var largeContentBlock = new LargeContentBlock();

    while (!largeContentBlock.Complete && aggregatePageFeed.ShapeList3.Any())
    {
    while (aggregatePageFeed.ShapeList1.Any()
                    && largeContentBlock.CanAddBlock(aggregatePageFeed.ShapeList1.Peek().Size)
                    && !largeContentBlock.Complete)
    {
        largeContentBlock.Add(aggregatePageFeed.ShapeList1.Pop());
    }

    while (aggregatePageFeed.ShapeList2.Any()
           && largeContentBlock.CanAddBlock(aggregatePageFeed.ShapeList2.Peek().Size)
           && !largeContentBlock.Complete)
    {
        largeContentBlock.Add(aggregatePageFeed.ShapeList2.Pop());
    }

        if (!largeContentBlock.Complete && largeContentBlock.CanAddBlock(aggregatePageFeed.ShapeList3.Peek().Size))
            largeContentBlock.Add(aggregatePageFeed.ShapeList3.Pop());
    }

    return largeContentBlock;

That's pretty ugly, I have it a little nicer by wrapping the while statements in functions. What pattern can I be using to make this nicer? I feel as if this is a solved problem.


texts: Architecture and error handling in simple java program

texts:
I'm trying to get my basic coding principles right but there's still a long way to go. This is an exercise for CodeGym. They logic itself isn't very hard and I passed the exercise easily but I'd like my code reviewed with the following in mind:

In terms of the general architecture, I wasn't quite sure if I needed two methods. It felt tidier to me to have a method for the first task (copy) and one for the second (append) but I couldn't figure out a way to avoid calling the second method from the first.
Should read the inputs from the console in the main method and pass the result to the class? Or it totally depends on the context of the application I'm working for?
About error handling, I got completely lost. After doing some research I just decided to let the caller handle the error but I'm sure there's some stuff missing. I wasn't sure for example if I should have two try blocks on the first method but it also depended on the answer to the first point (architecture), so I gave up.
It's my first time using Javadocs, so I'm not sure what I wrote is enough
I know "Solution" is not the ideal name for the class, but I used the class created by CodeGym.

Please feel free to tear it apart :)

Thanks in advance!

public class Solution {

    public static void main(String[] args)  {
        FileProcessor fileProcessor = new FileProcessor();
        try {
            fileProcessor.copyFile();
        } catch (IOException e) {
            System.out.println("General I/O exception: " + e.getMessage());
            e.printStackTrace();
        }
    }

import java.io.*;

/**
 *  This class reads 3 filenames from console,
 *  copies content from the second file to the first and subsequently
 *  appends content from third file to first file.
 */

public class FileProcessor {
    // Study comment: Solution using "var" didn't work in this IntelliJ
    /**
     * Reads inputs, copies second file to first and calls method to append file
     * @throws IOException
     */
    public void copyFile() throws IOException {
        String outputFile;
        String sourceToCopy;
        String sourceToAppend;

         try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
             System.out.println("Enter a filename for the output:");
             outputFile = reader.readLine();
             System.out.println("Enter the path of the file to be copied");
             sourceToCopy = reader.readLine();
             System.out.println("Enter the path of the file to be appended");
             sourceToAppend = reader.readLine();
         }

        try (FileOutputStream out = new FileOutputStream(outputFile);
             FileInputStream copy = new FileInputStream(sourceToCopy)) {
            byte[] buffer = new byte[1024];
            while (copy.available() > 0) {
                int count = copy.read(buffer);
                out.write(buffer, 0, count);
            }
        }

        appendFile(sourceToAppend, outputFile);
    }

    /**
     *
     * @param source file to append
     * @param output final result file
     * @throws IOException
     */
    public void appendFile(String source, String output) throws IOException {
        try (FileOutputStream appended = new FileOutputStream(output, true);
             FileInputStream toAppend = new FileInputStream(source)
        ) {
            byte[] buffer = new byte[1024];
            while (toAppend.available() > 0) {
                int count = toAppend.read(buffer);
                appended.write(buffer, 0, count);
            }
        }
    }
}


texts:
I am writing a simple image rotation script. Users press either the prev or next button to view the previous or next images. It works well, but the code looks over the top. Is there a way I can reduce the amount of code used?

index.php

<input type="button" name="prev" id="prev" value="prev" />
<input type="button" name="next" id="next" value="next" />

jQuery

$('#next').click(function(){
    if($('#pic1').hasClass('top-pic')){
        $('#pic1').removeClass('top-pic');
        $('#pic2').addClass('top-pic');
    }else if($('#pic2').hasClass('top-pic')){
        $('#pic2').removeClass('top-pic');
        $('#pic3').addClass('top-pic');
    }else if($('#pic3').hasClass('top-pic')){
        $('#pic3').removeClass('top-pic');
        $('#pic4').addClass('top-pic');
    }else if($('#pic4').hasClass('top-pic')){
        $('#pic4').removeClass('top-pic');
        $('#pic1').addClass('top-pic');
    }

});

$('#prev').click(function(){
    if($('#pic1').hasClass('top-pic')){
        $('#pic1').removeClass('top-pic');
        $('#pic4').addClass('top-pic');
    }else if($('#pic4').hasClass('top-pic')){
        $('#pic4').removeClass('top-pic');
        $('#pic3').addClass('top-pic');
    }else if($('#pic3').hasClass('top-pic')){
        $('#pic3').removeClass('top-pic');
        $('#pic2').addClass('top-pic');
    }else if($('#pic2').hasClass('top-pic')){
        $('#pic2').removeClass('top-pic');
        $('#pic1').addClass('top-pic');
    }

});


texts:
A practice interview question:

  How would you design a stack which, in addition to push and pop, also has a function getMin which returns the minimum element? Push, pop and min should all operate in O(1) time.

class stackWithMin
{
private:
    std::vector<int> stack;
    std::vector<int> minLoc;
    int min, current, minCurrent;

public:
    stackWithMin()
    {
        min = NULL;
        current = 0;
        minCurrent = 0;
    }

    void print()
    {
        std::cout<<"Min: "<<min<<" --- ";

        for (int i=0;i<stack.size();i++)
        {
            std::cout<<""<<stack.at(i)<<", ";
        }
        std::cout<<""<<std::endl;
    }

    void push(int num)
    {
        stack.push_back(num);

        if(num<=min || current == 0)
        {
            minLoc.push_back(current);
            minCurrent++;
            min = num;
        }
        current++;
        print();
    }

    void pop()
    {
        if(current==0)
        {
            std::cout<<"Stack is empty"<<std::endl;
            return;
        }

        // Check if the number to be popped is the current lowests
        if(minLoc.at(minCurrent-1)==current-1)
        {
            if(minCurrent>1)
            {
                int loc = minLoc.at(--minCurrent-1);
                minLoc.pop_back();
                min = stack.at(loc);
            }
            // No more elements
            else
            {
                min = NULL;
            }
        }

        current--;
        stack.pop_back();
        print();
        return;
    }

    int getMin(){return min;}

};


texts: Utility Method to find the Square root of a number

texts:
Utility to calculate the square root of a number. The method also accept an epsilon value, which controls the precision. The epsilon value could range to any number including zero. I am expecting a general code review or if there is a better way to write the code.

/**
 * The class MathUtil contains methods for performing basic numeric operations
    such as the squareRoot functions. Square root of 2.0: 1.4142135623746899
 */
public class MathUtil {

    /**
     * Returns the correctly rounded positive square root of a double value.
     * Special cases: If the argument is NaN or less than zero, then the result
     * is NaN. If the argument is positive zero or negative zero, then the
     * result is the same as the argument. Otherwise, the result is the double
     * value closest to the epsilon.
     *
     * Function takes a non-negative real number             *
     * @param a double
     * @param epsilon double
     * @return double
     */
    public static double squareRoot(final double a, final double epsilon) {
        if (a == 0)
            return a;
        else
            return internalSqrRoot(a, a / 2, epsilon);

    }

    /**
     * Method internalSqrRoot.
     *
     * @param a double
     * @param x double
     * @param epsilon double
     * @return double
     */
    public static double internalSqrRoot(final double a, final double x,
            final double epsilon) {
        if (closeEnough(a, x, epsilon)) {
            return x;
        } else {
            return internalSqrRoot(a, betterGuess(a, x), epsilon);
        }

    }

    /*
     * return true if the current guess is close enought o accepted value

     * Method closeEnough.
     *
     * @param a double
     * @param x double
     * @param epsilon double
     * @return boolean
     */
    public static boolean closeEnough(double a, double x, double epsilon) {

        return (Math.abs(x - ((a / x) + x) / 2)) <= epsilon;

    }

    /*
     * perform a simple manipulation to get a better guess (one closer to the
     * actual square root) by averaging y with x/y

     * Method betterGuess.
     * @param a double
     * @param x double
     * @return double
     */
    public static double betterGuess(double a, double x) {
        return ((a / x) + x) / 2;
    }
}


texts:
From searching online I have identified two ways to get the user email, but I don't know if either has pro's/con's beyond Option.1 being a larger number of lines of code?
Option.1
I have a dedicated ClaimsPrincipalExtension.cs class, which I can call from anywhere in my app using var email = ClaimsPrincipalExtensions.GetLoggedInUserEmail(User);. Within which I have a method to get the email as shown:
using System;
using System.Security.Claims;

namespace FunctionalLogicLibrary {

public static class ClaimsPrincipalExtensions {
public static string GetLoggedInUserEmail(this ClaimsPrincipal principal) {
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirstValue(ClaimTypes.Email); }
 }
}

Option.2
I just add using System.Security.Claims; to any class where I need it and use
var email = User.FindFirstValue(ClaimTypes.Email);

I'm just trying to learn here. Which method is more appropriate and why?


texts: Map-range supporting different precisions

texts:
I'm writing a Mandelbrot Set implementation, and to map the "Mandelbrot" coordinates to screen coordinates, I'm using Quil's map-range function. Essentially, it takes a number within a certain range, and "maps" it to a number of another range. It worked great when I was first testing since it's fast, but it forces using float numbers, which is unacceptable since I need far more precision.

I looked up the source of the function, and wrote my own Clojure version. It works, but it's painfully slow. The following measurements were taken using the Criterium library's bench function. Casting times were not included in the measurement:

quil's version: 31.7ns
my version, no casting: 450.7ns
my version, casting input to float: 130.1ns
... casting to double: 122.5ns
... casting to long: 440.8ns
... casting to BigDecimal: 880.2ns

Ideally, I'd like to be using BigDecimal, but using it currently causes the entire IDE to freeze, and froze my entire computer once.

The main problem is, the code is so simple, I don't know how I could possibly improve it. It's literally just a math equation:

(defn map-range [value start1 stop1 start2 stop2]
  (+ start2
     (* (- stop2 start2)
        (/ (- value start1)
           (- stop1 start1)))))

I understand that BigDecimal will always be slower, I've accepted that. But even a float to float comparison is more than 4x slower.

Is there any kind of trickery I can use to at least make this as fast as quil's version? All they use is plain math; my code is a direct translation from Java's infix notation to Clojure's prefix notation.

Any advice here would be appreciated.