texts:
I am building a store. When a user decides to make a purchase I need to store it in the database, but since the purchase might be of more than 1 item I'm wondering which way is the best to insert multiple rows, here are my 3 options.

I use a database object that combines PDO with PDOStatement, which is why I don't define $stmt anywhere.

The input is:

$input = array(
    'user_id' => 15,
    'food_id' => 2,
    'quantity' => 15
);

The table I'm inserting into:

 CREATE TABLE `users_foods` (
 `user_id` int(10) unsigned NOT NULL,
 `food_id` int(10) unsigned NOT NULL,
 KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Option one

$insert_data = array();

while($input['quantity']){
    $insert_data[] = array($input['user_id'], $input['food_id']);
    $input['quantity']--;
}

$db->insert('users_foods', array('user_id', 'food_id'), $insert_data);

Respectively used functions are

public function insert($table, array $columns, array $values){
    $valArr = array();
    $data = array();

    $id = 0;
    if(!empty($values)){
        if(is_array($values[0])){
            foreach($values as $k => $v){
                foreach($v as $key => $val){
                    $data[':i'.$id] = $val;
                    $v[$key] = ':i'.$id;
                    $id++;
                }
                $valArr[] = '('.join(',', $v).')';
            }
        }else{
            foreach($values as $key => $val){
                $data[':i'.$id] = $val;
                $v[$key] = ':i'.$id;
                $id++;
            }
            $valArr[] = '('.join(',', $v).')';
        }
    }

    return $this->prepare('INSERT INTO '.$table.' ('.join(',', $columns).') VALUES '.join(',', $valArr))->execute($data);
}

private function parseWhereClause(array $where, $iteration = 0, $id = 0, $sd = null){
    $sql = array();
    $data = array();

    if(count($where) == 3 && !is_array(reset($where))){
        if(is_array($where[2])){
            foreach($where[2] as $expr){
                $sql[] = ':w'.$iteration.$id;
                $data[':w'.$iteration.$id++] = $expr;
            }
            switch(strtolower($where[1])){
                case 'in': $sql = $where[0] . ' ' . $where[1] . ' ('.join(',', $sql).')'; break;
                case 'between': $sql = $where[0] . ' ' . $where[1] . ' '.join(' AND ', $sql); break;
            }
        }else{
            $sql = $where[0] . ' ' . $where[1] . ' :w'.$iteration.$id;
            $data[':w'.$iteration.$id] = $where[2];
        }
    }else{
        if(!empty($where)){
            $id = 0;

            foreach($where as $c => $expressions){
                $recur = $this->parseWhereClause($expressions, ++$iteration, $id++, $c);
                $sql[] = $recur['sql'];
                $data += $recur['data'];
            }

            $sql = '('.join(' '.$sd.' ', $sql).')';
        }else{
            $sql = '1';
        }
    }

    return array(
        'sql' => $sql,
        'data' => $data
    );
}

This method will only run one large query.

Option two

$db->prepare('INSERT INTO users_foods (user_id, food_id) VALUES (?, ?)');

while($input['quantity']){
    $db->execute(array($input['user_id'], $input['food_id']));
    $input['quantity']--;
}

not quite sure how this prepare-execute thing works under the hood though, but I believe that this will run 15 queries (because quantity is 15 in the example).

Option three

MySQL

CREATE PROCEDURE `buy_food`(IN `user_id` INT UNSIGNED, IN `food_id` INT UNSIGNED, IN `quantity` INT UNSIGNED)
BEGIN

 WHILE quantity > 0 DO
   INSERT INTO users_foods (`user_id`, `food_id`) VALUES (user_id, food_id);
   SET quantity = quantity - 1;
 END WHILE;

END

PHP

$db->prepare('CALL buy_food(?, ?, ?)')->execute(array(

    $input['user_id'],
    $input['food_id'],
    $input['quantity']

));

Which one do you think is the best way to go and why?


texts:
From the related questions here, I've found this and this answers, both of which suggest Replacing Conditional with Polymorphism, are probably what I'm looking for. However, I'm not sure if polymorphism would be a good choice for my particular case. Below are the relevant code snippets (sorry they're incomplete).

public enum Code : byte
{
    A = 0x01,
    B,
    C,

    // there's more

    a - 0x41,
    b,
    c,
    // there's more
}

The class constructor:

Code? code = null;
byte[] data = null;

public ContentHolder(Code code, byte[] data)
{
    this.code = code;
    this.data = data;
}

The switch statement:

int length = data.Length;

switch(code)
{
    case Code.A:
    case Code.E:
    case Code.F:
    case Code.G:
        QR = data[0];
        if (code == Code.F)
            // set another property
        break;
    case Code.B:
        if (length < 13)
            throw new ArgumentException();
        Index = data[0];
        break;
    case Code.C:
        int content_length = data[1];
        if (length < content_length + 30)
            throw new ArgumentException();
        Flag = (ContentFlag)data[0];
        ContentLength = data[1];
        if (Flag & ContentFlag.FlagA == ContentFlag.FlagA)
        {
            Content = new byte[content_length];
            Array.Copy(data, 2, Content, 0, content_length);
        }
        if (Flag & ContentFlag.FlagB == ContentFlag.FlagB)
        {
            // set property
        }
        // 5 more flags
        break;
    case Code.D:
        int genre = data[2];
        int genre_length = 2;
        switch (genre)
        {
            case Genre.TypeA:
                genre_length += 4;
                break;
            case Genre.TypeB:
                genre_length += 8;
                break;
            case Genre.TypeC:
                genre_length += 1;
                break;
            case Genre.TypeD:
                genre_length += 15;
                break;
        }
        if (length != genre_length)
            throw new ArgumentException();
        Array.Copy(data, 0, Target, 0, 2);
        switch (genre)
        {
            case Genre.TypeA:
                GenreID = BitConverter.ToUInt32(data, 2);
                break;
            case Genre.TypeB:
                GenreID = BitConverter.ToUInt64(data, 2);
                break;
            case Genre.TypeC:
                GenreID = data[2];
                break;
            case Genre.TypeD:
                GenreID = ASCIIEncoding.ASCII.GetString(data, 2, 15);
                break;
        }
        break;
default:
    throw new ArgumentException();

Basically, I have a class that takes in a byte array and a code. Based on the code, I am setting properties of the class. There will be more than 20 cases in total, each case may or may not have precondition verifications and may or may not be handled differently, as shown in the snippets. I feel this is already getting pretty hard to read and maintain, so I might end up with 20 implementation classes if I use polymorphism. What would the best way to refactor this?

Update

I guess my main concern is that I may have too many implementation classes if I use one for each case (except for the common ones which is about 10-15% of all cases), not to mention there'll likely be more codes added with other ways of being handled, and it doesn't make sense to not put them in one namespace...or is this not a problem at all?

Any advice is appreciated!


texts:
i am  trying to implement factory pattern for getting XML Document from server

(using javax.xml.parsers.DocumentBuilder)

I have the classes below for now, could you give your opinion ? Does the structure  make sense for this pattern?

DocumentGeneratorFactory (abstract factory)

public interface DocumentGeneratorFactory {

    public Document createDocument(String scheme, String authority,
            String path, HashMap<String, String> parameters)
            throws ParserConfigurationException, SAXException, IOException;

    public Document createDocument(String scheme, String authority,String path)
            throws ParserConfigurationException, SAXException, IOException;
}

ProductDocumentGeneratorFactory (Concreate factory)

public class ProductDocumentGeneratorFactory implements
        DocumentGeneratorFactory {

    public Document createDocument(String scheme, String authority,
            String path, HashMap<String, String> parameters)
            throws ParserConfigurationException, SAXException, IOException {

        Uri.Builder uri = new Uri.Builder();
        uri.scheme(scheme);
        uri.authority(authority);
        uri.path(path);

        Set<Map.Entry<String, String>> set = parameters.entrySet();

        for (Map.Entry<String, String> params : set) {
            uri.appendQueryParameter(params.getKey(), params.getValue());
        }

        URL url = new URL(uri.toString());

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();

        return doc;
    }

    public Document createDocument(String scheme, String authority, String path)
            throws ParserConfigurationException, SAXException, IOException {

        Uri.Builder uri = new Uri.Builder();
        uri.scheme(scheme);
        uri.authority(authority);
        uri.path(path);

        URL url = new URL(uri.toString());

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();

        return doc;

    }

}

Request (Abstract Product)

public abstract class Request {
    Document doc;
    HashMap<String, String> queryStrings;

    abstract void prepareRequest() throws ParserConfigurationException, SAXException, IOException;

}

ProductRequest (Product)

public class ProductRequest extends Request{
    ProductDocumentGeneratorFactory DocumentGeneratorFactory;
    HashMap<String, String> queryStrings;

    public ProductRequest(ProductDocumentGeneratorFactory DocumentGeneratorFactory,HashMap<String, String> queryStrings){
        this.DocumentGeneratorFactory = DocumentGeneratorFactory;
        this.queryStrings = queryStrings;
    }

    @Override
    void prepareRequest() throws ParserConfigurationException, SAXException, IOException {
        doc = this.DocumentGeneratorFactory.createDocument("http", "ip-address", "default.aspx",this.queryStrings);
    }

}


texts: Searching for log entries in SQLite that involve a particular IP subnet

texts:
This reads a huge database (SQLite) and extract any IP address similar to ip_base:

for num_db=1:10
 i=1;

%     connection to different db
db_name='C:\Users\galotibi\Documents\MATLAB\user';
obj_name='jdbc:SQLite:C:\Users\galotibi\Documents\MATLAB\user';

databases=strcat(db_name,num2str(num_db),'.db');
objects=strcat(obj_name,num2str(num_db),'.db');
conn=database(databases,'','','org.sqlite.JDBC',objects);
% ----------------------------------------------------------------------

num_row='select count(*)from IP_logs';
results=exec(conn,num_row);
results=fetch(results);
Fcount=results.Data;
count=cell2mat(Fcount);
start_a=0;
start_b=10000;
% 10000 to know how many round do we need, data is huge
row=count/start_b;
row=ceil(row);
% rounding the value
query_base='select * from IP_logs where rowid>';
wiki=cell(1,7);
for ii=1:row

        % to take 10000 record every time
        query_1=strcat(query_base, num2str(start_a+(ii-1)*start_b));
        query_2=strcat(query_1, ' and rowid<=');
        query_3=strcat(query_2, num2str(start_b*ii));

        results= exec(conn,query_3);
        results=fetch(results);

        ip_base='91.198.174.';

            for n=1:10000
                if n>size(results.Data,1)
                break;
                end;
  if strncmp(results.Data(n,2), ip_base,length(ip_base)) ||     strncmp(results.Data(n,4), ip_base,length(ip_base))

                    wiki(i,:)=results.Data(n,:);
                    i=i+1;

                end

            end;

        clear results;


texts: Vigenere Cipher - Haskell Implementation

texts:
I'm reading 'Haskell Programming from First Principles' book written by Christopher Allen and Julie Moronuki. As part of the exercises, I'm supposed to implement encryption and decryption functions for Vigenere cipher.

This is my implementation. I'm using recursion for every letter in the plain text.

shift :: (Int -> Int -> Int) -> Char -> Char -> Char
-- shift applies a arithmetic function to given characters
-- after converting it from ASCII value to Int
-- This can be used to Encrypt or Decrypt the character
shift f i k = let i' = ord i - 65
                  k' = ord k - 65
              in  chr $ ((f i' k') `mod` 26) + 65

crypt :: (Int -> Int -> Int) -> (String, Int) -> (String, Int) -> String -> String
-- crypt applies given artithmetic function and does Vigenere encryption/decryption.
-- This function moves forward on the string, encrypts the
-- current char using corresponding char in key. It maintains
-- current position of the string and key it is working on. When
-- it encounters space, it skips the en(de)cryption and doen't move forward
-- in the key. After encrypting the current char, it recursively calls
-- itself by passing next positions in string to be encrypted along with
-- position of key.
crypt cryptFunc (words', wpos) (key, kpos) cipherText
    | length words' <= wpos =  cipherText
    | otherwise =
        let c  = words' !! wpos
            c' = case c of
                    ' ' -> ' '
                    _ -> shift cryptFunc c $  key !! kpos
            kpos' = case c of
                    ' ' -> kpos `mod` (length key)
                    _   -> (kpos + 1) `mod` (length key)
            in crypt cryptFunc (words', wpos + 1) (key, kpos') (cipherText ++ [c'])

encrypt :: [Char] -> [Char] -> [Char]
encrypt i k = crypt (+) (i, 0) (k, 0) []

decrypt :: [Char] -> [Char] -> [Char]
decrypt i k = crypt (-) (i, 0) (k, 0) []

-- input = "MEET AT DAWN"
-- key = "ALLY"
-- output = "MPPR AE OYWY"

Do you think the implementation is efficient and obvious way to do it? Please tell if there are any improvements I can do.


texts:
I have built a website using HTML and CSS. Actually I wanted to learn by implementing real world examples. I have built a site like Google. The search box does not work(I actually did not wanted to go further in the form action part and also did not wanted to use any search engine) and I have not copied anything from their site. Its just an effort to learn HTML and CSS. Please have a look and review it.

CODE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>MyGoogle</title>

Web

Images

News

Translate

Books

Scholar

Gmail

        <form action="http://www.datafeedfile.com/examples/javascript_search.php" method="get">

        <input type="text" title="Search Text" accesskey="s" alt="Search Text" size="60px" maxlength="80" value="" />

      <input type="submit" value="Google Search"/>
      <input type="submit" value=" I'm Feeling Lucky">

</form>


texts: Extracting an IP address from a hosts file by hostname

texts:
I am currently working with Vagrant for the first time, and therefore also working with Ruby for the first time. I have a specific hostname and IP address I would like set for my VM, both of which are stored in my hosts file. I would like to define the hostname in my Vagrantfile, and then have it automatically pull the matching IP address out of my hosts file for me. To do so, I have written the following code in my Vagrantfile:

Vagrant.configure("2") do |config|
  hostname = "vagrantvm"
  hostfile = "/etc/hosts"

  ip_address = File.foreach(hostfile).grep(/\b#{hostname}\b/) { |m| /^([0-9\.]*)\b.*/.match(m)[1] }.first

  config.vm.network :private_network, :ip => ip_address
  config.vm.hostname = hostname
  config.vm.provision :shell, :path => "bootstrap.sh"
end

Line 5 where I am assigning ip_address works, however I am not sure if it is the right way to do it. It seems a little ugly and long. I was thinking that maybe I should not put the code block passed to grep all on the same line. Or is it even necessary to have 2 separate regexes in there? Can it be done in 1 step?

It also seems strange to me that I need to add .first on the end in order to get the IP address string out of the array returned by grep. I feel like there is a better way to do this that I am missing.


texts: Python generate custom combinations of sub lists

texts:
I'm generating a custom combination of sub lists without using itertools.

Here's what I've come up with:

input =  [[1, 2], [2, 3], [4, 3]]
output = [[1, 2, 2, 3], [1, 2, 4, 3], [2, 3, 4, 3]]

def getList():
    a = [[1, 2], [2, 3], [4, 3]]
    return(a)

c=[]                        # output list
l = len(getList())
for i in range(l):
    for j in range(i+1,l):
        a=getList()
        a[i].extend(a[j])
        c.append(a[i])

As the extend() updates the input list, I defined a function to redefine the input. Is it a recommended practice? What could be improved here?


texts: First use of std::map in factors and prime factorization program

texts:
This is from an older question of mine that I decided to revisit:

Simplifying and optimizing factors and prime factorization generator

In that question, someone suggested I use an std::map to hold the factors generated from my inputted number.  I've also decided to use it with my generated prime factorization, which also works.  Based on what I've found online, auto is one way of iterating through an std::map.  I've decided to use that since it appears that my compiler supports C++11.

Am I using std::map appropriately here, or am I developing some bad habits?  I want to develop good habits since I'm interested in using it more in the future.

#include <iostream>
#include <cstdint>
#include <map>
#include <cmath>

void displayFactors(const std::map<uint64_t, uint64_t> &factors);
void displayPrimeFactorization(const std::map<uint64_t, uint64_t> &primeFactorization);
void findFactors(uint64_t, std::map<uint64_t, uint64_t> &factors);
void findPrimeFactorization(uint64_t positiveInt, std::map<uint64_t, uint64_t> &primeFactorization);

int main()
{
    std::map<uint64_t, uint64_t> factors;
    std::map<uint64_t, uint64_t> primeFactorization;
    uint64_t positiveInt;

    std::cout << "\n\n> Positive Int: ";
    std::cin >> positiveInt;

    findFactors(positiveInt, factors);
    std::cout << "\n\n  * Factors:\n\n";
    displayFactors(factors);

    findPrimeFactorization(positiveInt, primeFactorization);
    std::cout << "\n  * Prime Factorization:\n\n      ";
    displayPrimeFactorization(primeFactorization);

    std::cout << std::endl << std::endl;
    std::cin.ignore();
    std::cin.get();
}

void displayFactors(const std::map<uint64_t, uint64_t> &factors)
{
    for (auto iter = factors.begin(); iter != factors.end(); ++iter)
    {
        std::cout << "      " << iter->first << " x " << iter->second << "\n";
    }
}

void displayPrimeFactorization(const std::map<uint64_t, uint64_t> &primeFactorization)
{
    for (auto iter = primeFactorization.begin(); iter != primeFactorization.end(); ++iter)
    {
        if (iter != primeFactorization.begin()) std::cout << " x ";
        std::cout << iter->first;
        if (iter->second > 1) std::cout << '^' << iter->second;
    }
}

void findFactors(uint64_t positiveInt, std::map<uint64_t, uint64_t> &factors)
{
    uint64_t sqrtInt = static_cast<uint64_t>(sqrt(static_cast<double long>(positiveInt)));

    for (uint64_t iter = 1; iter <= sqrtInt; ++iter)
    {
        if (positiveInt % iter == 0)
        {
            uint64_t quotient = positiveInt / iter;
            factors[iter] = quotient;
        }
    }
}

void findPrimeFactorization(uint64_t positiveInt, std::map<uint64_t, uint64_t> &primeFactorization)
{
    uint64_t divisor = 2;
    uint64_t power = 0;

    while (positiveInt != 1)
    {
        while (positiveInt % divisor == 0)
        {
            positiveInt /= divisor;
            power++;
        }

        if (power > 0)
            primeFactorization[divisor] = power;

        power = 0;
        divisor++;
    }
}


texts: Passing a form reference for accessing control in other class

texts:
I have a form and one other class that basically maintains initialization state of the form (in this case, loading data from Json file to controls in form).

My form code:

Public Class PublishDigital
    Dim init As New InitForm(Me)
    Dim jhandler As New JsonHandler(Me)
    Dim jsonPath As String
    Dim jsonTxt As String

    Private Sub PublishDigital_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        jsonPath = Application.StartupPath + "\Addons\CG_Tools\cgSave.json"
        jsonTxt = File.ReadAllText(jsonPath)
        init.Setter()
        init.JenisOrder()
        init.FinishingA3()
        init.LayoutList()
        init.SisiMuka()
        init.Imposition()
        init.Folder()
    End Sub
End Class

And on initialization class, which calls a custom function to load JSON data to specified controls in main form (with prefix "cb"):

Imports Newtonsoft.Json.Linq

Class InitForm
    Private frm As PublishDigital
    Public Sub New(ByVal parentform As PublishDigital)
        frm = parentform
    End Sub
    Public Sub Setter()
        'FillTabwithCB(ByVal frm As PublishDigital, cbdata As JArray, XOffset As Integer, YOffset As Integer, maxRow As Integer)
        JsonHandler.FillCBfromJson(frm.cb_operator, Globals.JsonObj("cgSetter"), "kode", "nama")
    End Sub
    Public Sub JenisOrder()
        JsonHandler.FillCBfromJson(frm.cb_jenisorder, Globals.JsonObj("cgJenisOrder")("katJenisOrder"), "id", "nama")
    End Sub
    Public Sub BahanUkuran()
        Dim parsedJenis = JsonHandler.ParseJsonToDictionary(Globals.JsonObj("cgJenisOrder")("dataJenisOrder"))
        JsonHandler.FillCBfromJson(frm.cb_bahan, parsedJenis(CType(frm.cb_jenisorder.SelectedValue, String)).Root, "kode", "bahan")
    End Sub
    Public Sub FinishingA3()
        JsonHandler.FillTabwithCB(frm, DirectCast(Globals.JsonObj("cgFinishing")("a3colorfn"), JArray), 7, 7, 5)
    End Sub
    Public Sub SisiMuka()
        JsonHandler.FillCBfromJson(frm.cb_sisimuka, Globals.JsonObj("cgLayout")("sisimuka"), "kode", "type")
    End Sub
    Public Sub LayoutList()
        Dim parsedJenis = JsonHandler.ParseJsonToDictionary(Globals.JsonObj("cgLayout"))
        JsonHandler.FillCBfromJson(frm.cb_layout, parsedJenis(CType(frm.cb_jenisorder.SelectedValue, String)).Root, "kode", "type")
    End Sub
    Public Sub Imposition()
        JsonHandler.FillCBfromJson(frm.cb_imposition, Globals.JsonObj("cgLayout")("imposition"), "kode", "type")
    End Sub
    Public Sub Folder()
        frm.cb_folder.Items.AddRange(Globals.TypeFolder.ToArray)
        frm.cb_folder.SelectedIndex = 0
        JsonHandler.FillCBfromJson(frm.cb_grouporder, Globals.JsonObj("cgPermanent")("kategori"))
    End Sub
End Class

These code works, but I feel like it could be improved somehow. Is this correct way to pass form controls to other classes?


texts:
I made this function to delete a directory with all its contents recursively, will it work as expected in a production environment ? is it safe ? I don't want to wake up one day with /home contents is gone :D

public static function delTree($dir) {
    if(!is_dir($dir)){return false;};

    $files = scandir($dir);if(!$files){return false;}
    $files = array_diff($files, array('.','..'));

    foreach ($files as $file) {
        (is_dir("$dir/$file")) ? SELF::delTree("$dir/$file") : unlink("$dir/$file");
    }

    return rmdir($dir);
}

Note: I use this function internally, meaning there are no client parameters like directory names is taken from the client before I call it, so there is no chance for traversal attacks, and I check the base path with another function before I call it, for example to delete a client folder I do something like this

$clientsFolderPath = $_SERVER['DOCUMENT_ROOT'] . "/../clients"
$clientFolderPath = "$clientsFolderPath/$clientId";

$realBase = realpath($clientsFolderPath);
$realClientDir = realpath($clientFolderPath);
if ( !$realBase || !$realClientDir || strpos($realClientDir, $realBase) !== 0 ){
    //error, log , and exit;
} else {
    ExtendedSystemModel::delTree($clientFolderPath);
}


texts:
My data is in this format:

  龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\n

And I want to return:

('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/')

In C I could do this in one line with sscanf, but I seem to be  f̶a̶i̶l̶i̶n̶g̶ writing code like a schoolkid with Python:

    working = line.rstrip().split(" ")
    trad, simp = working[0], working[1]
    working = " ".join(working[2:]).split("]")
    pinyin = working[0][1:]
    english = working[1][1:]
    return trad, simp, pinyin, english

Can I improve?


texts:
Kata: https://www.codewars.com/kata/linked-lists-insert-sort/train/python

Description

  Write an InsertSort() function which rearranges nodes in a linked list so they are sorted in increasing order. You can use the SortedInsert() function that you created in the "Linked Lists - Sorted Insert" kata below. The InsertSort() function takes the head of a linked list as an argument and must return the head of the linked list.

var list = 4 -> 3 -> 1 -> 2 -> null
insertSort(list) === 1 -> 2 -> 3 -> 4 -> null

  If the passed in head node is null or a single node, return null or the single node, respectively. You can assume that the head node will always be either null, a single node, or a linked list consisting of multiple nodes.

My Solution

def insert_sort(head):
    node = head
    while node:
        if node.next and (node.next.data < node.data):
            to_insert = node.next
            node.next = to_insert.next
            head = sorted_insert(head, to_insert.data)  #Inserts a node containing it's second argument at the correct position in the linked list that begins with its first argument.
            continue
        node = node.next
    return head


texts:
I'm a PHP Developer. I'm trying to learn Python. So I tried to create a simple game, a Number Guesser.

I tried to comment out as much as possible without making super obvious comments.

I also made the attempts message color to be red.

Here's my code.

# 1. Print a message about the game
# 2. Tell the user that the random number is between some numbers
# 3. Run a while loop to continue the input, break the loop when the guess is right.
# 4`. When the user guessed the number, tell them that they're right.

import random

# Simple message to the user.
print "Welcome to the Number Guesser game."
print "I have a number in my mind that's between 1-20."

number = random.randint(0, 20)

# Guess the number
# >
prompt = "> "

# Start out as 5 and then decrement it on wrong guesses.
attempts = 5

while attempts > 0:
    print "What's your guess? "

    # Simple validation
    try:
        guess = int(raw_input(prompt))
    except ValueError:
        print "Only numbers are allowed. \n"
        break

    if guess > number:
        print "Go lower."
    elif guess < number:
        print "Go higher."
    else:
        print "Nice! You've guessed it right. The number was %d." % number
        print "And you got it with %d attempts!" % attempts
        # Exit.
        break

    # Decrement the attempts each time the guess isn't right.
    attempts -= 1

    if attempts == 0:
        print "You didn't guessed it, the number was %d. You lose." % number
        # Exit the script.
        break
    # Print with the color red.
    print("\033[91m You have {} guesses left. \033[00m").format(attempts)


texts:
Since rsync lacks compression and I'm not a big fan of rdiff, I thought I'd try my own little backup script. Since I'm very inexperienced with file management in Python, I'm sure there is lot of room for improvement.

The script creates the entire folder structure within the backup folder and then creates syncs recursively for all files within the source folders. Every file above a certain threshold gets gziped  on the way.

A possible command would be:

  python3 sync.py -target MY_BACKUPFOLDER -source IMPORTANT_1 IMPORTANT_2

Please tell me what you think of the source:

""" Simple backup script which just creates the root structure in an other
folder and syncs everything which recursevely lies within one of the source
folders. For files bigger than a threshold they are first gziped."""

import argparse
import gzip
import os
import shutil
import sys

def parse_input():
    parser = argparse.ArgumentParser()
    parser.add_argument('-target', nargs=1, required=True,
                        help='Target Backup folder')
    parser.add_argument('-source', nargs='+', required=True,
                        help='Source Files to be added')
    parser.add_argument('-compress', nargs=1,  type=int,
                        help='Gzip threshold in bytes', default=[100000])

    # no input means show me the help
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    return parser.parse_args()

def size_if_newer(source, target):
    """ If newer it returns size, otherwise it returns False """

    src_stat = os.stat(source)
    try:
        target_ts = os.stat(target).st_mtime
    except FileNotFoundError:
        try:
            target_ts = os.stat(target + '.gz').st_mtime
        except FileNotFoundError:
            target_ts = 0

    # The time difference of one second is necessary since subsecond accuracy
    # of os.st_mtime is striped by copy2
    return src_stat.st_size if (src_stat.st_mtime - target_ts > 1) else False

def sync_file(source, target, compress):
    size = size_if_newer(source, target)

    if size:
        transfer_file(source, target, size > compress)

def transfer_file(source, target, compress):
    """ Either copy or compress and copies the file """

    try:
        if compress:
            with gzip.open(target + '.gz', 'wb') as target_fid:
                with open(source, 'rb') as source_fid:
                    target_fid.writelines(source_fid)
            print('Compress {}'.format(source))
        else:
            shutil.copy2(source, target)
            print('Copy {}'.format(source))
    except FileNotFoundError:
        os.makedirs(os.path.dirname(target))
        transfer_file(source, target, compress)

def sync_root(root, arg):
    target = arg.target[0]
    compress = arg.compress[0]

    for path, _, files in os.walk(root):
        for source in files:
            source = path + '/' + source
            sync_file(source, target + source, compress)

if __name__ == '__main__':
    arg = parse_input()
    print('### Start copy ####')
    for root in arg.source:
        sync_root(root, arg)
    print('### Done ###')


texts: Building a string with only two repeating characters (different code)

texts:
Context
I would like to receive feedback on my code for the question which can be seen here.
Problem
This is another C# implementation for the a function for given parameters int a, int b - both represent characters 'A' and 'B' respectively, where the function should return a string containing both characters 'A' and 'B' occurring a times and b times respectively but neither 'A' nor 'B' repeating consecutively for more than 2 times. Both values for a and b are given in a way that a string can be build using those numbers - so eg: Foo(0,3) or Foo(1,7) shall not be invoked.
eg:
Foo(3,3) returns "BBAABA" or "AABBAB"
Foo(4,1) returns "AABAA"
Foo(3,5) returns "BAABBABB" or "BBAABBAB"
Code
static string GenerateString (int a, int b)
{

    int remainingTwiceChar = a;
    int remainingOnceChar = b;

    string twiceChar = "A";
    string onceChar = "B";

    if(b>a)
    {
        twiceChar = "B";
        onceChar = "A";
        remainingTwiceChar = b;
        remainingOnceChar = a;
    }

    int mod = (a + b) % 3;
    int div = (a + b) / 3;
    StringBuilder sb = new StringBuilder(a + b);

    for(int x = 0; x < div ; x++)
    {
        if (remainingTwiceChar >= 2 && remainingOnceChar >= 1)
        {
            sb.Append(twiceChar);
            sb.Append(twiceChar);
            sb.Append(onceChar);
            remainingTwiceChar -= 2;
            remainingOnceChar--;
        }
        else
        {
            sb.Append(twiceChar);
            sb.Append(onceChar);
            sb.Append(onceChar);
        }
    }

    for (int x = 0; x < mod; x++)
    {
        if (remainingOnceChar > 0)
        {
            sb.Append(onceChar);
            remainingOnceChar--;
        }
        if (remainingTwiceChar > 0)
        {
            sb.Append(twiceChar);
            remainingTwiceChar--;
        }
    }

    return sb.ToString();
}

Even though the implementation in the original question has a bug, my code does not have it. I attended this question a code testing platform. I guess, the code works (even it does not have the flaw that the code in the question has), however the testing platform gave only 33.33% marks to my question. Can anybody suggest me what I am doing wrong.


texts: Usage of static block vs. direct static variable initialization

texts:
Suppose, I have a data access layer class, where I want to specify database connection parameters. Usually, I do it as static variables and initialize it right after definition, e.g. see DB_NAME variable case.

Performing code review, I paid attention that sometimes such logic is implemented with a static block, e.g. see DB_HOST variable case.

public class DAL {

    private static final String DB_NAME = "MY_DB";
    private static final String DB_USER = "DB_ADMIN";
    private static final String DB_HOST;

    static {
        DB_HOST = "127.0.0.1";
    }
}

The questions:

Is there any benefit from using a static block in such specific scenario?
When should I prefer to use a static block over a regular static variable initialization?

P.S. I found a similar question on SO: Why use static blocks over initializing instance variables directly?, but if you have something to add, you're welcome.


texts:
I can recently coded an emulation system and in this project I have a PacketHandler for each player connected to a socket server, and each player receives packets (data) from the client application.

Can someone please let me know if this code can be improved in any way? I will post the code below for the PlayerPacketHandler class, if you need any other classes that are used in this class let me know and I can add them.

Thanks.

How is ProcessPacketData called?

private void IncomingPacket(IAsyncResult iAr)
{
    try
    {
        var bytesReceived = _playerSocket.EndReceive(iAr);

        if (bytesReceived == 0)
        {
            Dispose();
            return;
        }

        var packet = new byte[bytesReceived];
        Array.Copy(_buffer, packet, bytesReceived);
        _playerPacketHandler.ProcessPacketData(packet);
    }
    catch (Exception)
    {
        Dispose();
    }
    finally
    {
        try
        {
            _playerSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, IncomingPacket, _playerSocket);
        }
        catch
        {
            Dispose();
        }
    }
}

The class I am asking to be reviewed:

using System;
using System.IO;
using Sahara.Core.Logging;

namespace Sahara.Base.Game.Players
{
    internal class PlayerPacketHandler
    {
        private readonly Player _player;
        private readonly LogManager _logManager;
        private bool _decryptedData;
        private byte[] _dataReceived;
        private bool _dataCompleted;

        public PlayerPacketHandler(Player player)
        {
            _player = player;
            _logManager = Sahara.GetServer().GetLogManager();
        }

        public void ProcessPacketData(byte[] data)
        {
            try
            {
                if (_player.RC4Client != null && !_decryptedData)
                {
                    _player.RC4Client.Decrypt(ref data);
                    _decryptedData = true;
                }

                if (_dataCompleted)
                {
                    byte[] fullDataRcv = new byte[_dataReceived.Length + data.Length];
                    Buffer.BlockCopy(_dataReceived, 0, fullDataRcv, 0, _dataReceived.Length);
                    Buffer.BlockCopy(data, 0, fullDataRcv, _dataReceived.Length, data.Length);

                    ProcessPacketData(fullDataRcv);
                    _dataCompleted = false;

                    return;
                }

                using (var reader = new BinaryReader(new MemoryStream(data)))
                {
                    if (data.Length < 4)
                        return;

                    int messageLength = HabboEncoding.DecodeInt32(reader.ReadBytes(4));

                    if ((reader.BaseStream.Length - 4) < messageLength)
                    {
                        _dataReceived = data;
                        _dataCompleted = true;
                        return;
                    }

                    if (messageLength < 0 || messageLength > 5120)
                        return;

                    var packet = reader.ReadBytes(messageLength);

                    using (var binaryReader = new BinaryReader(new MemoryStream(packet)))
                    {
                        int packetHeader = HabboEncoding.DecodeInt16(binaryReader.ReadBytes(2));

                        byte[] Content = new byte[packet.Length - 2];
                        Buffer.BlockCopy(packet, 2, Content, 0, packet.Length - 2);

                        IncomingPacket clientPacket = new IncomingPacket(packetHeader, Content);
                        onNewPacket.Invoke(clientPacket);

                        _decryptedData = false;
                    }
                }
            }
            catch (Exception exception)
            {
                var method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                _logManager.Log("Error in " + method + ": " + exception.Message, LogType.Error);
                _logManager.Log(exception.StackTrace, LogType.Error);
            }
        }
    }
}


texts: Find index of an object with a specific value stored in an array

texts:
I am using the following code in order to retrieve the index for an object stored in a JavaScript array.

Scripts works fine, but I would like your opinion regarding performance.

Also  would like to know also if using [].map() could be more appropriate of [].some().

http://jsbin.com/nasiyiyavi/1/

var data = [{ id: 3 }, { id: 4 }, { id: 1 }, { id: 0 }, { id: 2 }];

function findIndexInData(optionsArg) {
    var options = {
        data: optionsArg.data,
        where: optionsArg.where,
        what: optionsArg.what
    },
    result = -1;
    options.data.some(function (item, i) {
        if (item[options.where] === options.what) {
            result = i;
            return true;
        }
    });
    return result;
}
alert(findIndexInData({ data: data, where: 'id', what: 2 }));


texts: Stored procedure to describe the reason that a particular employee is unsuitable for a particular task

texts:
I used the following Stack Overflow questions as references for writing this code:

Select columns from result set of stored procedure
What is the equivalent of String.Join on TSQL?

The idea behind my stored procedure is to give an explanation of why a particular worker is unsuitable to care for a particular patient under specific circumstances. For example, you obviously can't assign an RN to do physical therapy visits.

I have a Disciplines table, which has a structure that's kind of like this:

--------------------------------------------
| Discipline | Discipline ID | Other Field |
--------------------------------------------
| RN         | 1             | 2           |
--------------------------------------------
| PT         | 2             | 5           |
--------------------------------------------
| CNA        | 3             | 7           |
--------------------------------------------
| MD         | 4             | 23           |
--------------------------------------------

Obviously this is hypothetical data and I've modified the column names a bit (this is mostly for illustration).

What I want is to retrieve the list of Disciplines as a single string and concatenate it with an existing string. Workers might have several disciplines. (This is determined in a table that's not shown). An example of one possible output would be The worker does not have the appropriate disciplines. They have the following discipline(s): RN, PT (if that employee is both a RN and a PT - not too likely, obviously, but let's assume that they are).

I haven't included the entire stored procedure, but this is pretty representative and is the main part that I'm looking for a critique of:

 -- @IsAppropriate is a bit type
 SELECT @IsAppropriate = dbo.fnCheckIfWorkerHasDisciplineForSvc(@BusinessUnitID, @WorkerID, @ServiceTypeID, GetDate(), GetDate())

IF @IsAppropriate = 0
BEGIN
    SET @output = 'The worker does not have the appropriate disciplines. They have the following discipline(s):'

    CREATE TABLE #Result
    (
            Discipline nvarchar(max),
            IsPrimary bit,
            EffectiveDate DateTime,
            EndDate DateTime
    )

            -- Get which discipline a particular worker practices (PT, MD, RN, etc.)
    INSERT #Result EXEC spGetWorkerDiscipline @WorkerID

    DECLARE @disciplines nvarchar(max);

            -- Get them as a nice list
    SELECT @disciplines = coalesce(@disciplines + ', ', '') + Discipline from #Result

    SET @output = @output + @disciplines

    DROP TABLE #Result

            -- Skip the rest of the stored procedure
            -- See comments below - is this a terrible thing to do?
    GOTO eom
END

-- Check some other reasons that the worker might be inappropriate...

-- Return the resulting string to the user
eom:
select @output

I verified that the query does, in fact, work. However, I have a few concerns:

Is using GOTO like that in SQL really terrible? If so, is there a better way to accomplish the same thing? I'm almost embarrassed to post code that contains it, since I'm aware that, in general, GOTO is considered harmful.
Will I take a performance hit for creating and dropping a temporary table like that? Could some of the other suggestions in the linked posts be a better choice here?
Am I inappropriately mixing my architectural layers by creating a string for use on the front end in the database like this? (I'm using ASP.NET Web Forms).


texts:
Update: revised code.

I work at a Starbucks and one of the things that screams at me week after week for automation is the tedious calculation of the tip distribution. So here is my attempt to provide a simple tool for this. (Previous attempt required special software and special instruction to explain how it works.)

It has fields for inputting the number of hours for each partner and the amount of money to be dispersed. Clicking "calculate" produces the output with blank lines to help orient the output with the input rows.

As a javascript noob, I feel certain I've done some stupids in here I can learn from.

    <title>Tip Calculator</title>

Tip Calculator

    Hours:

        <input type=button value="add row" onclick="add_row()">
        Dividend: <input id=dividend type=text size=5 maxlength=5>
        <input type=button value="calculate" onclick="calc()">

    &nbsp;


texts:
I'm wondering if there is a faster way to do the following code, which works fine. It needs to be applied to every row of the DataFrame df. class_dct contains a different NLTK NaiveBayes classifier for each of 9 regions.

for region in regions:
    new_app=[]
    for title in df.booktitle:
        nlp_genre=class_dct['Classif_%s'% region].classify(features(title))
        new_app.append((title,region,nlp_genre))


texts:
My current code takes 2.7-4.5 seconds to complete, is there any way to make it faster?

I need to return a list of the income in all days in a month.  My idea was to loop through the days of one month, but this takes so long should not be a hard task.

What can I improve?  I was thinking on GroupBy a date range.

    public IEnumerable<GetSellInfo> GetSellInvoices(int month, int year, int offset)
{
    DateTime startDate = new DateTime(year, month, 1, 0, 0, 0).AddMinutes(offset);
    DateTime endDate = new DateTime(year, month, DateTime.DaysInMonth(year, month) , 23, 59, 59, 999).AddMinutes(offset);
    DateTime utc = DateTime.UtcNow.AddMinutes(-offset);
    DateTime maxDate = new DateTime(utc.Year, utc.Month, utc.Day, 23, 59, 59, 999).AddMinutes(offset);

    if (endDate > maxDate) endDate = maxDate;

    var invoices =
        db.SellInvoices.Where(invoice => invoice.Date >= startDate && invoice.Date <= endDate);

    List<GetSellInfo> result = new List<GetSellInfo>();
    DateTime counterDate = startDate;

    while (counterDate <= endDate)
    {
        DateTime iDate = new DateTime(counterDate.Year, counterDate.Month, counterDate.Day, 0, 0, 0).AddMinutes(offset);
        DateTime jDate = new DateTime(counterDate.Year, counterDate.Month, counterDate.Day, 23, 59, 59, 99).AddMinutes(offset);
        var dayInvoices = invoices.Where(invoice => invoice.Date >= iDate && invoice.Date <= jDate);

        decimal cfCard = dayInvoices.Select(x => x.CardSettlementSum).DefaultIfEmpty(0).Sum();
        decimal cfCash = dayInvoices.Select(x => x.CashSettlementSum).DefaultIfEmpty(0).Sum();
        decimal depositsCard = dayInvoices.Select(x => x.CardDepositSum).DefaultIfEmpty(0).Sum();
        decimal depositsCash = dayInvoices.Select(x => x.CashDepositSum).DefaultIfEmpty(0).Sum();
        decimal notSyledsDecimal = dayInvoices.Select(x => x.NotStyledsSum).DefaultIfEmpty(0).Sum();
        decimal discountsDecimal = dayInvoices.Select(x => x.DiscountsSum).DefaultIfEmpty(0).Sum();

        result.Add(new GetSellInfo
        {
            Date = counterDate,
            TotalCard = cfCard + depositsCard,
            TotalCash = cfCash + depositsCash,
            DepositsInCard = depositsCard,
            DepositsInCash = depositsCash,
            NotStyleds = notSyledsDecimal,
            Discounts = discountsDecimal,
            Returns = cfCard - depositsCard + cfCash + depositsCash,
            Total = cfCard + depositsCard + cfCash + depositsCash,
        });
        counterDate = counterDate.AddDays(1);
    }

    return result;
}


texts:
This is the current Makefile that I use with my C projects.  Here is what I would like to be reviewed:

Reusability - is this Makefile easy to use for multiple separate projects with minimal modification?
Organization - is this Makefile organized in a logical and readable way?
Dynamics - are there Make features (or compiler options/warnings) that I am not taking advantage of that could make my Makefile more powerful?
Miscellaneous - what other things could I improve?

CXX = g++-4.9
CC = gcc-4.9
DOXYGEN = doxygen
CFLAGS = -fdiagnostics-color=always -std=gnu11 -s -c -g3 -O3 -time
WARNINGS = -Werror -Wall -Wextra -pedantic-errors -Wformat=2 -Wno-import -Wimplicit -Wmain -Wchar-subscripts -Wsequence-point -Wmissing-braces -Wparentheses -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused
LDFLAGS =
LIBRARIES = -lcurl
SOURCES = main.c test.c
OBJECTS = $(SOURCES:.c=.o)
EXECUTABLE = test

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@ $(LIBRARIES)

debug: CFLAGS += -DDEBUG -g
debug: $(SOURCES) $(EXECUTABLE)

.c.o:
    $(CC) $< -o $@ $(CFLAGS) $(WARNINGS)

.PHONY: doc clean
doc:
    $(DOXYGEN) doxygen.config
clean:
    rm -rf $(EXECUTABLE) $(OBJECTS)


texts: Determining if the mouse is on top of a box

texts:
I have 4 picture boxes and a collision detection to see if my mouse is on top of any of them, but I have to run the same code 4 different times, but just changing the name. Also, the else if statements can be regular if statements.

PictureBox display = sender as PictureBox;
Point drop = PointToClient(Cursor.Position);

if (((displayCollision(drop, pbDisplay1)) == true) && (display != pbDisplay1))
{
    display.Location = pbDisplay1.Location;
    display.Size = pbDisplay1.Size;

    pbDisplay1.Location = defaultLocation;
    pbDisplay1.Size = defaultSize;
}
else if (((displayCollision(drop, pbDisplay2)) == true) && (display != pbDisplay2))
{
    display.Location = pbDisplay2.Location;
    display.Size = pbDisplay2.Size;

    pbDisplay2.Location = defaultLocation;
    pbDisplay2.Size = defaultSize;
}
else if (((displayCollision(drop, pbDisplay3)) == true) && (display != pbDisplay3))
{
    display.Location = pbDisplay3.Location;
    display.Size = pbDisplay3.Size;

    pbDisplay3.Location = defaultLocation;
    pbDisplay3.Size = defaultSize;
}
else if (((displayCollision(drop, pbDisplay4)) == true) && (display != pbDisplay4))
{
    display.Location = pbDisplay4.Location;
    display.Size = pbDisplay4.Size;

    pbDisplay4.Location = defaultLocation;
    pbDisplay4.Size = defaultSize;
}
else
{
    display.Location = defaultLocation;
}


texts: Testing whether a given string has unique characters

texts:
Here is my code which tests whether a given string has unique characters. The function is_unique which does a linear search for each character in the string is \$O(n^2)\$ (if I am right). Is there any more efficient way of doing the same with more efficient DS that takes less time (or space)?

I know with some library functions it can be done more easily, such as len(set(strr)) == len(strr)

def is_unique(strr):
    """Without using any library functions"""
    def _contains(string, char):
        for c in string:
            if c == char: return True
        return False

    for index in range(len(strr)):
        if _contains(strr[:index], strr[index]): return False
    return True

def main():
    for string in ['abc', 'abcc', 'aabc']:
        print is_unique(string)

if __name__ == '__main__':
    main()

Edit 1 (Adds constraints)

Don't change the original string and memory used should be \$O(1)\$ hence sorting the string may not be the valid solution.


texts:
I use Ruby 1.8.7.  I have a method which selects records according to the item that I pass to the method.

In my opinion, the code is not DRY.  Could somebody offer suggestions on refactoring it to make it shorter?

def get_record (id,item)
  case item
   when "category"
      @temp = Category.find(id)
   when "status"
      @temp = Status.find(id)
   when "industry"
     @temp = Industry.find(id)
   end
 return @temp.name if @temp
end


texts: Android app with config and customization classes

texts:
I have an Android app with three different Activity classes. Each of the Activities uses and changes config and user-customization data stored in a wrapped SharedPreferences. The code could stand some refactoring, so I'm thinking that rather than have each Activity instantiate the SharedPreferences by calling PreferenceManager.getDefault... in their constructors, I can make a 'base' abstract Activity to serve as a parent class and then have each of the Activities subclass the abstract Activity and wrap the SharedPreferences in an inner class of the abstract Activity, like so:

public abstract class AbstractBaseActivity extends AppCompatActivity
{
    private static AppPrefs instance;

    private interface PrefKeys
    {
        String KEY_BOOL_SETUP =  "KEY_BOOL_SETUP";
        String KEY_STR_USER_EMAIL = "KEY_STR_USER_EMAIL";
        String KEY_LONG_LAST_EMAIL_SENT = "KEY_LONG_LAST_USE";
        //...remaining keys omitted...//
    }

public static class AppPrefs implements PrefKeys
{
  private SharedPreferences prefs;
  private String no_email;

        private AppPrefs(AbstractBaseActivity activity)
        {
            prefs = PreferenceManager.getDefaultSharedPreferences(activity);
            no_email = activity.getString(R.string.no_email);
        }

        public static AppPrefs getInstance(AbstractBaseActivity activity)
        {
            if(instance == null)
            {
                instance = new AppPrefs(activity);
            }
            return instance;
        }

        public String getUserEmail()
        {
          return prefs.getString(AppPrefs.KEY_STR_USER_EMAIL, no_email);
        }

        public boolean setUserEmail(String email)
        {
          return prefs.edit().putString(AppPrefs.KEY_STR_USER_EMAIL, email).commit();
        }

         //... getter/setter methods to modify the SharedPreferences ...//
    }
}

I like this approach because it simplifies getting the SharedPreferences. I just call AppPrefs.getInstance(this) from within the Activities or AppPrefs.getInstance(getActivity()) from within a Fragment. Currently, my SharedPreferences are wrapped in a custom Object -- AppPrefs -- which uses obviously named getters and setters to interact with my SharedPreference data without actually having to muck about with key-value pairs and remembering to call commit() when changing data, but it is a stand-alone class. It seems to make sense to make the AppPrefs class an inner class of the AbstractBaseActivity class, but I'd welcome any criticisms of the approach.

I'm also uncertain about how I'm dealing with getting the AppPrefs object -- is there a better way to implement instantiation?

What are the downsides I'm not seeing?


texts:
I need to compute the number of target values \$t\$ in the range: \$-10000 \le t \le 10000\$ (inclusive) such that there are distinct numbers \$x, y\$ in the input file that satisfy \$t= x+y\$. I have the code which does work and would like to optimize it to run it faster.

Also, we'll count the sum \$t\$ only once. If there are two \$x,y\$ pairs that add to 55, you will only increment the result once.

public static int Calculate(int start, int finish, HashSet<long> numbers)
{
    int result = 0;
    for (int sum = start; sum <= finish; sum++)
    {
        foreach (long n in numbers)
        {
            if (numbers.Contains(sum - n) && n != (sum - n))
            {
                result++;
                break;
            }
        }
    }

    return result;
}

This is an assignment and I completed it with full marks. My code is taking like 30 minutes to run against the data set of 1 million numbers. I tried to think a way to optimize my code, but couldn't get to the right thought and would appreciate some help.


texts:
I am parsing excel data and need to create object based on StartDate-EndDate difference.

Is there a better way to have only one linq perform this task and return two different result sets ? Only difference in both linq is just the variable on which its applied.

private Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] ParseData(ExcelFile file, Dictionary<string, string>[] ConfigMap)
{

    // Extract the information from the excel file
    var excelData = file.GetWorksheetData(sheet: 0, rowStart: 2);

    var monthlyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days > 1);
    var dailyRows = excelData.Rows.Where(r => (DateTime.FromOADate((double)r[EndDateCol]) - DateTime.FromOADate((double)r[StartDateCol])).Days == 1);

    var monthlyData = monthlyRows.Where(r => r[KeyCol] != null && ConfigMap[0].ContainsKey((string)r[KeyCol]))
                                   .GroupBy(r => (string)r[KeyCol])
                                   .ToDictionary(g => g.Key,
                                                 g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
                                                       .ToDictionary(c => c.Key,
                                                                     c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
                                                                           .ToList()));

    var dailyData = dailyRows.Where(r => r[KeyCol] != null && ConfigMap[1].ContainsKey((string)r[KeyCol]))
                                  .GroupBy(r => (string)r[KeyCol])
                                  .ToDictionary(g => g.Key,
                                                g => g.GroupBy(r => DateTime.FromOADate((double)r[DateCol]))
                                                      .ToDictionary(c => c.Key,
                                                                    c => c.Select(r => new DataPoint(DateTime.FromOADate((double)r[StartDateCol]), new Decimal((double)r[PriceCol])))
                                                                          .ToList()));

    return new Dictionary<string, Dictionary<DateTime, List<DataPoint>>>[] { monthlyData, dailyData };
}


texts:
Just seeing if there is anyway to shorten these for statements?

...
      fillMonthSelect: function() {
        var month = new Date().getMonth() + 1;

        for (var i = 1; i <= 12; i++) {
          $('.card-expiry-month').append($('<option value="'+i+'" '+(month === i ? "selected" : "")+'>'+i+'</option>'));
        }
      },

      fillYearSelect: function() {
        var year = new Date().getFullYear();

        for (var i = 0; i < 12; i++) {
          $('.card-expiry-year').append($("<option value='"+(i + year)+"' "+(i === 0 ? "selected" : "")+">"+(i + year)+"</option>"));
        }
      },
...


texts:
I need to calculate the height of an optional (not AVL, binary) tree. For input I receive an n integer positive number: parent(0), parent(1), ... parent(n-1). Here, parent(i) is a parent of node i. If parent(i) == -1, that i is the root of the tree. It is guaranteed that the sequence has only one root and presets a tree.

Limitation:

\$1 \le n \le 1e5\$

Example input:

5
4 -1 4 1 1

Output:

3

 1
/ \
3  4
   /\
   0 2

My program on C++ works but it looks like that the algorithm is not optimal. The program is verified automatically and one of the test failed with error "Time limit exceeded". Could you advise me, please, on how I can optimize the program?

#include "iostream"

int tree[10000];
int n = 0;

int Height(int parent);

int main ()
{
    std::cin >> n;

    for (int i = 0; i < n; ++i)
    {
        std::cin >> tree[i];
    }

    std::cout << Height(-1) - 1;
    return 0;
}

int Height(int parent)
{
    int height = 1;
    for (int i = 0; i < n; ++i)
    {
        if (tree[i] == parent)
        {
            height = std::max(height, 1 + Height(i));
        }
    }
    return height;
}


texts: Creating a booking based on a POST request

texts:
I want to make a booking entry. I want to ask whether the code that i wrote below is rightly format or not?

I haven't tried it, because there's still more code that needs to be written. I just want to ask this before I continue to write.

<?php
    require 'Connection.php';

    //Check Connection
    if ($conn->connect_error){
        die("Connection Failed: ". $conn->connect_error);
    }

    //Create Variable Submitted Booking
    $MarketingName = $_POST["Marketing"];
    $CustomerName = $_POST["CustName"];
    $CustomerEmail = $_POST["CustEmail"];
    $HouseID = $_POST["IDHouse"];
    $UnitNo = $_POST["UnitNo"];
    $Remarks = $_POST["Remarks"];

    //Select All Data in Database
    $sql = $conn->prepare ("SELECT Property_No FROM cust_bookedfr WHERE Property_No = '" . $UnitNo . "' ");
    $result = mysqli_query($conn, $sql);

    if ($result->num_rows > 0) {
        //Validate Username
        echo "Property Unit is already taken.";

    } else {
        echo "Creating a Booking.";

        if (filter_var($Marketing, FILTER_SANITIZE_STRING)) {
            if (filter_var($CustName, FILTER_SANITIZE_STRING)) {
                if (filter_var($Cust_Email, FILTER_SANITIZE_EMAIL)) {
                    if (filter_var($HouseID, FILTER_VALIDATE_INT)) {
                        if (filter_var($UnitNo, FILTER_SANITIZE_STRING)) {
                            if (filter_var($Remarks, FILTER_SANITIZE_STRING)) {
                                //Insert the Username and Password into Database
                                $sql2 = $conn->prepare ("INSERT INTO cust_bookedfr (NULL, Marketing_Name, Cust_Name, Cust_Email, Property_Name, Property_ID, Property_No, Property_Qty, Property_Price, Remarks, DateAccess)
                                VALUES ('" . $MarketingName . "', '" . $CustomerName . "', '" . $CustomerEmail . "', 'Fajri Residential', '" . $HouseID . "', '" . $UnitNo . "', '', '', '" . $Remarks . "', NOW())");
                                if ($conn->query($sql2) === TRUE) {
                                    echo "New record created successfully";
                                } else {
                                    echo "Error: " . $sql2 . "<br>" . $conn->error;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
$sql->close();
$sql2->close();
$conn->close();

?>


texts: Parallel factorial algorithm using std::thread

texts:
This code calculates the factorial of a number on multiple threads. My issue: it is only a little bit faster than the sequential version of it (and I think I know why, I just can't find a way to solve this).

I use boost::multiprecision::cpp_int so the limits of default integers are not a problem, the size of integers is only limited by memory.

Only showing the relevant parts:

// ... other includes ...
#include <boost/multiprecision/cpp_int.hpp>

#define THREAD_COUNT 4
std::atomic<int> thread_num(1);         // global variable

// stuff...

void threaded_factorial(unsigned long long int num, boost::multiprecision::cpp_int& bigInt)
{
    int threadid = thread_num++;     // thread_num is atomic, so this is safe
    boost::multiprecision::cpp_int N = 1;
    for (unsigned long long int i = threadid; i <= num; i = i + THREAD_COUNT)
    {
        N *=(i);

    }

    std::lock_guard<std::mutex> lock(mu);      // race condition --> mutex needed
    bigInt *= N;
}

// more stuff ...

And the call of the function:

// ...

boost::multiprecision::cpp_int result = 1;
std::thread workers[THREAD_COUNT];

for (int i = 0; i < THREAD_COUNT; ++i)
{
    workers[i] = std::thread(threaded_factorial, num, std::ref(result));
}
for (int i = 0; i < THREAD_COUNT; ++i)
{
    workers[i].join();
}

// ...

The results seem correct, but as I said, this is not much faster than sequential code.

For example. The calculation of the factorial of 325253 took

67586 ms on 4 threads
76226 ms on a single thread

That is some really poor performance.

The reason, I think is that the for cycle in the threaded_factorial function roughly takes the same amount of time for each thread to complete, so when the std::mutex mu is locked, (THREAD_COUNT-1) threads have to wait for the one which locked the mutex.

This way, most of the work (by far the largest multiplications) is happening in a sequential manner, so the algorithm is really slow.

How can I work around this issue and make this work efficiently?


texts: Do I need to use inheritance and classes for my OOP webscraper?

texts:
I am currently writing python code that scrapes information from the web.
I have to scrape several sites, but there a two types of procedures:

Directly scrape from the website
Download pdf and scrape it with regexes

I consider the following 3 options, which one would be recommended?
Option 1
Use inheritance:
import requests
import PyPDF2
from bs4 import BeautifulSoup
import re

class Scraper:
    def __init__(self, name):
        self.name = name
        self.url = None

    def get_text_from_pdf(self, page_number):
        self.download_pdf(self.url, './data/{}.pdf'.format(self.name))
        mypdf = open('./data/{}.pdf'.format(self.name), 'rb')
        fileReader = PyPDF2.PdfFileReader(mypdf)
        page = fileReader.getPage(page_number)
        text = page.extractText()
        return text

    def download_pdf(self, self.url, path):
        response = requests.get(self.url)
        with open(path, 'wb') as f:
            f.write(response.content)

    def get_soup_from_url(self):
        response = requests.get(self.url)
        result = response.text
        soup = BeautifulSoup(result)
        return soup

class Website1(Scraper):
    def __init__(self):
        super().__init__('website1')
        self.url = 'https://website1.com'

    def get_info(self, soup):
        '''
        Parse the html code through Beautifullsoup
        '''

class Website2(Scraper):
    def __init__(self):
        super().__init__('website2')
        self.url = 'https://website2.com/some_pdf.pdf'

    def get_info(self, text):
        '''
        Parse the pdf text through regexes
        '''

if __name__ == "__main__":
    Website1_Scraper = Website1()
    raw_info = Website1_Scraper.get_soup_from_url()
    Website1_Scraper.get_info(raw_info)

    Website2_Scraper = Website2()
    raw_info = Website2_Scraper.get_text_from_pdf(page_number=0)
    Website2_Scraper.get_info(raw_info)

    #Website3_Scraper, 4, 5 ... 10

Option 2
Only use the sub classes Website1 and Website2and convert the methods of the Scraper class to regular functions
Option 3
Delete all classes and only use functions, such as: get_info_from_website1() and get_info_from_website2()


texts: Creating an interactive tour for a website

texts:
I'm using grumble to create an interactive tour for a website I'm working on (I'm aware there is a plugin called crumble that does this but I want to have full control of the functionality).

Basically, I initialise 6 grumbles (this is the amount of tour bubbles I need), then hide the last 5 and then attach each click handler separately. In each click handler I hide the one that is clicked and show the next one.

$(document).ready(function() {

 // First grumble
 $('#someID').grumble({
  text: 'This is a short tour, click to continue',
  angle: 130,
  distance: 10,
  type: 'firstGrumble '
 });

 // Second grumble
 $('#someOtherID').grumble({
  text: 'This is some tour text',
  angle: 30,
  distance: 230,
  type: 'secondGrumble '
 });

 // Third grumble
  $('#someOtherOtherID').grumble({
  text: 'This is some more tour text',
  angle: 5,
  distance: 30,
  type: 'thirdGrumble '
 });

 // Fourth grumble
 $('#anotherID').grumble({
  text: 'This is another bit of tour text',
  angle: 60,
  distance: 30,
  type: 'fourthGrumble '
 });

 // Fifth grumble
 $('#yetAnotherID').grumble({
  text: 'This is also another bit of tour text',
  distance: 30,
  type: 'fifthGrumble '
 });

 // Sixth grumble
 $('#andAnotherID').grumble({
  text: 'This is the end of the tour',
  angle: 300,
  distance: 30,
  type: 'sixthGrumble '
 });

 // Hide the freshly created gumbles
 $('.secondGrumble').hide();
 $('.secondGrumble + div').hide();
 $('.thirdGrumble').hide();
 $('.thirdGrumble + div').hide();
 $('.fourthGrumble').hide();
 $('.fourthGrumble + div').hide();
 $('.fifthGrumble').hide();
 $('.fifthGrumble + div').hide();
 $('.sixthGrumble').hide();
 $('.sixthGrumble + div').hide();

 // Click handler for first grumble
 $(document).on("click", '.firstGrumble + div', function() {
  $('.firstGrumble').hide();
  $('.firstGrumble + div').hide();
  $('.secondGrumble').show();
  $('.secondGrumble + div').show();
 });

 // Click handler for second grumble
 $(document).on("click", '.secondGrumble + div', function() {
  $('.secondGrumble').hide();
  $('.secondGrumble + div').hide();
  $('.thirdGrumble').show();
  $('.thirdGrumble + div').show();
 });

 // Click handler for third grumble
 $(document).on("click", '.thirdGrumble + div', function() {
  $('.thirdGrumble').hide();
  $('.thirdGrumble + div').hide();
  $('.fourthGrumble').show();
  $('.fourthGrumble + div').show();
 });

 // Click handler for fourth grumble
 $(document).on("click", '.fourthGrumble + div', function() {
  $('.fourthGrumble').hide();
  $('.fourthGrumble + div').hide();
  $('.fifthGrumble').show();
  $('.fifthGrumble + div').show();
 });

 // Click handler for fifth grumble
 $(document).on("click", '.fifthGrumble + div', function() {
  $('.fifthGrumble').hide();
  $('.fifthGrumble + div').hide();
  $('.sixthGrumble').show();
  $('.sixthGrumble + div').show();
 });

 // Click handler for sixth grumble
 $(document).on("click", '.sixthGrumble + div', function() {
  $('.sixthGrumble').hide();
  $('.sixthGrumble + div').hide();
 });

});

I want to know a way to make this code more DRY.  I'm thinking some form of an each statement and a counter to create the 6 classes, but I could be wrong.


texts:
Here is the problem description from hackerearth.com:

  Rohan loves Palindromes. Palindrome is a string that read same forward
  and backward. For example abba is a palindrome while abca is not.

  Rohan is forming a palindrome of length lesser than or equal to \$n\$,
  with first \$k\$ characters of lowercase English letters. He needs your
  help to find out the number of possible palindromes.

  Output the result modulo \$10^9 + 7\$

  Input Format: First line contains 2 space separated integers, \$n\$ and \$k\$

  Output Format: Output a single integer, which is answer to the problem

  Constraints: \$1 ≤ n ≤ 10^9\$        \$1 ≤ k ≤ 26\$

  Sample input:

3 2

  Sample Output:

8

I tried making it and it was working fine for some small input but in case of large input its saying time limit exceeded. I think my code running time is \$O(n^2)\$, but I am not sure.

My code:

a,b = raw_input().split()
a = int(a)
b = int(b)
sum = 0
z = b
for i in xrange(1,a+1,2):
    d = z*2
    sum +=d
    z = z*b

if (a+1) % 2 == 0:
    sum = sum - (d/2)
print sum%1000000007

I am interested in knowing that where I am doing wrong with my code and how can I fix this. Also what should I do at first when I face these kind of problem whenever I have to deal with long input because every time I see any time limit error I am not able to fix it.


texts:
I am implementing merge sort in Java and I have a performance problem in this method:

    private static void marge(int[] source, int[] buffer, int startingIndex, int count) {
        int index1 = startingIndex;
        int index2 = startingIndex + count / 2;
        int maxIndex1 = index2;
        int maxIndex2 = startingIndex + count;

        for(int i = 0; i < count; i++){
            if(index2 >= maxIndex2 || (index1 < maxIndex1 && source[index1] < source[index2])){
                buffer[startingIndex + i] = source[index1];
                index1++;
            }
            else{
                buffer[startingIndex + i] = source[index2];
                index2++;
            }
        }

//      System.arraycopy(source, startingIndex, buffer, startingIndex, count);
    }

If I replace this method content with the content of the comment, like this:

private static void marge(int[] source, int[] buffer, int startingIndex, int count) {
    System.arraycopy(source, startingIndex, buffer, startingIndex, count);
}

It performs 10 to 20 times faster. I understand that I have more calculations in my original method but "10 to 20 times" seems too much for me.

Do you have any idea how to improve performance?


texts: Passing functions using higher order components in React

texts:
After reading this, I'm on board, however it doesn't get into passing methods from the parent class. In my mixins right now I have a lot of helper functions that are used across the various components that use the mixin.

I would simply do something like below, unless someone has a better approach? Note I have anywhere from half a dozen to a dozen of these helper functions, so I'm just wondering if someone has a better approach than this, for example, if I could pass all the existing methods in one fell swoop instead of explicitly specifying each one.

## PARENT COMPONENT THAT I WOULD REPLACE MY MIXIN WITH

TableBase = (Component) ->

  Table = React.createClass

    isTableEmpty: ->
      @props.items.length is 0

    getStateBy: ->
      if @props.state is 'active'
        return
This is active

      if @props.state is 'inactive'
        return
This is no longer active.

    render: ->
      return (
        <Component
          {...@props}
          {...@state}
          isTableEmpty={@isTableEmpty}
          getStateBy={@getStateBy}
          ..etc
        />
      )

module.exports = TableBase

## EXAMPLE USING IT WITH ONE OF MY TABLES
UsersTable = React.createClass

  render: ->

    ## and access my functions and props here...
    if @props.isTableEmpty()
      return <EmptyTableMsg msg='No items to show' />

    return (

        ## etc.

    )

buildUsersTable = TableBase(UsersTable)

module.exports = buildRacksTable


texts:
What I have is an outer loop which loops through a list of strings, followed by another loop which loops through a list of filters; and if the current column is the current filter in the list of filters, it then applies this filter.

I'm just trying to tidy up a messy function but can't see anyway of doing so.

public static bool PassRules(List<string>columnsList, List<Customfilters> customfilters )
{
    var i = 0;
    foreach (var column in columnsList)
    {
        var curFilter = new Customfilters();

        foreach (var customfilterse in customfilters.Where(customfilterse => customfilterse.Field.Equals(Filed[i])))
        {
            curFilter = customfilterse;
        }

        if ( !string.IsNullOrEmpty(curFilter.Filter))
        {
            int n;
            var isNumeric = int.TryParse(column, out n);
            if (isNumeric)
            {
                if (!Compare(curFilter.Expression, Convert.ToDouble(column), Convert.ToDouble(curFilter.Filter)))
                {
                    return false;
                }
            }
            else
            {
                if (curFilter.Expression.Equals("IN") || curFilter.Expression.Equals("NOT IN"))
                {
                    var toList = curFilter.Filter.Split(Convert.ToChar(","));

                    if (!CompairInNotIn(toList.ToList(), curFilter.Expression, column))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!Compare(curFilter.Expression, column, curFilter.Filter))
                    {
                        return false;
                    }
                }
            }
        }
        i++;
    }
    return true;
}

public static bool Compare<T>(string op, T left, T right) where T : IComparable<T>
{
    switch (op)
    {
        case "<": return left.CompareTo(right) < 0;
        case ">": return left.CompareTo(right) > 0;
        case "<=": return left.CompareTo(right) <= 0;
        case ">=": return left.CompareTo(right) >= 0;
        case "==": return left.Equals(right);
        case "!=": return !left.Equals(right);
        default: throw new ArgumentException("Invalid comparison operator: {0}", op);
    }
}

public static bool CompairInNotIn(List<string> list, string op, string column)
{
    if (op.Equals("IN"))
    {
        return list.Any(column.Contains);
    }
    if (op.Equals("NOT IN"))
    {
        return !list.Any(column.Contains);
    }
    return true;
}

Just to explain a few fields:

var tmpFilter1 = new Customfilters { Field = "IMA01", Expression = "==", Filter = "HP" };

Field[i] is a dictionary of <int,string> and basically returns the ID of the field name.


texts: Adjust Hours on UTC String to Account for TimeZoneOffset

texts:
I have a library that provides a time-picker HTML element, which takes a UTC string as an input. The timepicker adjusts any UTC string it receives to local time. So, for example, if it takes '0001-01-01T17:00:00.000Z' in, it will show the time as 12pm, not 5pm, since it subtracts 5 . I am working off the assumption that it's impossible to form a Javascript Date object as the UTC string I want.

Method I need: public adjustUtcStringToAccountForLocalOffSet(utcTime: string): string
Sample input: '0001-01-01T17:00:00.000Z'
Sample output (in EST timezone): '0001-01-01T17:00:00.000Z'
Random note: Time needs to be in 24 hour format, but I do NOT care about the date, since the timepicker only returns a time. So if offset is -5 from 02 hrs, result should be 24-2 = 22; date does NOT need to adjust.

class Tester {

  const lengthOfUtcHourSegment: number = 2;

  public adjustUtcStringToAccountForLocalOffSet(utcTime: string): string {
    let dt = new Date(utcTime);
    let currentTimeZoneOffsetInHours: number = dt.getTimezoneOffset() / 60;
    let startOfHourSegmentIdx: number = utcTime.indexOf('T') + 1;
    let endOfHourSegmentIdx: number = startOfHourSegmentIdx + this.lengthOfUtcHourSegment;
    let utcHourSegment: string = utcTime.substring(startOfHourSegmentIdx, endOfHourSegmentIdx);
    let adjustedHourSegment: string = this.adjustHourSegmentForOffset(utcHourSegment, currentTimeZoneOffsetInHours).toString();
    let utcStringAsArray: string[] = utcTime.split('');
    utcStringAsArray.splice(startOfHourSegmentIdx, this.lengthOfUtcHourSegment, adjustedHourSegment);
    let adjustedUtcString: string = utcStringAsArray.join('');

    console.log(adjustedUtcString); //Here for testing

    return adjustedUtcString;
  }

  private adjustHourSegmentForOffset(hours: number, localOffSetInHrs: number): number{
    let adjustedHours: number = hours - localOffSetInHrs;
    adjustedHours = this.ensureTimeIsInTwentyFourHourFormat(adjustedHours);
    return adjustedHours;
  }

  private ensureTimeIsInTwentyFourHourFormat(hours: number): hours {
    if (hours < 0 ){
      hours = 24 - Math.abs(hours);
    }

    return hours;
  }

  constructor() {}
}

//Testing code
let tester = new Tester();
tester.adjustUtcStringToAccountForLocalOffSet('0001-01-01T02:00:00.000Z'); //should return 21 in EST
tester.adjustUtcStringToAccountForLocalOffSet('0001-01-01T17:00:00.000Z'); //should return 12 in EST
tester.adjustUtcStringToAccountForLocalOffSet('0001-01-01T24:00:00.000Z'); //should return 19 in EST

Link to Working Code


texts: Singleton Pattern + unavoidable Public Constructor

texts:
We have an object that needs to be converted to a different type before storing it in database. For that purpose, the library provides an annotation over the field that specifies the appropriate class[given as ClassName.class] to use for converting back & forth.

The class implements an interface of the library that has the marshall & unmarshall methods.

public class ObjectConverter implements Marshaller<Instant> {

    public static final ObjectConverter CONVERTER = new ObjectConverter();

    @Override
    public String marshall(Instant obj) {
        return obj.toString();
    }

    @Override
    public Instant unmarshall(Class<Instant> clazz, String obj) {
        return Instant.parse(obj);
    }
}

Now, we need to manually convert Instant to appropriate type at certain places. A straight-forward approach would be to create a new instance everywhere and invoke those public methods.

My colleague was suggesting to have a static final field of itself and use it wherever needed in order to avoid creating it each and every time. But, my argument was that nobody is stopping from creating a new instance, thus defeating the purpose of the static instance.

A better way to handle this, in case object creation is really costly would be to have a utility class that has static methods for converting back & forth. These can be invoked in both the marshaller and during manual conversions. Is there any better approach?

Is it a good practice to have both static instance and public constructor at the same time?


texts: Game Of Life implemented with for-loops and a boolean-array

texts:
There's a Follow-up: Game Of Life rewritten into two classes, PetriDish and Cell

I wrote an implementation of the Game Of Life using the easiest approach, a bunch of loops and a boolean array. Yet I feel like I missed something very elemental.

The basic implementation is:

Check the old generation with loops
Check each neighbor of each cell...with loops
Set the status in the generation
Copy the new generation over the old one

This seems to have some serious downsides, especially the heavy use of loops which makes me a little bit itchy.

private boolean[] cells; // Will be set at construction
private int width;
private int height;

/**
 * Evolve into the next nextGeneration.
 */
private void doGeneration() {
    boolean[] nextGeneration = new boolean[cells.length];

    for (int x = 1; x < width - 1; x++) {
        for (int y = 1; y < height - 1; y++) {
            int neighbors = 0;

            // Check surrounding cells.
            for (int neighborX = x - 1; neighborX <= x + 1; neighborX++) {
                for (int neighborY = y - 1; neighborY <= y + 1; neighborY++) {
                    if (neighborX != x || neighborY != y) {
                        if (cells[neighborX * width + neighborY]) {
                            neighbors++;
                        }
                    }
                }
            }

            int idx = x * width + y;

            switch (neighbors) {
                case 0:
                case 1:
                    nextGeneration[idx] = false;
                    break;

                case 2:
                    nextGeneration[idx] = cells[idx];
                    break;

                case 3:
                    nextGeneration[idx] = true;
                    break;

                default:
                    nextGeneration[idx] = false;
                    break;
            }
        }
    }

    cells = nextGeneration;
}

Edit: The whole application (Slick dependent for input and drawing) can be found at GitHub.

Edit2: There's a bug in the above code. The index should of course be y * width + x. I stumbled against that yesterday when I tried to handle non-square grids, but I just realized what was wrong some minutes ago while riding the bus.


texts:
I'm worried about my own attempt at a solution for a Sphere-Plane collision testing. I originally implemented a solution I found on a mix of Game Development websites around the place, which was similar enough to the following:

bool intersecting(BoundingSphere const& s, Vector3 const& s_origin, BoundingPlane const& p, float const p_distance) {
    Vector3 const p_origin = p.normal * p_distance;
    Vector3 const cp = s_origin + p.normal * dot((p_origin - s_origin), p.normal);

    return (distance2(s_origin, cp) < s.radius * s.radius);
}

But I have recently spent a bit more time doing linear algebra since and basic geometry, and decided upon revising the above solution (to see if I understood the problem space better).

In thinking about it as a simple check: distance of a point from a line being less than the radius. I came up with the following:

bool intersecting2(BoundingSphere const& s, Vector3 const& s_origin, BoundingPlane const& p, float const p_distance) {
    return abs<float>(dot(p.normal, s_origin) - p_distance) < s.radius;
}

It has so far passed all my tests practically, but I still worry about my mathematical ability and I don't want an edge case to bite me in the ass that I might have missed. One thing I have definitely noticed is the solution is highly sensitive to the normalised form of the plane normal. If it is simply a rough estimation, ie not truly normalised, it will fail completely (exponential error).

The fact I never saw a solution that short worries me haha.

edit: My testbed: http://pastie.org/3512889

proposed tags: collision-detection && math


texts:
This is a console application which takes as an argument either a .cs file or a directory. If it's a .cs file, it scans it; if it's a directory, it scans all .cs files within the directory.

A simplified view of a method which chooses whether it's a file or a directory and reports errors is this one:

public static void ProcessPath(string path)
{
    if (path.EndsWith(".cs"))
    {
        if (File.Exists(path))
        {
            Program.ScanFile(path);
        }
        else
        {
            Console.WriteLine("The specified file doesn't exist.");
            Environment.Exit(1);
        }
    }
    else
    {
        if (Directory.Exists(path))
        {
            Program.ScanDirectory(path);
        }
        else
        {
            if (File.Exists(path))
            {
                Console.WriteLine("The path corresponds to a file, but only *.cs files are supported.");
            }
            else
            {
                Console.WriteLine("The specified directory doesn't exist.");
            }

            Environment.Exit(1);
        }
    }
}

How can I rewrite the if/else logic in a more elegant way? Would it improve readability?


texts: Elegant way of processing an "options" parameter

texts:
In this constructor function I'm assigning everything to the proper variables. For the third parameter it accepts an options argument that contains the optional settings.

To prevent a Cannot read property x of undefined. error I'm always checking this variable by steps, since the options variable can contain both complex objects and primitive data types.

I'm wondering if there is a more elegant way I could write this?

Constructor

function LiveDate(timeUrl, element, options) {
    this.timeUrl = timeUrl;
    this.element = element;

    this.format = options && options.format ? options.format : LiveDate.formats.ISO8601;
    this.offset = options && options.offset ? options.offset : 0;

    this.weekdayNames = {
        long: options && options.weekdayNames &&  options.weekdayNames.long ? options.weekdayNames.long : [
            'Sunday',
            'Monday',
            'Tuesday',
            'Wednesday',
            'Thursday',
            'Friday',
            'Saturday'
        ],
        short: options && options.weekdayNames && options.weekdayNames.short ? options.weekdayNames.short : [
            'Sun',
            'Mon',
            'Tue',
            'Wed',
            'Thu',
            'Fri',
            'Sat'
        ]
    };

    this.monthNames = {
        long: options && options.monthNames && options.monthNames.long ? options.monthNames.long : [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
            'July',
            'August',
            'September',
            'October',
            'November',
            'December'
        ],
        short: options && options.monthNames && options.monthNames.short ? options.monthNames.short : [
            'Jan',
            'Feb',
            'Mar',
            'Apr',
            'May',
            'Jun',
            'Jul',
            'Aug',
            'Sep',
            'Oct',
            'Nov',
            'Dec'
        ]
    };

    this.start();
}


texts:
I implemented an algorithm for solving sudoku using reduction from sudoku to SAT.

Now, I am trying to refactor the code using code review principles. I find some difficulties apply the principles. Because of that I would like to share the following code snippet in order to get some hints how to approach this problem efficiently.

The following method generate boolean expressions in CNF such that for any entry puzzle_{ij} a boolean expression E in CNF will be generated such that E = true iff there is exactly one literal x_{ijk}, k in {1, 2, ..., 9} such that x_{ijk} = true

// DIGITS := {1, 2, ..., 9}
// Combinatorics.product(DIGITS) = {(1,1), (1,2), ..., (9,8), (9,9)}

static List<List<Integer>> exactlyOneDigitForEachEntry() {
    ArrayList<Pair> pairs = Combinatorics.product(DIGITS);
    List<List<Integer>> clauses = new ArrayList();
    for (Pair pair : pairs) {
        ArrayList<Integer> literals = new ArrayList();
        for (int k : DIGITS) {
            int literal = (100 * pair.getA()) + (10 * pair.getB()) + k;
            literals.add(literal);
        }
        List<List<Integer>> expression = exactlyOneOf(literals);
        extendClauses(clauses, expression);
    }

    return clauses;
}

.

/**
 *
 * @param literals A set of literals
 * @return a boolean expression E in conjunctive normal form such that E =
 * true iff there is exactly one literal that is true.
 */
private static List<List<Integer>> exactlyOneOf(ArrayList<Integer> literals) {
    // The arrayList represents a boolean formula F such that F = true iff
    // there is exaclty one literal l such that l = true
    List<List<Integer>> expression = new ArrayList();
    expression.add(literals);
    ArrayList<Pair> pairs = Combinatorics.combinations(literals);
    for (Pair pair : pairs) {
        List<Integer> clause = new ArrayList();
        clause.add(-1 * pair.getA());
        clause.add(-1 * pair.getB());
        expression.add(clause);
    }
    return expression;
}


texts:
Yesterday I found some nice video from some IT conference about removing if statements from code. I saw a very nice example of refactoring. I am curious what do you think about it, especially what weak points do you see in such approach.

1) We have a class with very "nice" method:

public int inferCategoryID(Component c) {
        if(c.hasOneChannel() && c.hasValidCertificate() && c.isTested() && c.frequentlyUsed()) {
            return 24;
        }
        if(c.hasOneChannel() && c.hasValidCertificate() && !c.isTested() && c.frequentlyUsed()) {
            return 95;
        }
        if(c.hasOneChannel() && !c.hasValidCertificate() && c.isTested() && c.frequentlyUsed()) {
            return 221;
        }
        if(c.hasTwoChannels() && c.hasValidCertificate() && c.isTested() && c.frequentlyUsed()) {
            return 2004;
        }
        if(c.hasTwoChannels() && c.hasValidCertificate() && !c.isTested() && c.frequentlyUsed()) {
            return 20044;
        }
        if(c.hasTwoChannels() && c.hasValidCertificate() && !c.isTested() && !c.frequentlyUsed()) {
            return 2003;
        }
        // etc...
    }

As you can see all conditions are mutually exclusive.

2) The idea was, to create a separate class for each condition - under a common interface:

interface CategoryIDCondition  {
        public boolean isTrue(Component c);
        public int getID();
    }

class Cat24Condition implements CategoryIDCondition {
    public boolean isTrue(Component c){
        return c.hasOneChannel()
                && c.hasValidCertificate()
                && c.isTested()
                && c.frequentlyUsed();
    }

    public int getID(){
        return 24;
    }
}

// etc...

3) Usage example:

public int inferCategoryID(Component c) {
        List<CategoryIDCondition> conditions = new ArrayList<>();
        conditions.add(new Cat24Condition);
        conditions.add(new Cat95Condition);
        // etc... (btw. not a good place for list init but never mind...)

        for (CategoryIDCondition cond : conditions) {
            if(cond.isTrue(c)){
                return cond.getID();
            }
        }
    }

What weak points do you see in such approach apart from that, that conditions have to be mutually exclusive, or have to be added to conditions list in a very specific order? Would you decide to use such strategy in your code?


texts:
So I wrote a rather primitive login logic in Node.js, which authenticates the user and handles JWT. Is it any good in terms of security, efficiency, building, async/sync, logging. SECURITY is my main concern.
On in a prettier format the question would be:

SECURITY: Is my website secure in any way, shape, or form? I'm wondering if I could implement any security measures other than the ones that are built in to the methods provided by Node.js. Also, I know the passwords are plainly obvious to guess, but they are like that to ensure logging in as different users works.
EFFICIENCY: Is how I'm checking usernames and password efficient? Is there any better way to do this?
BUILDING: Is how I loaded my website acceptable? Reading from a file and then ending the response?
ASYNC/SYNC: I know I preform async and sync calls at the same time. Is there any problem to this?
LOGGING: I log all connections to the server, and all login attempts. Is this a good practice, or am I overdoing what logging is supposed to accomplish?
(Source: Login Server with Node.js)

My code is:
// main login logic
app.post('/api/login', apiLimiter, async function (req, res) {
  // TODO: implement cookie check whether a still valid token is set and if so respond with cookie already set
  // TODO: add roles into jwt and add roles checking into other code
  // TODO: if wrong password send a response telling there's a wrong password/username
  try  {
    const pw = req.body.password;
    const submittedUser = req.body.email;

    User.findOne({eMail: req.body.email}, async function (err, user) {
      if (err) throw err;
      console.log(user);
      const match = await bcrypt.compare(pw, user.password);
      console.log(match);
      if (match === true && user.eMail == submittedUser) {
        jwt2.sign({user}, 'secrettokenhere', { expiresIn: '15min'}, (err, token) =>{
          res.cookie(
            'access_token', 'Bearer '+ token, {
              //domain: 'localhost',
              path: '/',
              expires: new Date(Date.now() + 900000), // cookie will be removed after 15 mins
              httpOnly: true // in production also add secure: true
            })
            .json(
              user
            );
        });
      }
      else {
        res.status(200).send("Bad login");
      }
    });
  } catch (err) {
    res.status(500).send();
    console.log(err);
  }
});

P.S. there's gonna be a follow-up separate question with Frontend logic.


texts:
I have been solving a set of online Clojure problems.  One of them involves the look and say sequence.

(defn look-and-say [s]
   (let [las (loop [item (first s) coll s counts [] count 0]
      (cond
         (nil? (seq coll)) (conj counts count item)
         (= item (first coll)) (recur item (rest coll) counts (inc count))
         :else  (recur (first coll)  coll (conj counts count item) 0)))]
      (lazy-seq (cons las (look-and-say las)))))

I would like know what I did right and what I could do better. Any feedback is welcome.


texts:
I have the following code to open and close some popup divs. I'd like to know whether there is a shorter solution to close the currently opened divs, as soon as another div is opened, so that there is only one open div.

The current solution works as you can see in this jsFiddle, but I guess it is a bit inconvenient.

jQuery:

$('.details').hide();
$('#item-a').click(function () {
$('#detail-1').fadeToggle(600);
 $('#detail-2,#detail-3').fadeOut("slow");
});

$('#item-b').click(function () {
$('#detail-2').fadeToggle(600);
 $('#detail-1,#detail-3').fadeOut("slow");
});

$('#item-c').click(function () {
$('#detail-3').fadeToggle(600);
 $('#detail-1,#detail-2').fadeOut("slow");
});

$('.btn-close').click(function () {
 $(this).parent().parent().fadeOut("slow");
});

HTML:

 item a

 item b

 item c

close

 Some detailed text 1..

close

 Some detailed text 2..

close

 Some detailed text 3..


texts:
Background

I have a query in Mongoose that finds a set of objects, and then returns these said objects together with the total number of them:

var itemsPerPage = 4, pageNum = 1;

Survey.find({})
    .limit(itemsPerPage)
    .skip(itemsPerPage * pageNum)
    .then(docs => {
        if (docs.length === 0)
            console.log("There are no results matching your query.");
        else
            DocModel.count({})
                .then(number => {
                    console.log(JSON.stringify({number, docs}));
                });
        })
        .catch(console.log);

To achieve this I do:

find query with params
use limit and skip to obtain results from correct page
if docs is not empty, start a count query
return information

Problem

The problem here, since I need pagination in the query, is that I have to make 2 separate requests to the DB (find and count) which can potential be very heavy.

To optimize this, I would like to avoid the count query, but I don't know how.

Another issue is the nested promises anti pattern, but that is not the issue I would like to focus on right now.

Question

I am open to any suggestions on improving this code you may have!


texts:
I created a new endpoint for an API (Django REST Framework) that generates a PDF from an HTML template. I follow the example from the plugin django-easy-pdf.

It's working, but I would like to improve and to know what could be done in a better way.

Asset is an object from the database with information. The idea is to print some rows on an HTML template to then convert to PDF. The HTML is fine, but I'm just not sure if I could improve on this view.

URLs:

 url(r'^report/asset/(?P<pk>[0-9]+)$', api.DemoPDFView.as_view()),

views.py

from easy_pdf.views import PDFTemplateResponseMixin, PDFTemplateView

class DemoPDFView(PDFTemplateView):
    template_name = 'reports/asset.html'
    pdf_filename = 'asset.pdf'

    def get_context_data(self, **kwargs):
        pk = self.kwargs.get('pk', None)

        asset = Asset.objects.get(id=pk)
        project = asset.project.name
        id = asset.id
        name = asset.title

        return super(DemoPDFView, self).get_context_data(
            pagesize='A4',
            title='Asset',
            project=project,
            name=name,
            id=id,
            **kwargs
        )

The plugin is available:

http://django-easy-pdf.readthedocs.io/en/v0.2.0-dev1/


texts:
My database:

Class:

Class Category {
    function __construct($db) {
        $this->db = $db;
    }

    public function groupByUnderCategoryName() {
        $query = $this->db->prepare("SELECT categoryName, id, title FROM test2");
        $query->execute();
        return $query->fetchAll(PDO::FETCH_GROUP);
    }
}

Seeing picture above, probably first thing comes to mind is, creating another table for categories and JOIN them. Actually that is what I already did, please see above picture as a result of joining two tables.

This is result of above query:

array (size=3)
  'Action' =>
    array (size=2)
      0 =>
        object(stdClass)[5]
          public 'id' => string '1' (length=1)
          public 'title' => string 'Action#1' (length=8)
      1 =>
        object(stdClass)[7]
          public 'id' => string '3' (length=1)
          public 'title' => string 'Action#2' (length=8)
  'Drama' =>
    array (size=2)
      0 =>
        object(stdClass)[6]
          public 'id' => string '2' (length=1)
          public 'title' => string 'Drama#1' (length=7)
      1 =>
        object(stdClass)[9]
          public 'id' => string '5' (length=1)
          public 'title' => string 'Drama#1' (length=7)
  'Comedy' =>
    array (size=1)
      0 =>
        object(stdClass)[8]
          public 'id' => string '4' (length=1)
          public 'title' => string 'Comedy#1' (length=8)

As very proud I am to use PDO::FETCH_GROUP to get result above, I am not sure if it's a good idea to print it like that, and I would like you to review and help with me better practice:

$category = new Category($db);

foreach ($category->groupByUnderCategoryName() as $key => $value) {
    echo "
{$key}
";

    foreach ($value as $t_value) {
        echo "
{$t_value->title}
";
    }
}

Result: