texts:
I recognize that this is a common question area with lots of answers:
Here and here for example.
Specifically I'm trying to better understand how to use Enums in Python. Suits in a deck of cards seems appropriate, but implementing them as a class seems extra, and I'm curious if there's a more pythonic way to do it?
class Suits(Enum):
    Club = 1
    Heart = 2
    Diamond = 3
    Spade = 4

class Card:
    def __init__(self, value, suit):
        self.value = value
        self.suit = suit

class Deck:
    def __init__(self):
        self.cards = self.initDeck()

    def initDeck():
        cards = {}
        for suit in Suits:
            for i in range(14):
                cards.add(Card(i, suit))
        return cards

The whole point of Enums is to prevent you from adding a bad value though, right? (Like, making a new card as Card(0, 'joker')) so maybe this isn't the right application for it? Currently there would be no error if I passed Card(4, 'dimond') and that's exactly what enums are supposed to prevent, right?
Hoping for a bit more insight/education. Thanks!


texts: Check if a directed graph contains a cycle

texts:
I am trying to optimize execution time of this function which detects cycle in a directed graph:

g = {
    1: [2, 3],
    2: [3]
}

cur_path = set()
def isCyclic(g, vertex):
    global cur_path
    cur_path.add(vertex)
    for neighboor in g.get(vertex, []):
        if neighboor in cur_path:
            return True
        else:
            if neighboor in g and isCyclic(g, neighboor):
                return True
    cur_path.remove(vertex)
    return False

I look for redundant calls, or information that I can store somewhere to improve the execution time (which is O(E), right?).


texts:
there is a other way to write in JS the switch statement ,
This code is working :)

_update: function(oHtml, oConfig) {
        var _this = this;
        var oParent;
        if (oConfig.attributes != null) {
            oConfig.attributes.forEach(function(oAttr) {
                //debugger;
                oParent = oHtml.find("#" + oAttr.id);
                switch (oAttr.action) {
                    case 'upd':
                        _this._updateAttr(oParent, oAttr);
                        break;
                    case 'new':
                        _this._insertAttr(oParent, oAttr);
                        break;
                    case 'del':
                        _this._removeAttr(oParent, oAttr);
                }
            });
            return oHtml;
        }
    },

We are using require JS


texts:
What do you think of the following function to offer an alternative to fgets, looking for insights about portability, safety, readability and performance:
#include <stdio.h>
#include <errno.h>

int sc_gets(char *buf, int n)
{
    int count = 0;
    char c;

    if (__glibc_unlikely(n <= 0))
        return -1;

    while (--n && (c = fgetc(stdin)) != '\n')
        buf[count++] = c;
    buf[count] = '\0';

    return (count != 0 || errno != EAGAIN) ? count : -1;
}

#define BUFF_SIZE 10

int main (void) {
    char buff[BUFF_SIZE];

    sc_gets(buff, sizeof(buff)); // how to use
    printf ("%s\n", buff);

    return 0;
}

NB: I have already read fgets() alternative which was interesting but my code is different.

Second version thanks to the comments and vnp's insight:

#include <stdio.h>
#include <errno.h>

long sc_gets(char *buf, long n)
{
    long count = 0;
    char c;

    while (--n && (c = fgetc(stdin)) != '\n') {
        if (c == EOF)
            break;
        buf[count++] = c;
    }
    buf[count] = '\0';

    return (count != 0 || errno != EAGAIN) ? count : -1;
}

#define BUFF_SIZE 1024

int main (void) {
    char buff[BUFF_SIZE];
    sc_gets(buff, sizeof(buff));
    printf ("%s\n", buff);

    return 0;
}


texts: Create dummy variables in dataframe using for loop and apply lambda

texts:
I like to compute dummy variables based on the existing values in a dataframe and a dictionary with certain "cut off" points. I wonder whether I need to get rid of the for loop in the example below. And if so, how?
The second answer in this Stackoverflow post compellingly urges to avoid looping through dataframes. In my real dataset (about 20.000 rows and 50 columns/variables) the "apply lambda" for the rows indeed performs much better than a for loop (which after a few hours still wasn't finished). Yet, the for loop for the columns doesn't really give a problem with time and it is handy to automatically name the variables.
Here is an example dataset
import pandas as pd
# create df
dict={'file':['a', 'b', 'c'],'t_0':[1.5, 2.5, 3.5], 't_1':[0.5, 1.5, 0]}
df=pd.DataFrame(dict,index=['0', '1', '3'])
print(df)
# create dictionary with cut off points for dummy variable
d = dict={'t_0_cut_off':1, 't_1_cut_off':2}
print(d)

And here the for loop and apply lambda function which I use to compute the dummy variables.
for column in df.columns[-2:]:
    df[f'{column}_result']=df[f'{column}'].apply(lambda x: 1 if x> d[f'{column}_cut_off'] else 0)
df

The results look like this (and appear as I expect)
  file  t_0  t_1  t_0_result  t_1_result
0    a  1.5  0.5           1           0
1    b  2.5  1.5           1           0
3    c  3.5  0.0           1           0


texts: New Year Chaos (HackerRank problem) - find minimum swap count

texts:
The goal of the function is to find and print the minimum number of swaps (bribes) in what was initially a sorted array of ints - https://www.hackerrank.com/challenges/new-year-chaos/problem

I have passed this problem with the following code:
def minimumBribes(q):
    bribeCount = 0
    simulated = list(range(1, len(q) + 1))

    for i in range(0, len(q)):
        if q[i] > i+3:
            print("Too chaotic")
            return
    for i in range(0, len(simulated)):
        if simulated[i] == q[i]:
            continue
        while(simulated[i] != q[i]):
            # do 2 bribes
            if i + 3 == q[i]:
                simulated[i + 2], simulated[i + 1] = simulated[i + 1], simulated[i + 2]
                simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
                bribeCount += 2
            # do 1 bribe
            else:
                simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
                bribeCount += 1

    print(bribeCount)

My approach was to first scan through the array to determine whether it is valid, as 1 person can only bribe (swap) twice, hence the first for loop.
Then I go through each entry in my initial state array(simulated) and do swaps until the simulated entry at position i matches that in the final array at the same position.
I'm wondering if there is a better way to do this or whether something can be improved in my approach? I rarely do while loops like this as it seems it could go infinite, but I guess it's okay for this problem as we know only 2 swaps are possible for any entry.


texts: PHP Factory Method Pattern Implementation

texts:
This is an attempt at the Factory Method Pattern
It emulates the logical model

and also the physical model

Resources:

http://en.wikipedia.org/wiki/Factory_method_pattern

http://msdn.microsoft.com/en-us/library/ee817667.aspx

http://www.oodesign.com/factory-pattern.html

Is this a correct implementation of the Factory Method Pattern? I think I have followed all the required features of it. Any suggestions are welcome.

/** contract for all flyable vehicles **/
interface iFlyable {
    public function fly();
}

/* concrete implementations of iFlyable interface */
class JumboJet implements iFlyable {
    public function fly() {
        return "Flying 747!";
    }
}

class FighterJet implements iFlyable {
    public function fly() {
        return "Flying an F22!";
    }
}

class PrivateJet implements iFlyable {
    public function fly() {
        return "Flying a Lear Jet!";
    }
}

/** contract for conrete Factory **/
/**
* "Define an interface for creating an object, but let the classes that implement the interface
* decide which class to instantiate. The Factory method lets a class defer instantiation to
* subclasses."
**/
interface iFlyableFactory {
    public static function create( $flyableVehicle );
}

/** concrete factory **/
class JetFactory implements iFlyableFactory {
    /* list of available products that this specific factory makes */
    private  static $products = array( 'JumboJet', 'FighterJet', 'PrivateJet' );

    public  static function create( $flyableVehicle ) {
        if( in_array( $flyableVehicle, JetFactory::$products ) ) {
            return new $flyableVehicle;
        } else {
            throw new Exception( 'Jet not found' );
        }
    }
}

$militaryJet = JetFactory::create( 'FighterJet' );
$privateJet = JetFactory::create( 'PrivateJet' );
$commercialJet = JetFactory::create( 'JumboJet' );


texts:
How can I simplify this code?

  if (directory.Exists)
  {
    smallFileNames = directory.GetFiles("*.csv").Select(i => i.FullName).ToList();
    if(smallFileNames.Count == 0)
      smallFileNames = DivideIntoFiles(fileName);
  }
  else
    smallFileNames = DivideIntoFiles(fileName);

I confused by identical lines...


texts:
Whilst self-studying algorithms, I came across the Karp-Rabin rolling hash search algorithm here. I decided to have a go at implementing it in Python:

For ease of reading; the data-structure description and formulas embedded in append() and skip() are:

import random
from time import process_time

def is_prime(n):
    if n <= 1:
        return False
    elif n <= 3:
        return True
    elif (n % 2 == 0) or (n % 3 == 0):
        return False
    i = 5
    while (i*i) <= n:
        if (n % i == 0) or ((n % (i + 2)) == 0):
            return False
        i += 6
    return True

def find_prime_above(x):
    x = int(x)
    if x < 0:
        x = 0
    if x > 100:
        interval = int(x / 10)
    else:
        interval = x + 1
    count = 0
    found = False
    while not found:
        if (x % 2) == 0:
            start = x + 1
        else:
            start = x
        n = random.randrange(start, start + interval, 2)
        if is_prime(n):
            found = True
            return n
        count += 1
        if count > (interval / 2):
            interval *= 2
            count = 0

class hash_div(object):
    def __init__(self, size):
        if not is_prime(size):
            ValueError("Use a prime as the base")
        self.mod = size

    def h(self, num):
        return num % self.mod

class rolling_hash(hash_div):
    # built for strings
    def __init__(self, base, size):
        self.a = base
        self.uModP = 0
        self.size_x = 0
        self.ax = 1
        super(rolling_hash, self).__init__(size)

    def r(self):
        return self.uModP

    def update_ax(self, up_down):
        if up_down == "up":
            self.size_x += 1
        elif up_down == "down":
            self.size_x -= 1
        self.ax = self.h(self.a**(self.size_x - 1))

    def append(self, char):
        self.uModP = self.h((self.uModP*self.a) + ord(char))
        self.update_ax("up")

    def skip(self, char):
        self.uModP = self.h(self.uModP - (ord(char) * self.h(self.ax)))
        self.update_ax("down")

def search_file(fileStr, term):
    size = find_prime_above(len(fileStr))
    rs = rolling_hash(256, size)
    rt = rolling_hash(256, size)

    for c in term:
        rs.append(c)

    for c in fileStr[:len(term)]:
        rt.append(c)

    for i in range(len(term), len(fileStr)):
        rt.skip(fileStr[i - len(term)])
        rt.append(fileStr[i])
        if rs.r() == rt.r():
            # Found 1st instance, now print index of occurance
            print(i)
            # print rest of line
            ind = i - len(term) + 1
            ch = fileStr[ind]
            while ch != '\n':
                print(ch, end = "")
                ind += 1
                ch = fileStr[ind]
            print("\n")
            return i

test = input("Do you want to run in test mode?: ")

if test in ["yes", "y"]:
    fileName = "Shakey.txt"
    searchTerms = []
    with open(fileName, "r") as fp:
        words = fp.read().split()
        for i in range(100):
            searchTerms.append(random.choice(words))
else:
    fileName = input("Type File Name: ")
    searchTerms = [input("Type search term: ")]

total_t = 0

with open(fileName, "r") as fp:
    fileStr = fp.read()
    for term in searchTerms:
        t0 = process_time()
        search_file(fileStr, term)
        t = process_time() - t0
        total_t += t
        print(term, "took:", t, "s")
        print("----")

print("Average Time: ", total_t/len(searchTerms))

I'm using the works of Shakespeare as a test case, and it takes on average 0.5s to find a particular word (based on my test case embedded in code). My is_prime() function is verbatim from here, and I know that my find_prime_above() function is a bit of a dogs dinner.

But I have a few main questions:

Is there anything in my implementation that could be done to improve the constant factors (using the Karp-Rabin algorithm) and make it run faster?
How should I structure my tests (I am self taught, so I don't have anyone to tell me best practices)? Should they be in a separate file?


texts:
The question was:

  Write a function that calculates the root of a given number.

Answer A = I wrote it for integers. just run up to half of the number
Answer B+C = are for double, using Newton's law.

I just implemented this in C#.

They all work and were tested.Please comment me about anything from not well written code, complexity, style, or give a better solution.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class FindSquareRoot
    {
        public FindSquareRoot()
        {
            int numberToFind = 49;
            int res = SquareRoot(numberToFind);
            Console.WriteLine(res);

            double doubleNumberToFind = 157.0;
            double resDouble = SquareRoot(doubleNumberToFind);
            Console.WriteLine(resDouble);
            resDouble = SquareRootBetter(doubleNumberToFind);
            Console.WriteLine(resDouble);
        }

        public int SquareRoot(int number)
        {
            int half = number / 2;
            int counter = 0;
            while (counter < half)
            {
                if (Math.Pow(counter, 2.0) == number)
                {
                    return counter;
                }
                counter++;
            }
            return half;
        }

        public double SquareRoot(double number)
        {
            double precision = 10e-8;
            double low = 0.0;
            double high = 0.0;
            double prev = 0.0;
            double mid = number / 2.0;

            while(Math.Abs(mid - prev) > precision )
            {
                if(Math.Pow(mid,2) > number)
                {
                    high = mid;
                }else
                {
                    low = mid;
                }
                prev = mid;
                mid = (low+high)/ 2.0;
            }
            return mid;
        }
        public double SquareRootBetter(double number)
        {
            double precision = 10e-8;
            double prev = 0.0;
            double mid = number;
            while(Math.Abs(mid - prev ) > precision)
            {
                prev = mid;
                mid = (mid +(number/ mid))/2.0;
            }
            return mid;
        }
    }
}


texts:
Problem statement: Perform a depth first traversal on a BST and print the elements traversed.

class Node(object):
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class BST(object):
    def __init__(self, value):
        self.root = Node(value)

    def insert(self, value):
        current = self.root
        while current:
            if value > current.value:
                if current.right is None:
                    current.right  = Node(value)
                    break
                else:
                    current = current.right
            else:
                if current.left is None :
                    current.left  = Node(value)
                    break
                else:
                    current = current.left

    def preorder(self,root):
## root,left,right

        if root:
            print root.value
            if root.left:
                self.preorder(root.left)
            if root.right:
                self.preorder(root.right)

    def postorder(self,root):
## left, right, root

        if root:
            if root.left:
                self.postorder(root.left)
            if root.right:
                self.postorder(root.right)
            print root.value

    def inorder(self,root):
## left, root, right

        if root.left:
            self.inorder(root.left)
        print root.value
        if root.right:
            self.inorder(root.right)

t = BST(100)
t.insert(12)
t.insert(92)
t.insert(112)
t.insert(123)
t.insert(2)
t.insert(11)
t.insert(52)
t.insert(3)
t.insert(66)
t.insert(10)
print "preorder traversal is this "
t.preorder(t.root)
print "postorder traversal is this "
t.postorder(t.root)
print "inorder traversal is this "
t.inorder(t.root)

How can this code be more efficient?


texts:
Since you can't use regular expressions in Maxcript is there a better way to capitailse a string that may contain whitespace.

The script below works fine; but I can't help feeling that I'm missing a trick here. Any tips?

function capitaliseName str =
(
    theName = ""
    str = toLower str -- lowercase everything

    for word in (filterString str "_, ") do
    (
        n = substring word 1 word.count
        n = capitaliseIt (n)
        thename += n + " "
    )
    theName = trimright theName " "
    return theName
)

function capitaliseIt str =
(
    cap = substring str 1 1 -- get the first letter of the sting
    cap = toUpper cap -- capitilse it
    str = cap + substring str 2 str.count -- add it back to the rest of the string
    return str
)

capitaliseName "SPOOn Man" -- Spoon Man
capitaliseName "ms miley cyrus" -- Ms Miley Cyrus
capitaliseName "professor Xavier" -- Professor Xavier
capitaliseName "Billy_ray_valentine" -- Billy Ray Valentine


texts:
I'm posting my C++ code for LeetCode's Snapshot Array. If you have time and would like to review, please do so. Thank you!
Problem

Implement a SnapshotArray that supports the following interface:

SnapshotArray(int length) initializes an array-like data structure with the given length.  Initially, each element equals 0.
void set(index, val) sets the element at the given index to be equal to val.
int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id

Example 1:
Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation:

SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5);  // Set array[0] = 5
snapshotArr.snap();  // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5

Constraints:

1 <= length <= 50000
At most 50000 calls will be made to set, snap, and get.
0 <= index < length
0 <= snap_id < (the total number of times we call snap())
0 <= val <= 10^9

LeetCode Template
class SnapshotArray {
public:
    SnapshotArray(int length) {

    }

    void set(int index, int val) {

    }

    int snap() {

    }

    int get(int index, int snap_id) {

    }
};

/**
 * Your SnapshotArray object will be instantiated and called as such:
 * SnapshotArray* obj = new SnapshotArray(length);
 * obj->set(index,val);
 * int param_2 = obj->snap();
 * int param_3 = obj->get(index,snap_id);
 */

Accepted C++
class SnapshotArray {
public:
    SnapshotArray(const int array_length) {}
    int curr_shot_id = 0;
    std::unordered_map<int, std::vector<pair<int, int>>> id_map;

    // Returns current snapshot O(1)
    const int snap() {
        return curr_shot_id++;
    }

    // Setter with unordered_map
    const void set(const int key, const int shot_id) {
        if (id_map[key].empty() || id_map[key].back().first != curr_shot_id) {
            id_map[key].push_back({curr_shot_id, shot_id});

        } else {
            id_map[key].back().second = shot_id;
        }
    }

    // Getter with binary searching -> O(1) memory O(log N) time
    const int get(const int key, const int shot_id) {
        const auto iter = std::upper_bound(id_map[key].begin(), id_map[key].end(), std::pair<int, int>(shot_id, INT_MAX));
        return iter == std::begin(id_map[key]) ? 0 : std::prev(iter)->second;
    }
};

Reference
LeetCode is a platform only for interviewing and competitive programming. On LeetCode, there is a class usually named Solution (for this post is SnapshotArray) with one or more public functions which we are not allowed to rename.

Question
Discussion


texts: Manipulating arrays to extract unique objects and count occurrences

texts:
The data describes cycling activities (key1) and chunks of them (key2). In total there are around 1,000 key1 objects and arrays under key1 are 1-100 long.

Is there a simpler, more semantic, faster, or otherwise better way than to use two nested map in step 1?
I realise that step 3 is longer than it should be and there has to be a better way to do it. How can step 3 be improved?

// Original array
const arr = [
    {key1: [{key2: {id: 1, name: 'a'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}]},
    {key1: [{key2: {id: 2, name: 'b'}}, {key2: {id: 3, name: 'c'}}]}
];
console.log(arr);

// Step 1: Extract meaningful information from original array
const arrOfArrOfObj = arr
    .map(category => category.key1
        .map(subCategory => (
                {
                    id: subCategory.key2.id,
                    name: subCategory.key2.name
                }
            )
        )
    );
console.log(arrOfArrOfObj);

// Step 2: Make the array one dimensional
const arrOfObj = [].concat(...arrOfArrOfObj);
console.log(arrOfObj);

// Step 3: Remove duplicates and count object occurrences.
let dedupedArrWithCount = [];
l = arrOfObj.length;
for (let i = 0; i < l; i++) {
    let objExists = false;
    for (let j = 0; j < dedupedArrWithCount.length; j++) {
        // Two objects are identical if their ids are identical.
        if (arrOfObj[i].id === dedupedArrWithCount[j].id) {
            objExists = true;
            dedupedArrWithCount[j].count += 1;
        }
    }
    if (!objExists) {
        dedupedArrWithCount.push({
            id: arrOfObj[i].id,
            name: arrOfObj[i].name,
            count: 1
        })
    }
}

console.log(dedupedArrWithCount);


texts: C# easier ways to filter values in data-grid by month

texts:
Goal:
My goal is to filter datagrid by selected month from dropdown options.
January, February, March etc...
I'd like to know if there are easier methods to my current method..
Code:
public Schedule()
{
    InitializeComponent();
    RefreshGrid();

    Dictionary<string, string> allOptions = new Dictionary<string, string>();
    allOptions.Add("1", "All");
    allOptions.Add("2", "January");
    allOptions.Add("3", "February");
    allOptions.Add("4", "March");
    allOptions.Add("5", "April");
    allOptions.Add("6", "May");
    allOptions.Add("7", "June");
    allOptions.Add("8", "July");
    allOptions.Add("9", "August");
    allOptions.Add("10", "September");
    allOptions.Add("11", "October");
    allOptions.Add("12", "November");
    allOptions.Add("13", "December");

    Months.DataSource = new BindingSource(allOptions, null);
    Months.DisplayMember = "Value";
    Months.ValueMember = "Key";

}

public void RefreshGrid()
{
    string value = "";

    // Select All
    if(Months.SelectedIndex == 0)
    {
        value = "";
    }
    // Select * from January
    if(Months.SelectedIndex == 1)
    {
        value = " where month(date_purchased) = 1;";
    }
    // Select * from February
    if (Months.SelectedIndex == 2)
    {
        value = " where month(date_purchased) = 2;";
    }
    //... and son on...

    // MySQL connection string
    using (var conn = new MySqlConnection(ConnectionString.ConnString))
    {
        //Select query
        using (var mySqlDataAdapter = new MySqlDataAdapter("select * from table "+ value +";", conn))
        {
            using (var dataSet = new DataSet())
            {
                DataSet DS = new DataSet();
                mySqlDataAdapter.Fill(DS);

                //Assign headers to Data Grid View
                scheduleData.DataSource = DS.Tables[0];
                scheduleData.Columns[0].HeaderText = "ID";
                scheduleData.Columns[1].HeaderText = "Equipment Name";
                scheduleData.Columns[2].HeaderText = "Date Purchased";

                //Set visibility to false for the columns to work in the background
                scheduleData.Columns[0].Visible = false;
            }
        }
    }
}

private void Months_SelectedIndexChanged(object sender, EventArgs e)
{
    RefreshGrid();
}

This idea does work - but Seems like there is too much unnecessarily code. But I cannot think of an alternative.


texts: Optimizing the function in R by replacing for loop

texts:
I am trying to create a function that I want to use in my real data. Is there any way to optimize the following function? This is a function I created to filter the data.

filter <- function(x, m, delt) {
  series <- x
  series_filtered <- rep(0,length(series))
  delta_t <- delt # time step between data points (hours)
  tau_crit <- 3 # critical period (hours)
  theta_crit <-  2*pi*delta_t/tau_crit # critical frequency
  M <- m # number of time steps before and after available in filtering window
  h <- rep(0,(2*M+1)) # initialize the weights
  # get the lanczos coefficients
  for (n in (-1*M):M) {
    h[M+n+1] <- ifelse(n == 0,theta_crit*delta_t/pi,
                       (sin(n*theta_crit*delta_t)/(pi*n)) * (sin(n*pi/M)/(n*pi/M)))
  }
  # need to adjust the weights so that they add up to 1
  h_unbiased <-  h/sum(h)
  h <- h_unbiased
  # step through each time for which we'd like to create a filtered value
  for (t in (1+M):(length(series)-M)) {
    for (n in (-1*M):M) {
      # apply the cofficients to create the filtered series
      series_filtered[t] = series_filtered[t] + series[t+n] * h[M+n+1]
    }
  }
  # Filtered data
  y2 <- series_filtered[(M+1):(length(series)-M)]
  return(y2)
}

Any suggestions on removing for loop and replacing by apply or any other function is appreciated.

In the above function, I have one single for loop and one double for loop.

Edit:

A testing can be done by the following data:

x <- 1:100
series <-  sin(2*x)+sin(x/4) + sin(x/8) + rnorm(100)
jd2 <- filter(x=series,m=4, delt=(40/60))


texts:
Given an array of size n that has the following specifications:

  Each element in the array contains either a policeman or a thief.

  Each policeman can catch only one thief.

  A policeman cannot catch a thief who is more than K units away from the policeman.

  We need to find the maximum number of thieves that can be caught.

Here's code for policemen catch thieves written in Python3, I would like feedback/suggestions.

import random

def tp_build(n):
    thief_police = []
    for i in range(n):
        thief_police.append(random.choice(['T', 'P']))
    return thief_police

def catch(k=2, n=10):
    tp_list = tp_build(n)
    print('List: %s' % tp_list)
    if 'P' not in tp_list:
        return 'No Police!'
    if 'T' not in tp_list:
        return 'No Thieves!'
    p_indexes = []
    t_indexes = []
    for i in range(n):
        if tp_list[i] == 'P':
            p_indexes.append(i)
        elif tp_list[i] == 'T':
            t_indexes.append(i)
    combinations = []
    for limit in range(1, k + 1):
        for police in p_indexes:
            if police + limit in t_indexes:
                combinations.append((police, police + limit))
        for police in p_indexes:
            if police - limit in t_indexes:
                combinations.append((police, police - limit))
    p_list = []
    t_list = []
    for i, j in combinations:
        p_list.append(i)
        t_list.append(j)
    new_p = []
    new_t = []
    for i in p_list:
        if i not in new_p:
            new_p.append(i)
    for j in t_list:
        if j not in new_t:
            new_t.append(j)
    final_combinations = list(zip(new_p, new_t))
    print('Number of thieves caught: %s'%(len(final_combinations)))
    return len(final_combinations)

if __name__ == '__main__':
    for i in range(100):
        catch()


texts:
This code will accept user input from the command line.

The first user can enter the limit of series.

e.g: user may enter 5

After that, the user will be prompted for 5 numbers of a series.

e.g:

2
4
8
10
12

Here in this series, 6 is missing, so I am going to find the missing series from common difference series.

I got the correct output from this code. Is it the correct way?  Is there any other simple code to do the same?

<?php
    fscanf(STDIN, "%d\n", $count);
    $series = array();
    $common_diff = array();
    $prev_element = null;
    for($i=0;$i<$count;$i++){
        fscanf(STDIN, "%d\n", $series[$i]);
        if($prev_element != null){
            $common_diff[] = $series[$i] - $prev_element;
        }
        $prev_element = $series[$i];
    }
    $c = array_count_values($common_diff);
    asort($c);
    end($c);
    $common_d = key($c);
    $prev_element = $series[0];
    $missed_no = 0;
    for($i=1;$i<$count;$i++){
        $diff = $series[$i] - $prev_element;
        if($diff != $common_d){
            $missed_no = $prev_element + $common_d;
        }
        $prev_element = $series[$i];
    }
    echo $missed_no;
    exit;
?>

example input

5
2
4
8
10
12


texts:
This is my implementation of the famous Number Guessing Game. It is not object oriented, but the goal was to create a simple to read, procedural program. Have I accomplished this goal?

import java.util.Random;
import java.util.Scanner;

class Main {
  private static int lowerRange = 1;
  private static int upperRange = 99;
  private static int tries = 6;

  private static Scanner input = new Scanner(System.in);
  private static Random random = new Random();

  public static void main(String[] args) {
    showDescription();
    boolean run = true;
    while (run) {
      play();
      System.out.print("Play again? (Y / N): ");
      run = input.nextLine().equalsIgnoreCase("Y") ? true : false;
    }
  }

  private static void showDescription() {
    System.out.println("You have to guess a number between " + lowerRange + " and " + upperRange + ".");
    System.out.println("You have " + tries + " tries.");
  }

  private static void play() {
    int randomNumber = generateRandomNumber(lowerRange, upperRange);
    int triesSoFar = 0;
    boolean won = false;
    while (triesSoFar < tries && won == false) {
      System.out.print("Your try: ");
      int guess = Integer.parseInt(input.nextLine());
      if (guess > randomNumber) {
        System.out.println("The secret number is smaller.");
      } else if (guess < randomNumber) {
        System.out.println("The secret number is higher.");
      } else {
        won = true;
        break;
      }
      triesSoFar++;
    }

    if (won) {
      System.out.println("You found the secret number!");
    } else {
      System.out.println("You lose. The secret number was " + randomNumber + ".");
    }
  }

  private static int generateRandomNumber(int lowerRange, int upperRange) {
    return random.nextInt(upperRange - lowerRange) + lowerRange;
  }
}


texts:
The following code will generate a number plate and then generate a random speed and see if it's speeding

import random, string, time

class Car:
    def __init__(self):
        self.plate = self.genPlate()
        self.limit = 60
        self.checkSpeeding()

    def checkSpeeding(self):
        self.speeding = random.randint(0, 1)

        if self.speeding:
            self.speed = random.randint(self.limit+3, self.limit+20)
        else:
            self.speed = random.randint(self.limit-20, self.limit+2)

    def genPlate(self):
        plateFormat = ['L', 'L', 'N', 'N', 'L', 'L', 'L']
        genPlate = []

        for i in plateFormat:
            if i == 'L':
                genPlate.append(random.choice(string.ascii_letters[26:]))

            elif i == 'N':
                genPlate.append(str(random.randint(0, 9)))

        genPlate.insert(4, " ")

        return  "".join(genPlate)

allCars = []
x = 0

while True:
    allCars.append(Car())

    print(allCars[x].plate + " was going " + str(allCars[x].speed) + "mph in a " + str(allCars[x].limit) + "mph zone")
    if allCars[x].speeding:
        print("speeding fine issued")

    print("\n")

    time.sleep(5)
    x += 1

Here is a link to the original source


texts:
I'm somewhat new to SQL (using it in the past but only being exposed to it heavily in my current role). Unfortunately nobody at my current company has really given me any advice on formatting. How can I format this better / what should I avoid doing that I may have done below? Any feedback on re-factoring would be greatly appreciated also.

/* Uncomment when testing this SQL */
declare @period_id as int = 252 -- ### Potentially redundant ###
declare @building_id as varchar(10) = '20500'
declare @section_name as varchar(20) = 'ALL'
declare @lease_expiry_period as int = 1;

/* SQL for Section_Name parameter on report */
select   'ALL',
         1 as order_by
union all
select distinct upper(isnull(section_name, '')) as section_name,
                2 as order_by
from     property.lease_period
where    section_name <> ''
order by 2;

declare @truncateddate as date = dateadd(d,0,datediff(d,0,getdate()));

/* SQL for Report (dsDetail) */
select
    lp.period_id ,
    lp.building_id ,
    lp.suite_id ,
    lp.lease_id ,
    lp.tenant_trading_name,
    lp.suite_status ,
    lp.suite_name ,
    lp.suite_area,
    lp.lease_status ,
    lp.lease_current_start_date ,
    lp.lease_current_stop_date ,
    lp.lease_current_term ,
    lp.lease_occupancy_date ,
    lp.lease_vacated_date
from
    property.lease_period lp
where
    lp.lease_current_stop_date < @truncateddate
    and (upper(lp.lease_status) = 'ACTIVE' or upper(lp.lease_status) = 'OVERHOLDING')
    --and lp.period_id = @period_id -- ##Potentially redundant (query now running into the future)
    and lp.building_id = @building_id
    and not exists
    (
        select  1
        from    lease_deal.lease l
        where   lp.building_id = l.building_id
                and lp.lease_id = l.lease_id
    )
    and (@section_name = 'ALL'
        or (@section_name <> 'ALL' and upper(section_name) = upper(@section_name)))
    and lp.lease_current_stop_date between @truncateddate
        and dateadd(MONTH, @lease_expiry_period, @truncateddate)
order by period_id desc


texts: Preorder, Postorder, inorder Traversal in an Binary Search Tree

texts:
This is code for Inorder, Preorder, Postorder Traversal of a Tree. Suggest some ways to improve it (since I have made root public and want to make it Private).

#include<iostream.h>
#include<conio.h>

struct Node
{
  int data;
  Node *left;
  Node *right;
};

class Tree
{
  private:
    Node *p;
  public:
    Node *root;
    Tree()
    {
      root=NULL;
    }
    void Insertion();
    void Traversal();
  protected:
    void SearchPos(Node *);
    void Inorder_Traversal(Node *);
    void Preorder_Traversal(Node *);
    void Postorder_Traversal(Node *);
};

void Tree::Insertion()
{
  p=new Node;
  p->left=p->right=NULL;
  if(root==NULL)
  {
    cout<<"Enter Root Value to be inserted:";
    cin>>p->data;
    root=p;
  }
  else
  {
    cout<<"\nEnter Value to be inserted:";
    cin>>p->data;
    SearchPos(root);
  }
}

void Tree::SearchPos(Node *tmp)
{
  if(p->data<tmp->data && tmp->left==NULL)
  {
    tmp->left=p;
    return;
  }
  else if(p->data>tmp->data && tmp->right==NULL)
  {
    tmp->right=p;
    return;
  }
  else if(p->data<tmp->data && tmp->left!=NULL)
  {
    SearchPos(tmp->left);
  }
  else if(p->data>tmp->data && tmp->right!=NULL)
  {
    SearchPos(tmp->right);
  }
}

void Tree::Traversal()
{
  cout<<"\nInorder Traversal:";
  Inorder_Traversal(root);
  cout<<"\nPreorder Traversal:";
  Preorder_Traversal(root);
  cout<<"\nPostorder Traversal:";
  Postorder_Traversal(root);
}

void Tree::Inorder_Traversal(Node *tmp)
{
  if(tmp->left==NULL && tmp->right==NULL)
  {
    cout<<tmp->data<<" ";
    return;
  }
  else if(tmp->left!=NULL)
  {
    Inorder_Traversal(tmp->left);
  }
  cout<<tmp->data<<" ";
  if(tmp->right!=NULL)
  {
    Inorder_Traversal(tmp->right);
  }
}

void Tree::Preorder_Traversal(Node *tmp)
{
  if(tmp->left==NULL && tmp->right==NULL)
  {
    cout<<tmp->data<<" ";
    return;
  }
  else if(tmp->left!=NULL)
  {
    cout<<tmp->data<<" ";
    Preorder_Traversal(tmp->left);
  }
  if(tmp->right!=NULL)
  {
    Preorder_Traversal(tmp->right);
  }
}

void Tree::Postorder_Traversal(Node *tmp)
{
  if(tmp->left==NULL && tmp->right==NULL)
  {
    cout<<tmp->data<<" ";
    return;
  }
  else if(tmp->left!=NULL)
  {
    Postorder_Traversal(tmp->left);
  }
  if(tmp->right!=NULL)
  {
    Postorder_Traversal(tmp->right);
    cout<<tmp->data<<" ";
  }
}

void main()
{
  clrscr();
  char choice;
  Tree t;
  do
  {
    t.Insertion();
    cout<<"\nMore to Insert???Enter(y/n):";
    cin>>choice;
  }while(choice=='y'||choice=='Y');
  t.Traversal();
  getch();
}


texts:
I'm trying to parse Double from String in Java. The string input is not necessarily a number, any non number input should be treated as 0.

Given below is a solution using try-catch, where a Array of string is converted into a Array of Double:

public static void main(String[] args) {
    // Array of strings to be parsed as double.
    // In case of NaN I have to assign it a value 0.
    ArrayList<String> dirtyList = new ArrayList();
    dirtyList.add("Null");
    dirtyList.add("1.24");
    dirtyList.add("0");
    dirtyList.add("0asd");
    ArrayList<Double> doubleList = new ArrayList();
    for ( String item : dirtyList) {
        doubleList.add(parseDouble(item));
    }
    System.out.println(doublelist);
}

// Function to clean data
static Double parseDouble(String x) {
    Double a;
    try {
        a = Double.parseDouble(x);
    } catch (Exception ParseException) {
        a = (double) 0;
    }
    return a;
}

Output:

[0.0, 1.24, 0.0, 0.0]

Is it okay to exploit try-catch in situations like this? Is there a better approach?


texts: transform columns to binary encoded columns in R

texts:
I have some nominal variables encoded as integers (not ordinal), which I would like to encode as binary (not dummies nor one hot!). The following code is what I came up with (adapted from other code I found). Is this a valid/scalable approach? Thanks!
library(binaryLogic)

df <- data.frame(x1 = c(1, 1, 2, 3), x2 = c(1, 2, 3, 4))

encode_binary <- function(x, name = "binary_") {
    x2 <- as.binary(x)
    maxlen <- max(sapply(x2, length))
    x2 <- lapply(x2, function(y) {
        l <- length(y)
        if (l < maxlen) {
            y <- c(rep(0, (maxlen - l)), y)
        }
        y
    })
    d <- as.data.frame(t(as.data.frame(x2)))
    rownames(d) <- NULL
    colnames(d) <- paste0(name, 1:maxlen)
    d
}

df <- cbind(df, encode_binary(df[["x1"]], name = "binary_x1_"))
df <- cbind(df, encode_binary(df[["x2"]], name = "binary_x2_"))

df


texts:
I was tasked with re-writing a login VBScript we use on about 50 machines. The original script was hacked together by someone who clearly had no idea what they were doing (multiple lines that literally did nothing, including creating persistent shares, deleting them, then recreating them 4+ times in a ForEach loop)

I don't have any scripting experience in vbs, so I'm assuming there's a good amount of stuff here that should be cleaned up. The ultimate goal is to create up to three mapped drives (P:, Q:, R:) that point at registers in the location. Every site should have an identical set up other than the first two Consts, for ease of re-use.

Option Explicit

Const STORE_NUMBER = "29"
Const NUM_REGS = 3

Const EVENT_SUCCESS = 0
Const EVENT_FAIL = 1

Class Mapping
    Public strLocalDrive
    Public strUNCPath
    Public strPersistent
    Public strUsr
    Public strPas
End Class

Dim alMappings : Set alMappings = CreateObject("System.Collections.ArrayList")

Dim objNetwork : Set objNetwork = WScript.CreateObject("WScript.Network")
Dim oShell     : Set oShell = CreateObject("WScript.Shell")

' ## Mapping Objects ##

' POS 1
If NUM_REGS >= 1 Then
    Dim udtPOSOne : Set udtPOSOne = New Mapping
    With udtPOSOne
         .strLocalDrive = "P:"
         .strUNCPath = "\\10.0." & STORE_NUMBER & ".101\dpalm"
         .strPersistent = "False"
         .strUsr = "somename"
         .strPas = "somepass"
    End With
    alMappings.add(udtPOSOne)
End If

' POS 2
If NUM_REGS >= 2 Then
    Dim udtPOSTwo : Set udtPOSTwo = New Mapping
    With udtPOSTwo
         .strLocalDrive = "Q:"
         .strUNCPath = "\\10.0." & STORE_NUMBER & ".102\dpalm"
         .strPersistent = "False"
         .strUsr = "somename"
         .strPas = "somepass"
    End With
    alMappings.add(udtPOSTwo)
End If

' POS 3
If NUM_REGS >= 3 Then
    Dim udtPOSThree : Set udtPOSThree = New Mapping
    With udtPOSThree
         .strLocalDrive = "R:"
         .strUNCPath = "\\10.0." & STORE_NUMBER & ".103\dpalm"
         .strPersistent = "False"
         .strUsr = "somename"
         .strPas = "somepass"
    End With
    alMappings.add(udtPOSThree)
End If

oShell.LogEvent EVENT_SUCCESS, "Mappings built"

Dim udtMapping
For Each udtMapping in alMappings
    ' Unmap the drive if it's currently mapped
    On Error resume Next
    objNetwork.RemoveNetworkDrive udtMapping.strLocalDrive, True
    On Error goto 0

    ' Map the drive
    objNetwork.MapNetworkDrive udtMapping.strLocalDrive, udtMapping.strUNCPath, _
                               udtMapping.strPersistent, udtMapping.strUsr, _
                               udtMapping.strPas

    ' Windows event logging
    if err.number <> 0 then
        oShell.LogEvent EVENT_FAIL, "Login script failed" & vbcrlf &_
                "Error #: " & err.number & vbcrlf & "Error: " & err.description &_
                "Failed to map " & udtMapping.strUNCPath & " to " & udtMapping.strLocalDrive
    else
        oShell.LogEvent EVENT_SUCCESS, "Login script successfully mapped " &_
                udtMapping.strUNCPath & " to " & udtMapping.strLocalDrive
    end if

Next


texts: Applying different equations to a Pandas DataFrame

texts:
I wrote a task using pandas and I'm wondering if the code can be optimized. The code pretty much goes as:

All the dataframes are 919 * 919. socio is a dataframe with many fields. matrices is a dictionary that holds different dataframes objects.

I apply a series of formulas and store the results in the result dataframe.

import numpy as np

frame = [zone for zone in range(taz_start_id, taz_end_id +1)]
#frame = list from 1 to 919

result = DataFrame(0.0, index=frame, columns=frame)

#Get a seires type and apply the results to all the rows of the dataframe by index
temp = np.log(socio["ser_emp"] + 1) * 0.36310718
result = result.apply(lambda x:  x + temp[x.index], axis = 0)

#Divide two columns apply a coefficient and fill all the nan to 0. apply results to result dataframe
temp = (socio["hhpop"] / socio["acres"]) * -0.07379568
temp = temp.fillna(0)
result = result.apply(lambda x:  x + temp[x.index], axis = 0)

result = (matrices['avgtt'].transpose() * -0.05689183) + result

# set a 1.5 value if dist is between values or 0 if not
result =((matrices["dist"] > 1) & (matrices["dist"] <= 2.5))  * 1.5 + result

# see if each cell is 0 if not set value to exp(value)
result = result.applymap(lambda x: 0 if x == 0 else exp(x))


texts: How can I refactor the validation code to minimize it?

texts:
I am using Django Rest Framework and below is the code of one of the API Endpoints. The code creates generates the PUBLIC and SECRET Values based on Stellar SDK.
def create(self, request):
        try:
            if 'app_id' not in request.data:
                response = {'status': 'FAIL', 'data': 'App ID field not found'}
                return Response(response, status=status.HTTP_400_BAD_REQUEST)

            if 'customer_id' not in request.data:
                response = {'status': 'FAIL', 'data': 'Customer ID field not found'}
                return Response(response, status=status.HTTP_400_BAD_REQUEST)

            customer_id = request.data['customer_id']
            app_id = request.data['app_id']
            app = App.objects.get(id=app_id)

            # Creating Stellar Account
            addr, secret = create_account()

            if addr is None and secret is None:
                response = {'status': 'FAIL', 'data': 'Could not generate customer Wallet'}
                return Response(response, status=status.HTTP_200_OK)

            # Make sure we do not add duplicate customers
            wallet_count = Wallet.objects.filter(customer_id=customer_id).count()
            if wallet_count > 0:
                response = {'status': 'FAIL', 'data': 'The customer ID already exist'}
                return Response(response, status=status.HTTP_200_OK)

            # The customer does not exist, hence create his wallet.
            wallet = Wallet(customer_id=customer_id, app=app, address=addr, secret=secret)
            wallet.save()

            if wallet.pk is None and wallet.pk > 0:
                response = {'status': 'OK', 'data': 'success'}
            else:
                response = {'status': 'FAIL', 'data': 'Messed up'}
        except App.DoesNotExist:
            response = {'status': 'FAIL', 'data': 'The App ID not found'}
            return Response(response, status=status.HTTP_404_NOT_FOUND)

        return Response({'status': 'OK', 'data': 'success'}, status=status.HTTP_200_OK)

As you can see there is repetition of codeblock like below:
response = {'status': 'FAIL', 'data': 'The customer ID already exist'}
                return Response(response, status=status.HTTP_200_OK)

It'd be nice if I can reduce all this code either by passing to a function or someway once and let it handle based on request dict.


texts:
I wrote this code as my first self-directed effort and would appreciate any input on things that I've done seriously wrong. I worry that perhaps I'm over-relying on if-statements, for example, but am not sure how to change the pieces of code to use them less.

import random

def playchosengame(chosengame):
    if chosengame == 1:
        doorchoice = int(raw_input("How many doors would you like to play with? > "))
        onegameatatime(doorchoice)
    elif chosengame == 2:
        numberofgames = int(raw_input("How many games would you like to play? > "))
        strategy = int(raw_input("Would you like to always change your answer (1) or keep it the same (2)? > "))
        doorchoice = int(raw_input("How many doors would you like to play with? > "))
        onestrategy(numberofgames,strategy,doorchoice)
    else:
        print "What did you say?"

def onestrategy(chosennumberofgames,chosenstrategy,doorchoice):
    # for playing x number of Monty Hall games with one type of strategy
    wincount = 0
    i = 1

    for i in range(1,chosennumberofgames + 1):
        possibleanswers = range(1,doorchoice + 1)
        correctanswer = random.randint(1,doorchoice)
        incorrectpossibilities = possibleanswers
        incorrectpossibilities.remove(correctanswer)

        youranswer = random.randint(1,doorchoice)

        if youranswer == correctanswer:
            otherremaining = random.choice(incorrectpossibilities)
        else:
            otherremaining = youranswer

        incorrectpossibilities.remove(otherremaining)

        print "The correct answer is NOT one of these: %r" % incorrectpossibilities

        if youranswer == correctanswer:
            print "Which means it is either your answer: %r, or the only other remaining option, %r." % (correctanswer, otherremaining)
            if chosenstrategy == 1:
                finalanswer = otherremaining
            else:
                finalanswer = correctanswer
        else:
            print "Which means it is either your answer: %r, or the only other remaining option, %r." % (youranswer, correctanswer)
            if chosenstrategy == 1:
                finalanswer = correctanswer
            else:
                finalanswer = youranswer

        print "You chose %r" % finalanswer

        if finalanswer == correctanswer:
            wincount += 1
            print "You win!"
        else:
            print "You lose!"

        i += 1

    print "You won %r out of %r games. Congrats!" % (wincount, i - 1)

def onegameatatime(doorchoice):
    # for playing one Monty Hall game at a time.
    playagain = 1

    while playagain == 1:
        possibleanswers = range(1,doorchoice + 1)
        correctanswer = random.randint(1,doorchoice)
        incorrectpossibilities = possibleanswers
        incorrectpossibilities.remove(correctanswer)

        youranswer = int(raw_input("Pick a door number from 1 - %r > " % doorchoice))

        if youranswer == correctanswer:
            otherremaining = random.choice(incorrectpossibilities)
        else:
            otherremaining = youranswer

        incorrectpossibilities.remove(otherremaining)

        print "The correct answer is NOT one of these: %r" % incorrectpossibilities

        if youranswer == correctanswer:
            print "Which means it is either your answer: %r, or the only other remaining option, %r." % (correctanswer, otherremaining)
        else:
            print "Which means it is either your answer: %r, or the only other remaining option, %r." % (youranswer, correctanswer)

        finalanswer = int(raw_input("Which do you choose? > "))

        if finalanswer == correctanswer:
            print "You win!"
        else:
            print "You lose!"

        playagain = int(raw_input("Play again? (1 = yes, 0 = no) > "))

    print "Thanks for playing!"

gamechoice = int(raw_input("Play one game at a time (1) or play your chosen number of games with one strategy (2)? > "))
playchosengame(gamechoice)


texts:
Here is my coded solution to the LeetCode zig-zag problem -

  The string "PAYPALISHIRING" is written in a zigzag pattern on a given
  number of rows like this (you may want to display this pattern in a
  fixed font for better legibility) -

P   A   H   N
A P L S I I G
Y   I   R

  And then read line by line: "PAHNAPLSIIGYIR"

  Write the code that will take a string and make this conversion given
  a number of rows.

I know the final line is a bit messy, and I could unpack it into a two-line for loop, but I really like single-line for loops.

def zigzag() -> list:
    """Returns the zig-zag word of a given input as a list."""
    array = []
    for _ in range(num_rows):
        array.append([])
    increasing = 1
    array_index = 0
    word_index = 0
    while word_index < len(word):
        if increasing:
            array[array_index].append(word[word_index])
            array_index += 1
            word_index += 1
        else:
            array[array_index].append(word[word_index])
            array_index -= 1
            word_index += 1
        if array_index == -1 and increasing == 0:
            increasing = 1
            array_index = 1
        if array_index == num_rows and increasing == 1:
            increasing = 0
            array_index = num_rows - 2
    return array

if __name__ == "__main__":
    word = "PAYPALISHIRING"
    num_rows = 3
    print("".join(line for array in zigzag() for line in array))


texts:
This is my attempt at making a 'rock, paper, scissors' game in python. The game takes the user's input and the computer's random selection and calculates who has won. All feedback appreciated.

from random import randint

def getUser():
    print('Rock, Paper, Scissors: ')
    userIn = input().lower()
    if userIn == 'r':
        userIn = 0
    elif userIn == 'p':
        userIn = 1
    elif userIn == 's':
        userIn = 2
    else:
        getUser()
    return(userIn)

def getComp():
    compIn = randint(0,2)
    return(compIn)

def calc(user, comp):
    if user == comp:
        print("Draw!")
    elif user == 0:
        if comp == 1:
            print("You lose - ",  comp, "smothers", user)
        else:
            print("You win -", user, "smashes", comp)
    elif user == 1:
        if comp == 2:
            print("You lose - ", comp, "slices", user)
        else:
            print("You win -", user, "smothers", comp)
    elif user == 2:
        if comp == 0:
            print("You lose - ", comp, "smashes", user)
        else:
            print("You win -", user, "slices", comp)

again = 'yes'
while again != 'no':
    calc(getUser(), getComp())
    again = input('Would you like to play again? ')
print('Thank you for playing.')


texts: Preprocessing Markdown Documents for Keywords

texts:
I recently added a feature to my application to serve arbitrary markdown documents from a directory. This is designed to allow authors to populate a folder full of help documents, and be able to view them without any code changes. However, because this is an MVC application, I needed a few extra features. Straight to it, here's my controller:

public class DocumentationController : Controller
{
    private const string DefaultDocPage = "Overview";
    public ActionResult Index(string id = null)
    {
        ViewBag.HomeLinkPage = string.IsNullOrEmpty(id) || id == DefaultDocPage ? string.Empty : DefaultDocPage;
        if (string.IsNullOrEmpty(ViewBag.HomeLinkPage))
        {
            id = DefaultDocPage;
        }
        var filePath = Server.MapPath(Url.Content("~/Content/Documentation/" + id.Trim("/".ToCharArray()) + ".md"));
        if(!System.IO.File.Exists(filePath))
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return null;
        }
        var contents = new StringBuilder(System.IO.File.ReadAllText(filePath));

        contents.Replace("{{AppRoot}}/", Url.Content("~"));
        contents.Replace("{{Documentation}}", Url.Content("~/Documentation"));
        contents.Replace("{{DocumentationImages}}", Url.Content("~/Content/Documentation/images"));
        contents.Replace("{{SupportLink}}", ConfigurationManager.AppSettings["SupportLink"]);
        return View("Index", (object)contents.ToString());
    }
}

In short, it allows passing a file name (without ".md") called "id" (poor name is my fault for lazy routing), assigns a default document if a file name was not passed, sets a ViewBag link to the homepage if we're not on the default document, maps the file name to a markdown document in the directory, replaces some preprocessed keywords, and returns the view with the contents of the document.

My view renders the homepage link, if applicable, then the document using MarkdownSharp. I haven't seen my idea of "preprocessed keywords" in markdown before, so I was wandering what others think. It's really useful for resolving links in documents, without worrying about them while writing. It allows document writers to write:

  To view your user page [click here]({{AppRoot}}/User/Me) and here's an image: ![image]({{DocumentationImages}}/UserPageImage.png)

Which is transformed to this, on localhost, without the author worrying about the actual path to the application, or the content directory:

  To view your user page [click here](http://localhost/MyApp/User/Me) and here's an image: ![image](http://localhost/MyApp/Content/Documentation/images/UserPageImage.png)

I also added one for the support link, so I could pull in that setting from ConfigurationManager.AppSettings.

My questions, succinctly:

Are there any realistic cases that I may not be anticipating?
Is there a best practice that I'm not aware of, for having pre-processed text replaced in markdown?
Is there a better way than StringBuilder.Replace for processing each of my keywords?


texts: Python - ternary operator or if statement?

texts:
Which of these two alternatives is more readable?

token = map.get(token_str)
if not token:
   token = Course(token_str)
return token

or

token = map.get(token_str)
token if token else Course(token_str)


texts: Recursively find data in array of objects

texts:
On this script I look up properties in an array of objects. There is an original array of strings list to get the objects that match the name property, then I look up their respective line managers, reports recursively but only up to the rank 2, finally I merge their entries with the manager ones.
I was wondering if there is a more efficient way to achieve this result as I am having to make an object to index the managers that have already been checked, otherwise I get duplicates when two people have the same manager. Also having to specify the rank limit twice.

const data = [
  {
    name: 'rebecca',
    reports: '',
    rank: 1
  },
  {
    name: 'will',
    reports: 'rebecca',
    rank: 2
  },
  {
    name: 'jose',
    reports: 'will',
    rank: 3
  },
  {
    name: 'tomas',
    reports: 'jose',
    rank: 4,
  },
  {
    name: 'matt',
    reports: 'jose',
    rank: 5
  },{
    name: 'alison',
    reports: 'john',
    rank: 5
  }
]

// Initial list of names
const list = ['tomas', 'matt']

// Get the people on the list first
const filterList = data.filter(({ name }) => list.includes(name))

// Helper object to account for managers already checked and avoid duplicates
const managers = {}

// Find missing managers recursively
const findManager = (manager) => {
  const next = data.find(({ name }) => name === manager)
  managers[next.name] = true
  return next.rank > 2 ? [next, ...findManager(next.reports)] : [next]
}

// Get the line managers for the filterList array
const missingManagers = []
for (const { reports, rank } of filterList) {
  if (!list.includes(reports) && rank > 2 && !managers[reports] ) {
    missingManagers.push(...findManager(reports))
  }
}

const result = [...missingManagers, ...filterList]

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }


texts: Drawing a roaming figure in a field, with less flickering

texts:
I'm a student to programming. I currently just working a thing where the player can walk around a field of hashtags. so far you can only walk horizontally but before i go any further, i realized that the program flickers a lot? Is there any cure for this? I'm using python 3 on windows.

import os
from msvcrt import getch

def clear():
    os.system( 'cls' )

map1=("#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#","#")
def draw_setting(x):
    edit_map=list(map1)
    del edit_map[x]
    edit_map.insert(x,"o") #The player is represented by o
    print (*edit_map, sep='')

x=0
draw_setting(x)
while True:
    key = ord(getch()) #Fetching the key pressed
    if key==100: #If d is pressed
        if x<30:
            x=x+1
            load_map=1
    elif key==97: #If a is pressed
        if x>0:
            x=x-1
            load_map=1
    elif key=="stop":
        break
    if load_map==1: #Only render if necessary
        clear()
        draw_setting(x)
        load_map=0


texts:
I have a conditional active record query that checks to see if a relationship of type X exists (.count > 0) where attribute x and attribute y match specific input or if they match when attribute x and attribute y are switched.

I currently use an || operator with two long active record queries to cover both situations.

def coach_of?(user)
  if UserRelation.where(relation_type: 'coach-student').where(user_id: self.id).where(with_user_id: user.id).count > 0 ||
     UserRelation.where(relation_type: 'coach-student').where(user_id: user.id).where(with_user_id: self.id).count > 0
    true
  else
    false
  end
end

Is there a more clever way to do this or is this kind of query acceptable?


texts:
This is a jQuery time update events for a video player with multiple ids. I feel the code is too long and I need to add more ids to fire events.

 $(document).ready(function() {
           var i = 0;
           var a = 0;
           var b = 0;
           var c = 0;
           var j = 0;

           $("#r-news-week1, #r-news-week2").bind("play", function() {
                if (i < 1) {
                    console.log("Video Started");
                    ga('send', 'event', 'Videos', 'Started', 'Video');
                }
                i = i + 1;
            });

             $("#r-news-week1, #r-news-week2").bind("timeupdate", function() {
                  var currentTime = this.currentTime;
                  if (currentTime > 0.75 * (this.duration)) {
                    if (c < 1) {
                      console.log("watched 75%");
                      ga('send', 'event', 'Videos', 'Watched 75%', 'Video');
                    } c = c + 1;
                  } else if (currentTime > 0.50 * (this.duration)) {
                      if (b < 1) {
                      console.log("watched 50%");
                      ga('send', 'event', 'Videos', 'Watched 50%', 'Video');
                    } b = b + 1;
                  } else if (currentTime > 0.25 * (this.duration)) {
                      if (a < 1) {
                      console.log("watched 25%");
                      ga('send', 'event', 'Videos', 'Watched 25%', 'Video');
                    } a = a + 1;
                  }
              });

            $("#r-news-week1, #r-news-week2").bind("ended", function() {
                if (j < 1) {
                    console.log("Finished 100%");
                    ga('send', 'event', 'Videos', 'Finished 100%', 'Video');
                }
                j = j + 1;
            });

        })


texts: Checking for spelling errors with a trie

texts:
I have been lately working in my C++, and I finished up this trie, and I want to know how my C++ is looking so far.

Node.hpp

#pragma once

#include <memory>

static const int ALPHABETSIZE = 26;

struct Node {
    bool isEnd;
    int prefixCount;
    std::shared_ptr<Node> child[ALPHABETSIZE];
};

Trie.hpp

#pragma once

#include "Node.hpp"
#include <string>
#include <vector>

class Trie {
    std::shared_ptr<Node> head;

public:
    Trie();

    void insert(const std::string& word) const;
    bool search(const std::string& word) const;

    unsigned int wordsWithPrefix(const std::string& prefix) const;
};

Trie.cpp

#include "Trie.hpp"

Trie::Trie() {
    head = std::make_unique<Node>();
    head->isEnd = false;
    head->prefixCount = 0;
    for (int i = 0; i < ALPHABETSIZE; ++i) {
        head->child[i] = nullptr;
    }
}

void Trie::insert(const std::string& word) const{
    auto current = head;
    for (int i = 0; i < word.length(); ++i) {
        int letter = word[i] - 'a';
        if (!current->child[letter])
            current->child[letter] = std::make_shared<Node>();
        current->child[letter]->prefixCount++;
        current = current->child[letter];
    }

    current->isEnd = true;
}

bool Trie::search(const std::string& word) const{
    auto current = head;
    for (int i = 0; i < word.length(); ++i) {
        auto letter = word[i] - 'a';
        if (!current->child[letter])
            return false;
        current = current->child[letter];
    }

    return current->isEnd;
}

unsigned int Trie::wordsWithPrefix(const std::string& prefix) const{
    auto current = head;
    for (int i = 0; i < prefix.length(); ++i) {
        auto letter = prefix[i] - 'a';
        if (!current->child[letter])
            return 0;
        current = current->child[letter];
    }
    return current->prefixCount;
}

Source.cpp

#include <iostream>
#include <fstream>
#include <algorithm>
#include "Trie.hpp"

int main() {
    Trie trie;
    std::ifstream file;
    std::string word = " ", input;

    file.open("dictionary.txt");

    //Ask for input
    std::cin >> input;
    std::transform(input.begin(), input.end(), input.begin(), ::tolower);

    auto beenHere = false;
    //Add every word to the trie.
    while (std::getline(file, word)) {
        std::transform(word.begin(), word.end(), word.begin(), ::tolower);
        //if word's first character equals to input's, go on, else, dont add it onto the trie.
        if (word[0] == input[0]){
            beenHere = true;
            trie.insert(word);
        }
        //If you've already been on the word's first character
        //, and it isn't the same as the input's you are done.
        if (beenHere && word[0] != input[0]) break;
    }

    std::string x = "";
    for (int i = 0, length = input.length(); i < length; ++i) {
        x += input.at(i);
        if (trie.wordsWithPrefix(x) == 0) {
            std::cout << x << "<" << input.substr(i+1, length - 1);
            break;
        }
    }

    file.close();
}


texts:
I am new to JavaScript and wondered if there is a more streamlined way of writing this code:

var choices = "ABBCD" // A string containing the letters A-D
var total = 0

function calculate() { // Iterate through choices and add to total depending on the letter
  for (var i=0; i<choices.length; i++) {
    if (choices[i]=="A") {
      total+=1;
    } if (choices[i]=="B") {
      total+=2;
    } if (choices[i]=="C") {
      total+=3;
    } if (choices[i]=="D") {
      total+=4;
    }
  }
}


texts: API Client: Querying data out of an endpoint

texts:
I have a simple piece of code which connects to an API, does a request and gets back the raw data.
After getting this data I create several objects (models) and persist them into a MongoDB database.

Example of a model:

class Match:
    def __init__(self, data):
        self.data = data

    @property
    def match_id(self):
        """The Match id"""
        return self.data['attributes']['id']
    ...

Example of API CLient

class Client:
    def __init__(self):
        self.session = requests.Session()

    def request(self, endpoint, params=None):
        response = self.session.get(endpoint, timeout=TIMEOUT, params=params)
        res_code = response.status_code
        if res_code != API_OK:
            exception = API_ERRORS.get(res_code)
            raise exception
        return response.json()

Example of the controller:

class Handler(Client):
    def __init__(self, api_key):
        super().__init__()
        self.api_key = api_key

    def query_match(self, match_id, shard='default'):
        res = []
        url = f'{SHARD_URL}/{shard}/matches/{match_id}'
        res = self.request(url)
        return Match(res)

And then I have the logic for getting the data into mongoDB after calling get_player

class BuildAndStore(Handler):
    def __init__(self, mongo_client, api_key):
        super().__init__(api_key)
        self.mongo_client = mongo_client
        self.players = list_players

    def process_matches(self, list_matches):
        ret = []
        for m_i in list_matches:
            match = self.query_match(m_id)
            json_data = build_json(match) # Extracts certain class properties
            ret.append(json_data)
        mongo.insert_many('matches', ret)

Having in mind I want to start consulting the API in parallel (multiple threads or moving to async) my questions are:

Is this pythonic? Is there a better way to do so?
Currently the Handler does the query and the Model receives the payback data. Instead of proceeding passing the JSON data, should I do the query for each model within their own class, passing the match_id and inheriting from "Handler" class Match(Handler): ?


texts: Terminated due to timeout Mapping phone numbers

texts:
I have a code based on the following problem "Mapping phone numbers to names", the problem is that when they are going to process large data(+100.000) the program ends by timeout. my code and problem is this, how can I optimize my code to consume less time?

my code

function processData(input) {
  var r=input.split(/\n/),o=Number(r[0]),c=r.length-1,x=[];
  r.splice(0,o+1);
  r.forEach((l)=>{
      var rx=new RegExp(l+"\\s(\\d+)"),o=input.match(rx);
      console.log(o==null?"Not found":l+"="+o[1]);
  });
}

Example Input

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Example Output

sam=99912222
Not found
harry=12299933

The program generates timeout in the following case

BIG Example Input and output
Thanks


texts:
I got this problem during a mock interview, and I would like to get code review for the backtracking solution. I include 7 test cases, and my solution passes 7 out of 7 test cases. See the online code compiler here

  Robot Paths

  Prompt:   Given a matrix of zeroes, determine how many unique paths exist from the top left corner to the bottom right corner

  Input:    An Array of Array of Integers (matrix)

  Output:   Integer

  Examples:

matrix = [[0,0,0,0],
          [0,0,0,0],
          [0,0,0,0]]
robotPaths(matrix) = 38

matrix = [[0,0,0],
          [0,0,0]]
robotPaths(matrix) = 4

# Note:     From any point, you can travel in the four cardinal directions. I decided to do backtracking approach to solve this problem.
#           (north, south, east, west). A path is valid as long as it travels
#           from the top left corner to the bottom right corner, does not go
#           off of the matrix, and does not travel back on itself

def robot_paths(matrix):
  num_of_rows = len(matrix)
  num_of_cols = len(matrix[0])

  def traverse(row, col):
    nonlocal num_of_rows
    nonlocal num_of_cols
    # is row and col in bounds?
    if row < 0 or row >= num_of_rows or col < 0 or col >= num_of_cols:
      return 0

    # has row, col already been visited?
    if matrix[row][col] == 1:
      return 0

    # is row, col the destination?
    if row == num_of_rows - 1 and col == num_of_cols - 1:
      return 1

    # mark coordinate as visited
    matrix[row][col] = 1

    # initialize sum of total unique paths to end from that coordinate
    s  = traverse(row, col + 1) + traverse(row + 1, col) + traverse(row - 1, col) + traverse(row, col - 1)

    # backtrack; mark coordinate as unvisited so it can be
    matrix[row][col] = 0

    return s

  return traverse(0, 0)

#############################################
########  DO NOT TOUCH TEST BELOW!!!  #######
#############################################

def expect(count, name, test):
    if (count == None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    errMsg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception as err:
        errMsg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if errMsg != None:
        print('       ' + errMsg + '\n')

def lists_equal(lst1, lst2):
    if len(lst1) != len(lst2):
        return False
    for i in range(0, len(lst1)):
        if lst1[i] != lst2[i]:
            return False
    return True

print('Robot Paths Tests')
test_count = [0, 0]

def test():
    matrix = [[0, 0, 0, 0],
              [0, 0, 0, 0],
              [0, 0, 0, 0]]
    example = robot_paths(matrix)
    return example == 38

expect(test_count, 'should work on first example input', test)

def test():
    matrix = [[0, 0, 0],
              [0, 0, 0]]
    example = robot_paths(matrix)
    return example == 4

expect(test_count, 'should work on second example input', test)

def test():
    matrix = [[0]]
    example = robot_paths(matrix)
    return example == 1

expect(test_count, 'should work on single-element input', test)

def test():
    matrix = [[0, 0, 0, 0, 0, 0]]
    example = robot_paths(matrix)
    return example == 1

expect(test_count, 'should work on single-row input', test)

def test():
    matrix = [[0],
              [0],
              [0],
              [0],
              [0]]
    example = robot_paths(matrix)
    return example == 1

expect(test_count, 'should work on a 5 x 8 matrix input', test)

def test():
    matrix = [[0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0]]
    print("  Please be patient, test 6 may take longer to run")
    example = robot_paths(matrix)
    return example == 7110272

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')


texts:
I am currently developing a touchless lightswitch via a Raspberry Pi, an ultrasonic module and a nice radio module.

However, I am quite a beginner in Python and it was a hard time (at least for me) to accomplish my goal. Whenever the measured distance is falling below the limit the switch is triggered "on" (1) and after that if the distance is falling short again the switch is triggered "off" (0).

#!/usr/bin/env python

import os
import sys
import time
import RPi.GPIO as GPIO

GPIOTrigger = 23
GPIOEcho    = 24

def wait(sec):
  while sec > 0:
    sys.stdout.write(str(sec) + '     \r')
    sec -= 1
    time.sleep(1)

def MeasureDistance():
  GPIO.output(GPIOTrigger, True)
  time.sleep(0.00001)
  GPIO.output(GPIOTrigger, False)
  StartTime = time.time()
  while GPIO.input(GPIOEcho) == 0:
    StartTime = time.time()
  while GPIO.input(GPIOEcho) == 1:
    StopTime = time.time()
  TimeElapsed = StopTime - StartTime
  Distance = (TimeElapsed * 34300) / 2
  return Distance
def main():
  STATUS = 0
  try:
    while True:
      Distance = MeasureDistance()
      if Distance > 10.0:
        time.sleep(0.01)
      else:
        if STATUS != 1:
      print("Passing by (%.1f cm)" % Distance)
          import subprocess
          subprocess.call(["/root/rcswitch-pi/send", "10000", "1", "1"])
          wait(5)
          STATUS = 1
        else:
          subprocess.call(["/root/rcswitch-pi/send", "10000", "1", "0"])
          wait(5)
          STATUS = 0

  except KeyboardInterrupt:
    print("Stopped by user")
    GPIO.cleanup()
if __name__ == '__main__':
  # use GPIO pin numbering convention
  GPIO.setmode(GPIO.BCM)
  GPIO.setup(GPIOTrigger, GPIO.OUT)
  GPIO.setup(GPIOEcho, GPIO.IN)
  GPIO.output(GPIOTrigger, False)
  main()

This works but I am unsure whether there is a nicer way of determining the last status of STATUS or if there are some pitfalls I might not see.


texts: Setting values inside of several input fields

texts:
In my JavaScript code, I have as below. very simply this is a for loop where I go through several dom elements, retrieve some values and set it. And, before doing it, I am also checking. Now, I feel like the code is not readable. To be honest, I can read it as I wrote it.

        for (var pos = startLoop, arrayPos = 0; arrayPos < (maxLocations); arrayPos++, pos++) {
          xmlMSVal[arrayPos] && $('.someParent .nf-repeater-row:nth-child(' + pos + ') .bed1').val(xmlMSVal[arrayPos].textContent);

          xmlPCVal[arrayPos] && $('.someParent .nf-repeater-row:nth-child(' + pos + ') .bed2').val(xmlLTVal[arrayPos].textContent);

          xmlRITVal[arrayPos] && $('.someParentr .nf-repeater-row:nth-child(' + pos + ') .bed3').val(xmlPCVal[arrayPos].textContent);

        }


texts:
I've just completed an assignment about class templates in C++. It works fine and produces the correct output. We were given the main function and had to construct and implement the class. I'm wondering if there is a better (more efficient) way to construct and implement this simple calculator class template.

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

template <typename T1, typename T2>
class Calculator{
public:
      Calculator(T1 first, T2 second);
      Calculator( const Calculator<T1, T2>& otherCalculator);
      void setValue1(T1 first);
      void setValue2(T2 second);
      T1 add();
      T1 multiply();
 private:
      T1 number1;
      T2 number2;
 };

 template <typename T1, typename T2>
 Calculator<T1, T2>::Calculator(T1 first, T2 second)
      :number1(first), number2(second)
 {}

 template <typename T1, typename T2>
 Calculator<T1, T2>::Calculator(const Calculator<T1, T2>& otherCalculator)
      :number1(otherCalculator.number1), number2(otherCalculator.number2)
 {}

 template <typename T1, typename T2>
 void Calculator<T1, T2>::setValue1(T1 first){
      number1 = first;
 }

 template <typename T1, typename T2>
 void Calculator<T1, T2>::setValue2(T2 second){
      number2 = second;
 }

 template <typename T1, typename T2>
 T1 Calculator<T1, T2>::add(){
      T1 answer = number1 + number2;
      return answer;
 }

template <typename T1, typename T2>
T1 Calculator<T1, T2>::multiply(){
      T1 answer = number1 * number2;
      return answer;
}

int main(){
      Calculator<int,int> simpleCalc(42, 3);
      cout << "Adding: " << simpleCalc.add() << endl;
      cout << "Multiplying: " << simpleCalc.multiply() << endl;
      simpleCalc.setValue1( 7);
      cout << endl;

      Calculator<int,int> copyCalc( simpleCalc);
      cout << "Adding: " << simpleCalc.add() << endl;
      cout << "Multiplying: " << simpleCalc.multiply() << endl;
      cout << endl;

      Calculator<float,double> realCalc(1.41421, 2.718281828459045);
      cout << "Adding: " << realCalc.add() << endl;
      cout << "Multiplying: " << realCalc.multiply() << endl;
      cout << endl;
      return 0;
}


texts:
I'm trying to improve my Angular skills by writing some basic applications that use a particular feature.  The following application uses the UI Bootstrap modal to add users to a list, or remove them again.

Any feedback on any part of the code is very much appreciated, but I have some specific concerns around the way data is passed between the modal and the parent scope.  It can be done by either setting scope=$scope in the $uibModal options, or by using resolve.  Which is better in this scenario and why?

Here's an extract from the main controller:

$scope.open = function() {
  var modalInstance = $uibModal.open({
    templateUrl: 'add_user.html',
    controller: 'ModalController',
    scope: $scope
  });

  modalInstance.result.then(function(res){
    $scope.userGroup = res;
  });
};

and here's an extract from the modal controller:

$scope.modalUserGroup = angular.copy($scope.userGroup);

$scope.add = function(){
  $scope.modalUserGroup.push($scope.newUser);
};

$scope.delete = function(userIndex){
  $scope.modalUserGroup.splice(userIndex, 1);
};

$scope.save = function() {
  $uibModalInstance.close($scope.modalUserGroup);
};

Here's the plunk. I've also written up my notes on it encase it's useful to anyone else.


texts:
Create a C++ program which will act like contact search app in mobile.
  For example, if the following contacts are saved in contact list:

    Massi
    Pradip
    Prasad
    Praveed
    Raju

  And if user type "a" then following names should be displayed:

    Massi
    Pradip
    Prasad
    Praveed
    Raju

  if user type "Pr" then following names should be displayed:

    Pradip
    Prasad
    Praveed

  Basically it should display all the names which contain the search
  string anywhere in name.

#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <map>
#include<iomanip>

using namespace std;

int main() {
    map<string,int> contacts;
    contacts["Pradip"]=999092456;
    contacts["Raju"]=999092457;
    contacts["Praveed"]=999092445;
    contacts["Prasad"]=999092415;
    contacts["Asim"]=999092785;
    contacts["Massi"]=999092215;
    int key_code;
    string key;
    while (true)
    {

            if ( kbhit() ){

                key_code = getch();
                system("CLS");

                if (key_code == 8 ){
                    key.size() ? key.pop_back(): 0;
                }
                else{
                    key+=key_code;
                }
                cout<<"Contacts with : "<<key<<endl;

                for (map<string,int>::iterator &tter = contacts.begin();tter != contacts.end();tter++)
                {
                    if (string::npos == tter->first.find(key) && !key.empty()){
                        continue;
                    }
                    std::cout<<setw(4)<<"Name : "<<setw(10)<< std::left <<tter->first.c_str()<<setw(14)<<", Number : "<<setw(10)<<tter->second<<std::endl;
                }

            }
            else
                continue;
    }
    return 0;
}


texts:
I have been given following problem to solve:

If the integer is divisible by 3, return the string "Java".
If the integer is divisible by 3 and divisible by 4, return the string "Coffee"
If the integer is one of the above and is even, add "Script" to the
end of the string. Otherwise, return the string "mocha_missing!"

Sample Input and Output

caffeineBuzz(1) => "mocha_missing"
caffeineBuzz(3) => "Java"
caffeineBuzz(6) => "JavaScript"
caffeineBuzz(12) => "CoffeeScript"

//Class

    public class CoffieScriptGenerator {

        public String caffeineBuzzz(Integer number) {

            if(isDivisbleByThreeAndFour(number))
            {
                if(isEven(number))
                return "CoffeeScript";
                else
                return "Coffee";
            }
            if(isDivisbleByThree(number))
            {
                if(isEven(number))
                return "JavaScript";
                else
                return "Java";
            }
            return "mocha_missing!";

        }

        private boolean isEven(Integer number) {
            return number%2==0;
        }

        private boolean isDivisbleByThreeAndFour(Integer number) {

            return isDivisbleByThree(number) && number%4==0;
        }

        private boolean isDivisbleByThree(Integer number) {
            return number%3==0;
        }

    }

Please provide suggestions to refactor it and improve it and how i can improve such nesting if else with help of patterns like strategy.


texts: Rails: create a relationship between comment and user

texts:
I'm trying to connect the create of a comment to the current_user. I have a model comment which is a polymorphic association.

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.string :content
      t.references :commentable, polymorphic: true
      t.timestamps
    end
  end
end

In the controller I'm trying to connect the @comment.user = current_user.
controllers/comments_controller.rb

  def create
    @comment = @commentable.comments.new comment_params
    @comment.user = current_user
    @comment.save
    redirect_to @commentable, notice: 'Comment Was Created'
  end

But I get the following error:

  NoMethodError: undefined method `user=' for #
  Did you mean?  user_id=

I would rather set up a relationship from which I can get to a user (The creator of comment) from the comment itself. For example @comment.user instead of just having the id.

I have the following models:

class Question < ApplicationRecord
  belongs_to :user
  has_many :comments, as: :commentable
  has_rich_text :content
end

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts
  has_many :questions
  has_one_attached :avatar

  before_create :set_defaults

  def set_defaults
    self.avatar = 'assets/images/astronaut.svg' if self.new_record?
  end
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

Since comment is a polymorphic association, I'm not sure if it should be connected to user via a belongs_to to user.

[5] pry(#<Questions::CommentsController>)> @comment
=> #<Comment:0x00007fb3e6df72e8
 id: nil,
 content: "some test content",
 commentable_type: "Question",
 commentable_id: 1,
 created_at: nil,
 updated_at: nil,
 user_id: nil>
[6] pry(#<Questions::CommentsController>)>

Does this mean, I should create a foreign_key in the comments migration to a user? How can I go about getting the creator of the comment from the comment itself? Something like @comment.creator or @comment.user?


texts: Bash script to send certain data from AWC EC2 to CloudWatch

texts:
Here's a little bash script I wrote, which basically checks something on an Amazon EC2 instance and reports data to CloudWatch every 60 seconds. I'll run this inside a container. Everything works just fine, but I think it's clunky, doesn't write anything to stdout/stderr so no logs, and doesn't handle any errors. I am open to refactoring this or even writing it in Python, to make my docker image more efficient. Any suggestions, criticism is most welcome.

Here's the full script less some sensitive data that I've xxx'd:

#!/bin/bash

INSTANCEID=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id/)
AZ=$(curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone)
REGION= $(echo $AZ | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:')

URL="xxx"

putdata() {
    aws cloudwatch put-metric-data "some other stuff" $1 "xxx"
    sleep 60
}
while true; do
    HTTP_RESPONSE=$(curl --write-out "%{http_code}" --silent --output /dev/null "$URL")
    if [ "$HTTP_RESPONSE" = "200" ]; then
        putdata 0

    else
        putdata 1
    fi
done

EDIT: just realized that the sleep command runs as a separate PID inside the container, which is why the container takes quite a while to stop. Running with --init flag improves the exit workflow as it better reaps the processes upon exit but that's another unwanted PID.


texts: Validating files and returning errors messages/boolean values

texts:
I am writing simple file validator for my java ee app and I am stack with my class api. I need specific error descriptions, but also I would like to have boolean values indicating whether file is valid or not. Please give me some hints how to do it 'smart'.

package pl.poznan.put.ims.business.attachments;

import java.util.List;
import java.util.ArrayList;

import com.google.inject.Inject;

import pl.poznan.put.ims.business.entities.Attachment;
import pl.poznan.put.ims.business.exceptions.AttachmentValidationException;
import pl.poznan.put.ims.settings.IFileSystemSettings;

public class AttachmentValidator implements IAttachmentValidator
{
      IFileSystemSettings messageSettings;
      private List<String> errors;

    @Inject
    public AttachmentValidator(IFileSystemSettings messageSettings)
    {
        this.messageSettings = messageSettings;
        this.errors = new ArrayList<String>();
    }

    @Override
    public boolean validate(List<Attachment> attachments) throws AttachmentValidationException
    {
        for (Attachment attachment : attachments) {
            validate(attachment);
        }

        if(attachments.size() > messageSettings.getMaxFilesCount())
            errors.add("Attachments max number exceeded.");

        if(!errors.isEmpty())
            throw new AttachmentValidationException(errors);

        return true;
    }

    @Override
    public boolean validate(Attachment attachment)
    {
        boolean isValid = validateLimitExceeded(attachment);
        isValid &= validateNull(attachment);

        return !isValid;
    }

    private boolean validateLimitExceeded(Attachment attachment)
    {
        boolean exceeded = attachment.getFileSize() > messageSettings.getMaxFileSize();
        if(exceeded)
            errors.add("Max file size limit exceeded. File: " + attachment.getFileDisplayName() + ". Size: "+ attachment.getFileSize()/1024/1024 + "MB.");

        return exceeded;
    }

    private boolean validateNull(Attachment attachment)
    {
        if(attachment == null) {
            errors.add("No attachment.");
            return false;
        }

        return true;
    }

    @Override
    public List<String> getErrors()
    {
        return errors;
    }

    @Override
    public long getTotalMaxFilesSize() {
        return messageSettings.getMaxFilesCount() * messageSettings.getMaxFileSize();
    }
}


texts: Removing the word "NULL" from a single column in Excel using VBA

texts:
I am using VBA in Excel to remove the word NULL from cells. I have the following code:

Sub RemoveNull()
    Dim c, count, r
    Application.ScreenUpdating = False

    count = 0
    r = ActiveCell.row
    c = ActiveCell.Column
    c = GetLetterFromNumber(c)

    For x = 1 To Range(c & Rows.count).End(xlUp).row Step 1
        count = count + 1
        If Range(c & x).Value = "NULL" Then
            Range(c & x).Clear
        End If
        'This section is for trouble shooting
        'If count = 1000 Then
        '    Range(c & x).Select
        '    count = 1
        'End If
    Next
    Application.ScreenUpdating = True
    MsgBox "Finished"
    Range(c & r).Select
End Sub

This works just fine and is designed to only check one column. I don't want to check the whole sheet with this I already have another sub that does this.

I want to make sure that this is the most efficient way to go about it. right now it checks each cell from top to bottom and then clears the contents if it contains NULL.


texts:
I am fairly new to bash (I have about 3 months of experience), and now I've written my first real application (sort of).

It's a function inside of ~/.bash_profile, but it has an installer. It is called loginfo and it keeps track of when the terminal was used by the user, and allows them to view this data.

It comes with an installer, and a built-in uninstaller.

install.sh

#!/bin/bash

width=$(tput cols)
printSolid(){
printf "%${width}s\n" " " | tr " " "$1"
}

printCenter(){
textsize=${#1}
padding=$((($width+$textsize)/2))
printf "%${padding}s\n" "$1"
}

install_loginfo(){
touch ~/.bash_profile
if grep -q "#loginfo-->" ~/.bash_profile
then
    echo "[ER] Already installed 'loginfo'."
else
    loginfofile=$(echo "$(dirname $0)/loginfo.txt")
    test ! -e $loginfofile && (echo "[ER] Unable to locate '$loginfofile'")
    cat $loginfofile >> ~/.bash_profile
    test $? -eq 0 && (echo "[OK] Successfully appended '$loginfofile' to '~/.bash_profile'")
    test $? -ne 0 && (echo "[ER] Something went wrong appending '$loginfofile' to '~/.bash_profile'")
fi
}

printSolid "#"
printCenter "Installer for 'loginfo'"
printCenter "By 545H4"
printSolid "#"
echo "Would you like to install 'loginfo'? (y/n)"
while true
do
read -n 1 -r -s confirm
case $confirm in
y | Y)
    install_loginfo
    break
    ;;
n | N)
    echo "'loginfo' was not installed."
    break
    ;;
*)  echo "Please enter a valid option (y/n)"
    ;;
esac
done
echo "You have got to restart your terminal for any change to take place."
exit

loginfo.txt

#loginfo-->

currLogin=$(date '+%d/%m/%Y %H:%M:%S')
echo "$currLogin" >> terminallogins.txt

deltLoginfo(){
while true
do
echo "Remove 'loginfo'? (y/n)"
read -n 1 -r -s confirm
case $confirm in
y | Y)
        echo "$(sed '/^#loginfo-->/,/^#<--loginfo/d' ~/.bash_profile)" > ~/.bash_profile
        test $? -eq 0 && (echo "[OK] Successfully removed 'loginfo' from '~/.bash_profile'")
        test $? -ne 0 && (echo "[ER] Failed to remove 'loginfo' from '~/.bash_profile'")
        touch ~/terminallogins.txt
        rm ~/terminallogins.txt
        test $? -eq 0 && (echo "[OK] Successfully removed '~/terminallogins.txt'")
        test $? -ne 0 && (echo "[ER] Failed to remove '~/terminallogins.txt'")
        echo "You have got to restart your terminal for any change to take place."
        break
        ;;
n | N)
        echo "'loginfo' wasn't removed."
        break
        ;;
*)
        echo
        ;;
esac
done
}

loginfo(){
case $1 in
last) echo "$(tail -2 ~/terminallogins.txt)" | head -n 1;;
curr) echo "$currLogin";;
list) cat ~/terminallogins.txt;;
delt) deltLoginfo;;
*) echo "Usage: loginfo <last/curr/list/delt>";;
esac
}

#<--loginfo

GitHub

Inside of the repository install.sh and loginfo.txt are in the same folder, I am new to GitHub as well but using two files seemed the most easy to manage.


texts: Video playback loop using promise chaining and setTimeout

texts:
Well this could seem redundant given the numerous topic about interaction between Promises and setTimeout but I can't find an answer that exactly fit my case (or that I am capable of interpreting !)

In the case of a Video player API usage, I need to loop on a sequence, and exit the loop when a certain condition is reached.

The following code works, but I was wondering if there was a sexier way, using Promise chaining instead of this :

export class LoopStep {
// looping from 0 to 5 seconds in the video
this.duration = 5;
this.start = 0;

onStart() { // entry point
    return this.onLoop();
}

onLoop() {
    return new Promise((resolve) => {
        this.loopAndResolve(resolve);
    });
}

loopAndResolve(resolve) { // start loop
    if(this.isLooping) { // exit condition when turned to false
        this.player.setTime(this.start);
        this.player.play();
        setTimeout(this.loopAndResolve.bind(this, resolve), this.duration * 1000); // callback
    } else {
        resolve();
    }
}
}

// Anywhere else
loopStep.onStart.then(()=> console.log('exiting loop successfully')); // OK

Actually I would find more appropriated to avoid passing the "resolve" function as a parameter (only because I have a feeling that this could be wrong, or at least not "the most efficient/sexy").


texts: Making this password search more intelligent

texts:
In a homework, there is an exercise in which I have a script that is used to search for a password.

One of the questions is if is possible to make it "more intelligent", and I'm stuck on it.

#!/bin/bash

space1="a b c d e f g h i j k l m n o p q r s t u v w x y z"

if [  $# -le 1 ]
then
    echo "Ussage: " $0 SALT PASSWORD_CODED
    exit
fi

for i in $space1
do
for j in $space1
do
for k in $space1
do

    variable=$(openssl passwd -crypt -salt "$1" "$i$j$k")
    if [ "$variable" = $2 ]
        then
        echo password found: $i$j$k
        exit
    fi
done
done
done

If it is possible, I prefer only a clue to help me to discover the answer correct, not the answer itself. I promise to post the result when I get the answer for myself.


texts: Simplifying Cryptography Key Generation without Losing Security

texts:
I am writing a helper class for encrypting string and other data types. My goal is to make it as easy as possible to use, while still keeping a substantial amount of security.

One issue I struggled with was simplifying all the different key and IV sizes. I've settled on having the caller provider a salt, and then generating my own key and IV data from the salt.

I assume this compromises the security very slightly, but not that much.

I would appreciate hearing other people's thoughts, especially those who have more experience with cryptography than I. Am I compromising my security too much?

public virtual byte[] EncryptBytes(byte[] data)
{
    using (SymmetricAlgorithm algorithm = TripleDES.Create())
    using (ICryptoTransform encryptor = algorithm.CreateEncryptor(GetKey(algorithm), GetIV(algorithm)))
    {
        MemoryStream ms = new MemoryStream();
        using (Stream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(data, 0, data.Length);
        }
        return ms.ToArray();
    }
}

public byte[] GetKey(SymmetricAlgorithm algorithm)
{
    return DeriveBytes(algorithm.KeySize / 8);
}

public byte[] GetIV(SymmetricAlgorithm algorithm)
{
    return DeriveBytes(algorithm.BlockSize / 8);
}

protected byte[] DeriveBytes(int bytes)
{
    Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(Password, Salt, 1000);
    return derivedBytes.GetBytes(bytes);
}


texts: Deploying treasure in 4×4 board and finding them in Python

texts:
Before starting I would like to say that I just made this program after studying python for 5 hours for the first time so I am totally new to this programming language.

This program tries to create 4X4 board denoting it with 0 everywhere. Now to deploy treasure, it randomly selects 9 position and deploy them on the board by denoting it with  '@'. Then tries to detect neighboring treasure which are there around vacant lands and counts them and then show them on those vacant lands area. It is just like Minesweeper game.

Since I am new to this python language so I would like to know that what changes do I have to make so that it will look like a Python program and what else I can do to make it work much better.

from random import randint

print "Welcome to Treasure Hunt \n"

q="@"     #For checking the treasure
board = []  #Board

for x in range(0,4):
    board.append(["0"] * 4)   # It creates 4x4 Board with 0 everywhere

treasure = 9
while treasure:                # Randomly spread treasure
 r = randint(0, len(board)-1)
 c = randint(0, len(board[0])-1)
 if board[r][c] != "@":
        board[r][c]="@"
        treasure -= 1

print "-------------------------------"
print "\n Treasures are here "
print "\n-------------------------------\n"
for row in board:
    print "     ".join(row)                  # Give output of board
    print "\n"

def hunt(a,b):              #Hunt function searches for treasure around the given land
    first = a-1
    second = b-1
    third = a+1
    fourth = b+1
    if(first < 0):
        first = first + 1;
    if(second < 0):
        second = second + 1;
    if(third == 4):
        third = third - 1;
    if(fourth == 4):
        fourth = fourth -1;

    h=0
    for i in range(first,third + 1):
        for j in range(second,fourth + 1):
            if(q==board[i][j]):
                h=h+1;
                board[a][b] = h

for k in range(len(board)):
    for l in range(len(row)):
        if(q!=board[k][l]):
            hunt(k,l)

for row in board:
    print "   ".join(map(str,row))