texts:
I've been watching digital technology in the last few days. This has aroused my interest. I would like to realize a program that simulates basic components of circuit technology and their functions. I have developed a small approach on how to implement the elements of circuit technology on an object-oriented level. Is that a good way of thinking, with which you can continue working? Or could one formulate the building blocks more elegantly in code?

Output.java

/* objects of classes that implement this interface can be used as signaler */

public interface Output {
    public boolean getOutput();
}

Signal.java

public class Signal implements Output {
    private boolean signal;

    public Signal(boolean value) {
        setSignal(value);
    }

    public void setSignal(boolean value) {
        signal = value;
    }

    public boolean getOutput() {
        return signal;
    }
}

LinkingElements.java

abstract public class LinkingElement {
    Output signal1;
    Output signal2;

    public LinkingElement(Output signal1, Output signal2) {
        this.signal1 = signal1;
        this.signal2 = signal2;
    }
}

And.java

public class And extends LinkingElement implements Output {
    public And(Output signal1, Output signal2) {
        super(signal1, signal2);
    }

    public boolean getOutput() {
        return signal1.getOutput() && signal2.getOutput();
    }
}

Or.java

public class Or extends LinkingElement implements Output {
    public Or(Output signal1, Output signal2) {
        super(signal1, signal2);
    }

    public boolean getOutput() {
        return signal1.getOutput() || signal2.getOutput();
    }
}

LightBulb.java

public class LightBulb {
    private Output signal;

    public LightBulb(Output signal) {
        this.signal = signal;
    }

    public void isActive() {
        if(signal.getOutput()) {
            System.out.println("The lightbulb is shining.");
        } else {
            System.out.println("The lightbulb is switched off.");
        }
    }
}

Main.java

This class is just for testing:

public class Main {
    public static void main(String[] args) {
        Signal s1 = new Signal(true);
        Signal s2 = new Signal(true);
        Signal s3 = new Signal(true);
        Signal s4 = new Signal(false);
        And a1 = new And(s1, s2);
        Or a2 = new Or(s3, s4);
        And a3 = new And(a1, a2);
        LightBulb lightBulb = new LightBulb(a3);
        lightBulb.isActive();
    }
}


texts:
I would like a review for this connection to RabbitMQ. I just developed it and seems to be working well, but I would like another set of eyes on it before putting this on the sever.

package models

import com.rabbitmq.client.Connection
import com.rabbitmq.client.ConnectionFactory
import com.rabbitmq.client.ConnectionFactory
import com.rabbitmq.client.MessageProperties

import anorm.SQL
import anorm.sqlToSimple
import anorm.toParameterValue
import play.api.Play.current

object RabbitMQConnection {
  private var connection: Connection = null
  def getConnection(ss:Connection): Connection = {
    println(ss+"  connection <<<<<<<<<<<<<<<<<<<<<<<<")
    connection=ss
    connection match {
      case null => {
        val factory = new ConnectionFactory()
        println("waiting for new connection")
        factory.setHost("172.22.22.222")
        println("host setted")
        connection = factory.newConnection()
        println("connection created")
        connection
      }
      case _ =>{
        println("connection is not null")
        connection
      }
    }
  }
}

object RMQ {
  var connection = RabbitMQConnection.getConnection(null)

  def setQ(qName: String, message: String) = {
    println("ping received")
    try {
      println(connection)
      if (connection != null) {
        if (connection.isOpen()) {
          println("connection is open")
        } else {
          connection = RabbitMQConnection.getConnection(null)
          println("connection is new "+connection)
        }
        println("connetion is ready to use")
        val channel = connection.createChannel()
        channel.queueDeclare(qName, true, false, false, null) //suggestion
        channel.basicPublish("", qName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes())
        println("status" + channel.close())
        println("setQ complete executed for " + qName)
        Map("result" -> "success")

      } else {
        println("connection can't established to rabbit mq for =>" + qName)
        LogFile.QLogs(qName, message)
        Map("result" -> "error")
      }
    } catch {
      case e: Exception =>
        println(e.printStackTrace())
        println("Rabbit Mq Server is Down for =>" + qName)
        LogFile.QLogs(qName, message)
        Map("result" ->"error")
    }
  }

}


texts: Calculate and use a linear equation based on sets of x and y values

texts:
The following asks for 2 sets of data (with corresponding x and y values), calculates a linear equation that matches the data as closely as possible, then allows you to "play around" with the equation by substituting x values.

import Data.Char

slope :: [Float] -> [Float] -> Float
slope xs ys
    | xN /= yN = error $ "x len: " ++ show xN ++ " y len: " ++ show yN
    | otherwise = (xN * (sum $ coorProds xs ys) - xSum * ySum) /
        (xN * (sum $ squares xs) - (xSum * xSum))
    where
        (xN,yN) = (fromIntegral $ length xs, fromIntegral $ length ys)
        (xSum,ySum) = (sum xs, sum ys)

intercept :: [Float] -> [Float] -> Float
intercept xs ys
    | xN /= yN = error $ "x len: " ++ show xN ++ " y len: " ++ show yN
    | otherwise = (ySum - (b * xSum)) / xN
    where
        b = slope xs ys
        (xN,yN) = (fromIntegral $ length xs, fromIntegral $ length ys)
        (xSum,ySum) = (sum xs, sum ys)

getEquation :: [Float] -> [Float] -> ((Float -> Float),Float,Float)
getEquation xs ys = (\x -> (inter + (b * x)) , inter, b)
    where
        inter = intercept xs ys
        b = slope xs ys

coorProds :: [Float] -> [Float] -> [Float]
coorProds xs ys = map (\(x,y) -> x * y) $ zip xs ys

squares :: [Float] -> [Float]
squares = map (\x -> x * x)

cutIntoPair :: String -> (String,String)
cutIntoPair = (\(x,y)-> (x,drop 1 y)) . break (== ' ')

isFloat :: String -> Bool
isFloat = all (\c -> isDigit c || c == '.')

toFloat :: String -> Float
toFloat s
    | isFloat s = read s :: Float
    | otherwise = error $ show s ++ " is not a number"

getPairs :: IO ([Float],[Float])
getPairs = do
    i <- getLine
    let (x,y) = cutIntoPair i
    if isFloat x
        then do
            (xs,ys) <- getPairs
            return ((toFloat x : xs), (toFloat y : ys))
        else return ([],[])

useEquation :: (Float -> Float) -> IO ()
useEquation e = do
    putStr "When x = "; x <- getLine
    putStrLn $ "y = " ++ (show $ e (toFloat x)) ++ "\n"
    useEquation e

showEquation :: Float -> Float -> String
showEquation i b = "y = " ++ show i ++ " + " ++ show b ++ "x"

main = do
    putStrLn $ "Enter x and y values seperated by a space\n\t" ++
        "Then type a non-number to continue"
    (xs,ys) <- getPairs
    let (linEq,i,b) = getEquation xs ys
    putStrLn $ showEquation i b
    putStrLn "Enter x values to get their calculated y values"
    useEquation linEq

I'm looking for general feedback, and suggestions regarding the following points:

getEquation has a couple issues.

I was able to write it point-free when the function only returned the equation, but now that I'm wrapping everything in a tuple, so I can also return the calculated slope and intercept values (to show the equation later), it's not behaving as I expected. I tried writing it as a section,  like (inter + (b *), but that attempts to apply + to the function (b*), which obviously results in a "No instance" error. My solution was to just wrap it in a lambda, but that's quite ugly, in my opinion.
Is there a better way of dealing with the need to have the slope and intercept after the function is "constructed" than passing them back with the equation? The optimal solution would the ability to extract them out of the function, but I'm pretty sure that's not possible.

cutIntoPair looks ugly too. It splits a string at the first space, then returns the 2 parts. Break leaves the space in the second slot though, so to remove it, I resorted to passing the result to a lambda that leaves the first part of the tuple the same, but drops the first char of the second slot. I'd like to know if there is a cleaner way to go about this task.
The slope and intercept functions are slightly messy, but I had to cram a lot of math into the space. Tips on how to format it neater would be appreciated.

To use it, type x and y values separated by a space, pressing enter between sets. When you're done entering, type a non-number, like so:

2 4
4 8
12 24
k


texts: Finding sequential recurrences in a list of numbers

texts:
I have a list like this:

seq = [-2,3,-2,3,5,3,7,1,4,-5,1,4,-5,1,4,-5]

I want to get all the sequential recurrences and where it happens, I feel the way I'm doing its too brute force and in reality I want this for several lists each with length of about 300.

dic = {}
for p1 in range(len(seq)):
    for p2 in range(p1+1,len(seq)):
        dic.setdefault(tuple(seq[p1:p2]), []).append((p1,p2))

which results in all unique sequences of numbers as keys and their positions as values, for example:

#-2,3: [(0,2),(2,4)]

But also results in a lot of entries that occur only once that don't interest me, I'm 'cleaning' these after by taking only values that have more than 1 entry:

def clean(dic):
    cleandic = {}
    for key, value in dic.items():
        if len(value) > 1:
            cleandic.setdefault(key,value)
    return cleandic

cleandic = clean(dic)

Now for the last step I'm trying to get rid of the occurrences that happens inside the bigger ones, so I sorted the dict by reverse len of keys (bigger keys comes first), for example:

#(1,4,-5,1,4,-5) : ([7,13),(10,16)]
#...
#(1,4,-5) : [(7,10),(10,13)]

The best I came up with to take out the small ones:

sorteddic = dict(sorted(cleandic.items(), key=lambda item: len(item[0]), reverse=True))

onlybigs = {}
while len(sorteddic) > 0:
    for key1, values1 in sorteddic.items():
        for key2, values2 in sorteddic.copy().items():
            if len(key2) == len(key1):
                continue
            for value1 in values1:     #ex: (7,13)
                for value2 in values2: #ex: (7,10)
                    if value2[0] >= value1[0] and value2[1] <= value1[1]:
                        sorteddic[key2].pop(sorteddic[key2].index(value2))
        onlybigs.setdefault(key1, sorteddic.pop(key1))
        break

#and a second clean in the end
readydic = clean(onlybigs)

This last step especially is taking too long because it compares each value for each key and my guess is the whole process can be done more efficiently somehow.

Any insights?


texts: Python Binary Search Tree Implementation

texts:
#BST
class Node:
    def __init__(self, val, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right

def search(root, k):
    if root is None or root.val == k:
        return root
    elif root.val < k:
        return search(root.right, k)
    else:
        return search(root.left, k)

def minimum(root):
    if root is None or root.left is None:
        return root
    return minimum(root.left)

def maximum(root):
    if root is None or root.right is None:
        return root
    return maximum(root.right)

def successor(root, node):
    if node.right is not None:
        return minimum(node.right)
    succ = None
    while root is not None and root.val != node.val:
        if root.val > node.val:
            succ = root
            root = root.left
        else:
            root = root.right
    return succ

def predecessor(root, node):
    if node.left is not None:
        return maximum(node.left)
    else:
        pred = None
        while root is not None and root.val != node.val:
            if root.val > node.val:
                root = root.left
            else:
                pred = root
                root = root.right
        return pred

def insert(root, key):
    if root is None:
        return Node(key)
    elif root.val < key:
        return Node(root.val, root.left, insert(root.right, key))
    else:
        return Node(root.val, insert(root.left, key), root.right)

def parent(root, node):
    if root is None:
        return root
    elif (root.left is not None and root.left.val == node.val) or \
         (root.right is not None and root.right.val == node.val):
        return root
    else:
        if root.val < node.val:
            return parent(root.right, node)
        else:
            return parent(root.left, node)

def delete(root, node):
    p = parent(root, node)
    if node.left is None or node.right is None:
        replacement = node.left if node.left is None else node.right
        if p is None:
            root = replacement
        elif p.val < node.val:
            p.right = replacement
        else:
            p.left = replacement
    else:
        replacement = successor(root, node)
        succ_parent = parent(root, replacement)
        succ_parent.left = replacement.right
        node.val = replacement.val
    return root

Require code review in terms of correctness, style consistency, efficiency, code readability, and "pythonic"ness. (I, of course, welcome any other comments on the code as well)

I know that this a bit big to review completely. Reviewing only one or more methods will be appreciated.

Also, the WikiPage talks about designing persistent data structures. When should one consider such design and what are the advantages?

Github: https://github.com/abhisheksp/algorithms
(the repo has the test cases)


texts:
I am new to OSGI. I have 10 threads, writing their names to a file. After recording thread sleep random 0..1 sec, this all must be a bundle. Any comments?

package helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import writer.StartThreads;
public class Activator implements BundleActivator {
    public void start(BundleContext context) throws Exception {
        System.out.println("Start Thred!!");

        new StartThreads().Execute();
    }

    public void stop(BundleContext context) throws Exception {
        System.out.println("Goodbye World!!");
    }
}

Other class

package writer;

import writer.WriterLogs;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class StartThreads {

    public static void Execute() {
        BufferedWriter writer = null;
        File textFile = new File("threadLog.txt");
        // if file doesnt exists, then create it
        if (!textFile.exists()) {
            try {
                textFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            writer = new BufferedWriter(new FileWriter(textFile, true));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (int i = 0; i < 10; i++) {
            WriterLogs wrt = new WriterLogs(writer);
            Thread worker = new Thread(wrt);

            worker.setName("Nisha-" + i);
            worker.start();
            try {
                worker.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And second class

package writer;

import java.io.BufferedWriter;
import java.io.IOException;

public class WriterLogs implements Runnable {

    private BufferedWriter writer;

     public WriterLogs(BufferedWriter wr) {
        this.writer = wr;
    }

    @Override
    public void run() {
         try
         {
             try {
                 synchronized(this.writer) {
                 this.writer.write(Thread.currentThread().getName() + "\n");
                 }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             // set random 0...1 s.
             Thread.sleep((long)(Math.random() * 1000));
             System.out.println(Thread.currentThread().getName());
         }
         catch (InterruptedException interruptedException)
         {
            /*Interrupted exception will be thrown when a sleeping or waiting
             * thread is interrupted.
             */
             System.out.println( Thread.currentThread().getName() +interruptedException);
         }
    }

}


texts:
I'm relatively new to Python, I decided to make a simple battleship game. Is there anything I should do to make it shorter, or in practice, "better"?

from pprint import pprint as pp
import random

Rows = 0
Columns = 0
turns = 0
Answer = "NaN"

print("Welcome to battleship!")

while (Rows > 10) or (Columns > 10) or (Rows <= 0) or (Columns <= 0):
    Rows = int(input("Please enter the number of rows you want. \n"))
    Columns = int(input("Please enter the number of columns you want. \n"))

def create_grid(Rows, Columns):
    #Creates the 2D Data Grid
    grid = []
    for row in range(Rows):
        row = []
        for col in range(Columns):
            row.append(' ')
        grid.append(row)
    return grid

grid = create_grid(Rows,Columns)

def display_grid(grid, Columns):
    #Prints the labels for the grid
    column_names = 'abcdefghijklmnopqrstuvwxyz'[:Columns]
    print('  | ' + ' | '.join(column_names.upper()) + ' |')
    for number, row in enumerate(grid):
       print(number + 1, '| ' + ' | '.join(row) + ' |')

grid = create_grid(Rows, Columns)
display_grid(grid, Columns)

def random_row(grid):
    #Makes a random row integer
    return random.randint(1,len(grid))

def random_col(grid):
    #Makes a random column integer
    return random.randint(1,len(grid[0]))

def update_gridHit(grid, GuessRow, GuessColumn):
    grid[GuessRow-1][GuessColumn-1] = 'O'

def update_gridMiss(grid, GuessRow, GuessColumn):
    grid[GuessRow-1][GuessColumn-1] = 'X'

ShipRow = random_row(grid)
ShipColumn = random_col(grid)

#Testing purposes only, comment out if needed.
print(ShipRow)
print(ShipColumn)

while (turns != 5):
    GuessRow = int(input("What row do you guess? \n"))
    GuessColumn = int(input("What column do you guess? \n"))

    if (GuessRow == ShipRow) and (GuessColumn == ShipColumn):
        turns += 1
        update_gridHit(grid, GuessRow, GuessColumn)
        display_grid(grid, Columns)
        print("You hit the battleship! Congratulations!")
        break

    else:
        if (GuessRow < 1 or GuessRow > Rows) or (GuessColumn < 1 or GuessColumn > Columns):
            #Warning if the guess is out of the board
            print("Outside the set grid. Please pick a number within it your Rows and Columns.")

        elif (grid[GuessRow-1][GuessColumn-1] == "X"):
            #If "X" is there than print that it missed
            print("You guessed that already.")

        else:
            #Updates the grid with an "X" saying that you missed the ship
            turns += 1
            print("You missed the ship.")
            update_gridMiss(grid, GuessRow, GuessColumn)
            display_grid(grid, Columns)

    if (turns >= 5):
        print("Game over! You ran out of tries")


texts: Reading lines from a file and processing them concurrently

texts:
I'd like to read lines from a file and process them concurrently.  I came up with the following code to do this:

var wg sync.WaitGroup

func main(){
  file := "data/input.txt"
  reader, _ := os.Open(file)
  scanner := bufio.NewScanner(reader)
  for scanner.Scan() {
    wg.Add(1)
    go processLine(scanner.Text())
  }
  wg.Wait()
}

func processLine(line string) {
  time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
  fmt.Println("line:", line)
  wg.Done()
}

I added the random sleep time in there to simulate potential differences in processing times.

Is there any potential drawbacks that I should be aware of with this method of concurrent processing?  Are there any better ways that I should consider concurrently processing lines in a file?


texts: K&R Exercise 1-13. Printing histogram of word lengths (horizontal variant)

texts:
I'm going through the K&R book (2nd edition, ANSI C ver.) and want to get the most from it. How does the following solution look to you? Note that, for the sake of exercise, I don't want to use techniques not introduced yet in the book. Also, I'm trying to reuse whatever code/philosophy already presented in the book.

/* Exercise 1-13. Write a program to print a histogram of the lengths of words in
 * its input. It is easy to draw the histogram with the bars horizontal; a vertical
 * orientation is more challenging.
 * */
/* Solution 1: Horizontal Bars
 * */
#include <stdio.h>

#define MAXLEN  10  /* Any word longer than this will get counted in the >MAXLEN histogram.
                     * For output formatting, the program assumes this won't be greater than 999.
                     * */
#define IN      1   /* inside a word */
#define OUT     0   /* outside a word */

int main()
{
    int c, state;
    int i, j;
    int histo[MAXLEN+1];
    int counter;

    for (i = 0; i < MAXLEN+1; ++i)
        histo[i] = 0;

    /* Perform the counting */
    state = OUT;
    counter = 0;
    while ((c = getchar()) != EOF)
        if (c == ' ' || c == '\n' || c == '\t') {
            if (state == IN && counter > 0) {
                if (counter-1 < MAXLEN)
                    ++histo[counter-1];
                else
                    ++histo[MAXLEN];
            }
            state = OUT;
            counter = 0;
        }
        else {
            ++counter;
            if (state == OUT)
                state = IN;
        }

    /* Print horizontal histogram. I'd use a function for formatting
     * with regards to max. number of digits, but functions haven't
     * been introduced yet.
     * */
    for (i = 0; i < MAXLEN; ++i) {
        if (MAXLEN < 10)
            printf(" %1d | ", i+1);
        else if (MAXLEN < 100)
            printf(" %2d |", i+1);
        else
            printf(" %3d |", i+1);
        for (j = 0; j < histo[i]; ++j)
            putchar('*');
        putchar('\n');
    }
    if (MAXLEN < 10)
        printf(">%1d |", i);
    else if (MAXLEN < 100)
        printf(">%2d |", i);
    else
        printf(">%3d |", i);
    for (j = 0; j < histo[i]; ++j)
        putchar('*');
    putchar('\n');
}

Output when run on the program code:

$ cat ch1-ex-1-13-01.c | ./ch1-ex-1-13-01
  1 |*********************************************************
  2 |****************************************************************
  3 |***************************************
  4 |************************************
  5 |**************
  6 |**********
  7 |************************
  8 |***********
  9 |*******
 10 |*********
>10 |**************


texts:
New to Python, learned a couple things. I'm trying to make a text based game and was told to come here for a review. Any tips would be appreciated to improve my code. I would like to expand this the more I learn.

import time
import random

def  game():
    #intro text
    print('******************************')
    print('     Welcome to the game!')
    print('*******************************')

    time.sleep(1)

    print('You awaken in a cave, unable to see. Darkness surrounds you.')
    time.sleep(1)
    print('\nSuddenly a small flickering light is seen in the distance.')
    time.sleep(1)
    print('\nyou get on your feet and decide wether you should head towards the light or wait where you are and hope help finds its way.')

#first question
def firstquestion():
    while True:
        print('\nDo you get up and see what could be the source of this light? \nOr do you wait?')
        Answer = input()
        if Answer == 'get up' or Answer == 'I get up':
            print('You begin to walk towards the light.')
            break
        elif Answer == 'wait':
            print('you wait, no one comes and you die...')
            break
        else:
            print('try again...')
#second question
def secondquestion():
    while True:
        print('\nThe light turns out to be a torch. Do you take this torch? enter y / n. ')
        Answer = input()
        if Answer == 'y':
            print('good choice, you pick up the torch and walk the out of the cave.')
            break
        elif Answer == 'n':
            print('well now your blind and dead...')
            break
        else:
            print('try again...')

game()
firstquestion()
secondquestion()
print()


texts: Strict types decorator (works only with Python 3.5)

texts:
I wrote a decorator which makes Python 3.5 raise exceptions if the arguments that are passed to a type-hinted function are of the wrong type.

from typing import get_type_hints

def strict_types(f):
    def type_checker(*args, **kwargs):
        hints = get_type_hints(f)

        all_args = kwargs.copy()
        all_args.update(dict(zip(f.__code__.co_varnames, args)))

        for key in all_args:
            if key in hints:
                if type(all_args[key]) != hints[key]:
                    raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))

        res = f(*args, **kwargs)

        if type(res) == hints['return']:
            return res
        else:
            raise Exception('Type of result is {} and not {}'.format(type(res), hints['return']))

    return type_checker

It's used like this:

@strict_types
def concatenate_with_spam(text: str) -> str:
    return text + 'spam'

and if something of the wrong type is passed to the decorated function e.g. concatenate_with_spam(42) an exception is raised:

Exception: Type of text is <class 'int'> and not <class 'str'>

The part that I'm worried about is the part that checks the result. It calls the original function (to learn result of what type it returns), but returns a wrapped function type_checker that will be called one more time, so the runtime of function is (at least) multiplied by 2. Are there any other things I have missed? What can be improved here (except for not using this not-pythonic decorator and crucifying me for writing it)?


texts: Finding the longest palindrome from the given string

texts:
Recently I came across this problem which instructs me to find the longest substring which is a palindrome:

  As we all know, a palindrome is a word that equals its reverse. Here
  are some examples of palindromes: malayalam, gag, appa, amma.

  We consider any sequence consisting of the letters of the English
  alphabet to be a word. So axxb,abbba and bbbccddx are words for our
  purpose. And aaabbaaa, abbba and bbb are examples of palindromes.

  By a subword of a word, we mean a contiguous subsequence of the word.
  For example the subwords of the word abbba are a, b, ab, bb, ba, abb,
  bbb, bba, abbb, bbba and abbba.

  In this task you will given a word and you must find the longest
  subword of this word that is also a palindrome.

  For example if the given word is abbba then the answer is abbba. If
  the given word is abcbcabbacba then the answer is bcabbacb.

I got this with dynamic programming, but for larger test cases it seems I am breaking the memory barrier. When the length is about 4500, it gives me a segmentation fault. That's probably because 4500 x 4500 = 20250000, which is about \$2*10^7\$, and the size of my boolean array is too much in front of the imposed memory limit of 64 MB.

#include <iostream>
#include <cstring>
#include <string>

void longestpalin(std::string str,int n){
    bool table[n][n];                   //boolean table for keeping records of palindromes
    std::memset(table,0,sizeof(table));

    int maxLength = 0;
    for(int i=0;i<n;i++){
        table[i][i] = true; // obviously every letter is palindrome of itself
    }

    int start = 0;

    for(int i=0;i<n-1;i++){
        if(str[i] == str[i+1]){
            table[i][i+1] = true; //two letters repeated is also a palindrome
            maxLength = 2;
            start = i;
        }
    }

    for(int k=3;k <= n;k++){
        for(int i=0;i<n-k+1;i++){
            int j = i + k - 1;
            if(table[i+1][j-1]&&str[i] == str[j]){//checking whether the middle letters are in a pallindrome or not
                table[i][j] = true;
                if(k > maxLength){
                    maxLength = k;
                    start = i;
                }
            }
        }
    }
    std::cout << maxLength << std::endl;
    std::cout << str.substr(start,maxLength) << std::endl;
}

int main (int argc, char const* argv[])
{
    int n;
    std::cin >> n;
    std::string word;
    std::cin >> word;
    longestpalin(word,n);
    return 0;
}

Is there a better approach to avoid a segmentation fault?


texts: Using combinations of OR and AND filters with RxJava

texts:
I'm trying to work out a way to create a combination of OR and AND filters in RxJava. Here's what I've done so far:

public interface IFilter<T> extends Transformer<T, Boolean> {}

public class OrFilter implements IFilter<T> {
    private final Observable<IFilter<T>>    filters;

    public OrFilter(Iterable<IFilter<T>> filters) {
        this.filters = Observable.from(filters);
    }

    @Override
    public Observable<Boolean> call(Observable<T> o) {
        return filters
            .flatMap(f -> o.compose(f))
            .exists(b -> b);
    }
}

public class AndFilter implements IFilter<T> {
    private final Observable<IFilter<T>>    filters;

    public OrFilter(Iterable<IFilter<T>> filters) {
        this.filters = Observable.from(filters);
    }

    @Override
    public Observable<Boolean> call(Observable<T> o) {
        return filters
            .flatMap(f -> t.compose(f))
            .all(b -> b);
    }
}

Abstract class to create simple filters:

public abstract class BaseSimpleFilter<T> implements IFilter<T> {

    private Func1<T, Boolean>   filter;

    protected abstract Func1<T, Boolean> filter();

    @Override
    public Observable<Boolean> call(Observable<T> observable) {
        if (this.filter == null) {
            this.filter = filter();
        }
        return observable
            .filter(this.filter)
            .exists(b -> true);
    }
}

That works nice and does what I expect. I've recently read "Don't break the chain: use RxJava's compose() operator", so that's what I tried to do. The thing is I have here to combine flatMap with compose to achieve my goal, so the compose inside the flatMap loses a bit of its value. Plus, I'm worried this would be too costly in terms of process time.

Is there a better (more performant in terms of process time) Rx way to combine filters efficiently that I missed?


texts:
I am developing a game, its map is based on a 2D city. The city is being generated as string, # are streets, O are buildings.

Here is an example:

#######
#OOOOO#
#OOOOO#
#######
#OOOOO#
#OOOOO#
#######

Now I am replacing the Os with other buildings, by replacing the character with an other. The other buildings are defined in a dictionary, where the identifying character is the key and the value is a number between 1 and 100 which is the propability of the building to replace an O.

Currently I am doing it like this:

// Turn city into charArray
char[] cityChars = renderedCity.ToCharArray();

// Cycle through all KeyValuePairs, ordered by Value ascending
foreach (KeyValuePair<char, byte> kvp in specialBuildings.OrderBy(key => key.Value))
{
    Random r = new Random(seed);
    // Do the following for all normal buildings in the city
    // If a random seeded number is smaller or equal to the propability of the spawn, change the building into the new one
    cityChars = cityChars.Select(c => c == 'O' ? (r.Next(0, 100) <= kvp.Value ? kvp.Key : c) : c).ToArray();
}

Is there a more elegant way to do this? In the best case, this would be achieved by using no loops at all, but I am struggling with LINQ a bit.


texts: Simple mathematical operations (add, sub, mul, div) in C++11 template

texts:
I made a simple script to implement basic mathematics operations by using variadic functions. I would like to know if my implementation is correct.

The code only works for Visual C++ compiler Nov 2013 CTP (CTP_Nov2013).

#include <iostream>
#include <string>
#include <exception>
using namespace std;

template <typename T>
T add(T&& item = T())
{
    return forward<T>(item);
}

template <typename T, typename ... Types>
auto add(T&& first, Types&& ... rest)
    -> decltype(first + add(forward<Types>(rest)...))
{
    return forward<T>(first) + add(forward<Types>(rest)...);
}

template <typename T>
T sub(T&& i = T())
{
    return forward<T>(i);
}

template <typename T, typename ... Types>
auto sub(T&& first, Types&& ... rest)
-> decltype(forward<T>(first) - sub(forward<Types>(rest)...))
{
    return forward<T>(first) - sub(forward<Types>(rest)...);
}

template <typename T>
T multiple(T&& i = T())
{
    return forward<T>(i);
}

template <typename T, typename ... Types>
auto multiple(T&& first, Types&& ... rest)
-> decltype(forward<T>(first) * multiple(std::forward<Types>(rest)...))
{
    return forward<T>(first) * multiple(forward<Types>(rest)...);
}

template <typename T>
T divide(T&& item = T())
{
    return forward<T>(item);
}

template <typename T, typename ... Types>
auto divide(T&& first, Types&& ... rest)
    -> decltype(forward<T>(first) / divide(forward<Types>(rest)...))
{
    if (divide(forward<Types>(rest)...) == 0)
        throw "Opps divided by Zero";
    return forward<T>(first) / divide(forward<Types>(rest)...);
}

template<typename... Types>
void termnate(Types&&...)
{
    std::cout << '\n';
}

template<typename... Types>
void result(Types&&... t)
{
    termnate{ ([&]{ std::cout << forward<Types>(t) << ' '; }(), 1)... };
}

int main()
{
    result(     add(1, 2.5, 3, 4, 5), " = ", "1 + 2,5 + 3 + 4 + 5");

    result(sub(sub(sub(sub(1, 2.5), 3), 4), 5), " = ", "1 - 2.5 - 3 - 4 - 5"); // OK = -13.5

    result(multiple(1, 2.5, 3, 4, 5), " = ", "1 x 2.5 x 3 x 4 x 5");

    result(divide(divide(divide(divide(1, 2.5), 3), 4.5), 5), " = ", "1 / 2.5 / 3 / 4 / 5"); // OK = .005926

    cout << add("\nTest ", "template: ", string("PASS\n"));
}


texts: Pythonic way to add each previous element in list

texts:
It's a very simple question, but I wonder if there is a more pythonic way to add each previous elements in a list like this (for example with a list comprehension maybe) :

input : L = [4, 2, 1, 3]
output : new_L = [4, 6, 7, 10]

Which I've done this way :

def add_one_by_one(L):
    new_L = []
    for elt in L:
        if len(new_L)>0:
            new_L.append(new_L[-1]+elt)
        else:
            new_L.append(elt)
    return new_L

new_L = add_one_by_one(L)


texts: Discovering words from letters in Clojure (Letterpress Solver)

texts:
I created a Letterpress solver that will take a string of letters and return a list of valid words that can be constructer with the provided letters. Not all letters need to be used in each word.

This works by reading all words into a list named dictionary, transforming that list of words into a map, letter-permutations, keyed on ordered letters (as a list of characters) with values of vectors containing anagrams of the key letters.

Then, calling find-words with a string of letters and a lower bound for word length, will find all distinct combinations of those letters with lengths from the lower bound to the size of the input string.

The combinations are then map'd over letter-permutations to pull out all valid words that can be made.

(def dictionary
  (clojure.string/split-lines (slurp "words")))

(def letter-permutations
  (group-by sort dictionary))

(defn get-combinations
  [letters lower-bound upper-bound]
  (mapcat #(distinct (combo/combinations letters %)) (range lower-bound (inc upper-bound))))

(defn find-words
  [letters lower-bound]
  (mapcat letter-permutations (get-combinations (sort letters) lower-bound (count letters))))

This works extremely well for letter Strings up to 22 characters in length. But with 23 characters and upwards there is a drastic increase in the amount of time taken, when the response will come in bursts of words with long pauses (garbage collection?) between each batch.

My testing for the above stats has been with the string "otxtzlsunowayzoyiwqyocetl" (which may of may not be my current board :)), but I've experienced the same same behaviour occurring for other strings as well.

I'm happy to hear feedback on all of the code, but particularly for insights to the cause of the bottlenecks and suggestions of how I could improve this.

Full source code can be seen on Github


texts: Whitelist input data for a lookup by name

texts:
I'm whitelisting the input data to an LDAP/AD search on 'sn' (=surname). The purpose is to stop penetration attacks through the app and into the LDAP servers (i.e. no brackets, please).

// whitelist input data.
string partialName = Regex.Replace(partialName, "[^. a-zA-Z-']", string.Empty);

Do you think this is a useful subset? I don't want to allow anything bad through but it does need to be usable.

UPDATE

Instead of whitelisting I should be escaping characters (@200_success):

// escape LDAP filter string characters.
partialName =
    partialName
    .Replace(@"\", @"\5c")
    .Replace(@"*", @"\2a")
    .Replace(@"(", @"\28")
    .Replace(@")", @"\29");

This works against my LDAP server. I can't pass an asterisk anyway as the interface is a REST url and that causes a Request.Path exception.


texts: Converting a SecureString to a byte array

texts:
Does it allocates something that hasn't freed? Something that remains in memory? Except result byte array, ofc.

private unsafe byte[] ToByteArray(SecureString secureString, Encoding encoding = null)
{
    if (secureString == null)
        throw new ArgumentNullException(nameof(secureString));
    if (encoding == null)
        encoding = Encoding.UTF8;

    int maxLength = encoding.GetMaxByteCount(secureString.Length);

    IntPtr bytes = Marshal.AllocHGlobal(maxLength);
    IntPtr str   = Marshal.SecureStringToBSTR(secureString);

    try
    {
        char* chars = (char*)str.ToPointer();
        byte* bptr  = (byte*)bytes.ToPointer();
        int len     = encoding.GetBytes(chars, secureString.Length, bptr, maxLength);

        byte[] _bytes = new byte[len];
        for (int i = 0; i < len; ++i)
        {
            _bytes[i] = *bptr;
            bptr++;
        }

        return _bytes;
    }
    finally
    {
        Marshal.FreeHGlobal(bytes);
        Marshal.ZeroFreeBSTR(str);
    }
}


texts:
I would like to ask those of you, who are a little bit more expirienced in development. I would like to ask about toString() method usage. In what situations do you use it?

I've found some info about it, for example here, but it's not what I'm looking for.

Is there any convension which says when should I use it for my custom objects? In model layer or in view? Let me show a simple example...

I've got a class called "Component". Component has some name, values etc... One of the fields can be a perfect information for the user about object's state. The rest is also important, but not nessesary to display on the screen (in a view layer). Moreover, this field is a String and should be translated depending on the language settings. It's also required to present this field as an upperCase().

So, the question is:
Should I put all the logic connected with forming a "user-friendly" string (locals, upperCase...) in a toString() method? Or maybe I should create a getUserFriendlyName() method instead and use toString(), for instance, for debugging (so in model). So, should toString() method have any influence on what the end user can see on the screen?

    @Override
    public String toString() {
        String toReturn;
        try {
            toReturn = language.getString("LOCAL_STRING_KEY_" + this.compInfo);
        } catch (MissingResourceException e) {
            logger.warning("No key found for " + compInfo);
            toReturn = this.compInfo;
        }
        return toReturn;
    }


texts: How many of a particular item of clothing do I need?

texts:
I am learning Go and want to do things the go-way, please have a look this code suggest how to make it better Go.

This is a simulation to determine how items of a particular type of clothing you need. Rules are as follows:

Simulation starts with all the clothes in the clean pile
Every morning you take one item from the clean pile and add it to the dirty pile (assuming an item of clothing becomes dirty the moment you put it on)
On wash days - before you put on a new item - all the items in the dirty pile go into washing pile
Every morning all items in the washing pile are put into the clean pile

Assuming there is a washing day every Monday, how many items of clothing do you need to never run out of clean ones?

There are some extra rules (I have made them flags):

Every second Thursday is also a washing day
There is an extra step in the washing process - drying. After an item is washed, the next day it is put into the drying pile, and only after drying does it go into the clean pile.

Code in the go-playground at: https://play.golang.org/p/3jawv55Y3p

package main

import (
    "flag"
    "fmt"
    "time"
)

func even(number int) bool {
    return number%2 == 0
}

func isWashingDay(today time.Time, thursday bool) bool {
    if today.Format("Mon") == "Mon" {
        fmt.Println("Monday!")
        return true
    } else if thursday && today.Format("Mon") == "Thu" {
        _, week := today.ISOWeek()
        if even(week) {
            fmt.Println("Thursday!")
            return true
        }
    }
    return false
}

func main() {
    numberOftshirtsPtr := flag.Int("shirts", 9, "a int number of tshirts")
    thursdayPtr := flag.Bool("thursday", true, "a bool use Thursday")
    dryingPtr := flag.Bool("drying", true, "a bool use drying")
    flag.Parse()

    var clean, minClean = *numberOftshirtsPtr, *numberOftshirtsPtr
    var dirty, washing, drying int
    today, _ := time.Parse(time.RFC3339, "2017-02-06T00:00:00+00:00")

    fmt.Println("Date       | C | D | W | Y ")

    testDays := 365
    for i := 0; i < testDays; i++ {
        if *dryingPtr {
            clean += drying
            drying = 0

            drying = washing
            washing = 0
        } else {
            clean += washing
            washing = 0
        }

        if clean == 0 {
            fmt.Println("Run out of clean shirts!")
            break
        }

        if isWashingDay(today, *thursdayPtr) {
            washing = dirty
            dirty = 0
        }

        // take a clean tshirt and wear it - it immediately becomes dirty
        clean--
        dirty++

        if clean < minClean {
            minClean = clean
        }

        fmt.Printf("%s | %d | %d | %d | %d \n", today.Format("2006-01-02"), clean, dirty, washing, drying)

        today = today.AddDate(0, 0, 1)
    }

    fmt.Println("Total days:", testDays)
    fmt.Println("Minimum clean shirts:", minClean)
}


texts: Optimising an iterative function over long strings

texts:
I'm doing a coding challenge for fun and to work on my skills - some of you may remember the Advent of Code challenge from last December, I'm working through that. I've got this code as the solution to one of the problems, which works, but it's uselessly slow.

inp = "1113122113"

def iterate(num):
    pos = 0
    new = ""
    while pos < len(num):
        counter = 0
        d = num[pos]
        for i in range(pos, len(num)):
            if num[i] == d:
                counter += 1
            else:
                break
        new+=str(counter)
        new+=str(d)
        pos += counter
    print len(new)
    return new

for i in range (50):
    inp = iterate(inp)

Past iteration 35 or so, it gets to the point where it's taking several minutes for each iteration. The objective is to generate a look-and-say sequence - so 1 goes to 11, then 21, 1211, 111221, 3112211 and so on. I need to find the length of the string after the 50th iteration, but it's 360154 characters long after 40 iterations and my code just isn't optimised enough to handle strings that long in a reasonable time. Can anyone give me some pointers?


texts:
A while ago I started working on a project, which does things mostly with jQuery and PHP. I had some problems with my structure and started using CodeIgniter which uses an MVC pattern. So the PHP part is all good now.

I am just a little worried about my jQuery code. It looks bloated and I feel like there is room for improvement. The problem is that the code is very simple and I don't know how to actually improve it.

My code looks like this:

$(function() {
    var baseURL = "index.php/";

    /* *
     * Fill the  list with all available objects
     */
        $(document).ready(function() {
            $.ajax({
                type: "POST",
                url: baseURL+"Objects/getList",
                dataType: "json",
                data: "",
                cache: false,
                success: function(data) {
                    $('#object-list').html();

                    var objects= "";
                    for (var i = 0; i < data.length; i++) {
                        objects+= "<option value='" + data.id +"'>" + data[i].name + "</option>";
                    }

                    $('#object-list').html(options);
                }
            });
        });

    /* *
     * Authenticate and login using a username and password
     */
        $('#login').click(function(event) {
            var username = $("#login-username").val();
            var password = $("#login-password").val();

            $.ajax({
                type: "POST",
                url: baseURL+"User/authenticateUser",
                dataType: "json",
                data: "username="+ username +"&password=" + password,
                success: function(data) {
                    var success = data.result;

                    if (!success) {
                        $("#login-window-inner-message").html("The credentials provided were not found. Please try again.");
                    } else {
                        $('#login-window').remove();
                        LoadGame();
                    }
                }
            });
        });

    /* *
     * Run all functions part of the startup procedure
     */
        function LoadGame() {
            UpdateNavigation();
            DisplayUserInfo();
        }

    /* *
     * Update the action screen
     */
        function UpdateActions() {
             $.ajax({
                type: "POST",
                url: baseURL+"Location/getOptions",
                dataType: "json",
                data: "",
                success: function(data){
                    $("#action1").html(typeof data.option1 != 'undefined' ? data.option1.title : "
");
                    $("#action2").html(typeof data.option2 != 'undefined' ? data.option2.title : "
");
                    $("#action3").html(typeof data.option3 != 'undefined' ? data.option3.title : "
");
                }
            });
        }

    /* *
     * Display the description of the current zone
     */
        function DisplayZoneDescription() {
             $.ajax({
                type: "POST",
                url: baseURL+"Location/getZoneDesciption",
                dataType: "json",
                data: "",
                success: function(data){
                    $("div#message-log").html("
" + data.description + "
");
                }
            });
        }
});

That's not the entire code (so some called functions might not be there), which would be too long to post here. But the gist of it is that I have about a hundred "hooks" to HTML elements which all fire an Ajax function which returns data after which the screen is updated.

Some things that come to mind:

In an MVC environment, should the Ajax data part be in the URL?
I will be splitting up the functions into different files an the production environment.
The main problem I'm having with this is that it just looks like it's hanging loosely together, and doesn't fit my structured MVC environment/code.


texts: Check value from two different dictionary with matched key

texts:
I have two dictionary with different keys but each key in dictionary is matched like job matches JobType, position matches PositionName, etc and I will like to compare if datadict value equals to exp value. I have following code and result is correct.
However, what is the better way for me to do it?

res = {}
exp = dict(
    job=['engineer', 'PM', 'teacher'],
    position=['officer', 'CEO', 'CFO'],
    name=['bob', ['John', 'amy']]
)
datadict = dict(JobType='teacher', PositionName='CEO', Name='a')
datadict2 = dict(JobType='teacher', PositionName='CEO', Name='x')
for j, v in zip(['job', 'position', 'name'], ['JobType', 'PositionName', 'Name']):
    res[j] = datadict[v]

for e, r in zip(sorted(exp), sorted(res)):
    if r == 'name':
        print(any(res[r] in s for s in exp[e][1]))
    else:
        print(res[r] in exp[e])

# result from datadict: True, True, True
# result from datadict2: True, False, True


texts:
I am learning Go by writing a simple CRUD REST API using gotilla/mux and Gorm.

I would like to get some feedback on the application code and on unit tests in particular. Please suggest me what to improve, what to do better, what not to do and generally tell me what comes to your mind.

func TestGetAllStudents(t *testing.T) {
    app := initApp()
    st := student{ID: "id-1", Age: 20, Name: "John Doe"}
    app.db.Save(st)
    req, _ := http.NewRequest("GET", "/students", nil)
    r := httptest.NewRecorder()
    handler := http.HandlerFunc(app.getAllStudents)

    handler.ServeHTTP(r, req)

    checkStatusCode(r.Code, http.StatusOK, t)
    checkContentType(r, t)
    checkBody(r.Body, st, t)
}

func TestAddStudent(t *testing.T) {
    app := initApp()
    var rqBody = toReader(`{"name":"John Doe", "age":20}`)
    req, _ := http.NewRequest("POST", "/students", rqBody)
    r := httptest.NewRecorder()
    handler := http.HandlerFunc(app.addStudent)

    handler.ServeHTTP(r, req)

    checkStatusCode(r.Code, http.StatusCreated, t)
    checkContentType(r, t)
    checkProperties(firstStudent(app), t)
}

func TestUpdateStudent(t *testing.T) {
    app := initApp()
    app.db.Save(student{ID: "id-1", Age: 25, Name: "Peter Doe"})
    var rqBody = toReader(`{"name":"John Doe", "age":20}`)
    req, _ := http.NewRequest("PUT", "/students/id", rqBody)
    req = mux.SetURLVars(req, map[string]string{"id": "id-1"})
    r := httptest.NewRecorder()
    handler := http.HandlerFunc(app.updateStudent)

    handler.ServeHTTP(r, req)

    checkStatusCode(r.Code, http.StatusOK, t)
    checkContentType(r, t)
    checkProperties(firstStudent(app), t)
}

func TestDeleteStudent(t *testing.T) {
    app := initApp()
    app.db.Save(student{ID: "id-1", Age: 20, Name: "John Doe"})
    req, _ := http.NewRequest("DELETE", "/students/id", nil)
    req = mux.SetURLVars(req, map[string]string{"id": "id-1"})
    r := httptest.NewRecorder()
    handler := http.HandlerFunc(app.deleteStudent)

    handler.ServeHTTP(r, req)

    checkStatusCode(r.Code, http.StatusOK, t)
    checkContentType(r, t)
    checkDbIsEmpty(app.db, t)
}

func initApp() App {
    db, _ := gorm.Open("sqlite3", ":memory:")
    db.AutoMigrate(&student{})
    return App{db: db}
}

func firstStudent(app App) student {
    var all []student
    app.db.Find(&all)
    return all[0]
}

func toReader(content string) io.Reader {
    return bytes.NewBuffer([]byte(content))
}

func checkStatusCode(code int, want int, t *testing.T) {
    if code != want {
        t.Errorf("Wrong status code: got %v want %v", code, want)
    }
}

func checkContentType(r *httptest.ResponseRecorder, t *testing.T) {
    ct := r.Header().Get("Content-Type")
    if ct != "application/json" {
        t.Errorf("Wrong Content Type: got %v want application/json", ct)
    }
}

func checkProperties(st student, t *testing.T) {
    if st.Name != "John Doe" {
        t.Errorf("Name should match: got %v want %v", st.Name, "Peter Doe")
    }
    if st.Age != 20 {
        t.Errorf("Age should match: got %v want %v", st.Age, 20)
    }
}

func checkBody(body *bytes.Buffer, st student, t *testing.T) {
    var students []student
    _ = json.Unmarshal(body.Bytes(), &students)
    if len(students) != 1 {
        t.Errorf("Wrong lenght: got %v want 1", len(students))
    }
    if students[0] != st {
        t.Errorf("Wrong body: got %v want %v", students[0], st)
    }
}

func checkDbIsEmpty(db *gorm.DB, t *testing.T) {
    var students []student
    db.Find(&students)
    if len(students) != 0 {
        t.Errorf("Student has not been deleted")
    }
}

Here are the concerns I already have (not sure, how relevant they are):

I didn't manage to mock DB, that's why I am using an in-memory DB
The verification code was too verbose, I extracted it into separate functions. Is it something you would do?
I didn't manage to test negative scenarios (as a result of the first concern).
I don't like having to call mux.SetURLVars to inject a path variable. How to do this better?
I didn't manage to test the code that initializes Mux routers


texts: MySQL stored procedure to search medical insurance claims

texts:
This stored procedure is taking a lot of time to execute. How can I optimize this query?

USE `asddadad`$$

DROP PROCEDURE IF EXISTS `repbillingpaymentsummary`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `repbillingpaymentsummary`(IN ptype VARCHAR(100), IN pAccountCodes VARCHAR(4000),
IN pFromDOS DATE, IN pToDOS DATE, IN pFromDOP DATE, IN pToDOP DATE, IN pFromDOE DATE, IN pToDOE DATE,
IN psalesCodes VARCHAR(4000))
BEGIN

    IF ptype = 'accountCode' THEN
        SELECT
            practiceCode AS dataCode, NAME AS dataName,
            IFNULL(SUM(IFNULL(creditAmount,0)),0) AS totalPayment
        FROM
            claimdetail clm, practice prac

        WHERE
            clm.practiceCode = prac.code
        AND
            clm.transType = 2
        AND
            clm.active = 1
        AND
            clm.fromDOS >= COALESCE(pFromDOS,clm.fromDOS)
        AND
            clm.fromDOS <= COALESCE(pToDOS,clm.fromDOS)
        AND
            clm.DOP >= COALESCE(pFromDOP,clm.DOP)
        AND
            clm.DOP <= COALESCE(pToDOP,clm.DOP)
        AND
            clm.DOE >= COALESCE(pFromDOE,clm.DOE)
        AND
            clm.DOE <= COALESCE(pToDOE,clm.DOE)
        AND
            FIND_IN_SET(clm.practiceCode,COALESCE(pAccountCodes,clm.practiceCode))
        AND
            FIND_IN_SET(IFNULL(clm.accountGroupName,'NA'),COALESCE(psalesCodes,IFNULL(clm.accountGroupName,'NA')))

        GROUP   BY
            clm.practiceCode

        ORDER BY
            totalPayment DESC;
    END IF;

    IF ptype = 'insCode' THEN
        SELECT
            tranPatientInsuranceCode AS dataCode, NAME AS dataName,
            IFNULL(SUM(IFNULL(creditAmount,0)),0) AS totalPayment
        FROM
            claimdetail clm, insurance ins

        WHERE
            clm.tranPatientInsuranceCode = ins.code
        AND
            clm.transType = 2
        AND
            clm.active = 1
        AND
            clm.fromDOS >= COALESCE(pFromDOS,clm.fromDOS)
        AND
            clm.fromDOS <= COALESCE(pToDOS,clm.fromDOS)
        AND
            clm.DOP >= COALESCE(pFromDOP,clm.DOP)
        AND
            clm.DOP <= COALESCE(pToDOP,clm.DOP)
        AND
            clm.DOE >= COALESCE(pFromDOE,clm.DOE)
        AND
            clm.DOE <= COALESCE(pToDOE,clm.DOE)
        AND
            FIND_IN_SET(clm.practiceCode,COALESCE(pAccountCodes,clm.practiceCode))
        AND
            FIND_IN_SET(IFNULL(clm.accountGroupName,'NA'),COALESCE(psalesCodes,IFNULL(clm.accountGroupName,'NA')))
        AND
            IFNULL(zeroTrans,0) = 0
        GROUP   BY
            clm.tranPatientInsuranceCode

        ORDER BY
            totalPayment DESC;
    END IF;

    IF ptype = 'CPTCode' THEN
        SELECT
            CPTCode AS dataCode, cpt.shortDescription AS  dataName,
            IFNULL(SUM(IFNULL(creditAmount,0)),0) AS totalPayment
        FROM
            claimdetail clm, cptcodes cpt

        WHERE
            clm.CPTCode = cpt.code
        AND
            clm.transType = 2
        AND
            clm.active = 1
        AND
            clm.fromDOS >= COALESCE(pFromDOS,clm.fromDOS)
        AND
            clm.fromDOS <= COALESCE(pToDOS,clm.fromDOS)
        AND
            clm.DOP >= COALESCE(pFromDOP,clm.DOP)
        AND
            clm.DOP <= COALESCE(pToDOP,clm.DOP)
        AND
            clm.DOE >= COALESCE(pFromDOE,clm.DOE)
        AND
            clm.DOE <= COALESCE(pToDOE,clm.DOE)
        AND
            FIND_IN_SET(clm.practiceCode,COALESCE(pAccountCodes,clm.practiceCode))
        AND
            FIND_IN_SET(IFNULL(clm.accountGroupName,'NA'),COALESCE(psalesCodes,IFNULL(clm.accountGroupName,'NA')))

        GROUP   BY
            clm.CPTCode

        ORDER BY
            totalPayment DESC;
    END IF;

    END$$

DELIMITER ;


texts: Using prototypes creating a Hangman game

texts:
I have a Hangman object constructor with a couple of methods connected to it.

I would like to know how I should encapsulate the logic.

Can I have logic outside the methods (as I'm doing, like hangman.letters.push(e.key);) on document.onkeydown or should I only call the methods here and they should strictly run the game?

Any logic improvements are welcome!

Thank you very much!

var hangman;

function Hangman() {
  this.words = ["sweden", "brazil", "spain", "germany"];
  this.secretWord = "";
  this.letters = [];
  this.guessedLetter = "";
  this.errorsLeft = 5;
  this.messages = {
    win: "You won!",
    loose: "Game over!",
    guessed: "You already guessed this letter, please try again..",
    notValidLetter: "Please enter a valid letter from a-z",
  };
}

Hangman.prototype._getWord = function() {
  return this.words[Math.floor(Math.random() * this.words.length)];
};

Hangman.prototype._checkIfLetter = function(keyCode) {
  return /^[a-zA-Z]*$/.test(String.fromCharCode(keyCode));
};

Hangman.prototype._checkClickedLetters = function(key) {
  return !this.letters.includes(key);
};

Hangman.prototype._addCorrectLetter = function(key) {
  if (this.secretWord.includes(key)) {
    console.log(`${key} is part of the secret word`);
    for (let ix = 0; ix < hangman.secretWord.length; ix++) {
      if (hangman.secretWord[ix] === key) {
        this.guessedLetter += key;
      }
    }
    if (this._checkWinner()) {
      console.log(this.messages.win);
    }
  } else {
    console.log(`${key} is NOT part of the secret word`);
    this._addWrongLetter();
    if (this._checkGameOver()) {
      console.log(this.messages.loose);
    }
  }
};

Hangman.prototype._addWrongLetter = function(letter) {
  return this.secretWord.includes(letter)
    ? this.errorsLeft
    : (this.errorsLeft -= 1);
};

Hangman.prototype._checkGameOver = function() {
  return this.errorsLeft === 0;
};

Hangman.prototype._checkWinner = function() {
  return (
    this.secretWord
      .split("")
      .sort()
      .join("") ===
    this.guessedLetter
      .split("")
      .sort()
      .join("")
  );
};

document.getElementById("start-game-button").onclick = function() {
  hangman = new Hangman();
  hangman.secretWord = hangman._getWord();
  console.log(hangman.secretWord);
};

document.onkeydown = function(e) {
  if (hangman != undefined) {
    // Check if char is a valid alpha char.
    if (hangman._checkIfLetter(e.keyCode)) {
      // Check if we already
      if (hangman._checkClickedLetters(e.key)) {
        hangman._addCorrectLetter(e.key);
        hangman.letters.push(e.key);
      } else {
        console.log(hangman.messages.guessed);
      }
    }
  } else {
    console.log(hangman.messages.notValidLetter);
  }
};
.game-logo {

}

#start-game-button {
  border: 0;
  box-shadow: 0;
  background: linear-gradient(to bottom, #9DA400, #BAC600);
  color: #fff;
  padding: 20px 40px;
  font-size: 30px;
  border-radius: 5px;
}

#hangman {
  text-align: center;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="stylesheets/styles.css">
  <title>The Hangman</title>

    <button id="start-game-button">START GAME</button>

    <canvas id="hangman" height="800px" width="1200px"></canvas>


texts:
Rails AR. validate one field, with 4 validators & 2 condition block

validates :inn,
          presence: { if: -> { user.is_a?(Client) } },
          inn: { if: -> { user.is_a?(Client) } },
          uniqueness: { if: -> { user.is_a?(Client) } },
          absence: { if: -> { user.is_a?(Department) } }

Could I have some tips on refactoring this?


texts:
I want to check if all items of a list meet a set of criteria:

bool AreValid(list<string> vals)
{
   bool allValid=true;

   foreach(string val in vals)
   {
       if(!condition1)
          ...
          allValid=false;
       else if(!condition2)
          ...
          allValid=false;
   }

   return allValid;

}

The reason I can't use LINQ All() is that for each failed condition I'm doing some job.

is it safe to set allValid as true by default?


texts: Largest palindrome that can be made from a product of 2 3-digit numbers (Project Euler 4)

texts:
This is my solution to Project Euler #4, which asks for the largest palindrome that can be made from a product of 2 3-digit numbers. I have done a brute force method, but it takes around 10-20 seconds to run. It works by looping through 2 variables, finding its product, and converting it to a string to check for palindromity. What steps can I take to improve the computational speed of this program?

#include <cmath>
#include <string>
#include <sstream>
#include <iostream>
int main()
{
int ans=0;
for(int i=100;i<1000;i++)
    for(int j=100;j<1000;j++)
    {
        int num_to_test=i*j;
        int num_of_digits=floor(log10(num_to_test))+1;
        string num_stringstream;
        ostringstream convert;
        convert << num_to_test;
        num_stringstream=convert.str();
        int counter=0;
        for(int i=0;i<num_of_digits;i++)
        {
            if(num_stringstream[i]==num_stringstream[num_of_digits-i-1])
            {
                counter++;
                if(counter==num_of_digits)
                    num_to_test>ans?ans=num_to_test:ans=ans;
            }
        }
    }
cout << ans << endl;
char quit;
cin >> quit;
}


texts: Spending a target sum, preferably split equally

texts:
I have a strange programming prompt. I managed to complete an algorithm to solve smaller test entries (which i'll post). One of my test cases has to complete a 200,000 int input and my algorithm isn't practical. I'll post the prompt and my algorithm. How should I go about optimizing the performance to handle large input sizes?

Prompt:

  You and your friend combine your prize tickets at a carnival. You plan
  to get 2 prizes whose total price is exactly M, M-1, or M-2 tickets
  (in that order) if possible. M is how many tickets you decide to
  spend. If there are several prizes that satisfy this condition, you
  want to minimize the difference between ticket cost.

  For example, say you're given M = 5, and prize values of [2,1,4,3]..
  the output would be 2+3=5.

My SLOW solution:

#sequence actually has +2 values. [0] is how many prizes and [last] is M
#ignore the setting
def checkForPrizes(seq):
    M = seq[len(seq)-1] #priori
#    print("M:",M)
    n = seq[0] #number of inputs

    seq = strip2(seq) #removes the +2 from the "n+2" inputs
    quick_sort(seq) #sorts the prize values
#    print("seq:",seq)
    returnList = []
    leftList = seq[0:int(len(seq)/2)]
    rightList = seq[int(len(seq)/2):len(seq)]

    current = seq[int(len(seq)/2)]
    print("current=",current)

#    print("left half:",leftList)
#    print("right half:",rightList)

    s1 = 0 #prize1
    s2 = 0 #prize2

    flag = False #checks the conditions in order

    if (flag is False):
        for i in range(len(leftList)):
            s1 = leftList[i]
            for j in range(len(rightList)):
                s2 = rightList[j]
                if(s1 + s2 == M):
                    returnList = [s1,s2]
 #                   print("[",s1,",",s2,"] ","is exactly M!",sep="")
                    flag = True

    if(flag is False): #try M-1
        for i in range(len(leftList)):
            s1 = leftList[i]
            for j in range(len(rightList)):
                s2 = rightList[j]
                if(s1 + s2 == (M-1)):
                    returnList = [s1,s2]
#                    print("[",s1,",",s2,"] ","is exactly M-1!",sep="")
                    flag = True

    if(flag is False): #try M-2
        for i in range(len(leftList)):
            s1 = leftList[i]
            for j in range(len(rightList)):
                s2 = rightList[j]
                if(s1 + s2 == (M-2)):
                    returnList = [s1,s2]
#                    print("[",s1,",",s2,"] ","is exactly M-2!",sep="")
                    flag = True

    if(flag is False):
        print("NO")
    else:
#        print("sol:",returnList)
        dispVal(returnList[0],returnList[1])


texts:
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

  A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

I used this as an excuse to play around with Java 8 Streams. It's my first time actually working with streams, so I'd like reviews covering my use of the Streams.

Any comments on code style, stream usage, potential optimizations (though it still runs in less than a second on my machine) of the basic logic are appreciated.

package complete;

import java.util.HashSet;
import java.util.stream.IntStream;

public class pe023 {
    public static final int MAX_POTENTIAL_NON_ABUNDANT_SUM = 28213;

    public static void main(String[] args) {
        int result = IntStream
                .rangeClosed(1, MAX_POTENTIAL_NON_ABUNDANT_SUM)
                .parallel()
                .filter(pe023::isNonAbundantSum)
            //  .peek(System.out::println)
                .sum();

        System.out.println(result);
    }

    /**
     * A number is a Non-abundant sum if it cannot be written as the sum of two abundant numbers.
     *
     * @param num the number to check
     * @return if the number is a non-abundant sum
     */
    public static boolean isNonAbundantSum(int num) {
        for (int low=1,high=num-1; low<=high; low++,high--) {
            if (isAbundant(low) && isAbundant(high)) {
                return false;
            }
        }
        return true;
    }

    static HashSet<Integer> isAbundantCache = new HashSet<>();
    static HashSet<Integer> notAbundantCache = new HashSet<>();

    /**
     * A number is abundant if the sum of its proper divisors is greater than the number.
     *
     * @param num the number to check
     * @return if the number is abundant
     */
    public static boolean isAbundant(int num) {
        if (isAbundantCache.contains(num)) {
            return true;
        }
        if (notAbundantCache.contains(num)) {
            return false;
        }

        if (properDivisors(num).sum() > num) {
            isAbundantCache.add(num);
            return true;
        } else {
            notAbundantCache.add(num);
            return false;
        }
    }

    public static IntStream properDivisors(int num) {
        IntStream stream = IntStream.of(1);
        for (int i=2; i<=num/2; i++) {
            if (num%i == 0) {
                stream = IntStream.concat(stream, IntStream.of(i));
            }
        }
        return stream;
    }
}

// 4179871


texts: GLSL Shader that displays a Rotating Rainbow Ring

texts:
I'm learning GLSL shaders on Book of Shaders and I decided to mess around with one of the examples. I wanted to see, whats a more efficient way to calculate to mask out the color?

#ifdef GL_ES
precision mediump float;
#endif

#define TWO_PI 6.28318530718

uniform vec2 u_resolution;
uniform float u_time;

//  Function from Iñigo Quiles
//  https://www.shadertoy.com/view/MsS3Wc
vec3 hsb2rgb( in vec3 c ){
    vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.0,4.0,2.0),6.0)-3.0)-1.0,0.0,1.0);
    rgb = rgb*rgb*(3.0-2.0*rgb);
    return c.z * mix( vec3(1.0), rgb, c.y);
}

void main(){
    vec2 st = gl_FragCoord.xy/u_resolution;
    vec3 color = vec3(0.0);

    // Use polar coordinates instead of cartesian
    vec2 toCenter = vec2(0.5)-st;

    float angle = atan(toCenter.y,toCenter.x);
    float radius = length(toCenter)*2.0;

    angle = angle + u_time;

    float outsideMask = 1.0 - step(distance(st, vec2(0.5)), 0.3);
    float insideMask = 1.0 - step(0.2, distance(st, vec2(0.5)));
    float visibleArea = 1.0 - insideMask - outsideMask;

    // Map the angle (-PI to PI) to the Hue (from 0 to 1)
    // and the Saturation to the radius
    color = hsb2rgb(vec3((angle/TWO_PI)+0.5,radius, 1.0));

    gl_FragColor = vec4(color, visibleArea);
}

Here is an image of the end result.

The outsideMask, insideMask and visibleArea variables in particular all have that 1.0 minus something, which seems weird to me. Any suggestions would be appreciated!


texts: Program for CodeHS 8.3.8: Word Ladder in Python 3

texts:
I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the question below.

  Your friend wants to try to make a word ladder! This is a list of
  words where each word has a one-letter difference from the word before
  it.

  Here’s an example:

cat
cot
cog
log

  Write a program to help your friend. It should do the following:

  Ask your friend for an initial word.
  Repeatedly ask them for an index and a letter.
  You should replace the letter at the index they provided with the letter they enter.
  You should then print out the new word.
  Stop asking for input when the user enters -1 for the index.

My answer to this is:

import os
get_index = 0
word = input("Enter a word: ")
for i in range(len(word)):
    while True:
        try:
            get_index = int(input("Enter an index (-1 to quit): "))
            if get_index == -1:
                os._exit(0)
            elif get_index < -1 or get_index > 2:
                raise ValueError
        except ValueError:
            print ("Invalid index!")
        else:
            while True:
                try:
                    letter = input("Enter a letter: ")
                    for c in letter:
                        if c.isupper():
                            raise ValueError
                except ValueError:
                    print ("Character must be a lowercase letter!")
                else:
                    if len(letter) > 1:
                        print ("Must be exactly one character!")
                    else:
                        word = word[:get_index] + letter + word[get_index + 1:]
                        print (word)
                        break

NOTE #1: Here is a link to the program run (output): OUTPUT

NOTE #2: I would also like to use an alternative for os._exit() as it takes time for the program to completely end.

So, I would like to know whether I could make this code shorter and more efficient.

Any help would be highly appreciated.


texts: Improving Matlab function within big simulation

texts:
I have a very big Matlab simulation project in my hands, which I wanted to optimize, since I'm running it many times to tune parameters and the like.

Using Matlab's profile I identified one function that is eating up most of my time, specifically the output(i,1) assignment line.

This function is called a LOT, where input is a 10x1 double passed as an argument, and output is also a 10x1 vector.

function output = my_function(input)

a = size(input,1);
output = input*0;
dens = density(input);

% for each i, output(i) is the maximum between output(i+1) and mean(output(i+1:end))
for i = 1:a-1
    output(i,1)= max(mean(dens(i+1:a,1)),dens(i+1,1));
end
output(a,1) = dens(a,1);

end

density() function:

function dens = density(input)

dens = 1000*(1 - (input+288.9414)./(508929.2.*(input+68.12963)).*(input-3.9863).^2);

end

My ideas:

I think vectorization would maybe help to get rid of the loop, but I'm not familiar at all with the technique.
Is there a faster/alternative way to calculate the mean (maybe without Matlab's built-in function call?)


texts:
I wrote a sub to remove the blank entries in a row without shifting the cells around but it seems unnecessarily clunky and I'd like to get some advice on how to improve it.

Public Sub removeBlankEntriesFromRow(inputRow As Range, pasteLocation As String)
    'Removes blank entries from inputRow and pastes the result into a row starting at cell pasteLocation

    Dim oldArray, newArray, tempArray
    Dim j As Integer
    Dim i As Integer

    'dump range into temp array
    tempArray = inputRow.Value
    'redim the 1d array
    ReDim oldArray(1 To UBound(tempArray, 2))
    'convert from 2d to 1d
    For i = 1 To UBound(oldArray, 1)
        oldArray(i) = tempArray(1, i)
    Next
    'redim the newArray
    ReDim newArray(LBound(oldArray) To UBound(oldArray))
    'for each not blank in oldarray, fill into newArray
    For i = LBound(oldArray) To UBound(oldArray)
        If oldArray(i) <> "" Then
            j = j + 1
            newArray(j) = oldArray(i)
        End If
    Next
    'Catch Error
    If j <> 0 Then
        'redim the newarray to the correct size.
        ReDim Preserve newArray(LBound(oldArray) To j)
        'clear the old row
        inputRow.ClearContents
        'paste the array into a row starting at pasteLocation
        Range(pasteLocation).Resize(1, j - LBound(newArray) + 1) = (newArray)
    End If
End Sub


texts: Basic form to create, load and edit entries (server-sided stored in a text file)

texts:
To understand the basic workings of PHP I wrote a test page where one can create, load and edit entries (name-info-pairs) in a list.

It would be cool if you could give me some advice on that to improve.

<?php
class User {
  public $name;
  public $info;
  Public function __construct($name, $info){
    $this->name = $name;
    $this->info = $info;
  }
}

function show_user_radio_button($user) {
  return '<input type="radio" name="load" value="' .
  $user->name .'">' . $user->name . "
\n";
}

function read_user_from_text_line($line) {
  $cells = explode(",", $line);
  return new User($cells[0], $cells[1]);
}

function user_to_text_line($user) {
  return $user->name . ',' . $user->info;
}

function load_all_users() {
  $contents = file_get_contents('user_database.csv');
  $lines = array_filter(explode("\n", $contents));
  $allUsers = array();
  foreach ($lines as $line)
    $allUsers[] = read_user_from_text_line($line);
  return $allUsers;
}

function save_all_users($allUsers) {
  $contents = '';
  foreach ($allUsers as $user)
    $contents .= user_to_text_line($user) . "\n";
  file_put_contents('user_database.csv', $contents);
}
function save_user($newUser) {
  $allUsers = load_all_users();
  $replaced = false;
  for ($i = 0; $i < count($allUsers); $i++) {
    $user = $allUsers[$i];
    if ($newUser->name === $user->name) {
      $allUsers[$i] = $newUser;
      $replaced = true;
    }
  }
  if (!$replaced) {
    $allUsers[] = $newUser;
  }
  save_all_users($allUsers);
}
function loadUser($name) {
  $allUsers = load_all_users();
  foreach ($allUsers as $user)
    if ($user->name === $name) return $user;
  return new User('', '');
}
function sanitize($str) {
  return filter_var($str, FILTER_SANITIZE_EMAIL);
}

$newName = sanitize($_POST['name']);
$newInfo = sanitize($_POST['info']);
if ($newName && $newInfo)
  save_user(new User($newName, $newInfo));
?>

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>basic form to create and edit entries in a text file</title>

  from database:

  <form name="load" action="index.php" method="get">
    <?php
    $allUsers = load_all_users();
    foreach ($allUsers as $user)
      echo show_user_radio_button($user);
    echo '<input type="submit" value="load">';
    ?>
  </form>

  -------

  edit or create

  <form name="save" action="index.php" method="post">
    <?php
    $user = loadUser($_GET['load']);
    echo 'name: <input type="text" name="name" value="' .
    $user->name . '">
';
    echo 'info: <input type="text" name="info" value="' .
    $user->info . '">
';
    ?>
    <input type="submit" value="save">
  </form>


texts: How do I add JDBC and Queue functionality to a simple server?

texts:
I would like to add some capabilities to the server.  Firstly, it should accept and handle connections with multiple clients, so that there are no mixups between clients.  Secondly, there should be some very basic JDBC connectivity: serialize a result set as a List, and then, as requested pop from the list and send that instance to a client for updates.  When the client sends back an updated record, update the database accordingly.

package net.bounceme.dur.driver;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server {

    private static final Logger log = Logger.getLogger(Server.class.getName());
    private final RecordQueue recordsQueue = new RecordQueue();

    public static void main(String[] args) {
        Properties props = PropertiesReader.getProps();
        int portNumber = Integer.parseInt(props.getProperty("port"));
        while (true) {
            try {
                new Server().inOut(portNumber);
            } catch (java.net.SocketException se) {
                Logger.getLogger(Server.class.getName()).log(Level.FINE, "spammy", se);
            } catch (IOException ioe) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ioe);
            } catch (ClassNotFoundException cnf) {
                Logger.getLogger(Server.class.getName()).log(Level.INFO, null, cnf);
            }
        }
    }

    public void inOut(int portNumber) throws IOException, ClassNotFoundException, java.net.SocketException {
        ServerSocket serverSocket = new ServerSocket(portNumber);
        Socket socket = serverSocket.accept();
        ObjectOutputStream objectOutputStream = null;
        MyRecord recordFromClient = null;
        try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            recordFromClient = (MyRecord) objectInputStream.readObject();
        }
        objectOutputStream.flush();
        objectOutputStream.close();
        log.info(recordFromClient.toString());
    }
}

Is that a reasonable progression from this server code?  Obviously, I would only add a single feature at a time.  While I would love to learn Log4J or a similar testing framework, my immediate concern is adding functionality to server code.

What are some pitfalls I might run into?  What would be the most pragmatic approach to increasing the functionality of the server side operations?

For example, I might start with a Queue, and then only later tie that into a database.  Each client will only have access to a single record, so I'm not concerned about corrupt data.  Will there be a problem when multiple clients are trying to access the Queue, however?  The clients will only need pop and add, nothing more.  The client will update, or modify, each record instance it receives.


texts:
I made up a quick and dirty implementation of the G-Set in C#.  I was hoping for some feedback on my approach.  I'm not totally happy with having the payload public but I can't see that I'm gaining much by making it private either.

public class GrowOnlySet<T>
{
    public HashSet<T> payload {get; private set;}

    public GrowOnlySet()
    {
        payload = new HashSet<T>();
    }

    public GrowOnlySet(HashSet<T> newstore)
    {
        payload = newstore;
    }

    public void Add(T element)
    {
        payload.Add(element);
    }

    public bool Lookup(T element)
    {
        return payload.Contains(element);
    }

    public bool Compare(GrowOnlySet<T> R)
    {
        return R.payload.IsSubsetOf(this.payload);
    }

    public void Merge(GrowOnlySet<T> R)
    {
        this.payload.UnionWith(R.payload);
    }
}


texts: C program to print input longer than 10 characters

texts:
The program will read the user's input, if it's longer or equal to 10 characters, it will print it.

It's pretty compact and works fine.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000

int main(void){
    char line[MAX_SIZE];
    int length; /*String length*/

    while((fgets(line, sizeof(line), stdin) != NULL)){
        line[length = (strlen(line)-1)] = '\0'; /*Remove the \n character*/
        if(length >= 10){
            printf("%s\n", line);
        }
    }
    return 0;
}

Not looking for anything specific, method, style, etc..


texts: Code minimizer - Remove unnecessary whitespace

texts:
I often do golf challenges, and thought it might be advantageous to write some code that automatically removes all the unnecessary whitespace from a program.

After a few refactors, this is what I ended up with. In all the tests I've run it through, it's correctly removed only the whitespace that doesn't change the meaning of the program.

Example:

(minimize-code (fn [a] (+ a 1)))

"(fn[a](+ a 1))"

Limitations:

It doesn't handle line-comments well. It doesn't remove comments, so anything after the first ; is commented out.
It only removes unnecessary whitespace. Names still need to be manually shortened (maybe a later project).

What I what advice on:

Really, I'm looking for any advice. It actually ended up being much simpler than I anticipated, and I'm fairly happy with the end result. I'm sure there's room for improvement though!

(ns bits.golf.helpers.minimizer)

(def safe-neighbors
  "The characters that indicate neighboring spaces are safe to remove."
  (set "(){}[]\" \t\n"))

(def minimizer-output-path "./minimized-code.clj")

(defn can-remove-cur-char?
  "Returns whether or not a character is safe to remove.
   A character is considered unsafe to remove if it doesn't change the meaning of the program.
   Expects that if prev-char or next-char aren't available, nil will be passed."
  [prev-char cur-char next-char]
  (cond
    (not (Character/isWhitespace ^Character cur-char))
    false

    (or (nil? prev-char) (nil? next-char))
    true

    :else
    (or (safe-neighbors prev-char) (safe-neighbors next-char))))

(defn safe-remove-whitespace
  "Removes any whitespace characters that don't effect the meaning of the program."
  [code-str]
  (loop [[chr & rest-str] code-str
         acc ""]
    (if-not chr
      acc
      (let [prev-chr (if (empty? acc) nil (last acc))
            next-chr (if rest-str (first rest-str) nil)
            can-remove? (can-remove-cur-char? prev-chr chr next-chr)
            replacement-chr (if (Character/isWhitespace ^Character chr)
                              \space chr)]
        (recur rest-str
               (if can-remove? acc (str acc replacement-chr)))))))

(defn minimize-code*
  "Removes unnecessary whitespace and outputs it to minimizer-output-path, then returns the minimized code."
  [code-str]
  (let [minimized-code (safe-remove-whitespace code-str)]
    (spit minimizer-output-path minimized-code)
    minimized-code))

(defmacro minimize-code
  "Removes unneccesary whitespace and outputs it to minimizer-output-path, then returns the minimized code."
  [& body]
  (minimize-code* (apply str body)))


texts: Summing 2D NumPy array by multiple labels

texts:
Each element of the array is a coordinate (x, y).
  Each coordinate has two labels.

  Goal:
      sum the elements that have the same two labels.

How can this be made faster?

import numpy
from scipy import ndimage

label1 = numpy.array([0, 0, 1, 1, 2, 2])
kinds_of_label1 = 3

label2 = numpy.array([0, 1, 0, 0, 1, 1])
kinds_of_label2 = 2

data = numpy.array([[1, 2], [3, 8], [4, 5], [2, 9], [1, 3], [7, 2]])
data_T = data.view().T

### processing ####
label1_and_2 = label1 * kinds_of_label2 + label2

result = numpy.empty((kinds_of_label1 * kinds_of_label2, 2))
result_T = result.view().T

result_T[0] = ndimage.measurements.sum(
    position.T[0], labels=label1_and_2,
    index=range(kinds_of_label1 * kinds_of_label2)
)

result_T[1] = ndimage.measurements.sum(
    position.T[1], labels=label1_and_2,
    index=range(kinds_of_label1 * kinds_of_label2)
)

### output ###
print(result)
# [[  3.   4.]
#  [  1.   2.]
#  [  8.  15.]
#  [  0.   0.]
#  [  0.   0.]
#  [  1.   6.]]


texts: Avoiding code duplication and retaining const correctness

texts:
Sometimes I run across the problem of having two member function overloads that only differ in the constness of this (and the return type, but that is less important):

int& operator[](int);
const int& operator[](int)const;

Most of the time these are one-liners, but even then, I hate the code duplication.
That's why I like to use (if possible) the const version to implement the non const version via const_cast:

const int& MyClass::operator[](int index)const {
    return const_cast<int&>(const_cast<MyClass&>(*this)[index]);
}

The first const_cast is required (at least I think so), but I wonder if the second one can be circumvented and if so, if the code is more readable then.

How do you solve this problem?


texts: Solving the knapsack problem with user provided input

texts:
This question was given in my college assignment to be done in C. After doing that, I rewrote the program again in rust.
I come from a C/Python background and this is my first rust program. Please critique it.
The Program is given inputs in the following format

{num_items} {max_weight}
{item_weight_1} ... {item_weight_num_items}

The output is the number of items and the indices of the chosen items to be put in the bag

use std::io::{self, BufRead};

fn main() {
    let reader = io::stdin();
    let top_line: Vec<i32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .trim()
        .split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
    let num_items: i32 = top_line[0];
    let max_weight: i32 = top_line[1];
    let items: Vec<i32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .trim()
        .split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
    let s: (i32, i32) = (1..1 << num_items)
        .map(|i| {
            (
                items
                    .iter()
                    .enumerate()
                    .filter(|&(t, _)| (i >> t & 1 == 1))
                    .map(|(_, elem)| elem.clone())
                    .sum::<i32>(),
                i,
            )
        })
        .map(|(elem, i)| (max_weight - elem, i))
        .filter(|&(elem, _)| (elem >= 0))
        .min_by(|(a, _), (b, _)| a.cmp(&b))
        .unwrap();
    let ans: Vec<i32> = (0..num_items)
        .filter(|&t| (s.1 >> t & 1 == 1))
        .map(|t| t + 1)
        .collect();
    println!("{}", ans.len());
    println!(
        "{}",
        ans.iter()
            .fold(String::new(), |acc, &arg| acc + &arg.to_string() + " ")
    );
}

Example input

6 44
14 13 21 8 56 3

Example output

3
1 4 3


texts: Efficient Pandas to MySQL "UPDATE... WHERE"

texts:
I have a pandas DataFrame and a (MySQL) database with the same columns. The database is not managed by me.

I want to update the values in the database in an "UPDATE... WHERE" style, updating only some columns wherever some other columns match.

Here's my code:

import sqlalchemy as sqla

def save_to_db(final_df, passwd):

    engine_str = 'mysql+mysqldb://username:{}@localhost/mydb'.format(passwd)

    engine = sqla.create_engine(engine_str)

    sm = sessionmaker(bind=engine)
    session = sm()

    metadata = sqla.MetaData(bind=engine)

    datatable = sqla.Table('AdcsLogForProduct', metadata, autoload=True)

    for ind, row in final_df.iterrows():
        u = sqla.sql.update(datatable) \
            .values({"q_ECI_B_x": row.q_ECI_B_x,
                     "q_ECI_B_y": row.q_ECI_B_y,
                     "q_ECI_B_z": row.q_ECI_B_z,
                     "q_ECI_B_s": row.q_ECI_B_s}) \
            .where(sqla.and_(datatable.c.year == row.year,
                             datatable.c.month == row.month,
                             datatable.c.day == row.day,
                             datatable.c.hours == row.hours,
                             datatable.c.minutes == row.minutes,
                             datatable.c.seconds == row.seconds,
                             datatable.c.milliseconds == row.milliseconds,
                             datatable.c.microseconds == row.microseconds))

        session.execute(u)

    session.flush()
    session.commit()

I'm doing this with plain sqlalchemy because apparently pandas' built-in SQL functions can't handle "UPDATE... WHERE" scenarios. However, this is really slow.

Isn't there a more efficient way to do this?


texts: Adding a class to an element in a plugin

texts:
I have the following code, and I just added a Class to the element that uses the plugin. I works perfectly, but I am wondering if there is a better way to do it.

(function ($) {

/**
 * jQuery Plugin Extension
 */
$.fn.extend({

    /**
     * build editable
     *
     * @param {string} saveUrl
     * @param {Object} options
     * @returns {*}
     */
    baseEditable: function (saveUrl, options) {

        var settings = $.extend(true, {
            name: 'value',
            onblur: 'submit',
            placeholder: $.i18n._('msg_click_to_add'),
            ajaxoptions: {
                dataType: 'json'
            }
        }, options);

        return this.each(function () {
            $(this).addClass('editable');
            var baseEditable = $(this).editable(saveUrl, settings);

            $(this).data('baseEditable', baseEditable);
        });

    }
});
})(jQuery);


texts: Move update_attributes into class and check for non-nil params to update only

texts:
There are a number of things wrong with the code here:

 @cust = Customer.find_by_id(params[:customer_id])
        upd = @cust.update_attributes({:city_id => params[:city],
                                       :zip_code => params[:zip],
                                       :first_name => params[:first_name],
                                       :last_name => params[:last_name],
                                       :phone => params[:phone].each { |s| s.gsub!(/\D+/,'')},
                                       :street1 => params[:street1],
                                       :street2 => params[:street2],
                                       :email => params[:email]
    })

It's currently in a controller action - I should move it to the Customer class
My params don't exactly match the keys in my collection (MongoDB) - but it's a bit too late for me to deal with that...
I use the .each with a block inside the update, I feel like I should separate that into it's own method
While I don't explicitly call save, it does actually save.  The documentation on update_attributes says that I should call save explicitly or it won't...

Here are some questions:

What is the right way to move this into the model such that it will return TRUE or FALSE so that my controller can then set a flash[:success] or flash[:error] ?
How do I normalize my params so that I can write ONE UNIVERSAL update method like @cust.update_attributes(params) which will intelligently update only non-nil params ?
Is it absolutely worth the time to go back to the view and normalize the name attributes of each input to match the param?

I have other methods that update more or less params depending on the view, and I want to just have a single method "update_customer" that will take any old params hash with any values and only update the values that exist.


texts: Count number of unique adjacent cells in a matrix

texts:
I want to write an algorithm to count how many islands are in a given matrix. Consider for example:

A = [
        [1, 2, 1, 3],
        [2, 2, 3, 2],
        [3, 3, 2, 3]
    ]

Directly adjacent (north, south, east, west, but not diagonally) numbers constitute an island, in this example matrix we have 9.

I've written the following code which works and performs fine. Any suggestions on how could I write this more cleanly and to make it work even faster?

def clean_neighbours(matrix, this_row, this_col):
    cell_value = matrix[this_row][this_col]
    if cell_value == 0:
        return

    matrix[this_row][this_col] = 0
    number_of_rows = len(matrix)
    number_of_columns = len(matrix[0])

    for shift in (
        (-1,0), (1,0), (0,-1), (0,1)
    ):
        row, col = [x+y for x,y in zip((this_row, this_col), shift)]
        if (row >= 0 and row < number_of_rows) and (
            col >= 0 and col < number_of_columns
        ):
            if matrix[row][col] == cell_value:
                clean_neighbours(matrix, row, col)

def count_adjacent_islands(matrix):
    number_of_islands = 0
    for row_index, row in enumerate(matrix):
        for column_index, _ in enumerate(row):
            if matrix[row_index][column_index] != 0:
                number_of_countries += 1
                clean_neighbours(matrix, row_index, column_index)
    return number_of_countries

import random
A = [ [random.randint(-1000,1000) for e in range(0,1000)] for e in range(0,1000) ]
print(count_adjacent_islands(A))


texts: Cryptocurrency bot for retrieving coin information

texts:
I am running a cryptocurrency bot that needs 2 things:

Get a list of all the coins every 10 minutes or a similar frequency
Get a list of all the prices for each coin

The problem lies in 2 where I cannot query all 1500+ coins at one go. I am chunking them into 50 coins per chunk and querying the prices of 50 coins and then moving to the next chunk.

Another aspect to consider is the rank of the coin, I don't want all the coin prices, just looking at the top 500 and refreshing their prices every minute or so works.

Given the complex circumstances, I wrote 2 functions that handle everything. These functions are part of a class and a single variable called coins should be able to maintain the updated list of coins at any time.

Is there a better way to achieve this task?

refresh(){
    let self = this
    async.eachSeries(self.coins, async(item, callback)=>{
        if(self.onRefresh){
            self.onRefresh(await self.priceMulti(item, "EUR,USD,BTC"))
        }
        await self.delay(self.priceRefreshFrequency)
    },
    async (error) => {
        self.coins = self.parseCoins(await self.coinsList())
        self.refresh()
    })
}


texts: Comparing multiple arguments and returns the smallest argument

texts:
I want to see if anyone knows how to optimize the code below:

public class smallestTest
{
   public static void main(String[] args)
   {
      double resultSmallest = smallest(2.5, 3.5, 4.5);
      System.out.println("The smallest number out of 2.5, 3.5, and 4.5 is: " + resultSmallest);
   }

  /**
  Computes the smallest of three variables
  @param x, y, z
  @returns smallestNumber
 */

    public static double smallest(double x, double y, double z)
    {
         double smallestNumber = 0;
         if ( x < y && x < z)
         {
           smallestNumber = x;

         }
         else if (y < x && y < z)
         {
            smallestNumber = y;

         }
         else if (z < x && z < y)
         {
            smallestNumber = z;

         }

         return smallestNumber;
      }
}


texts: Removing the largest values encountered so far in a list

texts:
The problem is, in summary:

  A set of values will be given. Whenever the input is -1, the largest number from the values inputted until then needs to be printed, and is then deleted.

Here is the code that I wrote for it:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
int main()
{
  int val;
  int N, M, x=0, i=0;
  vector<int> visits;
  cin>>N>>M;
  for(x=0; x<N+M; x++)
  {
    cin>>val;
    visits.push_back(val);
     if(val==-1)
      {

         cout<<*max_element(visits.begin(), visits.end())<<endl;
         i++;
         visits.erase(max_element(visits.begin(), visits.end()));
      }
  }

    return 0;
}

The program gives correct answers, but it exceeds the time limit for some of the test cases. The test data isn't given, so I don't know for what size of test data it fails. Is there some other way by which I can optimize my code?


texts:
Exercise 1: skips :: [a] -> [[a]]

  The nth list in the output should contain every nth element from the
  input list. For example, skips "hello!" == ["hello!", "el!", "l!",
  "l", "o", "!"].

The question UPenn Homework 3: skips function and it's associated answers inspired me to write a solution in Javascript. I used the opportunity to (finally) better understand high order array functions. If you would be so kind to critique:

Code Layout, specifically if nesting function skips() makes any sense and why.
Do higher order functions provide more than just readability, are they more efficient?
Can I make the nested function skips() better (readable/faster)?
Anything at all.

function skip(str, cb) {
  var input = str.split('');

  cb(input.map(skips));

  function skips(val, index, arr) {
    var res = [];
    var i = index;
    var iterator = i + 1;
    for (i; i < arr.length; i += iterator){
      res.push(arr[i]);
    }
    return res;
  }
}

skip('hello!', console.log);