texts:
I have a Python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the Python file is run.

Example:

myFile.py
import sys
def main(arg1....):
  ---code---

--more functions--

main()

When a person wants to run my file they'll type:

python myFile.py arg1 arg2 ...

The main function is supposed to accept in x number of arguments, however, in case the user doesn't wish to pass in any arguments we're supposed to have default values.

My program looks something like this and I'm hoping there is actually a better way to do this than what I have:

myFile.py
import sys
#Even though my function has default values, if the user doesn't wish
#to input in any parameter values, they still must pass in the word False
#otherwise, pls pass in parameter value
def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"):
   if len(sys) > 1:
      i =0
      while i < len(sys):
         if i == 0:
            if sys.argv[i] == "False":
               i += 1
               continue
            else:
                name = sys.argv[i]
                i += 1
                continue
         elif i == 1:
            if sys.argv[i] == "False":
     --------etc. etc.-----------


texts:
I'm a Java/C coder getting started with some Python for a side-project.  I've written some unit tests for a recent side-project I'm working on, but I have a sinking suspicion I'm just writing Java-code, translated into Python.

I've posted a small sample of some unit-tests I wrote.  I'd really appreciate any advice in how to make the code more Pythonic (best-practices, conventions, etc).

import unittest
import urllib2
from connectionstate import ConnectionState

class Test(unittest.TestCase):
  """Unit tests for the ConnectionState"""

  def test_connectionstate_reports_bad_network_connection(self):
    """ConnectionState reports a failure when currently disconnected"""

    #Set up ConnectionState around mock
    always_disconnected = mock_connection_check_func_always_disconnected
    connstate_with_mock = ConnectionState(always_disconnected)

    actual_state = connstate_with_mock.is_connected()
    self.assertEqual(actual_state, False)

  def test_connectionstate_detects_good_network_connection(self):
    """ConnectionState should report success when we can connect"""
    #Set up ConnectionState around mock
    always_connected = mock_connection_check_func_always_connected
    connstate_with_mock = ConnectionState(always_connected)

    actual_state = connstate_with_mock.is_connected()
    self.assertEqual(actual_state, True)

  def test_connectionstate_remembers_disconnections(self):
    """If the internet connection drops and then comes back, ConnectionState
    can remember that the connection dropped temporarily
    """
    #Set up ConnectionState around mock
    sometimes_connected = mock_conn_every_other_conn_succeeds
    connstate_with_mock = ConnectionState(sometimes_connected)

    #Call is_connected a few times so get an unsuccessful connection
    for count in range(0, 3):
      connstate_with_mock.is_connected()

    actual_result = connstate_with_mock.has_connection_dropped()
    self.assertEqual(actual_result, True)

  def test_connectionstate_doesnt_bring_up_ancient_history(self):
    """has_connection_dropped only reports failures that have happened
    since the last call to has_connection_dropped.  Calling
    """
    #Set up ConnectionState around mock
    sometimes_connected = mock_conn_every_other_conn_succeeds
    connstate_with_mock = ConnectionState(sometimes_connected)

    #Call is connected a few times so an unsuccessful connection is reported
    for count in range(0, 3):
      connstate_with_mock.is_connected()

    #Call once to clear failures
    connstate_with_mock.has_connection_dropped()

    actual_result = connstate_with_mock.has_connection_dropped()
    self.assertEqual(actual_result, False)

#Begin mock-connection functions
def mock_connection_check_func_always_disconnected(request=None, timeout=1):
  raise urllib2.URLError("Unable to connect to network")
def mock_connection_check_func_always_connected(request=None, timeout=1):
  pass
def mock_conn_every_other_conn_succeeds(request=None, timeout=1):
  #Initialize 'static' call-counter variable
  if "call_counter" not in mock_conn_every_other_conn_succeeds.__dict__:
    mock_conn_every_other_conn_succeeds.call_counter = 0;

  mock_conn_every_other_conn_succeeds.call_counter += 1

  if mock_conn_every_other_conn_succeeds.call_counter % 2 == 0:
    mock_connection_check_func_always_disconnected(request, timeout)
  else:
    mock_connection_check_func_always_connected(request, timeout)
#End mock-connection functions

if __name__ == "__main__":
  unittest.main()


texts:
I'm developing a shop system and using this method to store the customers with their respective orders:

try
{
    $connection = new PDO("mysql:host={$HOST};dbname={$DB_NAME}", $USERNAME, $PASS);
}

$connection->beginTransaction();
$sql = "INSERT INTO orders (customer_id, customer_name, order_value, order_date)
        VALUES (?, ?, ?, ?)";

$query = $connection->prepare($sql);
$query->execute(array
(
    $user_id,
    $user['user_name'],
    $order_value,
    $date
));

$id_of_respective_order = $connection->lastInsertId();

$sql = "INSERT INTO purchased_products (order_id, product_name, product_price, quantity)
        VALUES (?, ?, ?, ?)";

$query = $connection->prepare($sql);

foreach($_SESSION['cart'] as $product)
{
    $query->execute(array
    (
        $id_of_respective_order,
        $product['product_name'],
        $product['product_price'],
        $product['quantity']
    ));
}

$connection->commit();

By using this, later I can show all the products that belongs to their respective customers by using the Foreign Key order_id.

My question is simple: is this secure? If many people buy at the same time can I have problems? Is there a possibility of a product being directed to the wrong customer? Can I trust in this method?


texts: Supervisors and employees query, with a subselect and inner join

texts:
I want to replace or improve the SELECT command of tblVisor to make it faster.

Is there any way to improve this SQL command?

SELECT tblVisor.supervisor_id,
       tblVisor.last_name,
       tblVisor.first_names,
       tblVisor.employee_job_profile_id,
       org_employees.last_name,
       org_employees.first_name,
       org_employees.job_code
FROM (SELECT cp_supervisor_properties.supervisor_id,
             persons.last_name,
             persons.first_names,
             cp_supervisor_properties.employee_job_profile_id
      FROM cp_supervisor_properties
      INNER JOIN persons ON persons.person_id = cp_supervisor_properties.supervisor_id) as tblVisor
INNER JOIN org_employees ON org_employees.employee_number = tblVisor.employee_job_profile_id
LIMIT 100


texts: Tracks the number of calories consumed throughout the day

texts:
Tracks the number of calories a person consumes in a given meal it has helper method to get the day's total. The check method Tries to find any duplicate meals within the given list. The assumption is that a day can only contain one of each type of meal.

public class Meal {
    public enum Type {
        BREAKFAST,
        LUNCH,
        DINER,
    }

    public Type type;
    double caloriesConsumed;

    public Meal(Type type, double caloriesConsumed) {
        this.type = type;
        this.caloriesConsumed = caloriesConsumed;
    }

    //Gets calories burned
    public double getCaloriesConsumed() {
        return caloriesConsumed;
    }

    //Sets calories burned
    public void setCaloriesConsumed(double caloriesConsumed) {
        this.caloriesConsumed = caloriesConsumed;
    }

    //Get type
    public Type getType() {
        return type;
    }

    //Set type
    public void setType(Type type) {
        this.type = type;
    }

    public boolean equals(Meal meal) {
        return meal.getType() == meal.getType() && meal.getCaloriesConsumed() == getCaloriesConsumed();
    }

    public static void check(Meal... meals) throws Exception {
        /**
         * Tries to find any duplicate meals within the given list.
         * The assumption is that a day can only contain one of each type of meal.
         */
        ArrayList<Type> types = new ArrayList<Type>();
        for (int i = 0; i < meals.length; i++) {
            if (types.contains(meals[i].type))
            {
                throw new Exception();
            }
            else
            {
                types.add(meals[i].type);
            }
        }
    }

    public static double getTodaysCalories(Meal... meals) throws Exception
    {
        check(meals);

        double total = 0;
        for (Meal meal : meals) {
            total += meal.caloriesConsumed; //Add calories to total
        }
        return total;
    }

    public static void main(String[] args) {
        Meal breakfast = new Meal(Type.BREAKFAST, 500.7);
        Meal lunch = new Meal(Type.LUNCH, 378.9);
        Meal dinner = new Meal(Type.DINER, 620.1);

        try {
            double caloriesConsumed = Meal.getTodaysCalories(breakfast, lunch, dinner);
            System.out.println("Today's Total Calories is " + caloriesConsumed);
        } catch (Exception e) {
            System.out.println("Unable to calculate today's calories");
        }
    }
}


texts:
Taking inspiration from SICP Exercise 2.1, I decided to implement a module in Haskell for rational numbers.

Some of my concerns include:

Is this idiomatic Haskell?
Besides Num, Eq, Ord, Show, and Read, are there other typeclasses I should be implementing?  I've got "free-floating" functions toInteger' and rationalDiv.  Is there some typeclass that would accommodate them?
Is this a good way to handle division by zero?
How is the code layout and organization?

module Rational'
( toInteger'
, rationalDiv
) where

data Rational' = Rational' { numer :: Integer
                           , denom :: Integer
                           }

instance Num Rational' where
  (+)           = rationalAdd
  (-)           = rationalSub
  (*)           = rationalMul
  abs           = rationalAbs
  signum        = rationalSignum
  fromInteger   = rationalFromInteger

instance Eq Rational' where
  (==)          = rationalEq

instance Ord Rational' where
  compare       = rationalCompare

instance Show Rational' where
  show          = rationalShow

instance Read Rational' where
  readsPrec     = rationalRead

divByZero n = error ("Division by zero: " ++ (show n) ++ "/0")

rationalAdd :: Rational' -> Rational' -> Rational'
a `rationalAdd` b = reduce $ Rational' (an * bd + bn * ad) (ad * bd)
  where (Rational' an ad) = a
        (Rational' bn bd) = b

rationalSub :: Rational' -> Rational' -> Rational'
a `rationalSub` b = a + (Rational' (-bn) bd)
  where bn = numer b
        bd = denom b

rationalMul :: Rational' -> Rational' -> Rational'
a `rationalMul` b = reduce $ Rational' (an * bn) (ad * bd)
  where (Rational' an ad) = a
        (Rational' bn bd) = b

rationalDiv :: Rational' -> Rational' -> Rational'
a `rationalDiv` b = a * (Rational' bd bn)
  where bn = numer b
        bd = denom b

rationalAbs :: Rational' -> Rational'
rationalAbs (Rational' n d) = reduce $ Rational' (abs n) (abs d)

{- You might expect the result of signum to be an Int (namely -1 | 0 | 1), but
 - the Num typeclass requires it to be the same type as the input. -}
rationalSignum :: Rational' -> Rational'
rationalSignum (Rational' n d)
  | n == 0              = 0
  | (n > 0) == (d > 0)  = 1
  | otherwise           = Rational' (-1) 1

rationalFromInteger :: Integer -> Rational'
rationalFromInteger n = Rational' n 1

{- Truncates towards 0 -}
toInteger' :: Rational' -> Integer
toInteger' (Rational' n d) = n `div` d

rationalEq :: Rational' -> Rational' -> Bool
a `rationalEq` b = (a `rationalCompare` b) == EQ

rationalCompare :: Rational' -> Rational' -> Ordering
a `rationalCompare` b
  | (ad == 0)                   = divByZero a
  | (bd == 0)                   = divByZero b
  | (signum ad) == (signum bd)  = (an * bd) `compare` (bn * ad)
  | otherwise                   = (bn * ad) `compare` (an * bd)
  where (Rational' an ad) = a
        (Rational' bn bd) = b

rationalShow :: Rational' -> [Char]
rationalShow a = (show $ numer a) ++ "/" ++ (show $ denom a)

rationalRead :: Int -> [Char] -> [(Rational', [Char])]
rationalRead _ r = [(Rational' (read ns) (read ds), "")]
  where (ns, (_:ds)) = break (=='/') r

reduce :: Rational' -> Rational'
reduce a = Rational' (n `div` common) (d' `div` common)
  where (Rational' n d) = a
        d'
          | (d == 0)    = divByZero n
          | otherwise   = d
        common = (gcd n d') * (signum d')


texts: Use linq to compute length of line defined as array of points

texts:
I have an array of points:

 Point[] line; // { Point(1,1), Point(2,3), Point(1,1) }

Assuming Point has the relevant operators, what's the most linq-y way of computing the length of this line?

My best effort so far is:

float length = Enumerable.Range(0, line.Length-2)
    .Select(pointIndex => (line[pointIndex+1] - line[pointIndex]).Magnitude)
    .Sum();

Seems like there's a lot of subscripting in there though.

I would think there's a way to do something like this pseudocode:

float length = line.PairwiseMap(p1, p2 => (p2 - p1).Magnitude).Sum();

?


texts:
I have this (simple) data structure that maintains multiple LIFO stacks. Each such stack is assigned a priority. The less is the value of a priority key, the higher the priority. Pushing operation requires the element to push and its priority key. Whenever popping the queue, it removes the most recently added element of the highest priority stack.

I have no clue where one would need such a data structures (maybe someone could tell me?), yet it was fun implementing it.

PriorityStack.java:

package net.coderodde.util;

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * This class implements a priority stack. Each element added comes with a
 * priority key. The smaller the key, the higher is the priority of the element.
 * The elements with the same priority are organized with LIFO rule
 * ("last in, first out").
 *
 * @author  Rodion "rodde" Efremov
 * @version 1.6
 * @param   <E> the element type.
 * @param   <P> the priority key type.
 */
public class PriorityStack<E, P extends Comparable<? super P>> {

    private final Map<P, List<E>> map;
    private int size;

    public PriorityStack() {
        this.map = new TreeMap<>();
    }

    public boolean empty() {
        return size == 0;
    }

    /**
     * Pushes the input element to this stack.
     *
     * @param element  the element to push.
     * @param priority the priority of the input element.
     */
    public void push(E element, P priority) {
        if (!map.containsKey(priority)) {
            map.put(priority, new ArrayList<>());
        }

        map.get(priority).add(element);
        ++size;
    }

    /**
     * Returns but not removes the topmost element of the highest priority
     * substack.
     *
     * @return the top element.
     */
    public E peek() {
        if (size == 0) {
            throw new EmptyStackException();
        }

        List<E> list = map.entrySet().iterator().next().getValue();
        return list.get(list.size() - 1);
    }

    /**
     * Pops the topmost element from the stack with the highest priority.
     *
     * @return an element.
     * @throws EmptyStackException if the stack is empty.
     */
    public E pop() {
        if (size == 0) {
            throw new EmptyStackException();
        }

        Map.Entry<P, List<E>> entry = map.entrySet()
                                         .iterator()
                                         .next();
        P priority = entry.getKey();
        List<E> list = entry.getValue();
        E ret = list.remove(list.size() - 1);

        if (list.isEmpty()) {
            map.remove(priority);
        }

        --size;
        return ret;
    }

    public static void main(final String... args) {
        PriorityStack<String, Integer> stack = new PriorityStack<>();

        // -1: He is a
        // 2:  funky programmer
        // 3:  that likes to
        // 5:  code algorithms
        // 7:  and
        // 8:  data structures! :-]

        stack.push("a", -1);
        stack.push("and", 7);
        stack.push("is", -1);
        stack.push("programmer", 2);
        stack.push("algorithms", 5);
        stack.push("code", 5);
        stack.push(":-]", 8);
        stack.push("He", -1);
        stack.push("to", 3);
        stack.push("structures!", 8);
        stack.push("likes", 3);
        stack.push("data", 8);
        stack.push("who", 3);
        stack.push("funky", 2);

        while (!stack.empty()) {
            System.out.print(stack.pop());
            System.out.print(" ");
        }

        System.out.println();
    }
}

So, what do you think?


texts: Blinking LED code at a particular frequency

texts:
I wrote a function for interacting with my PIC16F1788. The code sends pulses out the RC4 port at a specific frequency, to make an LED blink according to that frequency. So the LED will blink faster or slower depending on the magnitude of the frequency. I decided to take a blinking code and vary the delay time according to my input frequency as follows.

void blink(int frequency){
/* starts the LED blinking at a particular frequency */

while(1)
{
 PORTCbits.RC4=0XFF;  // RC4 on
 __delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
 PORTcbits.RC4=0X00;   // RC4 off
 __delay_ms(1000/frequency);   // time in ms dealing with frequency values in kHz
}

}

would this code work, is this a good idea ,and is there anyway that I could improve it?


texts: More elegant way to count anagrams in Python?

texts:
Question

I feel like my code could be more elegant/more pythonic/faster, but I can't think of too much more to improve. So, I've come to the internet to see what more can be done with standard python.

What my code does

My code counts anagrams for each word in a list of words. For example:

post, spot stop, tops

are four of the words in my list and since all are anagrams of each other, each word should map to the number 4 in a dictionary. Specifically I'm counting the size of the anagram group each word would fit in. The output for a few words would look something like the following then:

{'1-2-3': 1,
 '1980s': 1,
 '1990s': 1,
  ...
  ...
 'top': 1,
 'topic': 2,
 'topics': 1,
 'topped': 1,
 'tops': 4,
 'tory': 2,
 'total': 1,
 'totals': 1,
 'touch': 1,
 'tough': 2,
  ...
  ...
 'zone': 1,
 'zones': 1,
 'zurich': 1}

My code

from itertools import permutations
from collections import Counter

def get_variants(word):
    return map(lambda t: "".join(t), set(permutations(word)))

def count_anagrams(words):
    anagram_counts = {w: 1 for w in words}

    word_counters = list(map(Counter, words))

    for i, (word, counter) in enumerate(zip(words, word_counters)):
        for other_word, other_counter in zip(words[i+1:], word_counters[i+1:]):
            if counter == other_counter:
                anagram_counts[word] += 1
                anagram_counts[other_word] += 1

    return anagram_counts


texts:
I was tasked with building three individual methods; one to create a Binary Search Tree (BST), one to carry out a Breadth First Search (BFS), and one to carry out a Depth First Search (DFS).

Create Binary Tree

class Node
  attr_accessor :value, :left, :right

  def initialize(value)
    @value = value
  end
end

def build_tree(array, *indices)
  array.sort.uniq!
  mid = (array.length-1)/2
  first_element = indices[0]
  last_element = indices[1]

  if !first_element.nil? && first_element >last_element
    return nil
  end

  root = Node.new(array[mid])
  root.left = build_tree(array[0..mid-1], 0, mid-1)
  root.right = build_tree(array[mid+1..-1], mid+1, array.length-1)

  return root
end

Breadth First Search

def breadth_first_search(search_value, tree)
  queue = [tree]
  visited = [tree]

  while !queue.empty?
    current = queue.shift
    visited << current
    left, right = current.left, current.right

    if current.value == search_value
      puts current
      exit
    end

    if !left.nil? && !visited.include?(left)
      if left.value == search_value
        puts left
        exit
      else
        visited << left
        queue << left
      end
    end

    if !right.nil? && !visited.include?(right)
      if right.value == search_value
        puts right
        exit
      else
        visited << right
        queue << right
      end
    end
  end
  puts "nil"
end

Depth First Search

def depth_first_search(search_value, tree)
  stack = [tree]
  visited = [tree]

  while !stack.empty?
    current = stack.last
    left, right = current.left, current.right

    if current.value == search_value
      puts current
      exit
    elsif !left.nil? && !visited.include?(left)
      if left.value == search_value
        puts left
        exit
      else
        visited << left
        stack << left
      end
    elsif !right.nil? && !visited.include?(right)
      if right.value == search_value
        puts right
        exit
      else
        visited << right
        stack << right
      end
    else
      stack.pop
    end
  end
  puts "nil"
end

Calling the Methods

binary_tree = build_tree([4,7,2,8,1,1,1,30,22,4,9])

breadth_first_search(9, binary_tree)
depth_first_search(7, binary_tree)


texts: Variable parser for the Hack programming language

texts:
I am optimizing the variable parser for my programming language, and also trying to make it more readable and concise (precedence: readable and concise > efficient). What is the best way to improve this code and make the best out of each line, and make it easier to understand for contributors?

namespace pro_compiler
{
    /* Handles all the variable declarations */
    public class VarParser : Parser
    {
        public VarParser( )
            : base()
        {
        }

        public string Parse(ref string line)
        {
            CheckVariable(ref line);
            return line;
        }

        public void CheckVariable(ref string line)
        {
            /* Check current line for the "var" keyword */
            if (line.StartsWith("var"))
            {
                string decl = line;
                decl += ';';
                line = decl;
                CheckFunctions(ref line);
            }
        }

        /* check if the var declaration contains any functions
         * e.g var input = readln; */
        public string CheckFunctions(ref string line)
        {
            var words = line.Split(' '); //check wether each word is a function
            line = ""; // clear the current line

            foreach (var word in words)
            {
                string w = word.Trim(); //trim all leading and trailing spaces.

                foreach(var pair in FuncTable.Instance.NormSet)
                {
                    if (w.StartsWith(pair.Key)) // if the word is a function
                    {
                        w = w.Replace(pair.Key, pair.Value + "( )"); // replace it with the C# equivalent
                    }
                }

                w = ((w == words[0]) ? "" : " ") + w; // reinsert trailing and leading spaces
                line += w; // add the words back to the current line
            }

            return line;
        }
    }
}

Also, I have used a lot of the C# standard library methods, since I figured that the people who wrote those have 10 times more skills than me and wrote them as efficiently as possible. Is this good? Or is it better to implement my own string functions?


texts:
I'm a bioinformatician and mainly use python, but I'm trying to learn Haskell. So far I like this language because it's beautiful and fun, but my Haskell scripts usually end up being much slower than my Python equivalent.

Here is my latest attempt:

-- Define type synonyms for fields in a fastq record.
type Name = String
type Nucleotides = String
type Qualities = String

data FastqRecord = FastqRecord Name Nucleotides Qualities
{-
Show is implemented so that the string representation of a FastqRecord
is actually its fastq formatted representation.
-}
instance Show FastqRecord where
    show (FastqRecord name s q) = unlines [name, s, "+", q]

-- Parse lines four by four, ignore the third of each batch.
getFastqRecords :: [String] -> [FastqRecord]
getFastqRecords [] = []
getFastqRecords (l1 : l2 : _ : l4 : ls) = FastqRecord l1 l2 l4 : getFastqRecords ls

{-
We assume that the records come in sorted by sequence.
Successive records having the same sequence are fused,
arbitrarilly keeping the first name, and taking the
highest quality at each position.
-}
fuseFastqRecords :: [FastqRecord] -> [FastqRecord]
fuseFastqRecords [] = []
fuseFastqRecords [r] = [r]
fuseFastqRecords (r1@(FastqRecord n s1 q1) : r2@(FastqRecord _ s2 q2) : rs)
    | s1 == s2 = fuseFastqRecords (FastqRecord n s1 (bestquals q1 q2) : rs)
    | otherwise = r1 : fuseFastqRecords (r2 : rs)

{-
For each position, we want to keep the highest quality
among the records that had the same sequence.
In fastq format, qualities are integers represented as ascii characters
Using max on Char does what we want.
-}
bestquals :: Qualities -> Qualities -> Qualities
bestquals = zipWith max

main :: IO ()
main = interact (concatMap show . fuseFastqRecords . getFastqRecords . lines)

On very small test input, this scripts runs 10 times faster than my python implementation.

On "real" input, the python code (using pypy) uses much more ram than the Haskell version, but runs in half the time.

If I understood my readings so far, Strings in Haskell are not implemented efficiently, so I guess I would have to use another type to process my text.
But the representation as a list of Char is actually very convenient for one of the operations I want to do (see the comments about the bestquals function).

What would you recommend to do?


texts: Bouncy castle 128bit AES/CBC/PKCS7 in java

texts:
I have been trying to do some encryption-decryption using bouncy castle and with the available docs and samples on the internet I have managed to prepare the below. Though this works without throwing any exception, i feel something fishy. Can somebody tell me if i have done it right or is there any thing that i should do :)

 private static void Test()
  {
  try
  {
    String keyString = "Olmy9iqs1LwWblwe";
    String input = "teststring";
    byte[] inputBytes = input.getBytes();
    String xiv = "1234567891234567";
    byte[] iv = xiv.getBytes("UTF-8");
    int length;
    //Set up
    AESEngine engine = new AESEngine();
    CBCBlockCipher blockCipher = new CBCBlockCipher(engine);
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher);
    KeyParameter keyParam = new KeyParameter(keyString.getBytes());
    ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);

    // Encrypt
    cipher.init(true, keyParamWithIV);
    byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)];
     length = cipher.processBytes(inputBytes,0,inputBytes.length, outputBytes, 0);
    cipher.doFinal(outputBytes, length);
    String encryptedInput = new String(Base64.encode(outputBytes));
    System.out.println("Encrypted String:" +encryptedInput);

    //Decrypt
    cipher.init(false, keyParamWithIV);
    byte[] out2 = Base64.decode(encryptedInput);
    byte[] comparisonBytes = new byte[cipher.getOutputSize(out2.length)];
    length = cipher.processBytes(out2, 0, out2.length, comparisonBytes, 0);
    cipher.doFinal(comparisonBytes, length); //Do the final block
    String s2 = new String(comparisonBytes);
    System.out.println("Decrypted String:"+s2);
}
  catch (Exception e)
  {
    e.printStackTrace();
  }
}


texts: C++ Implementation of a Python-like memoization decorator

texts:
Coming from a Python background, one thing I really miss in C++ is a memoization decorator (like functools.lru_cache. As I sometimes compete on Codeforces, I found myself implementing a similar thing in C++17 in case I ever need a quick and easy way to memoize function calls. I was wondering whether I could get some feedback on my implementation, and whether something like this could be effective and practical to use in production code.
Thanks!
#include <bits/stdc++.h>

// Using a map
template <typename RetType, typename... ArgTypes>
auto memoize(std::function<RetType(ArgTypes...)> func) -> decltype(func) {
    return [
        memo = std::map<std::tuple<ArgTypes...>, RetType>(),
        func = std::move(func)
    ](ArgTypes... args) mutable -> RetType {
        auto key = make_tuple(args...);
        if (auto it = memo.find(key); it != memo.end()) {
            return it->second;
        }
        auto [it, emplaced] = memo.emplace(key, func(args...));
        return it->second;
    };
}

// Using an unordered_map

// From boost
template<typename T>
inline void hash_combine(std::size_t& seed, const T& val) {
    std::hash<T> hasher;
    seed ^= hasher(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template <typename RetType, typename... ArgTypes>
auto memoizeHashed(std::function<RetType(ArgTypes...)> func) -> decltype(func) {
    using KeyType = std::tuple<ArgTypes...>;
    struct KeyHashFnc {
        size_t operator() (const KeyType& key) const {
            size_t result = 0;
            std::apply([&result](auto&&... args) {
                (
                    hash_combine(result, std::forward<decltype(args)>(args)),
                    ...
                );
            }, key);
            return result;
        }
    };
    return [
        memo = std::unordered_map<KeyType, RetType, KeyHashFnc>(),
        func = std::move(func)
    ](ArgTypes... args) mutable -> RetType {
        auto key = std::make_tuple(args...);
        if (auto it = memo.find(key); it != memo.end()) {
            return it->second;
        }
        auto [it, emplaced] = memo.emplace(key, func(args...));
        return it->second;
    };
}

// Intended usage (solves the problem: https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/)
using namespace std;
int INF = 1e9+5;
class Solution {
public:
    int minDifficulty(const vector<int>& arr, int d) {
        int N = arr.size();

        using DpFuncType = function<int(int,int)>;
        DpFuncType dp = [&dp, &arr, N](int i, int k) {
            int n = N-i;

            if (k <= 0) {
                return -1;
            }
            else if (k > n) {
                return -1;
            }
            else if (k == n) {
                return accumulate(arr.begin()+i, arr.end(), 0);
            }
            else { // k < n
                if (k == 1) {
                    return *max_element(arr.begin()+i, arr.end());
                }
                else {
                    int result = INF;
                    int maxVal = arr[i];
                    for (int j = i+1; j < N; ++j) {
                        int curr = dp(j,k-1);
                        if (curr != -1) {
                            result = min(result, maxVal + curr);
                        }
                        maxVal = max(maxVal, arr[j]);
                    }

                    if (result == INF) {
                        return -1;
                    }
                    else {
                        return result;
                    }
                }
            }
        };
        dp = memoizeHashed(dp); // memoize(...) can also be used here

        return dp(0,d);
    }
};
```


texts:
This is the first code of this type that I've attempted, so I'm wondering if anybody would be willing to critique it. It's "sort of" (I think) a factory class. I want to keep it as simple as possible (and still work, and be at least as elegant as Phyllis Diller - it doesn't have to be Elizabeth Taylor).

The situation is that we may eventually support any number of printer types (printing labels from a Windows CE device), but want to keep the client code to something as simple as:

var beltPrinter = new BeltPrinter();
beltPrinter.PrintLabel(price, description, barcode);

Each print job will consist of 0..N preparatory commands sent to the printer ("hey, wake up!") followed by 1..N print commands, followed by 0..N shutdown commands.

Based on that, does the following make sense? If not, what would you advise that I change?

interface IBeltPrinter
    {
        private List<string> printerSetupCmds;
        private List<string> printLabelCmds;
        private List<string> printerTeardownCmds;

        void PrintLabel();
    }

class BeltPrinter : IBeltPrinter
{
    if (<ZebraQL220>) // don't know yet how I will determine which printer is in use - perhaps from reading a config file
    {
        return ZebraQL220Printer;
    }
    else if (<ONeal>)
    {
        return ONealPrinter;
    }
}

class ZebraQL220Printer : IBeltPrinter
    {
        public void PrintLabel(string Price, string Desc, string Barcode)
        {
            var _price = Price;
            var _desc = Desc;
            var _barcode = Barcode;

            printerSetupCmds = new List<string>();
            printerSetupCmds.Add(''); // the format and commands, etc. will differ from other printers
            . . .
            printLabelCmds = new List<string>();
            printLabelCmds.Add('');
            . . .
            printerTeardownCmds = new List<string>();
            printerTeardownCmds.Add('');
            . . .

            foreach (string line in printerSetupCmds) {
    //send to ZebraQL220
            }
            foreach (string line in printLabelCmds) {
    //send to ZebraQL220
            }
            foreach (string line in printerTeardownCmds) {
    //send to ZebraQL220
            }
        }
    }

    class ONealPrinter : IBeltPrinter
    {
        public void PrintLabel(string Price, string Desc, string Barcode)
        {
            var _price = Price;
            var _desc = Desc;
            var _barcode = Barcode;

            printerSetupCmds = new List<string>();
            printerSetupCmds.Add(''); // the format and commands, etc. will differ from other printers
            . . .
            printLabelCmds = new List<string>();
            printLabelCmds.Add('');
            . . .
            printerTeardownCmds = new List<string>();
            printerTeardownCmds.Add('');
            . . .

            foreach (string line in printerSetupCmds) {
    //send to ONeal
            }
            foreach (string line in printLabelCmds) {
    //send to ONeal
            }
            foreach (string line in printerTeardownCmds) {
    //send to ONeal
            }
        }
    }


texts: SPOJ - POWFIB (Fibo and non fibo) Time Limit Exceeds

texts:
Problem

  Find (a^b)%M, where

  a = Nth non-fibonacci number

  b = Nth fibonacci number modulo M

  M = 1000000007

  Consider fibonacci series 1,1,2,3,.....

  INPUT

  First line contains T , the number of test cases.

  Each next T lines contains a  number N.

  OUTPUT

  Print T lines of output where each line corresponds to the required answer.

  EXAMPLE

  Input:

  3

  3

  2

  1

  Output:

  49

  6

  4

  Constraints

  1<=T<=100000

  1<=N<=10^7

Here is my code for the problem link

#include <cstdio>
#include <unordered_map>
using namespace std;

typedef long long int ll;

ll M = 1000000007;

ll mulmod(ll a, ll b)       //modular multiplication
{
    ll x = 0;
    ll y = a%M;
    while(b>0)
    {
        if(b%2)
            x = (x+y)%M;
        y = (y+y)%M;
        b/=2;
    }
    return x%M;
}

ll modulo(ll a, ll b)       //modular exponentiation
{
    ll x = 1;
    ll y = a;
    while(b)
    {
        if(b%2)
            x = mulmod(x,y);
        y = mulmod(y,y);
        b/=2;
    }
    return x%M;
}

unordered_map<ll,ll> Fib;

ll fibo(ll n)       //n+1 th fibonacci number
{
    if(n<2)
        return 1;
    if(Fib.find(n) != Fib.end())
        return Fib[n];
    Fib[n] = (fibo((n+1) / 2)*fibo(n/2) + fibo((n-1) / 2)*fibo((n-2) / 2)) % M;
    return Fib[n];
}

ll nonfibo(ll n)        //nth non-fibonacci number
{
    ll a = 1, b = 2, c = 3;
    while(n>0)
    {
        a = b;
        b = c;
        c = a+b;
        n-=(c-b-1);
    }
    n+=(c-b-1);
    return n + b;
}

int main()
{
    ll t;
    scanf("%lld",&t);
    while(t--)
    {
        ll n;
        scanf("%lld",&n);
        printf("%lld\n",modulo(nonfibo(n),fibo(n-1)));
    }
    return 0;
}

It exceeds the time limit, how do I improve the code?


texts:
How can I achieve a more performant tick code keeping my minimum frame rate high?

installLoops() {
        window.requestAnimationFrame(this.loop.bind(this));
    }

    loop() {
        this.now = Date.now();
        var delta  = this.now - this.last;
        this.last = this.now;

        this.dt = this.dt + delta;

        if (this.dt < this.rate) {
            window.requestAnimationFrame(this.loop.bind(this));
            return;
        } else {
            this.game.loop();
            this.draw();
            this.dt = this.dt - this.rate;
            this.game.loopKeyboardInput(this.key_pressed_map);
            this.key_pressed_map = {};
        }

        window.requestAnimationFrame(this.loop.bind(this));
    }

I moved

this.game.loopKeyboardInput(this.key_pressed_map);
    this.key_pressed_map = {};

to inside the block where the game loop is called, which improved my average from rate from 12.56 to 56+. However, in performance testing my framerate still drops down to 13 (lowest). (I'm not sure if this is happening because of the performance sampling).


texts: Efficiently calculate value of Pascal's Triangle using memoization and recursion

texts:
So reading about functional programming, applications to dynamic programming, and learning Scala. I figured I would try it out with a popular example, Pascal's Triangle, tests against known values work out fine. Any tips for optimization? Am I doing anything totally wrong? Is there a way to do this with tail recursion that I'm missing? Any feedback appreciated.
def pascal(c: Int, r: Int): Int = {
    // use a cache; map if (c,r) pair to value
    // fill in value recursively
    var cache: Map[(Int,Int), Int] = Map()
    cache += ((0,0) -> 1)
    var i = 0
    for(i <- 1 to r){
       cache += ((0,i) -> 1)
       cache += ((i,i) -> 1)
    }

    def getPascalValue(c: Int, r: Int): Int = {
        if (cache.contains((c, r))) {
            cache((c, r))
        } else {
            cache += ((c, r) -> (getPascalValue(c, r - 1) + getPascalValue(c - 1, r - 1)))
            cache((c, r))
        }
    }
    getPascalValue(c,r)
}


texts:
I'm attempting to write a (hopefully) efficient way of "expanding" a 2d array into a 1d array.  Let me illustrate what I mean:

Given the 2d array

{{1, 2},
 {3, 4}}

and a block width of 2 and a block height of 2, we can "expand" into a 1d array

{1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4}

Notice, if newlines are added this looks like

{1, 1, 2, 2,
 1, 1, 2, 2,
 3, 3, 4, 4,
 3, 3, 4, 4}

And the original has been "expanded"!

The code I have currently is

public int[] expand(int[][] src, int blockWidth, int blockHeight) {
    int[] dest = new int[src.length * src[0].length * blockWidth * blockHeight];
    for (int i = 0; i < src.length; i++) {
        for (int j = 0; j < src[i].length; j++) {
            int fromIndex = i * blockWidth * blockHeight * src[i].length + j * blockWidth;
            int toIndex = fromIndex + blockWidth;
            Arrays.fill(dest, fromIndex, toIndex, src[i][j]);
        }
        int srcPos = i * blockWidth * blockHeight * src[i].length;
        for (int k = 1; k < blockHeight; k++) {
            int destPos = srcPos + k * blockWidth * src[i].length;
            System.arraycopy(dest, srcPos, dest, destPos, src[i].length * blockWidth);
        }
    }
    return dest;
}

This method:

Creates the destination array equal to the total size of the source array times the block dimensions.
For each color in a row, fill the first row of the destination.
Copy the first row into the rest of the rows, completing the blocks.

I wonder if there's a way to make this method more efficient or cleaner?

Thanks!


texts:
I've knocked up this code to allow me to query for specific service names using PowerShell.

I'm after the executable (PathName) for the service, so the Get-Service cmdlet is not appropriate here. I don't actually have any services with special characters in their names; but I like to build robust code where I can foresee future gotchas.

I'm posting here as want to know if my ConvertTo-WmiEscapedQuery is the right way to escape a WMI Query.

function ConvertTo-WmiEscapedQuery {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Query
        ,
        [Parameter()]
        [string[]]$Parameters = @()
    )
    begin {
        [string]$EscapeCharatersRegex = '([\\''"])'
    }
    process {
        [string[]]$EscapedParameters = $Parameters | %{$_ -replace $EscapeCharatersRegex, '\$1'}
        $Query -f $EscapedParameters
    }
}

function Get-WmiService {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ServiceName
    )
    begin {
        [string]$Query = 'select * from win32_service where name = "{0}"'
    }
    process {
        Get-WmiObject -Query (ConvertTo-WmiEscapedQuery -Query $Query -Parameters $ServiceName)
    }
}

Get-WmiService 'John''s Example Service'

I realise some people don't like the | %{...} shorthand for a foreach statement.  I've deliberately opted to use such shorthand options only for foreach/% and where/? statements, since these are pretty universally known conventions.

(I've also posted here as this question falls into the grey area between question and code-review.)


texts: Finding the output of sequence (a + 2^(i*b))

texts:
I just started programming and have taken too much time to code the solution for this problem:

  In this problem you will test your knowledge of Java loops.  Given
  three integers, \$a\$, \$b\$, and \$n\$, output the following series:

  $$a + 2^{0}b, a + 2^{0}b + 2^{1}b, \ldots \ldots, a + 2^{0}b + 2^{1}b + \ldots + 2^{n-1}b$$

  Input Format

  The first line will contain the number of testcases \$t\$.  Each of
  the next \$t\$ lines will have three integers, \$a\$, \$b\$, and
  \$n\$.

  Constraints:

  \$0 \le t \le 500\$
  \$0 \le a, b \le 50\$
  \$1 \le n \le 15\$

  Output

  Print the answer to each test case in separate lines.

I just want to know whether this code can be further optimized in Java.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        int r=0,c=1;
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++){
            int a=sc.nextInt();
            int b=sc.nextInt();
            int n=sc.nextInt();
            r=a;
            for(int j=0;j<n;j++){
                if(j==0)
                    c=1;
                else
                    c=c*2;
                r= r +c*b;
                System.out.print(r +" " );
            }
            System.out.println( );
        }
    }
}


texts: Linq-to-Sql Contains an int? inside a list of int

texts:
Curious if there is a better way to write a repository method that receives argument List<int> and checks if the database Contains an int?.

public List<int> GetNumbersByNumbers(IEnumerable<int> numbers)
{
    var convertedNumbers = numbers.Select(m => (int?)m);
    return Context.TblNumbers
        .Where(m => convertedNumbers.Contains(m.Number))
        .Select(m => m.Number.GetValueOrDefault())
        .ToList();
}


texts: Programmatically close optical drive tray

texts:
I really liked the close tray program that CD-ROM drivers programs used to include in MS-DOS days.
Since I live in a place where even getting an internship is impossible, I've decided to learn by myself.
I implemented this "Hello World" C# script to do that with a twist.
It will check the optical drive status and if open, it will close it, otherwise it will tell you that a disk is present.
Note, I went through Stack Overflow and couldn't find a way to programmatically find if the tray is open.
Another note, it will not close the tray on most laptops where such mechanism does not exist.
And finally, I used an online code beautifier for indentation.
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Management;

class Program {
[DllImport("winmm.dll")] protected static extern int mciSendString(string Cmd, StringBuilder StrReturn, int ReturnLength, IntPtr HwndCallback);

  static void Main(string[] args) {

  ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MediaLoaded FROM Win32_CDROMDrive");
  ManagementObjectCollection moc = searcher.Get();
  var enumerator = moc.GetEnumerator();
  if (!enumerator.MoveNext()) throw new Exception("No elements");
  ManagementObject obj = (ManagementObject) enumerator.Current;
  bool status = (bool) obj["MediaLoaded"];

  if (!status) {
    MessageBox.Show("The drive is either open or empty", "Optical Drive Status");
    mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);
  }
  else MessageBox.Show("The drive is closed and contains an optical media", "Optical Drive Status");
 }
}


texts: Matching element of arrays on a condition

texts:
if node[i] and node[i+1] are present in the neighbor[i], then store the 'i' position of node and print the 'i' value of node.

this is also done by reversing the node array(only) and same type of check and print is done with the neighbor[i].

This code is written by me and works well, is there any other efficient method to perform this.

#include <stdio.h>
int main()
{
    int node[5] = {44,5,4,6,40};
    int neighbor[4]= {40,3,4,6};
    int i=0,j=0,k=0;
    int found_indices[5]; // array used to store indices of found entries..
    int count = 0; //n entries found;
    int fwd_count=0;
    int postn;
    int find;
    // to find in forward direction
     for (i=0; i<4; i++) {
        for (j=0; j<4; j++) {
            if (node[i]==neighbor[j]) {
                postn=node[i];
                for (k=0; k<4; k++) {
                    if (node[i+1]==neighbor[k]) {
                      found_indices[fwd_count ++] = postn; // storing the index of found entry

                    }
                }
            }
        }
    }

   if (fwd_count!=0) {
       for (i=0; i<fwd_count; i++)
           printf("forward relay for ==%d\n", found_indices[i]);

   } else{
     printf("Relay not found in forward\n");
  }

 // to find in backward direction
    for (i=4; i>0; i--) {
        for (j=0; j<4; j++) {
            if (node[i]==neighbor[j]) {
                postn=node[i];
                for (k=0; k<4; k++) {
                    if (node[i-1]==neighbor[k]) {
                      found_indices[count ++] = postn; // storing the index of found entry

                    }
                }
            }
        }
    }

   if (count!=0) {
       for (i=0; i<count; i++)
           printf("backward relayy for ==%d\n", found_indices[i]);

   }else{
      printf("Relay not found in backward \n");
   }

}


texts: Encapsulation, fields and properties for Asteroid class

texts:
After changing all variables in this code from public to private and adding get/set according to the need to get modified and/or read in another class, I'd like to know if this was done correctly.

// Main
public class Asteroid
{
    Random random = new Random();

    private Rectangle boundingBox;
    public Rectangle BoundingBox
    {
        get { return boundingBox; }
    }

    private Vector2 position;
    public Vector2 Position
    {
        get { return position; }
    }

    private bool isVisible;
    public bool IsVisible { get; set; }

    private Vector2 origin;
    private float rotationAngle;
    private int speed;
    private Texture2D texture;
    private float randomX, randomY;

    // Constructor
    public Asteroid(Texture2D newTexture, Vector2 newPosition)
    {
        position = newPosition;
        texture = newTexture;
        speed = 4;
        randomX = random.Next(0, 750);
        randomY = random.Next(-600, -50);
        isVisible = true;
    }

    // Load Content
    public void LoadContent(ContentManager Content)
    {

    }

    // Draw
    public void Draw(SpriteBatch spriteBatch)
    {
        if (isVisible)
            // spriteBatch.Draw(texture, position, Color.White);
            spriteBatch.Draw(texture, position, null, Color.White, rotationAngle, origin, 1.0f, SpriteEffects.None, 0f);
    }

    // Update
    public void Update(GameTime gameTime)
    {
        // Set bounding box for collision
        boundingBox = new Rectangle((int)position.X - (texture.Width / 2), (int)position.Y - (texture.Height / 2), texture.Width, texture.Height);

        origin.X = texture.Width / 2;
        origin.Y = texture.Height / 2;

        // Update Movement
        position.Y = position.Y + speed;

        if (position.Y >= 950)
        {
            isVisible = false;
        }

        // Rotating Asteroid
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        rotationAngle += elapsed;
        float circle = MathHelper.Pi * 2;
        rotationAngle = rotationAngle % circle;
    }
}


texts: Separate method for a single line code? Or embed in the caller function?

texts:
I'm having an argument with my boss about whether or not it's better to have a separate function for a single line of code.

The code reads something like:

while (count <= poscount)
{
    key = etc.substr(pos2prev+1, pos-pos2prev-1);
    std::string::iterator end_pos = std::remove(key.begin(), key.end(), ' ');
    key.erase(end_pos, key.end());

    val = etc.substr(pos+1, pos2-pos-1);

    //process key and val
    DEBUG("{\n\t%s:%s\n}\n", key.c_str(), val.c_str());
    json_object_object_add(paramList, key.c_str(), json_object_new_string(val.c_str()));

    count++;
    pos2prev = pos2;
    pos = etc.find("=", pos+1);
    pos2 = (count == poscount) ? etc.find("\0",pos2+1) : etc.find("&", pos2+1);
}

Is it better coding style to include the line

json_object_object_add(paramList, key.c_str(), json_object_new_string(val.c_str()));

in a separate function name such as processKeyVal(), or leave it as-is?


texts:
This is not "real life" code.  I'm trying to expand upon the well known Sakila sample database for MySQL to make it more complex. Step 7 (or 6) is running surprisingly slow.

PS: Note these are all separate queries executed against the same database in the order specified.

Add columns to sakila.customer table:

USE sakila;
ALTER TABLE customer
    ADD COLUMN multiplier DECIMAL(3,2) AFTER active;
ALTER TABLE customer
    ADD COLUMN cust_ranking VARCHAR(10) AFTER multiplier;

Duration: 0.289 sec
Create a proc to randomly distribute multiplier:

DROP PROCEDURE IF EXISTS sp_randCustMult;
DELIMITER //
CREATE PROCEDURE sp_randCustMult()

BEGIN
    -- declare a counter
    SET @start = (SELECT MIN(customer_id) FROM customer);
    SET @stop  = (SELECT MAX(customer_id) FROM customer);

    -- start while loop
    WHILE @start <= @stop
        DO
        -- select a random float variable
        SET @RAND = RAND();
        -- update NULL field
        UPDATE customer
        SET multiplier = (SELECT
            (CASE
                WHEN @RAND <= 0.65 THEN 1.00
                WHEN @RAND <= 0.90 THEN 0.85
                WHEN @RAND <= 1.00 THEN 1.05
                END))
        WHERE customer_id = @start;
            -- tick counter one up
            SET @start = @start + 1;
    END WHILE;
END//
DELIMITER ;

Duration: 0.001 sec
Call the proc to populate the rows:

CALL sp_randCustMult;

Duration: 0.761 sec
With Safe Update Mode OFF, add human-friendly values to cust_ranking based on multiplier.

UPDATE customer
    SET cust_ranking = 'Standard'
    WHERE multiplier = 1.00;
UPDATE customer
    SET cust_ranking = 'Premium'
    WHERE multiplier = 0.85;
UPDATE customer
    SET cust_ranking = 'Uplift'
    WHERE multiplier = 1.05;

Duration:
0.057 sec
0.037 sec
0.035 sec
Add a real_amount column to table payment:

ALTER TABLE payment
ADD COLUMN real_amount DECIMAL(5,2)
AFTER amount;

Duration: 0.749 sec
Create another proc to populate payment with real amounts:

DROP PROCEDURE IF EXISTS sp_RealAmtPayment;
DELIMITER //
CREATE PROCEDURE sp_RealAmtPayment()

BEGIN
-- declare a counter
SET @start = (SELECT MIN(payment_id) FROM payment);
SET @stop  = (SELECT MAX(payment_id) FROM payment);

WHILE @start <= @stop
DO
    UPDATE payment AS p
        INNER JOIN customer AS c
            ON p.customer_id = c.customer_id
    SET real_payment = (p.amount * c.multiplier)
    WHERE p.payment_id = @start;
    SET @start = @start + 1;
END WHILE;
END//
DELIMITER ;

Duration: 0.001 sec
CALL sp_RealAmtPayment;

Duration: 17.082 sec
SELECT * FROM payment;

1000 row(s) returned
0.002 sec / 0.002 sec

Step 7 seems extremely long considering the very small number of records.  What am I missing? All comments/critiques welcome!


texts:
I have a small (few elements) list of primary keys, sorted by hand. It come from user input. For example

$ids = [15, 75, 54, 13];

The SQL command is simple.

SELECT id, value, type FROM a_table WHERE id IN (15, 75, 45, 13);

This is SQL, so the order of output may be random. I want to
restore it in PHP. My first attempt.

# $ids - the input
# $result - output from database
function sort_to_input_1($ids, $result)
{
    $plain = array_map(function($a){return $a['id'];}, $result);
    $flipped = array_flip($plain);
    $sorted = array();
    foreach($ids as $id) {
        if (isset($flipped[$id])) {
            $idx = $flipped[$id];
            $sorted[] = $result[$idx];
        }
    }
    return $sorted;
}

The second, the brute force.

# $ids - the input
# $result - output from database
function sort_to_input_2($ids, $result)
{
    $sorted = array();
    foreach($ids as $id) {
        foreach($result as $row) {
            if ($row['id'] == $id)) {
                $sorted[] = $row;
            }
        }
    }
    return $sorted;
}

The third one.

# $ids - the input
# $result - output from database
function sort_to_input_3($ids, $result)
    $result_h = array();
    foreach($result as $row) {
        $id = $row['id'];
        $result_h[$id] = $row;
    }
    $sorted = array();
    foreach($ids as $id) {
        if (isset($result_h[$id])) {
            $sorted[] = $result_h[$id];
        }
    }
    return $sorted;
}

Witch one is the easiest to read? Or is there a fourth way?


texts:
I'm learning C so I thought to apply it to miniproject on reddit. The smorse function takes in a string and spits out some morse code. It works if you supply the function with only lowercase letters. I feel awkward making a first for loop in my smorse function to calculate the size of buffer I need to malloc and then making a second for loop to add the characters.

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

char **master = NULL;

char* smorse(char *str) {
    int i;
    char *ele;
    int end = strlen(str);
    char *output = "";
    int totalSize = 0;

    for (i = 0; i < end; i++) {
        ele = master[(*str) - 97];
        totalSize += sizeof(ele) * sizeof(char);
        str++;
    }

    output = malloc(totalSize);
    str -= end;

    for (i = 0; i < end; i++) {
        ele = master[(*str) - 97];
        strcat(output, ele);
        str++;
    }

    return output;
}

int main(int argc, char *argv[]) {
    int i;
    char key[] = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..";
    master = (char **)malloc(26 * sizeof(char *));
    char *ele = strtok(key, " ");

    for (i = 0; i < 26; i++) {
        if (i != 0)
            ele = strtok(NULL, " ");
        master[i] = (char *)malloc(sizeof(ele) * sizeof(char));
        master[i] = ele;
    }

    printf("%s\n", smorse("sos"));
    printf("%s\n", smorse("daily"));
    printf("%s\n", smorse("programmer"));
    printf("%s\n", smorse("bits"));
    printf("%s\n", smorse("three"));

    free(master);
    return 0;
}


texts: Find numbers with same number of divisors

texts:
I tried to resolve this task:

  The integers 14 and 15, are contiguous (1 the difference between them,
  noticeable) and have the same number of divisors.

14 ----> 1, 2, 7, 14 (4 divisors)
15 ----> 1, 3, 5, 15 (4 divisors)

  The next pair of contiguous integers with this property is 21 and 22.

21 -----> 1, 3, 7, 21 (4 divisors)
22 -----> 1, 2, 11, 22 (4 divisors)

  We have 8 pairs of integers below 50 having this property, they are:

[[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]]

  Let's see now the integers that have a difference of 3 between them.
  There are seven pairs below 100:

[[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]]

  Let's name, diff, the difference between two integers, next and prev,
  (diff = next - prev) and nMax, an upper bound of the range.

  We need a particular function, count_pairsInt(), that receives two
  arguments, diff, and nMax and outputs the amount of pairs of integers
  that fulfill this property, all of them being smaller (not less or
  equal) than nMax.

  Let's see it more clearly with examples.

count_pairs_int(1, 50) -----> 8 (See case above)
count_pairs_int(3, 100) -----> 7 (See case above)

Source: codewars.com

My code:

def count_pairs_int(diff, n_max)
  (1..n_max - diff).select { |n| getDivisors(n) == getDivisors(n + diff) }.count
end

def getDivisors(num)
  (1..num).select { |n| (num % n).zero? }.count
end

There is a problem with time of execution code:

  The process terminated. It took longer than 8000ms to complete

Initial tests are passed (first 10). Any ideas on how I can optimize the code?


texts: Deserializing multiple elements from XElement

texts:
I'm serializing multiple elements using this code:

public IEnumerable<Customer> GetCustomers(xmlString)
{
  var xml = XElement.Parse(xmlString);
  var customers = xml.Elements("Customer");
  var serializer = new XmlSerializer(typeof(Customer));
  return customers.Select(c =>
  {
    using (var reader = c.CreateReader())
      return (Customer)serializer.Deserialize(reader);
  });
}

I have this hunch that CreateReader is an expensive one, so:

Is there a way to serialize multiple elements out a collection of elements (without creating a Customers class)?
Do I need to dispose all those readers?
Any other way to read directly from XElement (should I use string)?

Update
I've initially asked the question with this code:

public IEnumerable<Customer> GetCustomers(xmlString)
{
  var xml = XElement.Parse(xmlString);
  var customers = xml.Elements("Customers");
  var serializer = new XmlSerializer(typeof(Customer));
  return customers.Select(c => (Customer)serializer.Deserialize(c.CreateReader()));
}


texts:
Is there a shorter way of taking a dict with varying length lists and printing it to screen? Shortcomings of this method also include that values which aren't lists are printed as letters separated by spaces, and values which are numbers produce an error.  Would it be better to write a class which could accept any type of dict value, or is it best to have different classes for different types of dict?

class PrintDict(object):
    """prints dict keys and values including lists
    except if values are numbers"""

    def print_dict_to_screen(self, data):

        self.data = data
        print ""
        for key in sorted(self.data):
            print "\n\n%s" % str(key)
            items = len(self.data[key])
            iterate = -1
            for i in range(items):
                iterate += 1
                print self.data[key][iterate],

crops = {'trees' : ['hazelnut'],
'potatoes': ['early', 'main'],
'legumes': ['broad beans', 'peas', 'runner beans'],
'brassicas': ['cabbages', 'sprouts', 'kale', 'swede', 'turnip'],
'onions and roots': ['carrots',   'parsnips',
'beetroot', 'onions', 'shallots'],
'other': ['lettuce', 'sweet corn', 'flowers'],
'fruit': ['blackberry', 'blackcurrant', 'raspberry']}

print_ = PrintDict()

print_.print_dict_to_screen(crops)


texts: Checking if the entries of a map exist in another map

texts:
I need to check if a map is subset of another map. For this, I have written the following code:

#include <string>
#include <iostream>
#include <map>

using namespace std;

/**
 * Checks if rhs is a subset of lhs
 */
template<class Map>
bool map_compare(Map &lhs, Map &rhs)
{
    if(rhs.size() > lhs.size() || rhs.empty()) return false;
    typename Map::iterator litr = lhs.begin();
    for (typename Map::iterator ritr = rhs.begin(); ritr != rhs.end(); ritr++)
    {
        if(litr == lhs.end() && ritr != rhs.end()) return false;
        while (litr != lhs.end())
        {
            if (litr->first == ritr->first)
            {
                if (litr->second == ritr->second)
                {
                    litr++;
                    break;
                }
                return false;
            }
            else
            {
                litr++;
            }
        }
    }
    return true;
}

int main()
{
    map<int, string> a, b;

    a[0] = "0";
    a[1] = "1";

    b[0] = "0";

    cout << "b ⊆ a? " << map_compare(a, b) << " (should be 1)\n";

    b[1] = "1";
    cout << "b ⊆ a? " << map_compare(a, b) << " (should be 1)\n";

    b[2] = "2";
    cout << "b ⊆ a? " << map_compare(a, b) << " (should be 0)\n";
}

I am looking for another implementation of map_compare which is either shorter or more efficient.


texts:
I just recently started working on python (interesting language, actually), and, as I always do when I learn a new language (with the exception of BrainFuck, that's too hard), I write a FizzBuzz program.

I notice there is no error-checking, so my program would have problems with incorrect input, but please ignore that as I haven't gotten to that part yet.

Code:

def getString(num, fizz, buzz):
    if num % (fizz * buzz) == 0:
        return "FizzBuzz"
    elif num % fizz == 0:
        return "Fizz"
    elif num % buzz == 0:
        return "Buzz"
    else:
        return num

def fizzbuzz(maxNum, fizz, buzz):
    num = 1;
    while num <= maxNum:
        print(getString(num, fizz, buzz))
        num += 1

fizz = int(input("Enter the number to Fizz: "))
buzz = int(input("Enter the number to Buzz: "))
maxNum = int(input("Enter the maximum number: "))
fizzbuzz(maxNum, fizz, buzz)

The code will take a fizz, buzz, and a maxNum as input, and will output, all the fizzing and buzzing the code is doing.

Concerns:

Does it follow Python conventions?


texts: Check if a site is indexed by google and stores status in Database

texts:
This is the script I need to speed up.

Things that I have already done to speed up are:

Using single quotes instead of double quotes wherever possible.
Created Database Index
Replaced queries containing 'select' * with 'select column_names'

It takes around 1.7 seconds per URL on average. I want to know if this can be made any faster by any optimizations in PHP or SQL.

<?php
    $servername = '127.0.0.1';
    $username = 'root';
    $password = '';
    $dbname = 'cron';
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if (!$conn)
    {
        die('Connection failed: ' . mysqli_connect_error());
    }
    $sql = 'SELECT Name FROM domain';
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_row($result))
    {
        $line = (string)$row[0];
        $auth = base64_encode('ABC:XYZ');
        $aContext = array('http' => array('proxy' => 'tcp://IP_ADDRESS', 'request_fulluri' => true, 'header' => 'Proxy-Authorization: Basic'.' '. $auth,),);
        $cxContext = stream_context_create($aContext);
        if (strstr(file_get_contents('http://www.google.com/search?q=site:'.$row[0], False, $cxContext), 'did not match any documents'))
        {
            $status = FALSE;
        }
        else
        {
            $status = TRUE;
        }
        date_default_timezone_set('Asia/Kolkata');
        $date = date('Y-m-d H:i:s');
        $sql = "UPDATE domain SET Index_Status = '$status', Last_Checked = '$date' WHERE Name = '$line' ";
        $result1 = mysqli_query($conn, $sql);
    }
    mysqli_close($conn);
    header( 'Location: /Cron/php/display.php');
?>


texts: Returning the sum of all multiples of a number up to 1000

texts:
I've been learning Python and in order to put my skills to the test, I created a simple program that returns the sum of all of the multiples of number num up to 1000.

def get_multiple_sum(num):
    sum = 0
    i = 0
    for i in range(0, 1001):
        if i % num == 0:
            sum += i
        else:
            continue
    return sum

Is this the fastest way to do this? I'm always looking for ways to make my code more efficient.


texts:
I created a boilerplate from react-boilerplate. I have removed redux and immutable for use context API and immer.

I wonder if I use the context API with a good design pattern.

I use like this:

// ./app/containers/LanguageProvider/index.js
import React from 'react';
import PropTypes from 'prop-types';
import { IntlProvider } from 'react-intl';
import {
  Context as ContextLanguageProvider,
  Consumer as ConsumerLanguageProvider,
} from './Context';

export const LanguageProvider = props => {
  const { children, messages } = props;

  return (
    <ContextLanguageProvider>
      <ConsumerLanguageProvider>
        {ctx => (
          <IntlProvider
            locale={ctx.state.locale}
            key={ctx.state.locale}
            messages={messages[ctx.state.locale]}
          >
            {React.Children.only(children)}
          </IntlProvider>
        )}
      </ConsumerLanguageProvider>
    </ContextLanguageProvider>
  );
};

LanguageProvider.propTypes = {
  messages: PropTypes.object,
  children: PropTypes.element.isRequired,
};

export default LanguageProvider;

and I created the context API like this:

// ./app/containers/LanguageProvider/Context.js
import React from 'react';
import PropTypes from 'prop-types';

import { initialState, reducer } from './reducer';

const { Provider, Consumer } = React.createContext('languageProvider');

export const Context = props => {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  const { children } = props;

  return (
    <Provider value={{ state, dispatch }}>
      {React.Children.only(children)}
    </Provider>
  );
};

Context.propTypes = {
  children: PropTypes.element.isRequired,
};

export { Consumer };

Here the reducer.js and actions.js:

// ./app/containers/LanguageProvider/reducer.js
/* eslint-disable consistent-return,no-param-reassign */
import produce from 'immer';
import { CHANGE_LOCALE } from './constants';
import { DEFAULT_LOCALE } from '../../i18n';

export const initialState = {
  locale: DEFAULT_LOCALE,
};

export const reducer = (state = initialState, action) =>
  produce(state, draft => {
    switch (action.type) {
      case CHANGE_LOCALE:
        draft.locale = action.locale;
        break;
      default:
        return state;
    }
  });

// ./app/containers/LanguageProvider/actions.js
import { CHANGE_LOCALE } from './constants';

export function changeLocale(languageLocale) {
  return {
    type: CHANGE_LOCALE,
    locale: languageLocale,
  };
}

I would like to know your reviews on my strategy and how to optimize.


texts: Comparing version numbers contained in a text string

texts:
I was trying to make something to compare two version numbers. The version numbers should consist of three parts (1.4.3). I also wanted to take into account if there is badly formatted data or if 1.4 is used instead of 1.4.0. Any bad data will be converted to a 0. I wanted to find something simple and fast. This is what I came up with:

version(a,b){

    // insure that there are enough decimal points
    a += ".0.0.0"
    b += ".0.0.0"

    //take only the first three elements
    a_arr = a.split(".",3)
    b_arr = b.split(".",3)

    a_int = a_arr.map(function (value) {
        val = parseInt(value, 10)
        return val ? val : 0
    })

    b_int = b_arr.map(function (value) {
        val = parseInt(value, 10)
        return val ? val : 0
    })

    console.log(a_int)
    console.log(b_int)

    status = "equal"
    i = 0

    do {
        if (a_int[i] < b_int[i])
            status = "less"
        else if (a_int[i] > b_int[i])
            status = "greater"
        i++
    }
    while (status == "equal" && i < 3)

    console.log("Status:" + status)

}

What are your thoughts? Is it a bit too hackish? What would be a better approach?


texts: Fully parameterized PowerShell function for file removal

texts:
I would like your opinion on my Remove-Files PowerShell function. It is used in my File-Removal-PowerShell-Script. It is designed to be very flexible so a script user can have configure it to remove files in multiple and various way as it often the chase.
Remove-Files function
function Remove-Files {
    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType([PSCustomObject])]
    param (
        [Parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)]
        [string]
        $FolderPath,

        [Parameter(Position = 1, Mandatory, ValueFromPipelineByPropertyName)]
        [string]
        $FileName,

        [Parameter(Position = 2, ValueFromPipelineByPropertyName)]
        [int]
        $OlderThen = 0,

        [Parameter(Position = 3, ValueFromPipelineByPropertyName)]
        [string]
        $Recurse = "false",

        [Parameter(Position = 4, ValueFromPipelineByPropertyName)]
        [string]
        $Force = "false"
    )

    begin {
        $DateToDelete = (Get-Date).AddDays(- $OlderThen)
    }

    process {
        $FolderSpaceFreed = 0
        $FilesRemoved = 0
        $FailedRemovals = 0

        if (-not (Test-Path -Path $FolderPath)) {
            Write-Log -Message "ERROR: $FolderPath folder does not exist"
            return
        }

        $FullPath = Join-Path -Path $FolderPath -ChildPath $FileName

        if ($Recurse -eq "true") {
            $FileList = Get-ChildItem -Path $FullPath -Recurse
        }
        else {
            $FileList = Get-ChildItem -Path $FullPath
        }

        $FileList = $FileList | Where-Object {$_.LastWriteTime -lt $DateToDelete}

        foreach ($File in $FileList) {
            $FileSize  = (Get-Item -Path $File.FullName).Length
            $SpaceFreed = Get-FormattedFileSize -Size $FileSize

            if ($Force -eq "true") {
                Get-Item -Path $File.FullName | Remove-Item -Force
            }
            else {
                Get-Item -Path $File.FullName | Remove-Item
            }

            if (-not (Test-Path -Path $File.FullName)) {
                $Message = "Successfully deleted " + $File.Name + " file - removed $SpaceFreed"
                $FolderSpaceFreed += $FileSize
                $FilesRemoved ++
            }
            else {
                $Message = "Failed to delete " + $File.Name + " file"
                $FailedRemovals ++
            }
            Write-Log -Message $Message
        }

        $SpaceFreed = Get-FormattedFileSize -Size $FolderSpaceFreed

        if ($FilesRemoved -gt 0) {
            Write-Log -Message "Successfully deleted $FilesRemoved files in $FolderPath folder, and $SpaceFreed of space was freed"
        }
        if ($FailedRemovals -gt 0) {
            Write-Log -Message "Failed to delete $FailedRemovals files in $FolderPath folder"
        }
        if ($FilesRemoved -eq 0 -and $FailedRemovals -eq 0) {
            Write-Log -Message "No files for delition were found in $FolderPath folder"
        }
        New-Object -TypeName psobject -Property @{
            FolderSpaceFreed =  $FolderSpaceFreed
            FilesRemoved = $FilesRemoved
            FailedRemovals = $FailedRemovals
        }
    }
}

Before someone says anything about it, I have to tell you why I did not use a switch type for -Recurse and -Force parameters, and it is because the function is feed from .csv file with data, and I did not find a elegant way to pass string value to a switch parameter.


texts:
The program was to turn an integer into exact change and uses a bunch of if statements.

Are there steps a beginner like me can do to remove some or is it just how it will be? I can't find anything on it. At least I'm not sure as I'm still in the basic course.

The program is turned in and was fine and this would be for my personal use. I know I may learn this in my classes in time, but I find more direct answers to help more.

change = int(input('')) # receive input from the user
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                               #
# This code it so provide exact change using the least amount of coins possible #
#                         COMPUTER SCIENCE 161A                                 #
#                                                                               #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if change > 0:                          # checks if there is change to provide coins
    if change >= 100:                   #checks if the amount is greater or equal to 100
        if (change // 100) != 0:        # this is to check if there is change at this point
            if (change // 100) > 1:     # provide the plural if more than 1
                print('{} Dollars'.format(change // 100))
                change = (change % 100)
            else:
                print('{} Dollar'.format(change // 100)) # prints the dollar amount without a float
                change = (change % 100) # this leaves the remainder after calculating the amount of change
        else:                           # if there is no change do this
            change = (change % 100)     # if there no change here there will be no output
    if change <= 99:                    #checks if the amount is lower or equal to 99
        if (change // 25) != 0:         # this is to check if there is change at this point
            if (change // 25) > 1:
                print('{} Quarters'.format(change // 25))
                change = (change % 25)
            else:
                print('{} Quarter'.format(change // 25))
                change = (change % 25)
        else:
            change = (change % 25)
    if change <= 24:                    #checks if the amount is lower or equal to 24
        if (change // 10) != 0:         # this is to check if there is change at this point
            if (change // 10) > 1:
                print('{} Dimes'.format(change // 10))
                change = (change % 10)
            else:
                print('{} Dime'.format(change // 10))
                change = (change % 10)
        else:
            change = (change % 10)
    if change <= 9:                     #checks if the amount is lower or equal to 9
        if (change // 5) != 0:          # this is to check if there is change at this point
            if (change // 5) > 1:
                print('{} Nickels'.format(change // 5))
                change = (change % 5)
            else:
                print('{} Nickel'.format(change // 5))
                change = (change % 5)
        else:
            change = (change % 5)
    if change <= 4:                     #checks if the amount is lower or equal to 4
        if (change // 1) != 0:          # this is to check if there is change at this point
            if (change // 1) > 1:
                print('{} Pennies'.format(change // 1))
            else:
                print('{} Penny'.format(change // 1))
else:
    print('No change')                  # tells the user to fuck off if there is nothing to convert


texts: Functional composition of member function predicates

texts:
In C++11, it is en vogue to use small lambda expressions to produce ad-hoc predicates. However, sometimes it's fun to create predicates in a functional, "point-free" way. That way, no function bodies need to be inspected, the code is mildly self-documenting, and it's a great icebreaker at parties.

Suppose I have a std::vector<std::vector<int>> v, and I want to remove all the empty inner vectors. The lambda-style remove_if call might look like this:

std::remove_if(v.begin(),
               v.end(),
               [](std::vector<int> const & w) -> bool { return w.empty(); });

This is verbose and redundant. The point-free approach uses std::mem_fn:

std::remove_if(v.begin(),
               v.end(),
               std::mem_fn(&std::vector<int>::empty));

This works fine. But now the problem: Suppose I want to further compose this predicate, say by negating it. In the lambda this would be a trivial change. But for the functional notation, we would like to use the library function std::not1 to produce a unary_negate wrapper.

However, the obvious std::not1(std::mem_fn(&std::vector<int>::empty)) does not compile. The problem appears to be that the result type of std::mem_fn defines its argument_type member type as a pointer to the class, not a reference; cf. 20.8.10/2:

  The simple call wrapper shall define two nested types named argument_type and result_type as synonyms for cv T* and Ret, respectively, when pm is a pointer to member function with cv-qualifier cv and taking no arguments, where Ret is pm’s return type.

This breaks the composability with std::not1.

I have written this type mangling work-around which strips the unwanted pointer:

#include <type_traits>

template <typename T>
struct result_type_mangler : T
{
    using argument_type = typename std::remove_pointer<typename T::argument_type>::type;
    result_type_mangler(T t) : T(t) { }
};

template <typename T>
result_type_mangler<T> mangle(T t)
{
    return result_type_mangler<T>(t);
}

Now I can compose the predicates:

std::not1(mangle(std::mem_fn(&std::vector<int>::empty)))

Is this a legitimate work-around? Can member function predicates be composed in an easier way? And why is the member function wrapper's argument_type defined in such a weird way?


texts:
Challenge:

  Write a program which determines the Mth to last element in a list.

Specifications:

  The first argument is a path to a file.
  The file contains series of space delimited characters
  followed by an integer.

  The integer represents an index in the list (1-based), one per line.
  Print out the Mth element from the end of the list, one per line.

  If the index is larger than the number of elements in the list,
  ignore that input.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MToLast {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            retrieveAndPrintMToLast(input.nextLine());
        }
    }

    private static void retrieveAndPrintMToLast(String line) {
        int targetIndex = Integer.parseInt(line.replaceAll("\\D", ""));
        String sanitized = line.replaceAll("[^a-zA-Z]", "");
        int limit = sanitized.length();

        if (targetIndex <= limit) {
            System.out.println(sanitized.charAt(limit - targetIndex));
        }
    }
}

This passes my tests, I tried to account for some edge cases, is there anything I missed or something I can improve?

For anyone interested, this challenge, and many others like it are available here.


texts: Redirect to previous page using Passport Facebook strategy in Express

texts:
Somehow, I couldn't redirect the user back after its authentication. I was using successReturnToOrRedirect property, but it kept sending it back to /. I checked req.session.returnTo and req.path and both of them have / as a value, even though I was calling /auth/facebook from a different page.

This was my first code:

 router.get('/auth/facebook', passport.authenticate('facebook', {scope: ['email', 'public_profile', 'user_friends']}));

router.get('/auth/facebook/callback',

      passport.authenticate('facebook', { successReturnToOrRedirect: '/',
                                          failureRedirect: '/' })

    );

            Continuar con  facebook

Now I'm using a middleware that I wrote that stores req.query in req.session. It seems to work pretty fine, however I'm not sure if it's a clean solution:

function checkUrl (req, res, next){
  req.session.Redirect = req.query.q;
  next();
};

router.get('/auth/facebook',checkUrl, passport.authenticate('facebook', {scope: ['email', 'public_profile', 'user_friends']}));

router.get('/auth/facebook/callback', passport.authenticate('facebook', {failureRedirect: '/' }), function (req, res) {
        res.redirect(req.session.Redirect || '/');
    }

    );

                Continuar con  facebook


texts: Simple simulation of animals eating other animals

texts:
I was given the exercise of refactoring the following code, thus ensuring it was following the SOLID design principles. It refers to an Animal Park, where there are a couple of different species of animals, and it defines the rules in which these animals can eat other animals. The Animal Park class processes a polymorphic array of the represented animals.

    public abstract class Animal
    {
        public Size Size { get; set; }
        public bool IsDead { get; set; }

        public Animal(Size size)
        {
            this.Size = size;
            this.IsDead = false;
        }

        public abstract void Eat(Animal obj);
    }

    public enum Size
    {
        Small,
        Medium,
        Big
    };

    public class Lion : Animal
    {
        public Lion(Size size) : base(size)
        {
        }

        public override void Eat(Animal animal)
        {
            if (animal is Lion && this.Size > animal.Size)
            {
                animal.IsDead = true;
            }

            if (animal is Hyena && this.Size >= animal.Size)
            {
                animal.IsDead = true;
            }
        }
    }

    public class Hyena : Animal
    {
        public Hyena(Size size) : base(size)
        {
        }

        public override void Eat(Animal animal)
        {
            if (animal is Hyena && this.Size > animal.Size)
            {
                animal.IsDead = true;
            }
        }
    }

    public static class AnimalPark
    {
        public static void Process(IList<Animal> animals)
        {
            int length = animals.Count;
            for (int i = 1; i < length; i++)
            {
                animals[i - 1].Eat(animals[i]);
            }
        }
    }

The code above breaks the Open/Closed Principle because every time I would need to add a new animal, I would not be able to do it just by extending the existing classes or by adding new ones: I would have to modify the existing classes. But I am struggling a lot to fix it properly. I came up with a solution (below), but not only I rely on Reflection, which I think can be avoided, it won't work in the cases where the Eat() method is not implemented, thus ending calling the Eat() method in the base class in a loop.

public interface IEater
{
    public void Eat(IEater obj);
}

public abstract class Animal : IEater
{
    public Size Size { get; set; }
    public bool IsDead { get; set; }

    public Animal(Size size)
    {
        this.Size = size;
        this.IsDead = false;
    }

    public void Eat(IEater obj)
    {
        if ( this.IsDead )
        {
            return;
        }
        var method = this.GetType().GetMethod("Eat", new Type[] { obj.GetType() });
        method.Invoke(this, new object[] { obj });
    }
}

public enum Size {
    Small,
    Medium,
    Big
};

public class Lion : Animal
{
    public Lion(Size size) : base(size)
    {
    }

    public void Eat(Hyena hyena)
    {
        if (this.Size >= hyena.Size)
        {
            hyena.IsDead = true;
        }
    }

    public void Eat(Lion lion)
    {
        if (this.Size > lion.Size)
        {
            lion.IsDead = true;
        }
    }
}

public class Hyena : Animal
{
    public Hyena(Size size) : base(size)
    {
    }

    public void Eat(Hyena hyena)
    {
        if (this.Size > hyena.Size)
        {
            hyena.IsDead = true;
        }
    }
}

public static class AnimalPark
{
    public static void Process(IList<IEater> animals)
    {
        int length = animals.Count;
        for(int i=1; i<length; i++)
        {
            animals[i - 1].Eat(animals[i]);
        }
    }
}

What are your thoughts on my solution? How would you handle this case?


texts:
The challenge:

  You managed to send your friend to queue for tickets in your stead, but there is a catch: he will get there only if you tell him how much that is going to take. And everybody can only take one ticket at a time, then they go back in the last position of the queue if they need more (or go home if they are fine).

  Each ticket takes one minutes to emit, the queue is well disciplined, Brit-style, and so it moves smoothly, with no waste of time.

  You will be given an array/list/vector with all the people queuing and the initial position of your buddy, so for example, knowing that your friend is in the third position (that we will consider equal to the index, 2: he is the guy that wants 3 tickets!) and the initial queue is [2, 5, 3, 4, 6].

  The first dude gets his ticket and the queue goes now like this [5, 3, 4, 6, 1], then [3, 4, 6, 1, 4] and so on. In the end, our buddy will be queuing for 12 minutes, true story!

  Build a function to compute it, resting assured that only positive integers are going to be there and you will be always given a valid index; but we also want to go to pretty popular events, so be ready for big queues with people getting plenty of tickets.

My code:

def queue(queuers,pos):
    minutes = 0
    while 1:
        minutes += 1
        queuers[0] -= 1
        if queuers[0] > 0:
            queuers.append(queuers[0])
        elif queuers[pos] == 0:
            break
        queuers.pop(0)
        if pos > 0:
            pos -= 1
        else:
            pos = len(queuers)-1
        queuers = queuers[:]
    return minutes

print(queue([2, 5, 3, 6, 4], 0))

pythonic code*:

def queue(queuers,pos):
    return sum(min(queuer, queuers[pos] - (place > pos)) for place, queuer in enumerate(queuers))

print(queue([2, 5, 3, 6, 4], 0))

*top voted code for the same kata, I am not the author of this

I obviously am not at that level.  How can I get there?  I understand (more or less) the pythonic one liners when I see them.  I'm just not yet at the point where I think that way from the get go.  Any suggestions?


texts:
I want to allow users to share documents (and other stuff) in a database-driven application.
I have designed the following schema to allow for this (PostgreSQL). Some of the tables like Party are skeletal for simplicity.
Diagram (minus lookup tables):

A lookup table for party types:
create table partyType(
  id int not null primary key,
  description text not null
);

insert into partyType values (1, 'Individual');
insert into partyType values (2, 'Organization');

A party is an individual or organization, such as a user or customer:
create table party(
  id serial primary key,
  type int not null,
  name text not null,

  foreign key (type) references partyType (id)
);

A party has many email addresses, and an email address can belong to multiple parties (such as "Barb and Jim Jones"):
create table emailAddress(
  id serial primary key,
  address text not null
);

create table partyEmailAddress(
  partyId int not null,
  emailAddressId int not null,

  primary key (partyId, emailAddressId),
  foreign key (partyId) references party (id),
  foreign key (emailAddressId) references emailAddress (id)
);

An item can be private or explicitly shared, or public but unlisted, or public and listed:
create table visibilityType(
  id int not null primary key,
  description text not null
);

insert into visibilityType values (1, 'Private / Explicit');
insert into visibilityType values (2, 'Public Unlisted');
insert into visibilityType values (3, 'Public Listed');

Someone with whom you share an item can be a viewer, commenter (can view too), or editor:
create table sharingRoleType(
  id int not null primary key,
  description text not null
);

insert into sharingRoleType values (1, 'Viewer');
insert into sharingRoleType values (2, 'Commenter');
insert into sharingRoleType values (3, 'Editor');

An item is the thing that you are sharing (this will be an actual type like Document later):
create table item(
  id serial primary key,
  ownerId int not null,
  visibilityType int not null default 1,
  publicRoleType int not null default 1 comment 'the role, if the item is public',
  onlyOwnerCanChangePermissions boolean not null default true,

  foreign key (ownerId) references party (id),
  foreign key (visibilityType) references visibilityType (id)
  foreign key (publicRoleType) references sharingRoleType (id)
);

Do you have a more succinct name than onlyOwnerCanChangePermissions? In gdocs, either only the owner can change permissions, or you can allow other editors to change permissions and add other users.
The below allows an item to be shared with many, and for a party (via their email) to have many items shared with it.
create table itemShare(
  itemId int not null,
  emailAddressId int not null,
  roleType int not null default 1,

  primary key (itemId, emailAddressId),
  foreign key (itemId) references item (id),
  foreign key (emailAddressId) references emailAddress (id),
  foreign key (roleType) references sharingRoleType (id)
);

Should item.ownerId be removed from item and added as a role type, and be added as an "automatic" itemShare?  It would be easier to query for all docs that a user has access to this way.

Is item.publicRoleType correct, seeing as it's only used if the item is public?  It seems somewhat denormalized.  I could move visibilityType to itemShare, get rid of publicRoleType, and make email addy nullable on itemShare.

Alternative schema - improved?

(source: snag.gy)


texts: Project Euler 1 (sum of multiples of 3 or 5 under 1000)

texts:
I solved this a while ago. In the moment I solved it I was learning Scheme and, well, I still am. I'm not looking at the best solution (I searched for it and coded it already, in Python), what I want is to improve this code, maintaining the same (brute) approach, so I can learn some best practices and tips in Scheme. Maybe there are some suggestions on how I wrote the routines, for example.

#lang racket
(define (check x) (or (= (modulo x 3) 0)
                      (= (modulo x 5) 0)))

(define (count-check x) (if (check x)
                            x
                            0))

(define (sum-multiples-rec actual limit acc) (if (< actual limit)
                                                 (sum-multiples-rec (+ actual 1) limit (+ (count-check actual) acc))
                                                 acc))

(define (sum-multiples lower-limit upper-limit) (sum-multiples-rec lower-limit upper-limit 0))

(sum-multiples 0 1000)


texts:
I know a lot about Java, PHP and stuff, but I'm fairly new to ruby.

I've written this script to look into the current working directory, get two parameters from the command line and then resize and rename all jpegs it can find.

To all rubyists, what could I have done better to make things ruby-ish?

require "rmagick"
require "readline"

CWD = Dir.pwd
MAX_DIM = ARGV[0]
PREFIX = ARGV[1]

puts "cwd: #{CWD}"
puts "max dimension: #{MAX_DIM}"
puts "prefix: #{PREFIX}"

read = Readline.readline "continue Y/n: "

exit if read.start_with? "n"

i = 1
Dir.foreach(CWD) do |file|
    next if file == "." or file == ".."
    next if !file.end_with? "jpg" and !file.end_with? "JPG"

    img = Magick::Image.read(file).first
    resized = img.resize_to_fit MAX_DIM
    newpath = CWD + "/" + PREFIX.sub("$", i.to_s) + ".jpg"

    resized.write(newpath) do
        self.quality = 80
    end

    File.delete file

    i = i + 1
    img.destroy!
    resized.destroy!
end


texts:
This is a simple Rock - Paper - Scissor game. I'm trying to find a better way to write the algorithm and keeping the scoreboard.

#!/usr/bin/python
#
import random
import os
import json
import pprint
#-------------------------------------------------#
def main():
    user, sys = 0, 0
    name = os.getlogin()
    while True:
        dictionary  = {1:'Rock', 2:'Paper', 3:'Scissors'}
        sysChoice   = random.choice(dictionary.keys())
        try:
            userChoice  = int(raw_input("Select One [1:Rock, 2:Paper, 3:Scissors, 0:Exit] : "))
            if (userChoice in (1,2,3)):
                print "Computer Choice is   : ", sysChoice,  dictionary[sysChoice]
                print "Your Choice is       : ", userChoice, dictionary[userChoice]
                result = rockPaperScissors(sysChoice, userChoice)
                print "Result               : ", result
                if (result == 'Win'):
                    user    = user + 1
                    sys     = 0
                    scoreBoard(user, sys, name)
                elif (result == 'Lose'):
                    user    = 0
                    sys     = sys + 1
                    scoreBoard(user, sys, name)
                else:
                    sys, user = 0, 0
                    scoreBoard(user, sys, name)
            elif(userChoice == 0):
                topScore()
                break
            else:
                continue
        except ValueError:
            continue
#-------------------------------------------------#
def rockPaperScissors (a, b):
    if ((a) % 3 + 1 == b):
        return "Win";
    elif ((b) % 3 + 1 == a):
        return "Lose"
    else:
        return "Draw"
#-------------------------------------------------#
def scoreBoard(u, s, name):
    if (os.path.isfile("score.json")):
        jsonFile = open("score.json", "r")
        data     = json.load(jsonFile)
        jsonFile.close()
        if name in data:
            print "Current Score        : ", u, s
            print "Top Score            : ", data[name]["user"], data[name]["sys"]
            if (u > (data[name]["user"])):
                data[name]["user"] = u
            if (s > (data[name]["sys"])):
                data[name]["sys"] = s
        else:
            data.update({name:{'user':0,'sys':0}})
        jsonFile = open("score.json", "w+")
        json.dump(data, jsonFile, indent=4)
        jsonFile.close()
    else:
        data = {name:{"user":0, "sys":0}}
        jsonFile = open("score.json", "w")
        json.dump(data, jsonFile, indent=4)
        jsonFile.close()
        os.chmod("score.json", 0666)
#-------------------------------------------------#
def topScore():
    if (os.path.isfile("score.json")):
        jsonFile = open("score.json", "r")
        data     = json.load(jsonFile)
        jsonFile.close()
        dicts = [{k: v} for (k,v) in data.items()]
        dicts.sort(key=lambda d: (d.values()[0]['user'], d.values()[0]['sys'],))
        dicts.reverse()
        print "Top Score : "
        for item in dicts:
            for key in item:
                print '{0:<10} {1:>2} {2:>2}'.format(key, item[key]['user'], item[key]['sys'])
#-------------------------------------------------#
if __name__ == '__main__':main()
#-------------------------------------------------#
# EOF

JSON file for keeping score:

    {
        "user1": {
            "sys": 2,
            "user": 2
        },
        "user2": {
            "sys": 3,
            "user": 3
        },
        "user3": {
            "sys": 0,
            "user": 6
        }
    }


texts: Split a string of hostnames, expand from regex, return non-duplicated names in original order

texts:
I have the following function. It can be passed a candidate_string such as the following examples:

"device1 device2"
"device1"
"device.*"
"device.region"
"device[123]

Assume that target_list contains at least the following:

['device1', 'device2', 'device3', 'device4']

I want the output of calling the function to return the following:

['device1', 'device2']
['device1']
['device1', 'device2', 'device3', 'device4']
['device.region']
['device1', 'device2', 'device3']

This code works (and I have unit tests for all of the above cases and more), I would like to know if it can be improved on.

I am passing an optional target_list into the function, only in my tests, this is so I don't have to mock that function out.

######################################################################
# sub hostname_regex_expand($host_string, @target_list)
#
# Returns a list of hostnames from $host_string.
#
# $host_string should be a space separated list of 1 or more
# host_names, or regex strings representing host_names. If the
# given host_name contains chars other than [a-zA-Z0-9-], then we
# will try to match the assumed regex against the list of names returned
# by get_hostlist. It is also possible that this is a device name
# of the form device.region or FQDN. In that case,
# we will not match anything from get_hostlist so will use the name
# as provided. If the hostname is just a hostname, then we use it as is.
######################################################################
sub hostname_regex_expand {
    my ($host_string, @target_list) = @_;

    # split by whitespace
    my @host_names = split(' ', $host_string);

    # load hostlist
    if (not @target_list) {
        @target_list = get_hostlist();
    }

    my (%host_hash, @hosts);
    foreach my $host_name (@host_names) {
        my $found = 0;
        foreach my $target (@target_list) {
            if ($target =~ m/^$host_name$/) {
                $found = 1;
                if (not $host_hash{$target}) {
                    $host_hash{$target} = 1;
                    push(@hosts, $target);
                }
            }
        }
        # If we didn't match anything in the target_list, just add this
        # host_name to the hash.
        if (not $found and not $host_hash{$host_name}) {
            push(@hosts, $host_name);
            $host_hash{$host_name} = 1;
        }
    }

    return @hosts;
}