texts:
I just started learning Haskell, and I made a simple program which can calculate factorials and powers:

Input:

What do you want to do (0=quit, 1=factorial, 2=power) 1
Enter a number: 10
The factorial of 10 is: 3628800
What do you want to do (0=quit, 1=factorial, 2=power) 2
Enter the base number: 2
Enter the exponent: 10
2^10 = 1024.0
What do you want to do (0=quit, 1=factorial, 2=power) 0

The code is:

import System.IO
import System.Exit
import Control.Monad

factorial :: Integer -> Integer
factorial n = product [1..n]

powerInternal :: Double -> Integer -> Double
powerInternal b 0 = 1
powerInternal b e = b * powerInternal b (e - 1)

power :: Double -> Integer -> Double
power b e = if e >= 0
  then powerInternal b e
  else 1 / powerInternal b (-e)

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering

  putStr "What do you want to do (0=quit, 1=factorial, 2=power) "
  input <- getLine

  when (read input == 0) exitSuccess

  if read input == 1
    then do
    putStr "Enter a number: "
    hFlush stdout

    num <- getLine
    putStrLn ("The factorial of " ++ num ++ " is: " ++ show (factorial (read num)))
  else do
    putStr "Enter the base number: "

    base <- getLine
    putStr "Enter the exponent: "
    expe <- getLine

    putStrLn (base ++ "^" ++ expe ++ " = " ++ show (power (read base) (read expe)))

  main

I am looking for suggestions on how to improve the code, make it shorter, ...


texts:
My code blinks text for an interval of time then clears the text.

I plan to use this code in a quiz web app. When the user gets an answer right, "CORRECT!" will blink on the screen for 10 seconds. When the user gets an answer wrong, "INCORRECT!" will blink on the screen for 10 seconds.

I'm looking for feedback on how I could simplify and improve it?

JS Bin: http://jsbin.com/ojetow/1/edit


texts:
The goal is to find the longest peak in a sequence of numbers. A peak is defined to be a strictly increasing elements until a tip is found and then a strictly decreasing elements.

e.g. (1): 3, 2, 1, 2, 3, 4, 3, 0, 10, 0, 1, 2, 2, 1, 0

1, 2, 3, 4, 3, 0 is a peak;
0, 10, 0 is a peak;
0, 1, 2, 2, 1, 0 is NOT a peak (there is no tip);

e.g. (2): 1, 3, 2 is a peak

e.g. (3): 1, 2, 3 is NOT a peak

I'm trying to do so without backtracking - i.e. without finding a peak and then going outwards from it both back and front.

Here's a code I came up with

def longestPeak(array):
    longest = peakStart = peakEnd = 0
    peakArrived = False
    for i in range(1, len(array) - 1):
        # Check for peak
        if array[i-1] < array[i] and array[i] > array[i+1]:
            peakArrived = True
            if len(array) == 3:  # special case
                return 3
        # Check for end
        if array[i] <= array[i+1] and array[i] < array[i-1]:
            peakEnd = i
        elif array[i+1] < array[i] and i+2 == len(array):
            peakEnd = i+1
        # Check for longest
        if peakArrived and peakEnd > peakStart and peakEnd - peakStart + 1 > longest:
            longest = peakEnd - peakStart + 1
            peakArrived = False
        # Check for start
        if array[i] < array[i+1] and array[i] <= array[i-1]:
            peakStart = i
        elif array[i] > array[i-1] and i == 1:
            peakStart = 0

    return longest


texts:
I have a 2D matrix in Matlab and I want to convert the Matlab code into C++.

In C++ I have int* channel_gr. The commented code is the original Matlab code.

Is there a faster way to execute this code?

//Gr(1:ROIY(1), :)      = clipLevel;
for (int i = 0; i < _roiY1; i++)
{
    for (int j = 0; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

//Gr(ROIY(2)+1:end, :)  = clipLevel;
for (int i = _roiY2-1; i < newHeight; i++)
{
    for (int j = 0; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}

//Gr(:, 1:ROIX(1))      = clipLevel;
for (int i = 0; i < newHeight; i++)
{
    for (int j = 0; j < _roiX1; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}
//Gr(:, ROIX(2)+1:end)  = clipLevel;
for (int i = 0; i < newHeight; i++)
{
    for (int j = _roiX2-1; j < newWidth; j++)
    {
        channel_gr[i*newWidth + j] = clipLevel;
    }
}


texts:
This is a calculator for Ohm's Law and Power Law. It works but I'd like some suggestions on making the code look a little cleaner, or run more efficiently.

 # ohm's law calculator

#These functions perform ohm's law and power law calculations based on variables from user input.
def voltage(i, r):
    return i * r

def current(r, v):
    return r / v

def resistance(i, v):
    return i / v

def power(v, i):
    return v * i

def pvolt(w, i):
    return w / i

def pcurrent(w, v):
    return w / v

# First user interface menu. let's user choose between ohm's law and power law calculations.

print "Ohm's Law Calculations:"

print "1. Voltage"
print "2. Current"
print "3. Resistance"

print "Power Law Calculations:"

print "4. Wattage"
print "5. Voltage"
print "6. Current"

#Line 48 is taking the user's menu choice and passing it to the "choice" options below.
choice = raw_input(">>> ")

#These if statements are calling the functions.

#This gives values to "i" "v"  "w" and "r" from user input as floating point numbers the print line calls the "voltage" function and prints out the results of its calculation using the "format" function which automatically displays the needed decimal places.

if choice == "1":
    i=float(raw_input("Enter current:"))
    r=float(raw_input("Enter resistance:"))
    print "{0} volts" .format(voltage(i, r))

elif choice == "2":
    r=float(raw_input("Enter resistance:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} amps" .format(current(r, v))

elif choice == "3":
    i=float(raw_input("Enter current:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} ohms" .format(resistance(i, v))

elif choice == "4":
    i=float(raw_input("Enter current:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} watts" .format(power(i, v))

#Line 82 solves voltage according to power law
elif choice == "5":
    w=float(raw_input("Enter wattage:"))
    i=float(raw_input("Enter current:"))
    print "{0} volts" .format(pvolt(w, i))

#Line 89 solves current according to power law. I am attempting to make it round of the answer
elif choice == "6":
    w=float(raw_input("Enter wattage:"))
    v=float(raw_input("Enter voltage:"))
    print "{0} amps" .format(pcurrent(w, v))

#This line is here partly because its funny, and partly because I thought it would be cool to create my own error message

else:
    print  "Invalid number. Your computer will now self destruct."


texts: Optimize a regex validating a version string

texts:
I develop an application which installs updates. These updates have a version id (this version id is created as a part of the application and the format is a fixed requirement) and I use a regex to parse/validate their id. Each group must be separated by a dot. The id must have 2 digits in the first group, one or two digits in the second group and the third group and at least one digit in the last group.

The regex I use is the following:

^[0-9]{2}\.[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,}$

The regex works like expected but when I look at it I have a feeling telling me that I can make it better, smarter and and and and ...

Should I stay with this solution or how would you make it better?

The regex should work with the .NET-Framework Regex class.


texts: Asynchronous parallel ForEach implemented using Task.Run

texts:
I wrote a simple implementation of aysnc parallel.ForEach( ... )

All it really does is create a list of tasks and wait for them all to complete and aggregate the exceptions if any.

But to use CancellationToken I added Task.Run but I am worried that this is not the best way of stopping a task from running.

I could add some shortcuts in case the token cannot be cancelled, empty collections and so on.

But those are minor tweaks.

Anything else I could do to make tasks.AddRange(source.Select(s => Task.Run(() => body(s), token))); more efficient while allowing me to cancel running tasks.

public static async Task ForEach<T>(ICollection<T> source, Func<T, Task> body, CancellationToken token )
{
  // create the list of tasks we will be running
  var tasks = new List<Task>(source.Count);
  try
  {
    // and add them all at once.
    tasks.AddRange(source.Select(s => Task.Run(() => body(s), token)));

    // execute it all.
    await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false);

    // throw if we are done here.
    token.ThrowIfCancellationRequested();
  }
  catch
  {
    // find the error(s) that might have happened.
    var errors = tasks.Where(tt => tt.IsFaulted).Select(tu => tu.Exception).ToList();

    // we are back in our own thread
    if (errors.Count > 0)
    {
      throw new AggregateException(errors);
    }
  }
}

Any suggestions where I could improve performance and the creation of tasks?


texts: Javascript email and phone validation regex

texts:
I'd like to get a review on 2 regexes, one for email and one for phone validation.

/* Add jQuery validator method to check if phone numbers are in correct format.
   Use regex101.com for explaination of the regex.
   Using value.replace with / /g to remove all spaces. Normal replace with ' ' only works once. */
$.validator.addMethod('phone_number', function(value, element) {
    return /^\+(?:\d{1,3}|\d-\d{3}|\d{2}-\d{4})(?:\s?)\d{5,14}$/.test(value.replace(/ /g, ''));
});

/* Add jQuery validator method to check emails correctly.
   The original jQuery validator email method didn't correctly check double dots
   Eg. test..something@email.com worked while it's an invalid email.
 */
$.validator.methods.email = function(value, element) {
    return /^(?:(?:\w)+[._]?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$/gi.test(value.replace(/\\/g,'').trim());
};

Regexes only:

Phone: /^\+(?:\d{1,3}|\d-\d{3}|\d{2}-\d{4})(?:\s?)\d{5,14}$/

Email: /^(?:(?:\w)+[._]?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$/gi


texts:
I am trying to split a string so that the first word goes into the first span, and the remaining (an unknown number of words) goes into the next.

This currently works fine, but is there an easy / faster / tidier way to do it ?

<?
// Explode the job role out and combine into the two spans

    $la_jobrole = explode(' ', $lo_designer->role);
    $ls_jobPrimary = '';
    $ls_jobSecondary = '';
    $i=0;
    foreach($la_jobrole as $role) {
        if ($i == 0) $ls_jobPrimary = $role;
        else {
            $ls_jobSecondary .= $role . " ";
        }
        $i++;
    }

?>

<?= $ls_jobPrimary ?> <?= $ls_jobSecondary ?>


texts: Propagate a default parameter of a function among several files

texts:
I am starting to write a CLI using argparse library. This is my first attempt to structure a large project, usually I write single script. The CLI auto is defined in a top directory, helper functions are in a subfolder named project and a main function (where I want to put the logic of my program) in sub-sub-folder named sync.

Here is the tree-structure:

├── top/
├── auto
├── __init__.py
  └── project/
  ├── helper.py
  ├── __init__.py
    └── sync/
    ├── __init__.py
    ├── sync_file.py

helper.py:

def play(device, verbose=False):
    if verbose:
        print device + "with verbose on"
    else:
        print device + "verbose off"

sync_file.py:

from .. import helper

def main(device, verbose=False):
    helper.play(device,verbose)

if __name__ == '__main__':
    #Test here the logic
    main('omv')
    main('omv',verbose=True)

auto:

#!/usr/bin/env python

import argparse
import project.sync.sync_file as logic_sync

def sync(args):
    if args.verbose:
        logic_sync.main(args.device,verbose=True)
    else:
        logic_sync.main(args.device)

parser = argparse.ArgumentParser(description='Info on my project')
subparsers = parser.add_subparsers()

sync_parser = subparsers.add_parser('sync', help='synchronize')
sync_parser.add_argument('--device', default='nas', help='specify the device name')
sync_parser.add_argument('--verbose', action='store_true', help='increase the output verbose')
sync_parser.set_defaults(func=sync)  # set the default function to sync

if __name__ == '__main__':
    args = parser.parse_args()
    args.func(args)

After I've made the auto file executable chmode +x auto I can use the CLI:

./auto sync
# nasverbose off
./auto sync --verbose
# naswith verbose on

I would like to keep this structure but I see a lot of repetition in propagating the verbose parameter from one file to another. Is there a better way to do it?


texts:
I am looking to make the following code more efficient since it it rather lengthy. However I need to include in the code constructor classes that include accessor methods for the container number, height, radius 1, radius 2, and a method that computes the liquid that the container can hold. So I am looking to leave these concepts in there but make it more efficient if it is possible.

public class PoolCleanRequest {
final static double PI = 3.14;
private String num;
private double height;
private String height1;
private String height2;
private String radius1;
private String radius2;
private double r1;
private double r2;
private String rad2;
private String rad3;
public PoolCleanRequest(String num1){
    num = num1;
}
public void setHeight(double h){
    height=h;
    height1=Double.toString(h);
    height2=Double.toString(h);
}
public void setR1(double rr){
    r1 = rr;
    radius1=Double.toString(rr);
    radius2=Double.toString(rr);
}
public void setR2(double rrr){
    r2 = rrr;
    rad2=Double.toString(rrr);
    rad3=Double.toString(rrr);
}
public String getNum(){
    return num;
}
public String getHeight1(){
   return height1;
}
public String getHeight2(){
   return height2;
}
public String getRadius1(){
    return radius1;
}
public String getRadius2(){
    return radius2;
}
public String getRad1(){
    return rad2;
}
public String getRad3(){
    return rad3;
}
public double getPoolCost(){
    return ((PI*height/3)*(r1*r1+r2*r2+r1*r2))/1000;
}
public static void main( String[] args ) {
    PoolCleanRequest pool1 = new PoolCleanRequest("1.0");
    PoolCleanRequest pool2 = new PoolCleanRequest("2.0");
    PoolCleanRequest height1 = new PoolCleanRequest("20.0");
    PoolCleanRequest height2= new PoolCleanRequest("15.0");
    PoolCleanRequest radius1 = new PoolCleanRequest("3.0");
    PoolCleanRequest radius2 = new PoolCleanRequest("5.0");
    PoolCleanRequest rad1 = new PoolCleanRequest("2.0");
    PoolCleanRequest rad3 = new PoolCleanRequest("4.0");
    pool1.setHeight(20.0);
    height1.setHeight(20.0);
    height2.setHeight(15.0);
    radius1.setR1(3.0);
    radius2.setR1(5.0);
    rad3.setR2(4.0);
    rad1.setR2(2.0);
    pool1.setR1(3.0);
    pool1.setR2(5.0);
    pool2.setHeight(15.0);
    pool2.setR1(2.0);
    pool2.setR2(4.0);
    System.out.println("Container Num: " + pool1.getNum());
    System.out.println("H: " + height1.getHeight1());
    System.out.println("R1: " + radius1.getRadius1());
    System.out.println("R2: " + radius2.getRadius2());
    System.out.println("Litres: " + pool1.getPoolCost());
    System.out.println();
    System.out.println("Container Num: " + pool2.getNum());
    System.out.println("H: "+ height2.getHeight2());
    System.out.println("R1: " + rad1.getRad1());
    System.out.println("R2: " + rad3.getRad3());
    System.out.println("Litres: " +  pool2.getPoolCost());
  }
}

This code gives the correct following output:

Container Num: 1.0
H: 20.0
R1: 3.0
R2: 5.0
Litres: 1.0257333333333334

Container Num: 2.0
H: 15.0
R1: 2.0
R2: 4.0
Litres: 0.43960000000000005


texts: Speed optimization for girth-counting algorithm

texts:
I have the following girth-counting algorithm on a large 0-1 matrix and I need to optimize it for speed:

function CountG8()
M = 512
N = 1024
H = rand(0:1,M,N)
girth_8 = 0

for i=1:M-3
    for j=1:N-1
        if H[i,j]==1
            for j1=j+1:N
                if H[i,j1]==1
                    for i1=i+1:M
                        if H[i1,j1]==1
                            for j2=1:N
                                if H[i1,j2]==1&&j2!=j1
                                    for i2=i+1:M
                                        if H[i2,j2]==1&&i2!=i1
                                            for j3=1:N
                                                if H[i2,j3]==1&&j3!=j2
                                                    for i3=i+1:M
                                                        if H[i3,j3]==1&&i3!=i2
                                                            if H[i3,j]==1
                                                                girth_8 += 1
                                                            end
                                                        end
                                                    end
                                                end
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end
end
end

The algorithm runs without errors, but it is too slow.

The code is supposed to count every cycle of length 8 in a bipartite graph.

A bipartite graph is a graph of two groups of nodes. Left group, Check Nodes (CNs) and right group, Variable Nodes (VNs). Every CN from left group is allowed to be connected to a VN from right group. This is known as Directed Graph (DG). A DG has only cycles of even length 4,6,8,10,.. The Girth of the graph is the length of shortest cycle in it.

The algorithm walks through the graph in a BFS fashion searching for all possible nodes combination forming a cycle of the specified length (here 8). Matrix H in the code represents the graph. Each row is a CN and each column is a VN in the graph.

Here is a Bipartite Graph with its corresponding matrix as well as 2 cycles of length 4 and 6 shown:

EDIT: A comment on matrix power approach given in the answer.

In my case, the adjacency matrix is (M+N)x(M+N) = 1536 x 1536. Watch out for the complexity of (1536x1536)^8.


texts: Find a Id that contains all mentioned values

texts:
I have a scenario to find the CategoryId which all have the mentioned Mode values.

The schema of the table ModeTester:

CREATE TABLE ModeTester (
    ModeId      INT IDENTITY(1, 1) NOT NULL,
    CategoryId  INT,
    Mode        CHAR(1),
    ModeValue   VARCHAR (20)
)

The dummy values:

INSERT INTO ModeTester (CategoryId, Mode, ModeValue)
SELECT 1, 'H', 'Hospital' UNION
SELECT 2, 'W', 'Work' UNION
SELECT 1, 'R', 'Rating' UNION
SELECT 3, 'W', 'Window' UNION
SELECT 3, 'H', 'Home' UNION
SELECT 3, 'R', 'Rail' UNION
SELECT 4, 'R', 'Royal' UNION
SELECT 4, 'H', 'Hide' UNION
SELECT 4, 'W', 'Work'

From the above data, I want to get the result of CategoryId those should have all Mode values W, R, H.

So, I wrote this query

SELECT C.CategoryId
FROM (
    SELECT CategoryId, Count(CategoryId) [CategoryCount]
    FROM ModeTester
    WHERE Mode IN ('H', 'W', 'R')
    GROUP BY CategoryId
) C
WHERE C.CategoryCount = 3

It returns the expected data:

CategoryId
----------
 3
 4

But, I want to know if there are any better ways to achieve this or fine-tune the query.

Here's a sample SQL Fiddle.

Hard-coding the CategoryCount = 3 is not helped on all cases. If the data increases, checking on category count condition is not working.


texts: Porting functional programming code to Linq

texts:
I am very new to C# programming, so for practice I thought I would try to port a simple haskell function over to Linq. From learn you a haskell, there is the following implementation of powerset:

powerset :: [a] -> [[a]]
powerset xs = filterM (\x -> [True, False]) xs

Where filterM is defined like so

filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
filterM _ []     = return []
filterM p (x:xs) = do
  flg <- p x
  ys  <- filterM p xs
  return (if flg then x:ys else ys)

De-sugaring the do notation and specializing to m = list, this is

filterM :: (a -> [Bool]) -> [a] -> [[a]]
filterM _ []     = [[]]
filterM p (x:xs) =
  p x >>= (\flg ->
    filterM p xs >>= (\ys ->
      if flg then [x:ys] else [ys]))

So, porting the above code to Linq, this is what I have:

//prepend taken from a stackexchange post
static class IEnumerableExtensions
{
    static IEnumerable<T> Prepend<T>(this IEnumerable<T> seq, T val)
    {
        yield return val;
        foreach (T t in seq)
        {
            yield return t;
        }
    }
}

class Program
{
    static List<List<T>> FilterND<T>(Func<T, List<bool>> preds, List<T> xs)
    {
        if (xs.Any())
        {
            //unrolling haskell do notation.
            //>>= becomes SelectMany
            return
            preds(xs.First()).SelectMany(b =>
            FilterND(preds, xs.Skip(1).ToList()).SelectMany(ys =>
                b ?
                new List<List<T>> { ys.Prepend(xs.First()).ToList() } :
                new List<List<T>> { ys }
            ))
            .ToList();
        }
        else
        {
            return new List<List<T>> { new List<T> { } }; //[[]]
        }
    }

    static List<List<T>> Powerset<T>(List<T> xs)
    {
        Func<T, List<bool>> preds = (x => new List<bool> { true, false });
        return FilterND<T>(preds, xs);
    }

    static void Main(string[] args)
    {
        var test = new List<int>() {1, 2, 3, 4, 5};
        var pow = Powerset(test);
        foreach (var xs in pow)
        {
            Console.Write("[");
            foreach (var x in xs)
            {
                Console.Write(x);
            }
            Console.Write("]\n");
        }
    }
}

My main questions are:

How do I go about making things lazy in the correct places?
In what ways should I be qualifying my input (ref, out, etc)?
Is it even possible to make this sort of code run fast?


texts:
According to Project Euler Problem #1

  If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
  Find the sum of all the multiples of 3 or 5 below 1000.
  The answer being 233168

The following is my code, which gives me the right answer

import time
start = (time.time())

def getmul(x, *args):
    s=0
    for i in range(1,x):
        for arg in args:
            if (i%arg==0):
                s+=i
                break
    return(s)

res = getmul(1000,3,5)
end = time.time() - start
print(res, end)

I built the function in such a way that arbitrary arguments can be inputted and the result obtained.
Are there more efficient ways of solving this problem?


texts: Counting the number of character occurrences

texts:
I've written some code that uses a SortedDictionary to count the number of occurrences of a character in a string.

How can I improve this code? What should I be doing differently? Any advice at all would be helpful.

    static void Main(string[] args)
    {
        string longText = @"The quick brown fox jumps over the lazy dog";

        var count = CharacterCount.Count(longText);

        foreach (var character in count)
        {
            Console.WriteLine("{0} - {1}", character.Key, character.Value);
        }
    }

CharacterCount class:

class CharacterCount
{
    public static SortedDictionary<char, ulong> Count(string stringToCount)
    {
        SortedDictionary<char, ulong> characterCount = new SortedDictionary<char, ulong>();

        foreach (var character in stringToCount)
        {
            if (!characterCount.ContainsKey(character))
            {
                characterCount.Add(character, 1);
            }
            else
            {
                characterCount[character]++;
            }
        }

        return characterCount;
    }

Here is the output:


texts:
Write a function that takes an amount of money M, a price P and returns the change given in the smallest number of coins. The following coins are available: 1c, 5c, 10c, 25c, 50c, and $1. Time: 20min.

I'm looking for all sorts of reviews considering the time limit and environment.

Here's my code:

#include <iostream>
#include <vector>

std::vector<int> getChange(double M, double P)
{
  /*
    1c, 5c, 10c, 25c, 50c, and $1
    getChange(3.14, 1.99) should return [0,1,1,0,0,1]
    getChange(4, 3.14) should return [1,0,1,1,1,0]
    getChange(0.45, 0.34) should return [1,0,1,0,0,0]
  */

  int denominations[] = {1, 5, 10, 25, 50, 100};
  std::vector<int> r(sizeof denominations / sizeof denominations[0]);

  // I had a floating-point problem here by computing cents = (M-P)*100;
  // it took me a few minutes to figure it out
  int cents = (int)(M*100) - (int)(P*100);

  for(int i = sizeof denominations / sizeof denominations[0] - 1; i >= 0; --i){
    r[i] = cents / denominations[i];
    cents = cents % denominations[i];
  }

  return r;
}

int main()
{
  auto change = getChange(5, 0.99);
  for(auto i : change){
      std::cout << i << ", ";
  }
  std::cout << std::endl;
  return 0;
}


texts:
I have an employee table, employees may have multiple peripherals. I want to bring back all employees that have a peripheral of type 1 or 2, but that don't have any others, and vice versa (i.e. have a peripheral of type other than 1 or 2 but not have any peripherals of 1 or 2). For each of these employees, there should be a flag to show which of the two categories/product types they have.

This query works, but feels a bit verbose:

SELECT employee_id,
       has_screen,
       has_keyboard
FROM
(
    SELECT e.employee_id,
    CASE WHEN SUM(CASE WHEN ep.type IN (1,2) THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END has_screen,
    CASE WHEN SUM(CASE WHEN ep.type > 2 THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END has_keyboard
    FROM employee e
    JOIN employee_peripheral ep
    ON e.employee_id = ep.employee_id
    GROUP BY e.employee_id
) T
WHERE has_screen <> has_keyboard


texts: Retrieving a thumbnail photo for an ActiveDirectory account

texts:
I have the following method and I would like to understand how it could be reorganized to be more unit-testable.

I think the section about binding to Active Directory could go to its own method, making this method more about either returning bytes or not.

public byte[] getThumbnail(String username) {
    SimpleBindRequest formInputBindRequest =
        new SimpleBindRequest(MASTER_USER_DN, MASTER_PASSWORD);
    try {
        LDAPConnection adConnection = getAdConnection();
        adConnection.bind(formInputBindRequest);

        SearchResult searchResults = adConnection.search(properties.getSearchBase(),
                SearchScope.SUB, "(sAMAccountName=" + username + ")", "thumbnailPhoto");
        if (searchResults.getEntryCount() > 0) {
            return searchResults.getSearchEntries()
                                .get(0)
                                .getAttributeValueBytes("thumbnailPhoto");
        }
        return null;
    }
    catch (Exception e)
    {
        return null;
    }
}


texts: List some things that to make it less verbose and more robust

texts:
I am quite new in django forms. I am woking on problem where in function name generate_outage_form passed two parameters name settings and segment Now I have to make function less verbose and more robust.
def generate_outage_form(settings, segment=None):
    form = None
    datacenters = settings.get('datacenters')
    datacenters = get_and_sort(datacenters, 'abbreviation')

    departments = settings.get('departments')
    departments = get_and_sort(departments, 'name')

    outage_types = settings.get('outage_types', [])
    outage_causes = settings.get('outage_causes', [])
    outage_impacts = settings.get('outage_impacts', [])

    # Put a check to determine what form should be shown
    if not segment:
        if session.get('division'):
            dc_search = re.search(r'global dc', session.get('division'), re.I)
            ent_search = re.search(r'support', session.get('division'), re.I)
            if dc_search:
                form = forms.RecordDCOutage()
                segment = 'datacenter'
            if ent_search:
                form = forms.RecordSupportOutage()
                segment = 'support'
            if not form:
                form = forms.RecordDCOutage()
                segment = 'datacenter'
        else:
            form = forms.RecordSupportOutage()
            segment = 'support'
    else:
        if segment == 'datacenter':
            form = forms.RecordDCOutage()
        elif segment == 'support':
            form = forms.RecordSupportOutage()
        else:
            form = forms.RecordSupportOutage()
            segment = 'support'

    form.outage_type.choices = [
        (
            i_type.get('name'),
            i_type.get('name')
        ) for i_type in outage_types if (
            i_type.get('active') and i_type.get(segment)
        )
    ]
    form.outage_type.choices.insert(0, ('', ''))
    form.outage_cause.choices = [
        (
            cause.get('name'),
            cause.get('name')
        ) for cause in outage_causes if (
            cause.get('active') and cause.get(segment)
        )
    ]
    form.outage_cause.choices.insert(0, ('', ''))
    form.outage_impact.choices = [
        (
            impact.get('name'),
            impact.get('name')
        ) for impact in outage_impacts if (
            impact.get('active') and impact.get(segment)
        )
    ]
    form.outage_impact.choices.insert(0, ('', ''))
    form.data_center.choices = [
        (
            dc.get('abbreviation'),
            '%s - %s' % (
                dc.get('abbreviation'),
                dc.get('name')
            )
        ) for dc in datacenters if dc.get('active')
    ]
    form.data_center.choices.insert(0, ('', ''))
    form.departments.choices = [
        (
            dept.get('name'),
            dept.get('name')
        ) for dept in departments if (
            dept.get('active') and dept.get(segment)
        )
    ]

    return form, segment


texts:
I am trying to make a cyclic iterator that works backwards and forwards. getNext() gets the next array item, getPrevious() gets the item before the last returned one from getNext(). This seems to work, but there must be a better way. How can this be refactored?

var cyclicIterator = function (arr) {
    var index = 0;
    var length = arr.length;
    var current;
    return {
        getNext: function () {
            current = arr[index];
            index = (index + 1) % length;
            return current;
           },
        getPrevious: function () {
            index = arr.indexOf(current);
            if (index === 0) {
                index = length - 1;
            }
            else {
                index = index - 1;
            }
            current = arr[index]
            return current;
        }
    };
};


texts: More Pythonic version of finding substring with one glob-like expression

texts:
Giving the following example list the task is: find out whether the
  second expression is in the first one. * shall be considered as a
  wildcard for any character and one should be able to escape it \*

  Hello,ell
This is good, is
CodeEval,C*Eval
Old,Young

  should evaluate to

  true
true
true
false

I wrote the following code which solves this problem. However, my solution seems very cumbersome and slow. Do you know how to improve it? (The task is for CodeEval and this solution is actually too slow. The actual solution which succeeded is much shorter but it does not check if the search_exprs are in the right order)

import sys
import re

def all_occ(ss, s):
    """ Finds All Occurences of substring ss in string s and returns
    for each occurence its last index
    """
    start = 0
    while True:
        try:
            start = s.index(ss,start)+len(ss)
        except ValueError:
            break
        yield start

def is_ss(s, ss):
    search_exprs = [x.replace('\*', '*') for x in re.split(r'(?<!\\)\*', ss)]

    # Get the list of all occurences of each search expression
    find_indices = [list(all_occ(sub, s)) for sub in search_exprs]

    # If any of the indices is not found, then the expression does not match
    if not any(find_indices):
        return "false"

    # Check if the expressions are in the right order
    start = 0
    for el in find_indices:
        start = min([e for e in el if e>start])
        if not start:
            return "false"

    return "true"

for line in open(sys.argv[1]).read().splitlines():
    if line:
        print is_ss(*line.split(','))

Here the actual solution that has been accepted by codeeval but would fail if the expressions were in the wrong order:

import sys
import re

def is_ss(s, ss):
    search_exprs = [x.replace('\*', '*') for x in re.split(r'(?<!\\)\*', ss)]

    if any(map(lambda x: x in s, search_exprs)):
        return "true"
    else:
        return "false"

for line in open(sys.argv[1]).read().splitlines():
    if line:
        print is_ss(*line.split(','))


texts:
My code converts repeating decimals to fractions. It works but I am interested in feedback on how I could improve and/or simplify it?

jsFiddle: http://jsfiddle.net/tfgTu/

<script>
// Repeating decimal
// 21.83(35745857)
var decimal = 21.8335745857

// Total length of the decimal
var decimalLength = 10;

// Length of the decimal before the repeating part
var decimalBeforeRepeatLength = 2;

// 10 to the total length of the decimal
var power1 = Math.pow(10, decimalLength);

// 10 to the length of the decimal before the repeating part
var power2 = Math.pow(10, decimalBeforeRepeatLength);

var finalPower = power1 - power2;

var decimal1 = decimal * power1;

var decimal2 = parseInt(decimal * power2);

var finalDecimal = decimal1 - decimal2;

var output = simplifyFraction(0, finalDecimal, finalPower);

document.write(output[1] + " / " + output[2]);

// Finds the greatest common divisor of 2 non-zero integers
// a = integer 1
// b = integer 2
function greatestCommonDivisor(a, b) {
    if (b === 0) {
        return a;
    }

    return greatestCommonDivisor(b, (a % b));
}

// Simplifies all forms of fractions
// Does not change form of fraction
// i = number
// n = numerator
// d = denominator
function simplifyFraction(i, n, d) {
    var gcd = greatestCommonDivisor(n, d);

    if (Math.abs(i) > 0 && n >= d) { // If mixed number AND improper fraction, assume the user wants a simplified mixed number

        if (i < 0) {
            n *= -1;
        }

        var temp = improperFractionToMixedNumber(n, d);

        return [temp[0] + i, temp[1] / gcd, temp[2] / gcd];
    }

    return [i, n / gcd, d / gcd];
}
</script>


texts: Generate random records for table in SQL

texts:
I'm doing a project in ms sql and I have to fill table with random records.

Here is a definition of table:

create table invoice(
    id_invoice INT PRIMARY KEY IDENTITY(1,1),
    id_employee INT FOREIGN KEY REFERENCES Employee(id_employee),
    id_client INT FOREIGN KEY REFERENCES Client(id_client),
    id_service INT FOREIGN KEY REFERENCES Service(id_service),
    amount MONEY,
    payment_way VARCHAR(20) CHECK (payment_way in ('cash', 'credit_card'))
);

And here is the code that generates random records:

ALTER PROCEDURE generate_invoices
AS
BEGIN
    DECLARE @id_employee INT
    DECLARE @id_client INT
    DECLARE @id_service INT
    DECLARE @amount INT
    DECLARE @payment_way VARCHAR(20)

    SET @id_employee = (SELECT TOP 1 id_employee FROM Employee ORDER BY NEWID())
    SET @id_client = (SELECT TOP 1 id_client FROM Client ORDER BY NEWID())
    SET @id_service = (SELECT TOP 1 id_service FROM Service ORDER BY NEWID())
    EXEC random 1000, 5000, @amount OUTPUT
    IF (@amount % 2 = 1) SET @payment_way = 'cash'
    ELSE SET @payment_way = 'credit card'
    INSERT INTO Invoice VALUES (id_employee, @id_clienta, @id_service, @amount, @payment_way)
END
GO

EXEC generate_invoices
GO 10

The code works obviously, but I would like to ask if there is better way (shorter, more efficient) to do same thing, because I must write over a dozen of similar procedure for other tables.


texts:
HTML / CSS Slider.  No JavaScript.

Wanted to make an all CSS Image Slider.  Though there are plenty of pre-made options setup a lot seem clunky or add a lot to load time. Have ideas for some more detailed ones, with and without JavaScript, but wanted to make a basic one first and get any feedback.

CodePen: https://codepen.io/LouBagel/pen/rgKXeY

HTML:

CSS Slider

No JavaScript

Manual Setup

Tedious to Update

CSS:

.slider-container{
  width: 100%;
  height: 500px; /* can be set based on design */
  background: red; /* to test if background shows */
  overflow: hidden; /* to hide slides that are off */
  position: relative; /* since slides are absolute */
  box-shadow: 0 2px 10px black;
}

.slide{
  /* positioning all slides normal position to full size of slider and in view */
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;

  animation: 12s linear infinite sliderAnimation;
  /*
  animation-name: sliderAnimation;
  animation-duration: 12s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  */

  border: 20px solid #1d1e22; /* thought it looked good */
  box-sizing: border-box; /* to keep total width at 100% */

  box-shadow: inset 0 0 20px black; /* inset shadow on the slides */

  display: flex;  /* to position the text inside*/
}

.slide:first-of-type{
  /* City */
  background: no-repeat 50% 20%/cover url('https://i.imgur.com/zN8znQk.jpg');
  /* positioning for the text inside */
  justify-content: flex-end;
  align-items: flex-start;
}
.slide:nth-of-type(2){
  /* Nature Bridge */
  background: no-repeat center/cover url('https://i.imgur.com/qtwGd3b.jpg');

  /* 12s - 9s = 3s... Will start after 3s */
  animation-delay: -9s;
}

.slide:nth-of-type(3){
  /* Painting */
  background: no-repeat center/cover url('https://i.imgur.com/Qxdy5Ue.jpg');
  /* Will start after 6s */
  animation-delay: -6s;

  /* positioning for the text inside */
  justify-content: flex-end;
  align-items: center;
}
.slide:last-of-type{
  /* Coffee */
  background: no-repeat bottom/cover url('https://i.imgur.com/UyWlZtO.jpg');
  /* Will start after 9s */
  animation-delay: -3s;

  /* positioning for the text inside */
  justify-content: center;
  align-items: center;
}

@keyframes sliderAnimation{
  /* 4 slides, 20% in place and 5% transition time = 100% */
  0%{transform: translateX(0); opacity: 1;} /* starts in view */
  20%{transform: translateX(0); opacity: 1;} /* stays in view */
  25%{transform: translateX(-100%); opacity: 1;} /* slides out left */
  70%{transform: translateX(-100%); opacity: 0;} /* Doesn't matter at what percent: changes to transparent so can't see it travel back across to the right. */
  71%{transform: translateX(100%); opacity: 0;} /* Doesn't matter at what percent: moves off right */
  95%{transform: translateX(100%); opacity: 1;} /* Becomes transparent and Ready to slide on from the right */
}

.slide p{
  /*style for the text*/
  margin: 5vw;
  font-size: 3vw;
  color: white;
  text-shadow: 0.1vw 0.1vw black;
  font-family: Arial Black, Georgia, Garamond, Palatino, Trebuchet MS, Verdana;
}

.slide:last-of-type p{
  /* because white text on white background */
  text-shadow: 0 0 15px black;
}
body{
  margin: 0;
  background: #3f4351;
  max-width: 100%;
}

Note: animation-delays are set to negative values as that causes them to be placed backwards into the animation.  If positive values they will sit in starting position and not slide in on first round.

Pros & Cons (IMO)

Pros:

Quick Loading
No Repaint (since using transform: translate)

Cons:

No buttons for user to control
Tedious to make changes, especially if changing quantity of slides


texts:
I have an ArrayList which contains Strings with a size of 1000. I am looping through that ArrayList and finding words and trying to form a square from them. For example as follows:

C A R D
A R E A
R E A R
D A R T

The square must match left to right and top to bottom. So first left to right word (card) must match first top to bottom (card) and so on. The list has [voes, rose, soon, odds] and so on, a 1000 of them all of length 4.

I am looping through them 1 by 1. So take 'voes' first, loop through remaining 999, find the first word starting with 'o', i store it as second word (example: odds) and move on to next loop.

This will give me for example:

voes
odds

loop 999 times again. first letter to start with 'e' and its 3rd letter is 'd' store that as 3rd name and move on to 4th loop.

This will give me for example:

voes
odds
eddo

loop 999 times again. Similar check for 4th word. And lets say I cant find any word that meets the condition. Break out of loop, go on top and replace the first word to the second word in the list and do it all over again.

I have managed to get it working but it involves a lot of nested looping. If I am reading this right, this is O(n^4). Is there a more efficient way to do this.

void makeWord(ArrayList<String> arr){

    String first, second, third, fourth;
    for (int i = 0; i < arr.size(); i++) {

        first = arr.get(i);

        for (int j = 0; j < arr.size(); j++) {
            if(first.substring(1,2).equals(arr.get(j).substring(0,1)) &&
                    (!first.equals(arr.get(j)))){
                second = arr.get(j);
            }
            else {
                second = "    ";
            }

            if (!second.trim().isEmpty()) {
                for (int k = 0; k < arr.size(); k++) {
                    if (first.substring(2, 3).equals(arr.get(k).substring(0, 1)) &&
                            second.substring(2, 3).equals(arr.get(k).substring(1, 2)) &&
                            (!first.equals(arr.get(k)) && (!second.equals(arr.get(k))))) {
                        third = arr.get(k);
                    } else {
                        third = "    ";
                    }

                    if (!third.trim().isEmpty()) {

                        for (int m = 0; m < arr.size(); m++) {
                            if(first.substring(3,4).equals(arr.get(m).substring(0,1)) &&
                                    second.substring(3,4).equals(arr.get(m).substring(1,2))&&
                                    third.substring(3,4).equals(arr.get(m).substring(2,3)) &&
                                    (!first.equals(arr.get(m)) && (!second.equals(arr.get(m))))){
                                fourth = arr.get(m);
                            }
                            else {
                                fourth = "    ";
                            }

                            if (!(fourth.trim().isEmpty())) {
                                System.out.println(first);
                                System.out.println(second);
                                System.out.println(third);
                                System.out.println(fourth);
                                System.out.println(" ");
                            }
                        }
                    }
                }
            }
        }
    }
}


texts: Knex query method which conditionally run a whereIn() in the query with .modify() to have a result based on the selection in another table

texts:
In a Knex query (PSQL) method I used .modify() to be able to run a if(...) to conditionally run a whereIn() when the condition is true and present from a request.
The method is used to determine a status of a conversation based on messages status.
As mandatory we have conversation.idas that is always present but in some specific situation is necessary to check by type of the user the status of a particular conversation.
That is why we have below a .modify() as I need to conditionally check the other table if that type is the same of the memberType. That changes the final result.
I want to confirm the result of the below method is the correct one but as is similar to do a .join() and I would like to know how to use join instead of modify and if that makes sense.
Like if modify has better benefits then use join or opposite. I'm not sure how to modify the below modify to have the same result with join.
Would like to see the usage of join() instead of the modify() if that has sense.
The query
status(id, type) {
    if (!id) {
      throw new UserInputError('Conversation ID is mandatory');
    }

    return this.tx(messageTable)
      .select(messageColumns.status)
      .innerJoin(
        tableName,
        `${messageTable}.${messageColumns.conversationId}`,
        `${tableName}.${columns.id}`
      )
      .where(messageColumns.conversationId, id)
      .modify(builder => {
        if (type) {
          builder.whereIn(messageColumns.memberId, function innerSelect() {
            this.select(memberColumns.id)
              .from(memberTable)
              .where(memberColumns.memberType, type);
          });
        }
      })
      .groupBy(messageColumns.status)
      .then(r => {
        return r.some(x => x.status === 'PENDING') ? 'PENDING' : 'DEFAULT';
      });
  }


texts: If any two items in a list is equal to a given number

texts:
I just subscribed to the daily coding problems and received my first today.

The problem is:

  Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

This is what I came up with:

def anyequalto(x, y):
    for i in x:
        if y - i in x:
            return True

anyequalto([10, 15, 3, 7], 17)

I was wondering if anyone had any notes or alternatives as I'm very new to Python and programming.


texts:
I am writing some code to transform an array of decimals so that they are discounted over time.

I initially wrote the following code:

private decimal[] deflateArray(decimal[] items, decimal deflateRate)
{
    decimal[] deflatedItems = new decimal[items.Count()];

    decimal factorAdjustment = 1;

    for (int i = 0; i < items.Length; i++)
    {
        deflatedItems[i] = items[i] / factorAdjustment;
        factorAdjustment = factorAdjustment * (1 + deflateRate);
    }

    return deflatedItems;
}

Then I realised that instead of having the factorAdjustment variable, I can just use to the power of:

private decimal[] deflateArray(decimal[] items, decimal deflateRate)
{
    decimal[] deflatedItems = new decimal[items.Count()];

    for (int i = 0; i < items.Length; i++)
    {
        deflatedItems[i] = items[i] / (decimal)Math.Pow((double)(1 + deflateRate), i);
    }

    return deflatedItems;
}

As Math.Pow() only accepts and returns doubles, I think it's easier to create a wrapper function for it:

private decimal PowerOf(decimal x, decimal y)
{
    return (decimal)Math.Pow((double)x, (double)y);
}

and then simplify:

private decimal[] deflateArray(decimal[] items, decimal deflateRate)
{
    decimal[] deflatedItems = new decimal[items.Count()];

    for (int i = 0; i < items.Length; i++)
    {
        deflatedItems[i] = items[i] / PowerOf(1 + deflateRate, i);
    }

    return deflatedItems;
}

Then I realised that I really just want to transform the array and don't need a second array:

private void deflateArray(decimal[] items, decimal deflateRate)
{
    for (int i = 0; i < items.Length; i++)
    {
        items[i] = items[i] / PowerOf(1 + deflateRate, i);
    }
}

and then I can simplify this to:

private void deflateArray(decimal[] items, decimal deflateRate)
{
    for (int i = 0; i < items.Length; i++)
    {
        items[i] /= PowerOf(1 + deflateRate, i);
    }
}

so my final version is:

private void deflateArray(decimal[] items, decimal deflateRate)
{
    for (int i = 0; i < items.Length; i++)
    {
        items[i] /= PowerOf(1 + deflateRate, i);
    }
}

private decimal PowerOf(decimal x, decimal y)
{
    return (decimal)Math.Pow((double)x, (double)y);
}

I'm sure it can probably done in a one-liner by someone who is cleverer than me. Which version is the most easily understood?

I am not really worried about the performance as the array of items will only ever have 100 or 200 items and it's never done in a loop.


texts: Node, Link, Node, Link, Node: Linking Nodes into a LinkedList

texts:
For practice in Python OOP (first time) and for some relaxation from trying to learn Serialization in Java, I decided to write a LinkedList in Python. Now, this class would be pretty useless, because in Python, instead of:

(Java)

int[] array = new int[size];
// initialization...
// Now add an object to the end
int[] newArray = Arrays.copyOf(array, size + 1);
newArray[size] = value; // Really annoying, is it not?

You can do:

array = [] # And other values
array.append(value)

When you want to add a value. But, since it's for practice, it's not for use.

class LinkedList:

    def __init__(self):
        self.first = None
        self.last = None
        self.size = 0

    def add(self, value):
        '''
        Adds the specified element to the end of the array.
        '''

        if not self.first: # first is None
            self.first = Node(None, None, value)
            self.last = self.first
        else:
            node = Node(self.last, None, value)
            self.last.after = node
            self.last = node

        self.size += 1

    def add_at(self, value, index):
        '''
        Adds the specified element at the specified position.

        If the given index is out of range of the list, the
        element is added to the end.
        '''

        if index >= self.size:
            self.add(value)

        if index == 0:
            new = Node(None, self.first, value)
            self.first.before = new
            self.first = new

        node = self.get_node(index)
        new = Node(node, node.after, value)
        node.after.before = node
        node.after = new

        self.size += 1

    def remove(self, index):
        '''
        Removes the specified element at the specified position.

        If the given index is out of range of the list, an
        IndexError is thrown.
        '''

        node = self.get_node(index)
        node.before.after = node.after
        node.after.before = node.before
        return node.value

    def get(self, index):
        '''
        Returns the specified element at the specified position.

        If the given index is out of range of the list, an
        IndexError is thrown.
        '''

        return self.get_node(index).value

    def get_node(self, index):
        '''
        Returns the specified node at the specified position.

        If the given index is out of range of the list, an
        IndexError is thrown.
        '''
        if index >= self.size:
            raise IndexError()

        node = None
        if index > self.size / 2:
            # From back
            node = self.last
            for i in range(index, self.size - 1):
                node = node.before
        else:
            # From front
            node = self.first
            for i in range(1, index):
                node = node.after

        return node

class Node:

    def __init__(self, before, after, value):
        self.before = before
        self.after = after
        self.value = value

Concerns:

I think I can separate Python from Java anc C++ now, so the ; is no longer there. But just in case, is there a stray ;?
Is the way this class is constructed Pythonic?
Are the docstrings good?


texts:
Recently I've tried to teach myself basic things about MySQL databases, however I received some help on Stack Overflow with creating a good database structure trying to avoid redundancy as much as possible.

I finally came up with the database structure below and would like to know if that's the way to go and if not, what you would improve/change to it.

CREATE TABLE artists (
    artist_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    artist_name varchar(100) UNIQUE,
    artist_aka varchar(255) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE labels (
    label_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    label_name varchar(100) UNIQUE,
    label_aka varchar(255) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE producers (
    producer_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    producer_forename varchar(100),
    producer_nickname varchar(100) UNIQUE,
    producer_lastname varchar(100)
) ENGINE = 'InnoDB';

CREATE TABLE years (
    year_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    year_value varchar(4) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE genres (
    genre_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    genre_name varchar(10) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE flags (
    flag_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    flag_name varchar(12) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE tags (
    tag_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tag_name varchar(16) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE sources (
    source_id TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    source_name varchar(30) UNIQUE
) ENGINE = 'InnoDB';

CREATE TABLE riddims (
    riddim_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    riddim_name varchar(40) UNIQUE,
    riddim_aka varchar(255) UNIQUE,
    genre_fk TINYINT,
    youtube varchar(11) UNIQUE,
    image varchar(11) UNIQUE,
    FOREIGN KEY (genre_fk) REFERENCES genres(genre_id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = 'InnoDB';

CREATE TABLE tunes (
    tune_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
    riddim_fk INT DEFAULT NULL,
    artist_fk INT DEFAULT NULL,
    tune_name varchar(60) DEFAULT NULL,
    tune_aka varchar(255) DEFAULT NULL,
    label_fk SMALLINT DEFAULT NULL,
    producer_fk SMALLINT DEFAULT NULL,
    year_fk TINYINT DEFAULT NULL,
    lyrics TEXT DEFAULT NULL,
    flag_fk TINYINT,
    tag_fk SMALLINT,
    source_fk TINYINT,
    last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (riddim_fk) REFERENCES riddims(riddim_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (artist_fk) REFERENCES artists(artist_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (producer_fk) REFERENCES producers(producer_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (year_fk) REFERENCES years(year_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (flag_fk) REFERENCES flags(flag_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (tag_fk) REFERENCES tags(tag_id) ON DELETE SET NULL ON UPDATE CASCADE,
    FOREIGN KEY (source_fk) REFERENCES sources(source_id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = 'InnoDB';

Later the website will contain information about "riddims" (rythms), artists that have a song on that riddim, songnames, release years etcetera.
I guess the best way to show what its supposed to do is showing you a first, unfinished version of the website.


texts:
I want to use JavaFX as a solution to Java's issues with buffered input making things like 'press any key to continue' not easy.

I plan to use an event listener to detect keyboard input. But before I start down that road I want to know if this is on the right track.

Is the code below a good way to use JavaFX to implement a shell-based program?

Is this the minimum JavaFX code required to do shell?
Am I missing something that's gonna bite me down the road (like some kind of object de-referencing: I am very new to JavaFX so I don't have a clue!)
Is it OK to consider the start method as effectively now my main method?

import java.util.Scanner;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

public class TextBased extends Application {
    public static void main(String argv[]) {
        Application.launch(argv);
    }

@Override
public void start(Stage primaryStage) {
    System.out.println("Hello world");
    Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    Platform.exit();
    }
}


texts:
I wrote some code which divides a line through the words of the text so that each substring is no longer than MaxWidth. It works well, but it's very slow.

Pattern pattern = Pattern.compile("(.{1," + symbols + "}(\\b|\\s))"); // symbols - MaxWidth
Pattern pattern2 = Pattern.compile("\\s.*");

while ((line = in.readLine()) != null) {  // reading file by lines
    String dopLine = "";
    if (pattern2.matcher(line).matches()) {
        // If a line begins with a space, it is the beginning of a paragraph and need to add \ n
        if(!tempDopLine.equals("")) { // tempDopLine - Some part of the previous line, which is not full screen
            tempStringBuffer.append(tempDopLine);
            tempStringBuffer.append("\n");
            lineCounter++;
            if (lineCounter == lines) {
                addPage(tempStringBuffer); // create page
                tempStringBuffer = new StringBuilder("");
                lineCounter = 0;
                numberOfPages++;
            }

        }
        tempDopLine = "";
        dopLine = line;
    } else {
        dopLine = tempDopLine + " " + line; // if this line
    }
    Matcher matcher = pattern.matcher(dopLine); // divide a string into a substrings

    HashMap<Integer, String> temp = new HashMap<Integer, String>();
    int i = 0;
    while (matcher.find()) {
        temp.put(i, matcher.group());
        i++;
    }
    for(i = 0; i < temp.size(); i++) {
        if (i<(temp.size()-1)) {
            String tempL = temp.get(i);

            tempStringBuffer.append(tempL);

            tempStringBuffer.append("\n");
            lineCounter++;
            if (lineCounter == lines) {
                addPage(tempStringBuffer);
                tempStringBuffer = new StringBuilder("");
                lineCounter = 0;
                numberOfPages++;
            }

        } else {
            tempDopLine = temp.get(i); // The last part of the string remember to display it along with the next line
        }
    }
}


texts: How to separate data from logic when serializing types - grid tile map example

texts:
I am creating a tile based game in Unity and ran into a problem with my architecture of the Map and Tile types. The tile class contains logic like events when the tile type changes. When I tried to save the type to disk those events were being serialized as well, which I don't want (causing several problems in Unity). I basically want to make sure that I only save pure data like x, y position and enum types. Here is my approach:

public class Tile
{
    public event EventHandler<TileTypeChangedEventArgs> TileTypeChanged;

    public const TileType defaultType = TileType.Empty;

    public TileType type
    {
        get { return _type; }
        set
        {
            if (Enum.IsDefined(typeof(TileType), value) == false)
                throw new InvalidOperationException("Trying to set undefined tile type.");

            if (value != _type)
            {
                _type = value;
                var args = new TileTypeChangedEventArgs(_type);
                OnTileTypeChanged(args);
            }
        }
    }

    public int x { get { return _x; } }
    public int z { get { return _z; } }

    TileType _type;

    readonly int _x;
    readonly int _z;

    public Tile(int x, int z, TileType type = Tile.defaultType)
    {
        _x = x;
        _z = z;
        this.type = type;
    }

    protected virtual void OnTileTypeChanged(TileTypeChangedEventArgs e)
    {
        var handler = TileTypeChanged;
        if (handler != null)
            handler.Invoke(this, e);
    }
}

public class TileTypeChangedEventArgs : EventArgs
{
    public TileType type { get; private set; }

    public TileTypeChangedEventArgs(TileType type)
    {
        this.type = type;
    }
}

public enum TileType
{
    Empty,
    Grass,
    Water,
    Dirt
}

[Serializable]
public sealed class TileData
{
    public static readonly int version = 1;

    public TileType type
    {
        get { return _type; }
        set { _type = value; }
    }

    public int x
    {
        get { return _x; }
        set { _x = value; }
    }

    public int z
    {
        get { return _z; }
        set { _z = value; }
    }

    TileType _type;
    int _x;
    int _z;

    public static TileData Convert(Tile tile)
    {
        var data = new TileData();
        data.x = tile.x;
        data.z = tile.z;
        data.type = tile.type;
        return data;
    }

    public static Tile Convert(TileData data)
    {
        return new Tile(data.x, data.z, data.type);
    }
}

I created the TileData class because it would work similar to Data Transfer Objects in web programming. This way I am sure that my data remains serializable and I don't run into problems when I save a tile map and change it simultaneously.

However, it also means duplicated code and more methods for conversion. What do you think of my approach? Would you just modify the tile class so that it serializes correctly? I believe that I would also need to include copy methods to make sure saving to disk works while modifying the map state etc.


texts: Matching items in different arrays and performing operations on them

texts:
I have a data structure that uses a Dictionary<ID,TimeSeries> to hold time series for different products. TimeSeries is implemented as something holding an array of Point, which contain a DateTime and a double.

Its interface is:

TimeSeries{
    int Length{ get; }
    Point ElementAt(int index);

    DateTime StartTime { get; }
    DateTime EndTime { get; }
}

Given a pair of elements of such data structure I need to find the first time instant where they diverge. For my definition of divergence, if a dictionary contains an element and the other doesn't I need to return the time of the first point of the TimeSeries I have.

This is the code I'm using to compute the difference and that I'd like you to review and comment:

bool TryFindFirstDivergenceTime(Dictionary<ID, TimeSeries> baseline, Dictionary<ID, TimeSeries> other, out DateTime firstDivergenceTime)
{
    firstDivergenceTime = default(DateTime);

    foreach(var baselineIDSeriesPair in baseline)
    {
        if(other.ContainsKey(baselineIDSeriesPair.Key))
        {
            firstDivergenceTime = Min(FindFirstDivergenceTime(baselineIDSeriesPair.Value, other[baselineIDSeriesPair.Key]), firstDivergenceTime);
        }
        else
        {
            firstDivergenceTime = Min(baselineIDSeriesPair.Value.Start, firstDivergenceTime);
        }
    }
    foreach(var otherIDSeriesPair in other)
    {
        if(!baseline.ContainsKey(otherIDSeriesPair.Key))
        {
            firstDivergenceTime = Min(otherIDSeriesPair.Value.Start, firstDivergenceTime);
        }
    }

    return firstDivergenceTime != default(DateTime);
}

public DateTime Min(DateTime first, DateTime second)
{
    if(first == default(DateTime))
        return second;
    if(second == default(DateTime))
        return first;
    return new DateTime(Math.Min(first.Ticks, second.Ticks));
}

DateTime FindFirstDivergenceTime(TimeSeries first, TimeSeries second)
{
    if(first.Length != second.Length)
    {
        throw new ArgumentException();
    }
    for(var i=0; i < first.Length; i++)
    {
        if(! first.ElementAt(i).Equals(second.ElementAt(i)))
        {
            return Min(first.ElementAt(i).Time, second.ElementAt(i).Time);
        }
    }
    return default(DateTime);
}

I have the feeling that I am not approaching the problem in the right way as the code contains the repetition of the logic to find the time of the first difference when I don't have the same product in both the dictionaries.

The other think that I don't particularly like is that I find myself breaking th symmetry and using for on dictionary Key and Value from its IEnumerable, while from the other I need to perform a lookup.

How would you address those issues?


texts: Optimizing code to find maximum XOR in Java

texts:
This problem is from HackerRank (not a competition, just for practice)

Basically what you do is take in two integers as a range and then finding the maximum XOR from a pair of integers in that interval.

Here is my code for doing so (it passed all the test cases):

static int maxXor(int l, int r) {
    int maxXor = l ^ r;
    for(int left=l;left<=r; left++) {
        for(int right=l;right<=r; right++) {
            if((left ^ right) > maxXor) {
                maxXor = left ^ right;
            }
        }
    }
    return maxXor;
}

I was able to tell that this code segment runs in \$\mathcal{O}(n^2)\$ because the outer for loop will run in \$\mathcal{O}(N)\$, \$N\$ as in number of integers in the range, and the inner loop will also run in \$\mathcal{O}(N)\$. Because each time the outer loop runs, the inner loop runs one time aswell, the entire code segment will in \$\mathcal{O}(N^2)\$. Is that good analysis?

But anyways, is there an optimization (for performance) for this code segment to get the runtime down to \$\mathcal{O}(N)\$ or \$\mathcal{O}(log N)\$ perhaps?


texts:
I have implemented a binary search algorithm in C#. Can anyone give me suggestions on improving its effectiveness?

using System;

namespace bs2
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] arr = new int[n];

            for(int i=0;i<n;i++)
            {
                arr[i] = i*14; //14 is a random number, I multiply by a number so that arr[i] would not be equal to i.
            }

            int searchingfor = int.Parse(Console.ReadLine());
            int min = 0;int max = n-1;int mid = (n-1)/2;
            while (true)
            {
                if (arr[mid] == searchingfor)
                {
                    Console.WriteLine("Element is on position {0}", mid);
                    break;
                }else if (arr[mid] < searchingfor)
                {
                    min = mid;
                    mid = (min + max) / 2;
                }else if (arr[mid] > searchingfor)
                {
                    max = mid;
                    mid = (min + max) / 2;
                }
            }

        }
    }
}


texts: Sourcing data format from multiple different structures

texts:
Problem

I want to read in the data to dictionary

person = {
    'name': 'John Doe',
    'email': 'johndoe@email.com',
    'age': 50,
    'connected': False
}

The data comes from different formats:

Format A.

dict_a = {
    'name': {
        'first_name': 'John',
        'last_name': 'Doe'
    },
    'workEmail': 'johndoe@email.com',
    'age': 50,
    'connected': False
}

Format B.

dict_b = {
    'fullName': 'John Doe',
    'workEmail': 'johndoe@email.com',
    'age': 50,
    'connected': False
}

There will be additional sources added in the future with additional structures.

Background

For this specific case, I'm building a Scrapy spider that scrapes the data from different APIs and web pages. Scrapy's recommended way would be to use their Item or ItemLoader, but it's ruled out in my case.

There could be potentially 5-10 different structures from which the data will be read from.

Implementation

/database/models.py

"""
Database mapping declarations for SQLAlchemy
"""

from sqlalchemy import Column, Integer, String, Boolean
from database.connection import Base

class PersonModel(Base):
    __tablename__ = 'Person'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)
    age = Column(Integer)
    connected = Column(Boolean)

/mappers/person.py

"""
Data mappers for Person
"""

# Abstract class for mapper
class Mapper(object):
    def __init__(self, data):
        self.data = data

# Data mapper for format A, maps the fields from dict_a to Person
class MapperA(Mapper):
    def __init__(self, data):
        self.name = ' '.join(data.get('name', {}).get(key) for key in ('first_name', 'last_name'))
        self.email = data.get('workEmail')
        self.age = data.get('age')
        self.connected = data.get('connected')

    @classmethod
    def is_mapper_for(cls, data):
        needed = {'name', 'workEmail'}
        return needed.issubset(set(data))

# Data mapper for format B, maps the fields from dict_b to Person
class MapperB(Mapper):
    def __init__(self, data):
        self.name = data.get('fullName')
        self.email = data.get('workEmail')
        self.age = data.get('age')
        self.connected = data.get('connected')

    @classmethod
    def is_mapper_for(cls, data):
        needed = {'fullName', 'workEmail'}
        return needed.issubset(set(data))

# Creates a Person instance base on the input data mapping
def Person(data):
    for cls in Mapper.__subclasses__():
        if cls.is_mapper_for(data):
            return cls(data)
    raise NotImplementedError

if __name__ == '__main__':
    from database.connection import make_session
    from database.models import PersonModel

    # Sample data for example
    dict_a = {
        'name': {
            'first_name': 'John',
            'last_name': 'Doe'
        },
        'workEmail': 'johndoe@email.com',
        'age': 50,
        'connected': False
    }
    dict_b = {
        'fullName': 'John Doe',
        'workEmail': 'johndoe@email.com',
        'age': 50,
        'connected': False
    }

    # Instantiate Person from data
    persons = [PersonModel(**Person(data).__dict__ for data in (dict_a, dict_b)]
    with make_session() as session:
        session.add_all(persons)
        session.commit()

Question

I have limited experience in Python programming and I'm building my first scraper application for a data engineering project that needs to scale to storing hundreds of thousands of Persons from tens of different structures. I was wondering if:

This is a good solution? What could be the drawbacks and problems down the line?
Currently I've implemented different subclasses for the mapping. Is there a convention or industry standard for these types of situations?

Update

For question 2, I found this question to be useful, but would still want to know if this approach in general is good.
Added style improvement suggestions from @Reinderien


texts:
I was wondering if this implementation of quicksort could be improved. Are there any things that I have done wrong?

template<typename Element>
size_t partition_quickSort(Element arr[], size_t start, size_t end) {
    auto pivot = arr[end];
    size_t index_partition = start;

    for (size_t i = start; i < end; ++i) {
        if (arr[i] <= pivot) {
            std::swap(arr[index_partition++], arr[i]);
        }
    }

    std::swap(arr[index_partition], arr[end]);
    return index_partition;
}

template<typename Element>
void quick_sort(Element arr[], size_t start, size_t end) {
    if (start < end) {
        size_t partition = partition_quickSort(arr, start, end);
        quick_sort(arr, start, partition - 1);
        quick_sort(arr, partition + 1, end);
    }
}
template<typename Element>
void quick_sort(Element arr[], size_t size) {
    quick_sort(arr, 0, size - 1);
}


texts: `Maybe` handling in Matrix manipulation in Elm

texts:
I'd like to learn if my rewrite is worse than the original, less clear or less "idiomatic".

I've found this code that handles updating two dimensional matrixes in Elm:

type alias Matrix a = Array.Array (Array.Array a)
type alias Location = (Int, Int)

get : Location -> Matrix a -> Maybe a
get location m =
  Array.get (row location) m `andThen` Array.get (col location)

set : Location -> a -> Matrix a -> Matrix a
set location value m =
  update location (always value) m

update : Location -> (a -> a) -> Matrix a -> Matrix a
update location f m =
  get location m
  |> Maybe.map (
    \current ->

      Array.get (row location) m
      |> Maybe.map (
          \oldRow ->
            Array.set (col location) (f current) oldRow
            |> (\newRow -> Array.set (row location) newRow m)
      )
      |> Maybe.withDefault m
  )
  |> Maybe.withDefault m

I couldn't understand update at first so I tried to write my own (using my own domain types):

type Player = PlayerOne | PlayerTwo
type Slot = Empty | PlayedBy Player
type alias Board = Array.Array (Array.Array (Slot))
type alias Position = (Int, Int)

get : Board -> Position -> Maybe Slot
get board (row, column) =
    Array.get row board `Maybe.andThen` Array.get column

setPosition : Board -> Position -> Player -> Board
setPosition board (row, column) player =
    case get board (row, column) of
        Nothing ->
            board
        Just Empty ->
            case Array.get row board of
                Nothing ->
                    board
                Just oldRow ->
                    let
                        newRow = Array.set column (PlayedBy player) oldRow
                    in
                        Array.set row newRow board
        Just s ->
            board

After rewriting I could understand what's going on in the original update function, but ended up feeling my version's clearer. This is my first day writing Elm so I'm no authority in Elm code clarity.


texts: Haskell basic typeclass primer (quadratic equations)

texts:
I have written Haskell code to my spec to help me grasp types and syntax, because I am learning.
I hope to generalize it further to accommodate more kinds of equations. I am (perhaps prematurely) worried that repeated usage of delta in multiple places is going to slow down my code, but I don't see how I can avoid it.
I am a bit confused about whether I should use Floating class or just use Float concrete type everywhere.
I appreciate any and all tips.
Here's the expected output
Equation -10.0x^2 +4.0x +1.0 = 0 has following 2 solutions:
0.28708285
-8.708288e-2

And the code
-- MathPrimer

delta :: Floating a => a -> a -> a -> a
x1 :: Floating a => a -> a -> a -> a
x2 :: Floating a => a -> a -> a -> a

delta a b c = b * b - 4 * a * c

x1 a b c = ( - b - sqrt(delta a b c)) / ( 4 * a * c )
x2 a b c = ( - b + sqrt(delta a b c)) / ( 4 * a * c )

class Algebraic equ where
    algebraicForm :: equ -> String

class (ZeroEquation equ) where
    solve :: equ -> [Float]
    solutionCount :: equ -> Int

data Equation = Quadratic {a :: Float, b :: Float, c :: Float}
    deriving (Show, Read, Eq)

instance (ZeroEquation Equation) where
    solve (Quadratic a b c) = solutions
        where
            both = [x1 a b c, x2 a b c]
            one = [x1 a b c]
            zero = []
            solutions = if _delta < 0 then zero else if _delta == 0 then one else both
            _delta = (delta a b c)
    solutionCount (Quadratic a b c) = count
        where
            count = if _delta < 0 then 0 else if _delta == 0 then 1 else 2
            _delta = (delta a b c)

instance (Algebraic Equation) where
    algebraicForm (Quadratic a b c) = show a ++ "x^2 +" ++ show b ++ "x +" ++ show c

showEquation :: Equation -> String
showEquation equ = "Equation " ++ description ++ " = 0 has following " ++ count ++ " solutions:\n" ++ solutions
    where
        count = show $ solutionCount equ
        description = algebraicForm equ
        solutions = unlines $ map show $ solve equ

main = do
    let equation = Quadratic (-10) 4 1
    putStrLn $ showEquation equation


texts: Safe navigating function for nested object properties

texts:
I've made a function to safely traverse deep objects.

var foo = {
    bar: {
        baz: 1
    }
};

function getDeepProp(obj, properties) {

    if (typeof properties === 'string')
        properties = properties.split('.');

    if (typeof obj === 'undefined')
        return;

    if (!properties.length)
        return obj;

    return getDeepProp(obj[properties[0]], properties.slice(1));
}

console.log(getDeepProp(foo, 'bar.baz')); // 1
console.log(getDeepProp(foo, 'baz.baz')); // undefined

// The function was created to avoid exceptions like:
console.log(foo.baz.baz); // Uncaught TypeError: Cannot read property 'baz' of undefined

Please suggest possible improvements.

http://jsfiddle.net/rtkczasa/


texts: Member list reveals member information on click (#1)

texts:
What I'm doing?

I'm creating a member-list where initially only the names are visible. Clicking the names reveals the member information. This is done with jQuery by adding/removing classes.

I left out the CSS with the transitions for this review.

HTML:

        member name

        member name

        member name

jQuery:


texts: Which is a better optmized CSS for a button design?

texts:
There are two ways I have been using to create links and style them as buttons:

background: url("/images/sing_up_btn.png") no-repeat scroll 0 0 transparent;
font-family: Arial,Helvetica,Sans-serif;
text-shadow: 0 -1px #444444;
text-transform: none;

Another one is:

a.btn_link
{
    background: #4468b2; /* Old browsers */
    background: -moz-linear-gradient(top,  #4468b2 0%, #3b5a9b 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#4468b2), color-stop(100%,#3b5a9b)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  #4468b2 0%,#3b5a9b 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  #4468b2 0%,#3b5a9b 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  #4468b2 0%,#3b5a9b 100%); /* IE10+ */
    background: linear-gradient(top,  #4468b2 0%,#3b5a9b 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4468b2', endColorstr='#3b5a9b',GradientType=0 ); /* IE6-9 */
    color:#fff;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    -webkit-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);
    -moz-box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);
    box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, .4);
  color: #FFFFFF;
  text-decoration:none;
  padding:5px 25px 5px 25px;
}
a.btn_link:active{
margin: 2px -2px 0px 2px;
box-shadow:none;
}

The image used as a background is almost the same as the second code creates a button design. I was wondering which is more efficient and optimized way to create button. With my little understanding, I would think that the one that doesn't uses image. But I have seen many new age well designed websites using images. Does that mean if I use such heavy CSS for a simple button, the code is not optimized?


texts:
I got a function to recalculate the image size based on two settings.

Force ratio, force the requested ratio, default the original ratio will be used.
Keepsmaller, the uploaded image may never become bigger

If keep smaller is not enabled, by default we will focus calculation on the first reached, it's hard to explain see enclosed excel screen you will probebly understand.

<?php
function recalc($oldWidth, $oldHeight, $reqWidth, $reqHeight, $forceRatio = false, $keepSmaller = false){
    if ($keepSmaller) {
        $maxWidth   = ($oldWidth < $reqWidth)   ? $oldWidth  : $reqWidth;
        $maxHeight  = ($oldHeight < $reqHeight)  ? $oldHeight : $reqHeight;
    } else {
        $maxWidth   = $reqWidth;
        $maxHeight  = $reqHeight;
    }

    $ratio      = ($forceRatio) ? ($reqWidth / $reqHeight) : ($oldWidth / $oldHeight);

    if ($ratio != ($maxWidth / $maxHeight))
    {
        if ($keepSmaller && $ratio > ($maxWidth / $maxHeight)){
            $maxHeight = $maxWidth / $ratio;
        } elseif (!$forceRatio && $ratio < ($maxWidth / $maxHeight)) {
            $maxWidth  = $maxHeight * $ratio;
        }
    }

    echo $maxWidth . ', ' . $maxHeight;
}

recalc( 480,  360, 1440, 1080); echo "
";
recalc(1920, 1440, 1440, 1080); echo "
";
recalc( 480,  360, 1920, 1080); echo "
";
recalc(3840, 2880, 1920, 1080); echo "
";
echo "
";

recalc( 480,  360, 1440, 1080, false, true); echo "
";
recalc(1920, 1440, 1440, 1080, false, true); echo "
";
recalc( 480,  360, 1920, 1080, false, true); echo "
";
recalc(3840, 2880, 1920, 1080, false, true); echo "
";
echo "
";

recalc( 480,  360, 1440, 1080, true); echo "
";
recalc(1920, 1440, 1440, 1080, true); echo "
";
recalc( 480,  360, 1920, 1080, true); echo "
";
recalc(3840, 2880, 1920, 1080, true); echo "
";
echo "
";

recalc( 480,  360, 1440, 1080, true, true); echo "
";
recalc(1920, 1440, 1440, 1080, true, true); echo "
";
recalc( 480,  360, 1920, 1080, true, true); echo "
";
recalc(3840, 2880, 1920, 1080, true, true); echo "
";
echo "
";

This are the input, params and outputs used for testing.
However some scenarios are still unwatched.

The 1st table states itself
the second contains the original sizes
the third the requested/target sizes
the last one is what 'we' expect for it to become


texts: Iterating through a list to generate calendars

texts:
I'm iterating through a list to generate calendars, the issue is each generator function has the same this.addToCalendar() function. I'd like to know how I could condense this into only being called once, rather than in each function.
The main generators I'd like to look at are the ones within method, where I am generating calendar links as well as calling an external api.
CSS has been removed to focus on JS logic.
<template>

      <button @click="calendar.generator">
        {{ calendar.type }}
      </button>

  <button @click="setExpanded(false)">
    Close
  </button>

</template>


texts: Reasonable ActiveSupport dependency and define_method usage?

texts:
I'm writing a results wrapper for a gem which wraps a Thesaurus API. Basically, when you lookup a word in the thesaurus, the results come back in approximately this JSON form:

{
  'noun' => {
    'syn' => ['array', 'of', 'synonyms'],
    'rel' => ['array', 'of', 'related terms']
   },
   'verb' => {
     'syn' => ['synonyms', 'of', 'verb', 'word form'],
     'ant' => ['antonyms', 'of', 'word']
   }
}

I would like to be able to access the results in the following ways:

Get an array of synonyms across all parts of speech. eg.

results.synonyms
# => ['array', 'of', 'synonyms', 'synonyms', 'of', 'verb', 'word form']

Indifferently (writing results['noun'] all the time is a PITA):

results[:noun]

Here is my code and questions:

Is it acceptable to create a dependance on ActiveSupport just so I can access the results indifferently, or should I just suck it up? THe only other AR method I'm using in the gem is blank?.
Is the usage of define_method too magical? Should I just define the convenience methods normally instead?

require "active_support/core_ext/hash/indifferent_access"

module Dinosaurus
  class Results < HashWithIndifferentAccess

    def initialize(data = {})
      super(data)
    end

    # Define some convenience methods.
    { 'synonyms' => :syn,
      'antonyms' => :ant,
      'similar_terms' => :sim,
      'related_terms' => :rel
    }.each do |name, key|
      define_method name do
        grouped(key)
      end
    end

  private

    def grouped(key)
      group = []
      self.each do |pos, type|
        group += type[key] if type[key]
      end
      group
    end
  end
end


texts:
I have a bit of code that converts a Sql Like expression to a regex expression for the purposes of a Linq to objects Like extension method. For some time I have been using this conversion.

This conversion replaces all "%" with ".*?" which works for contains patterns but is over matching for starts with or ends with patterns. So the conversion of %abc to .*?abc is capturing both "abcdef" and "123abcdef".

I've amended the conversion algorithm to account for starts with and ends with LIKE expressions.

Here is my code:

internal static string ConvertLikeToRegex(string pattern)
{
    // Turn "off" all regular expression related syntax in the pattern string.
    StringBuilder builder = new StringBuilder(Regex.Escape(pattern));

    // these are needed because the .*? replacement below at the begining or end of the string is not
    // accounting for cases such as LIKE '%abc' or LIKE 'abc%'
    bool startsWith = pattern.StartsWith("%") && !pattern.EndsWith("%");
    bool endsWith = !pattern.StartsWith("%") && pattern.EndsWith("%");

    // this is a little tricky
    // ends with in like is '%abc'
    // in regex it's 'abc$'
    // so need to tanspose
    if (startsWith)
    {
        builder.Replace("%", "", 0, 1);
        builder.Append("$");
    }

    // same but inverse here
    if (endsWith)
    {
        builder.Replace("%", "", pattern.Length - 1, 1);
        builder.Insert(0, "^");
    }

    /* Replace the SQL LIKE wildcard metacharacters with the
    * equivalent regular expression metacharacters. */
    builder.Replace("%", ".*?").Replace("_", ".");

    /* The previous call to Regex.Escape actually turned off
    * too many metacharacters, i.e. those which are recognized by
    * both the regular expression engine and the SQL LIKE
    * statement ([...] and [^...]). Those metacharacters have
    * to be manually unescaped here. */
    builder.Replace(@"\[", "[").Replace(@"\]", "]").Replace(@"\^", "^");

    return builder.ToString();
}

My initial units test are passing but not being overly conversant in regex syntax I am wondering if this is the best approach or if there are gaps in the conversion I am not seeing.


texts:
I'm working on writing a scripting language with ANTLR and C++. This is my first actual move from ANTLR grammars into the C++ API, so I'd like to know if this would be a good way to structure the grammar (later I will be adding a tree parser or tree rewriting rules though).

grammar dyst;

options
{
  language = C;
  output = AST;
  ASTLabelType=pANTLR3_BASE_TREE;
}

program : statement*;

statement : stopUsingNamespaceStm|usingNamespaceStm|namespaceDefineStm|functionStm|defineStm|assignStm|funcDefineStm|ifStm|whileStm|returnStm|breakStm|eventDefStm|eventCallStm|linkStm|classDefStm|exitStm|importStm|importOnceStm|directive;

namespaceDefineStm : 'namespace' ident '{' statement* '}';

usingNamespaceStm : 'using' 'namespace' ident (',' ident)* ';';

stopUsingNamespaceStm : 'stop' 'using' 'namespace' ident (',' ident)* ';';

directive : '@' directiveId argList? ';';

directiveId : ID (':' ID)*;

importOnceStm : 'import_once' expression ';';

importStm : 'import' expression ';';

exitStm : 'exit' expression? ';';

classDefStm : 'class' ident ('extends' ident (',' ident)*)? '{' (classSection|funcDefineStm|defineStm|eventDefStm)* '}';

classSection : ('public'|'private'|'protected') ':';

linkStm : 'link' ident 'to' ident (',' ident)* ';';

eventCallStm : 'call' ident (',' argList)? ';';

eventDefStm : 'event' ident '(' paramList? ')' ';';

returnStm : 'return' expression ';';

breakStm : 'break' int ';';

ifStm : 'if' '(' expression ')' '{' statement* '}';

whileStm : 'while' '(' expression ')' '{' statement* '}';

defineStm : 'global'? 'def' ident ('=' expression)? ';';

assignStm : ident '=' expression ';';

funcDefineStm : 'function' ident '(' paramList? ')' ('handles' ident (',' ident)*)? '{' statement* '}';

paramList : param (',' param)?;

param : ident ('=' expression)?;

functionStm : functionCall ';';

functionCall : ident '(' argList? ')';

argList : expression (',' expression)*;

//Expressions!
term : functionCall|value|'(' expression ')';

logic_not : ('!')* term;

bit_not : ('~')* logic_not;

urnary : '-'* bit_not;

mult : urnary (('*'|'/'|'%') urnary)*;

add : mult ('+' mult)*;

relation : add (('<='|'>='|'<'|'>') add)*;

equality : relation (('=='|'!=') relation)*;

bit_and : equality ('&' equality)*;

bit_xor : bit_and ('^' bit_and)*;

bit_or : bit_xor ('|' bit_xor)*;

logic_and : bit_or ('&&' bit_or)*;

logic_or : logic_and ('||' logic_and)*;

expression : logic_or;

value : ident|float|int|string|boolean|newObject|anonFunc|null_val;

anonFunc : 'function' '(' paramList? ')' '{' statement* '}';

newObject : 'new' ident ('(' argList ')')?;

ident : ID (('.'|'::') ID)*;

float : FLOAT;

int : INTEGER;

string : STRING_DOUBLE|STRING_SINGLE;

boolean : BOOL;

null_val : NULL_VAL;

FLOAT : INTEGER '.' INTEGER;
INTEGER : DIGIT+;

BOOL : 'true'|'false';

NULL_VAL : 'null'|'NULL';

STRING_DOUBLE : '"' .* '"';
STRING_SINGLE : '\'' .* '\'';

ID : (LETTER|'_') (LETTER|DIGIT|'_')*;

fragment DIGIT : '0'..'9';
fragment LETTER : 'a'..'z'|'A'..'Z';

NEWLINE : ('\n'|'\r'|'\t'|' ')+ {$channel = HIDDEN;};
COMMENT : '#' .* '\r'? '\n' {$channel = HIDDEN;};
MULTI_COMMENT : '/-' .* '-/' {$channel = HIDDEN;};

If you are wondering about exactly what it is I'm using this for, you can take a look here.


texts:
Using PHP and jQuery, I was able to make this countdown timer. I've searched various books and obviously on Google, but couldn't find this type of approach as used by me here. I sincerely feel there is something wrong with it. Can anyone tell me if this is the right approach?

                 <!DOCTYPE html>

recdisp.php

                         <?php
  date_default_timezone_set("Asia/KolKata");

  $time=1434402728+3600000*24*10000;//some time in future.
 echo "
";
  echo (date("d",$time-time())-1);
  echo "
";
  echo "
";
  echo " Days ";
  echo "
";
  echo "
";
  echo (date("h",$time-time()));
  echo "
";
 echo "
";
  echo " Hours ";
 echo "
";echo "
";
    echo (date("i",$time-time()));
  echo "
";
 echo "
";
 echo " Minutes ";
 echo "
";
  echo "
";
  echo (date("s",$time-time()));
 echo "
";
echo "
";
 echo " Seconds ";
 echo "
";
 ?>


texts:
Review this code, which should return true if a port is in use or false if the port is not in use.

Clarification: "In use" means that the port is already open (and used by another application). I'm trying to find a port number between (49152 and 65535) to open that is available.

private boolean isPortInUse(String hostName, int portNumber) {
        boolean result;

        try {

            Socket s = new Socket(hostName, portNumber);
            s.close();
            result = true;

        }
        catch(Exception e) {
            result = false;
        }

        return(result);
}


texts: Is my script secure to prevent email injection?

texts:
I have an email contact form that is PHP and very basic. I am concerned, however, that injections might be possible through it. So I was wondering if anyone with far superior PHP skills than myself would be willing to take a look and see if I have any gaps or vulnerabilities in my code that could be exploited. I very much appreciate any help with this.

PHP

<?php

$field_name = isset( $_POST['cf_name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['cf_name'] ) : "";
$field_email = isset( $_POST['cf_email'] ) ? preg_replace(  "/[^\.\-\_\@a-zA-Z0-9]/" , "", $_POST['cf_email'] ) : "";
$field_message = isset( $_POST['cf_message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['cf_message'] ) : "";

$mail_to = 'admin@mywebsite.com';
$subject = 'New Contact for My Website from '.$field_name;

$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;

$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

?>

For the brief moment I had this on Stack Overflow (before I was told that it should be here) the comment was made that I shouldn't be stripping characters out of emails. So... what should I do then? Is there a simple method to achieve the goal that I am missing? I am very new to this and just want to be as secure as possible.


texts: Optimizing variable order Markov Chain Implementation

texts:
I've created a variable order Markov chain built on top of a tree, but I can't train on datasets >1MB worth of text without running out of memory. I'm sure the tree can be replaced by something else more efficient, but I'm struggling with figuring that out. I've heard a linked list might work, but I'm not sure how.

Below is the AddString method for variable order chains (of characters).

public void AddString(string s)
{
    // Construct the string that will be added.
    StringBuilder sb = new StringBuilder(s.Length + 2 * (MarkovOrder));

    sb.Append(StartChar, MarkovOrder);
    sb.Append(s);
    sb.Append(StopChar, MarkovOrder);

    for (int i = 0; i < sb.Length; ++i)
    {
        // Get the order 0 node
        Node parent = root.AddChild(sb[i]);

        //add N-grams
        for (int j = 1; j <= MarkovOrder && j + i < sb.Length; j++)
        {
            Node child = parent.AddChild(sb[j + i]);
            parent = child;
        }
    }
}

(code base found here)

This code bloats my memory with every order up to the defined order, and I'm not sure how I'd alter it to only store one order without it completely breaking down. I'd like to do something like

markov = new markovChain(order = 3);.

I've been playing around with algorithms that can store a chain of order (i.e.) 4 without going through the other orders. These implementations aren't performing as well, and I keep resorting to several lists that make node creation complex for me.
(https://gist.github.com/mtbarta/8127895)

I'm not sure what structure to use so that I can generate a chain at a given order without bloating memory use. Can I implement a linked list that stores a list of following nodes? Does that ruin the point of a linked list while bloating my memory anyway?


texts: Creating a dictionary of all prefixes of a string in Python

texts:
a=raw_input()
prefix_dict = {}
for j in xrange(1,len(a)+1):
    prefix = a[:j]
    prefix_dict[prefix] = len(prefix)
print prefix_dict

Is there any possibility of memory error in the above code?


texts: Lambda to collect properties in a child object

texts:
I have a class:

public class ProductInvoice {
     //Some other properties.
    private List<ProductEntry> productEntries = newArrayList();
//otherMethods
}

And:

public class ProductEntry {
//other properties
    private Long quantity;
    private Long productId;
}

Now  I need to prepare a map of productId vs quantity by iterating over a collection of ProductInvoice objects:

List<ProductInvoice> entries = productInvoiceRepository.findByProductEntries_ProductIdIn(productIds);
        Map<Long, Long> productIdVsQuantity = newHashMap();
        entries.forEach( pi -> pi.getProductEntries().forEach(pe -> {
            if (productIdVsQuantity.containsKey(pe.getProductId())) {
                productIdVsQuantity.put(pe.getProductId(), productIdVsQuantity.get(pe.getProductId()) + pe.getQuantity());
            } else {
                productIdVsQuantity.put(pe.getProductId(), pe.getQuantity());
            }
        }));

Could there be a better way of doing this? I think this can be optimized using better lambda usage.


texts:
This code is about instantiating object attributes Just in Time.

I'm working on a REST API, where I currently create Python objects from the JSON data returned by the server, though not all attributes of the created objects will be called upon in user code. Hence only instantiating the attributes the user access via dot notation seems like a valid way to improve performance.

lazy_evaluate is a function, with a signature similar to functools.partial.
lazy_evaluate returns a function that when called multiple times only computes the result once.

I then take advantage of the builtin property function to create a getter that calls the function returned by lazy_evaluate.

There is clearly a trade off here. This only helps performance if a subset of the attributes are required in user code. Otherwise the extra code will slow it down.

The core of the idea is to use Python scoping to mutate a list in the scope outside the function evaluate. I dislike this the most.

Do you think it's a good idea?
Do you have a better solution?
Do you think the complexity is worth it?

I will try and create more context here as to why I want this. I have implemented this idea in my package async_v20 found here. I have written docs here.

I left this out as I felt it was a distraction from the concept.

JSON from the server does get parsed into a python dict. Though aiohttp does this for me.

When the server sends JSON:

All attributes are converted to snake_case via a dictionary lookup
Time data is turned into a pandas.TimeStamp (requires extra parsing)

In some cases there may be 5000 objects to instantiate or objects may be nested around 3 deep. Objects get instantiated in this module.

This example runs a benchmark:

from time import time

class Time(object):
    def __enter__(self):
        self.start = time()
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time()
        self.interval = self.end - self.start

def lazy_evaluate(func, *args, **kwargs):
    acc = []
    def evaluate():
        if acc == []:
            print('EVALUATING')
            acc.append(func(*args, **kwargs))
        return acc[0]
    return evaluate

class JitAttributes(object):

    foo = property(lambda self: getattr(self, '_foo')())
    bar = property(lambda self: getattr(self, '_bar')())
    baz = property(lambda self: getattr(self, '_baz')())

    def __init__(self, foo, bar, baz):
        self._foo = foo
        self._bar = bar
        self._baz = baz

class Attributes(object):

    def __init__(self, foo, bar, baz):
        self.foo = foo
        self.bar = bar
        self.baz = baz

a = 500 # Careful making this too big!
b = a * 2
c = b * 2

print('RUNNING JitAttributes')
repeats = range(100000)

with Time() as t:
    for _ in repeats:
        JitAttributes(
            lazy_evaluate(list, range(a)),
            lazy_evaluate(list, range(b)),
            lazy_evaluate(list, range(c)),
        )

print('TOOK ', t.interval, ' seconds')

print('RUNNING Attributes')

with Time() as t:
    for _ in repeats:
        Attributes(
            list(range(a)),
            list(range(b)),
            list(range(c)),
        )

print('TOOK ', t.interval, ' seconds')

Outputs:

RUNNING JitAttributes
TOOK  0.2956113815307617  seconds
RUNNING Attributes
TOOK  4.880501985549927  seconds

Console demonstration:

>>> jit_instance = JitAttributes(
...                 lazy_evaluate(list, range(a)),
...                 lazy_evaluate(list, range(b)),
...                 lazy_evaluate(list, range(c)),
...             )
>>> jit_instance.foo
# EVALUATING            <- Only evaluates once :)
# [0, 1, 2, 3, ... ]
>>> jit_instance.foo
# [0, 1, 2, 3, ... ]
>>> non_jit_instance = Attributes(
...                 list(range(a)),
...                 list(range(b)),
...                 list(range(c)),
...             )

>>> non_jit_instance.foo
# [0, 1, 2, 3, ...]
>>> non_jit_instance.foo
# [0, 1, 2, 3, ...]

Update

New review following on from this one


texts:
Your task is to sort an array of integer numbers by the product of the
  value and the index of the positions.

  For sorting the index starts at 1, NOT at 0! The sorting has to be
  ascending. The array will never be null and will always contain
  numbers.

My solution

int* sortByValueAndIndex(int* array, int arrayLength) {
  int* extraArray = malloc(arrayLength * sizeof(int));

  for (int index = 0; index < arrayLength; index++) {
    extraArray[index] = array[index] * (index + 1);
  }

  /* Bubble sort */
  for (int firstIndex = 0; firstIndex < arrayLength - 1; firstIndex++) {
    for (int secondIndex = 0; secondIndex < arrayLength - firstIndex - 1; secondIndex++) {
      if (extraArray[secondIndex] > extraArray[secondIndex + 1]) {

        int tmp = array[secondIndex];
        array[secondIndex] = array[secondIndex + 1];
        array[secondIndex + 1] = tmp;

        tmp = extraArray[secondIndex];
        extraArray[secondIndex] = extraArray[secondIndex + 1];
        extraArray[secondIndex + 1] = tmp;
      }
    }
  }

  free(extraArray);

  return array;
}