Moving a Rectangle using Keys I am working on making it so I can move a Rectangle using my arrow keys but what I have currently isn't working.

I initially had it so the Rectangle moved on it's own when I started the program. It moves based on the values of xVelocity and yVelocity. When I change those to 0 the object is stationary (as expected). But when I make it so they are initially 0 and when you press an arrow key the velocity changes, the object doesn't move. Any help?

Here is my Main class, Shapes. I have the keyListener in here print out the Velocity value when I press DOWN so I know it is changing the velocity properly.

package square;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Shapes extends JFrame {

public static int WIN_WIDTH = 400;
public static int WIN_HEIGHT = 400;

private Paddle paddle = new Paddle();

public Shapes() {
    Panel panel = new Panel();

    setSize(WIN_WIDTH, WIN_HEIGHT);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    add(panel);
    panel.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if(keyCode == KeyEvent.VK_DOWN) {
                paddle.yVelocity = -4;
                System.out.println(paddle.yVelocity);
            }
            if(keyCode == KeyEvent.VK_UP) {
                paddle.yVelocity = 4;
            }
            if(keyCode == KeyEvent.VK_RIGHT) {
                paddle.xVelocity = 4;
            }
            if(keyCode == KeyEvent.VK_LEFT) {
                paddle.xVelocity = -4;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }
    });
    setVisible(true);
}

public static void main(String[] args) {
    new Shapes();
}
}

Here is my Paddle class where the shape's values are stored, drawn, and updated. I have the velocities set to 0 initially

package square;

import java.awt.*;

public class Paddle {

int RECT_WIDTH = 200;
int RECT_HEIGHT = 100;
int x = Shapes.WIN_WIDTH/2-100;
int y = Shapes.WIN_HEIGHT/2-50;
int xVelocity = 0;
int yVelocity = 0;

public void paint(Graphics g) {
    g.setColor(Color.red);
    g.fillRect(x, y, RECT_WIDTH, RECT_HEIGHT);
}

public void update() {
    x += xVelocity;
    y += yVelocity;
    if(x < 0 || x > Shapes.WIN_WIDTH) {
        xVelocity = -xVelocity;
    }
    if(y < 0 || y > Shapes.WIN_HEIGHT) {
        yVelocity = -yVelocity;
    }
}
}

And finally my Panel class

package square;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Panel extends JPanel implements ActionListener {

Paddle paddle = new Paddle();
Timer timer;

public Panel() {
    this.setFocusable(true);
    timer = new Timer(5,this);

    timer.start();
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    paddle.paint(g);
}

public void update() {
    paddle.update();
}

@Override
public void actionPerformed(ActionEvent e) {
    repaint();
    update();
}
}

The reason the position of the paddle doesn't update is because the paddle that you adjust the velocity of in class Shapes is a different instance of paddle than the one you're drawing.
Make these changes to class Shapes:

delete field: private Paddle paddle = new Paddle();

add line
Paddle paddle = panel.paddle;

in the constructor after you declare Panel panel = new Panel();

Additionally, you will likely want to switch your yVelocity values, as pressing "down" sends the box up, and vice versa.


Short Clojure digit extraction I'm new to Clojure, and would appreciate feedback on this short program. The problem I set out to solve was selected at random from Project Euler, and is described in the comments. The part that I'm least happy about is the repeated series for the product, which I think could be replaced with a reduce call somehow.

; An irrational decimal fraction is created by concatenating the positive integers:
; 0.123456789101112131415161718192021...
;              ^
; It can be seen that the 12th digit of the fractional part is 1.
; If dn represents the nth digit of the fractional part,
; find the value of the following expression:
;    d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

(def d (apply str (map str (range 1 1000001)))) ; generate Champernowne's contant
(defn get-digit [x k] (read-string (.substring x k (+ k 1)))) ; get digit at position
(* (get-digit d 0)
   (get-digit d 9)
   (get-digit d 99)
   (get-digit d 999)
   (get-digit d 9999)
   (get-digit d 99999)
   (get-digit d 999999)
) ; product from problem statement

I'd simplify as follows:

(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))

codePointAt is a method of Java's String class.
digit is a static method of Java's Character class.

Both of these are in Java.lang, hence included by default.

(->> 1
     (iterate (partial * 10))
     (map (comp (partial get-digit d) dec))
     (take 7)
     (apply *))
;210

You can replace apply with reduce, if you prefer.

The calculation may be easier to follow as a series of bindings in a  let form:

(let [powers-of-ten (iterate (partial * 10) 1)
      digits (map (comp (partial get-digit d) dec) powers-of-ten)
      seven-digits (take 7 digits)
      answer (apply * seven-digits)]
  answer)


Emit different text and sound when each of three buttons is pressed I would like to use this same code on multiple pages of photos (to help my son recognize people). So instead of reinserting the name of each person, I created the appearingInPhoto (tuple or array), so I can utilize just .a .b .c, instead of having to go and rename each line of code.

Is there a way to simplify the code further, so I can just have code that checks if a button is pressed (check that sender.currentTitle is equal to any of the tuple values) and if yes, run this code?

print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a

This is the full function now:

var appearingInPhoto = (a:"omar", b:"john", c:"thomas")

@IBAction func buttonPressed(_ sender: UIButton) {
    var soundName: String? = nil
    if sender.currentTitle == appearingInPhoto.a {
        print("pressed \(appearingInPhoto.a)")
        label.text = appearingInPhoto.a
        soundName = appearingInPhoto.a
    }else if sender.currentTitle == appearingInPhoto.b {
        print("pressed \(appearingInPhoto.b)")
        label.text = appearingInPhoto.b
        soundName = appearingInPhoto.b
    }else if sender.currentTitle == appearingInPhoto.c {
        print("pressed \(appearingInPhoto.c)")
        label.text = appearingInPhoto.c
        soundName = appearingInPhoto.c
    }
    if let soundName = soundName {
        playSoundFile(soundName)
    }
  }

Slightly modified (using array):

var appearingInPhoto = ["omar", "john", "thomas"]

@IBAction func buttonPressed(_ sender: UIButton) {

    guard let soundName = sender.currentTitle else {
        return
    }
    if appearingInPhoto.contains(soundName) {
        print("pressed \(soundName)")
        label.text = soundName
        playSoundFile(soundName)
    }

}


Definite integral calculation in C# How do I better calculate the definite integral? I am using a function to integrate and another to find the factorial recursively.

I'l like to better the algorithm or the efficiency or even the accuracy for that matter.

    public static double testStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)
    {
        return (meanTreatmentSumOfSquares / meanErrorSumOfSquares);
    }

    public static double pValue(double fStatistic, int degreeNum, int degreeDenom)
    {
        double pValue = 0;
        pValue = integrate(0, fStatistic, degreeNum, degreeDenom);

        return pValue;

    }

    public static double integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)
    {
        int iterations = 100000;
        double x, dist, sum = 0, sumT = 0;
        dist = (end - start) / iterations;
        for (int i = 1; i <= iterations; i++)
        {
            x = start + i * dist;
            sumT += integralFunction(x - dist / 2, degreeFreedomT, degreeFreedomE);
            if (i < iterations)
            {
                sum += integralFunction(x, degreeFreedomT, degreeFreedomE);
            }
        }
        sum = (dist / 6) * (integralFunction(start, degreeFreedomT, degreeFreedomE) + integralFunction(end, degreeFreedomT, degreeFreedomE) + 2 * sum + 4 * sumT);
        return sum;
    }

    public static double integralFunction(double x, int degreeFreedomT, int degreeFreedomE)
    {
        double temp=0;
        temp = ((Math.Pow(degreeFreedomE, degreeFreedomE / 2) * Math.Pow(degreeFreedomT, degreeFreedomT / 2)) / (factorial(degreeFreedomE / 2 - 1) * factorial(degreeFreedomT / 2 - 1))) * (factorial(((degreeFreedomT + degreeFreedomE) / 2 - 1)))*((Math.Pow(x, degreeFreedomE / 2 - 1)) / (Math.Pow((degreeFreedomT + degreeFreedomE * x), ((degreeFreedomE + degreeFreedomT) / 2))));
        return temp;
    }

    public static double factorial(double n)
    {
        if (n == 0)
        {
            return 1.0;
        }
        else
        {
            return n * factorial(n - 1);
        }
    }
}
}

Check source code of the GSL library that is really well designed.
It includes implementations of many numerical integration algorithms.


Project Euler problem 92 - square digit chains Link to problem.

  A number chain is created by continuously adding the square of the
  digits in a number to form a new number until it has been seen before.

  For example,

  44 -> 32 -> 13 -> 10 -> 1 -> 1

  85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89

  Therefore any chain that arrives at 1 or 89 will become stuck in an
  endless loop. What is most amazing is that EVERY starting number will
  eventually arrive at 1 or 89.

  How many starting numbers below ten million will arrive at 89?

This solution to Project Euler problem 92 takes about 80 seconds. How can I reduce the time to well under 60 seconds?

def squareDigits(num):
    total = 0
    for digit in str(num):
        total += int(digit) ** 2
    return total
pastChains = [None] * 10000001
pastChains[1], pastChains[89] = False, True
for num in range(2, 10000001):
    chain = [num]
    while pastChains[chain[-1]] is None:
        chain.append(squareDigits(chain[-1]))
    for term in chain:
        if pastChains[term] is not None:
            pastChains[term] = pastChains[chain[-1]]
print pastChains.count(True)

1. Bug

There's a bug in your program. This line

if pastChains[term] is not None:

should be

if pastChains[term] is None:

2. Piecewise improvement

In this section I'm going to show how you can speed up a program like this by making a series of small piecewise improvements. This doesn't often work for the Project Euler problems: normally you have to come up with new algorithmic ideas. But here you're pretty close to getting under the minute mark, and that makes piecewise improvement a plausible approach.

Note that I'm using Python 2.7 here, which is generally faster than Python 3.

2.1. Base case

I'm going to start by putting your code into a form which is more convenien for testing (also, where we can run it for smaller limits than ten million, which can be convenient when making frequent measurement). Also, I'll improve the coding style while I'm about it (add docstrings; put local variables in lower_case_with_underscores; use the more meaningful values 1 and 89 instead of the Booleans False and True).

def square_digits(n):
    """Return the sum of squares of the base-10 digits of n."""
    total = 0
    for digit in str(n):
        total += int(digit) ** 2
    return total

def problem92a(limit):
    """Return the count of starting numbers below limit that eventually arrive
    at 89, as a result of iterating the sum-of-squares-of-digits.

    """
    arrive = [None] * limit # Number eventually arrived at, or None if unknown.
    arrive[1], arrive[89] = 1, 89
    for n in range(2, limit):
        chain = [n]
        while arrive[chain[-1]] is None:
            chain.append(square_digits(chain[-1]))
        for term in chain:
            if arrive[term] is None:
                arrive[term] = arrive[chain[-1]]
    return arrive.count(89)

>>> from timeit import timeit
>>> timeit(lambda:problem92a(10**7), number=1)
185.13595986366272

That's a lot slower than your reported "80 seconds": clearly you have a much faster machine than I do!

2.2. Avoiding number/string conversion

Now, let's do some work on the square_digits function. As written, this function has to convert the integer n to a string and then convert each digit back to a number. We could avoid these conversions by working with numbers throughout:

def square_digits(n):
    """Return the sum of squares of the base-10 digits of n."""
    total = 0
    while n:
        total += (n % 10) ** 2
        n //= 10
    return total

>>> timeit(lambda:problem92a(10**7), number=1)
61.409788846969604

Nearly under the minute already!

2.3. Second version

Here are some obvious minor improvements:

Avoid the repeated lookup of chain[-1] by remembering the value in a local variable.
Reduce the size of chain by one (because the last element in the chain is remembered in the local variable).
The test arrive[term] is None is unnecessary: by this point in the code we know that only the last term in chain was found in arrive.

That yields the following code:

def problem92b(limit):
    """Return the count of starting numbers below limit that eventually arrive
    at 89, as a result of iterating the sum-of-squares-of-digits.

    """
    arrive = [None] * limit # Number eventually arrived at, or None if unknown.
    arrive[1], arrive[89] = 1, 89
    for n in range(2, limit):
        chain = []
        while not arrive[n]:
            chain.append(n)
            n = square_digits(n)
        dest = arrive[n]
        for term in chain:
            arrive[term] = dest
    return arrive.count(89)

When transforming code like this, it's always important to check that our transformations didn't break anything. Here's where the ability to run the program for small values of limit comes in handy:

>>> all(problem92a(i) == problem92b(i) for i in range(1000, 2000))
True

And this yields a further 12% speedup:

>>> timeit(lambda:problem92b(10**7), number=1)
53.771003007888794

2.3. Third version

The largest number under ten million is 9999999, whose sum of squares of digits is just 567. All other numbers in the range have even smaller sums of squares of digits. So for 568 and up, there is no need to follow the chain: we can just look up the answer directly. That suggests the following approach:

def problem92c(limit):
    """Return the count of starting numbers below limit that eventually arrive
    at 89, as a result of iterating the sum-of-squares-of-digits.

    """
    sum_limit = len(str(limit - 1)) * 9 ** 2 + 1
    arrive = [None] * sum_limit
    arrive[1], arrive[89] = 1, 89
    for n in range(2, sum_limit):
        chain = []
        while not arrive[n]:
            chain.append(n)
            n = square_digits(n)
        dest = arrive[n]
        for term in chain:
            arrive[term] = dest
    c = arrive.count(89)
    for n in range(sum_limit, limit):
        c += arrive[square_digits(n)] == 89
    return c

Again, we better check that we didn't break anything:

>>> all(problem92a(i) == problem92c(i) for i in range(1000, 2000))
True

And this yields a further 30% improvement:

>>> timeit(lambda:problem92c(10**7), number=1)
37.56105399131775

That's about an 80% speedup on the original version, just by making piecewise and localized improvements.

3. New algorithm

For more radical improvements to the runtime, we need to rethink the algorithm completely. Here's a sketch of the combinatorial approach:

For each number k up to 567 that arrives at 89, we work out all the ways to partition k into a sum of no more than seven squares from 12 to 92 (using the partitioning technique we used in our answer to problem 76, say). This gives us a multiset of digits, and we can use combinatorial techniques to count the number of ways this multiset can be realised as a number up to 9999999.

For example, the starting number 4 arrives at 89. 4 can be partitioned into 22 or into 12 + 12 + 12 + 12. In the first case, there are 7 starting numbers in the range (2, 20, 200, 2000, 20000, 200000 and 2000000). In the second case, writing C(n, k) for the number of combinations of k items out of n, there are C(3,3) + C(4,3) + C(5,3) + C(6,3) = 35 starting numbers in the range (1111, 10111, 11011, and so on).

And here's some code, which I hope is self-documenting! Ask if you don't understand anything.

It uses the @memoized decorator from the Python Decorator Library to avoid unnecessary re-computation.

from collections import Counter
from math import factorial
from memoize import memoized

@memoized
def partitions(n, k, v):
    """Return partitions of n into at most k items from v, with
    repetition. v must be a tuple sorted into numerical order. Each
    partition is returned as multiset in the form of a Counter object
    mapping items from v to the number of times they are used in the
    partition.

        >>> partitions(4, 7, (1, 4))
        [Counter({1: 4}), Counter({4: 1})]

    """
    if n == 0:
        # Base case: the empty partition.
        return [Counter()]
    if k == 0 or len(v) == 0 or n < v[0]:
        # No partitions possible here.
        return []
    pp = [p.copy() for p in partitions(n - v[0], k - 1, v)]
    for p in pp:
        p[v[0]] += 1
    return pp + partitions(n, k, v[1:])

@memoized
def multinomial(n, k):
    """Return the multinomial coefficient n! / k[0]! k[1]! ... k[m]!.

        >>> multinomial(6, (2, 2, 2))
        90

    """
    result = factorial(n)
    for i in k:
        result //= factorial(i)
    return result

@memoized
def number_count(digit_counts, min_digits, max_digits):
    """Return the count of numbers (with between min_digits and max_digits
    inclusive) whose distinct non-zero digits have counts given by the
    sequence digit_counts. For example if we have three identical
    non-zero digits and four digits in total:

        >>> number_count((3,), 4, 4)
        3

    because the possible numbers resemble 1011, 1101, and 1110.
    Similarly

        >>> number_count((1,1), 4, 4)
        6

    because the possible numbers resemble 1002, 1020, 1200, 2001,
    2010, and 2100.

    """
    nonzero_digits = sum(digit_counts)
    total = 0
    for digits in range(max(min_digits, nonzero_digits), max_digits + 1):
        for i, d in enumerate(digit_counts):
            counts = (digit_counts[:i] + (d - 1,) + digit_counts[i+1:]
                      + (digits - nonzero_digits,))
            total += multinomial(digits - 1, tuple(sorted(counts)))
    return total

def problem92d(limit):
    """Return the count of starting numbers below limit that eventually arrive
    at 89, as a result of iterating the sum-of-squares-of-digits.

    """
    max_digits = len(str(limit - 1))
    assert(limit == 10 ** max_digits) # algorithm works for powers of 10 only
    sum_limit = max_digits * 9 ** 2 + 1
    arrive = [None] * sum_limit
    arrive[1], arrive[89] = 1, 89
    for n in range(2, sum_limit):
        chain = []
        while not arrive[n]:
            chain.append(n)
            n = square_digits(n)
        dest = arrive[n]
        for term in chain:
            arrive[term] = dest
    total = 0
    squares = tuple(i ** 2 for i in range(1, 10))
    for n in range(2, sum_limit):
        if arrive[n] == 89:
            for p in partitions(n, max_digits, squares):
                total += number_count(tuple(sorted(p.values())), 1, max_digits)
    return total

As usual, we need to check that this radically new approach computes the right results:

>>> all(problem92c(10**i) == problem92d(10**i) for i in range(3, 7))
True

Note that since we are using memoization, for fair timing results we must reload the code before running the timer (otherwise we'll get misleadingly fast times due to some of the computation having previously been done and stored in the memoization caches). But with a fresh Python instance:

>>> timeit(lambda:problem92d(10**7), number=1)
0.7318389415740967

Less than a second! I hope that it's clear now how important the choice of algorithm is. With the piecewise improvement approach the code became about five times faster (which is pretty decent result). But with a better algorithm the code is 250 times faster.

4. Questions in comments

You asked some questions in the comments.

Obviously in Python 3 you'd use range, not xrange. And in fact, even in Python 2.7, substituting xrange for range makes hardly any difference to the runtime (a percent or so), so in my revised answer I've eschewed that.
In Python, small integer objects like 1 and 89 are shared and reused:

>>> x = 89
>>> x is 8900 / 100
True

If you look at the source code for longobject.c, you'll see that numbers from NSMALLNEGINTS (−5) up to NSMALLPOSINTS-1 (256) are preallocated in an array. So there is no memory penalty to using them.
Iteration works in Python by fetching successive values from an "iterator" object (here the object returned by range(2, limit)), not by incrementing the loop variable as you might do in languages like C. So there is no need to be scared about updating the loop variable.
Yes, that's right. Project Euler asks "How many starting numbers below ten million will arrive at 89?" (my emphasis). So it's convenient to use limit like this.
Probably a copy-paste mistake on my part. I've revised the answer and hopefully the sequence of improvements is clearer now.


Diff for successive sorted slice I wrote some code to determine the additions and deletions that happened to a sorted slice after each (sorted) update.

Git repository (includes some tests)

Godoc

// Package slicediff is a utility to determine the additions and deletions that happened to a sorted slice after each update.
//
// All the slices are assumed to be sorted!
package slicediff

import "container/list"

// SliceDiff stores the current state of the sorted slice
type SliceDiff struct {
    l *list.List
}

// New creates a new SliceDiff
func New() *SliceDiff {
    return &SliceDiff{
        list.New(),
    }
}

// Append appends a slice at the end of the SliceDiff
//
// sa is assumed to be sorted
func (sd *SliceDiff) Append(sa []string) {
    for _, s := range sa {
        sd.l.PushBack(s)
    }
}

// SortedDiff compares the updated slice with l and returns the additions and deletions performed
//
// updated is assumed to be sorted
func (sd *SliceDiff) SortedDiff(updated []string) (additions []string, deletions []string) {
    if sd.l.Len() == 0 {
        sd.Append(updated)
        additions = make([]string, len(updated))
        copy(additions, updated)
        return additions, make([]string, 0)
    }

    e := sd.l.Front()

    additions = make([]string, 0)
    deletions = make([]string, 0)

    for _, s := range updated {
        // Delete the small elements at the beginning of the list
        for e != nil && e.Value.(string) < s {
            deletions = append(deletions, e.Value.(string))
            e = removeAndGetNext(sd.l, e)
        }

        if e == nil {
            // End of list is empty: simply push it
            additions = append(additions, s)
            sd.l.PushBack(s)
        } else if s == e.Value.(string) {
            // Same as current element: skip it
            e = e.Next()
        } else {
            // Smaller than current element: insert it
            additions = append(additions, s)
            sd.l.InsertBefore(s, e)
        }
    }

    // delete end of the list
    for e != nil {
        deletions = append(deletions, e.Value.(string))
        e = removeAndGetNext(sd.l, e)
    }

    return additions, deletions
}

func removeAndGetNext(l *list.List, e *list.Element) (next *list.Element) {
    next = e.Next()
    l.Remove(e)
    return
}

Example:

// Create a new SliceDiff
sd := New()

// Add some initial elements
sd.Append([]string{
    "a",
    "b",
    "d",
})

// Perform an update
update := []string{
    "a",
    "b",
    "c",
}
add, del := sd.SortedDiff(update)

// Get the diff
fmt.Println(add, del)
// Output: [c] [d]

I'm interested to know if my implementation is correct (all the tests are passing, but maybe I missed something) and if my "Go-style" can be improved.

Unnecessary optimization

You can safely remove this block of code without changing the behavior of the program:

if sd.l.Len() == 0 {
    sd.Append(updated)
    additions = make([]string, len(updated))
    copy(additions, updated)
    return additions, make([]string, 0)
}

Possible optimization

When you append to additions and deletions,
reallocation might occur.
If you don't mind spending a little extra space,
you could ensure that these slices have enough capacity to avoid reallocation.
You know that the maximum number of additions is the size of the input,
and the maximum number of deletions is the size of the current content:

additions = make([]string, 0, len(updated))
deletions = make([]string, 0, sd.l.Len())

Shorter format declaration

Instead of this:

func (sd *SliceDiff) SortedDiff(updated []string) (additions []string, deletions []string) {

You can use this shorter form:

func (sd *SliceDiff) SortedDiff(updated []string) (additions, deletions []string) {

Naming

Short names are very popular and encouraged in Go.
But l is really the worst of all single-letter variable names.
In addition to the usual badness of these variables,
depending on the viewer program,
l might be indistinguishable from 1 or I or |.
I suggest to never use l as a symbol name.

Alternative implementation

It seems to me that the use of container/List doesn't really buy you much.
It would be simpler and clearer to implement without it.
Consider this alternative implementation using only slices:

// Package slicediff is a utility to determine the additions and deletions that happened to a sorted slice after each update.
//
// All the slices are assumed to be sorted!
package slicediff

// SliceDiff stores the current state of the sorted slice
type SliceDiff struct {
    content []string
}

// New creates a new SliceDiff
func New() *SliceDiff {
    return &SliceDiff{}
}

// Append appends a slice at the end of the SliceDiff
//
// sa is assumed to be sorted
func (sd *SliceDiff) Append(sa []string) {
    sd.content = append(sd.content, sa...)
}

func diff(s1, s2 []string) (added, deleted []string) {
    len1, len2 := len(s1), len(s2)

    added = make([]string, 0, len2)
    deleted = make([]string, 0, len1)

    for i1, i2 := 0, 0; i1 < len1 || i2 < len2; {
        if i1 == len1 {
            added = append(added, s2[i2:]...)
            return
        } else if i2 == len2 {
            deleted = append(deleted, s1[i1:]...)
            return
        }

        if s1[i1] < s2[i2] {
            deleted = append(deleted, s1[i1])
            i1++
        } else if s1[i1] > s2[i2] {
            added = append(added, s2[i2])
            i2++
        } else {
            i1++
            i2++
        }
    }
    return
}

// SortedDiff compares the updated slice with l and returns the additions and deletions performed
//
// updated is assumed to be sorted
func (sd *SliceDiff) SortedDiff(updated []string) (additions, deletions []string) {
    additions, deletions = diff(sd.content, updated)
    sd.content = updated
    return
}


Asynchronous version of AutoResetEvent This is my second attempt to create asynchronous version of AutoResetEvent.
At first I tried to make it completely lock-less, but it turned out to be impossible.
This implementation contains a lock however the lock isn't an instance wide:

/// <summary>
///     Asynchronous version of <see cref="AutoResetEvent" />
/// </summary>
public sealed class AutoResetEventAsync {
    private static readonly Task<bool> Completed = Task.FromResult(true);

    private readonly ConcurrentQueue<TaskCompletionSource<bool>> handlers =
        new ConcurrentQueue<TaskCompletionSource<bool>>();

    private int isSet;

    /// <summary>
    ///     Initializes a new instance of the <see cref="AutoResetEventAsync" /> class with a Boolean value indicating whether to set the intial state to signaled.
    /// </summary>
    /// <param name="initialState">true to set the initial state signaled; false to set the initial state to nonsignaled.</param>
    public AutoResetEventAsync(bool initialState) {
        this.isSet = initialState ? 1 : 0;
    }

    /// <summary>
    ///     Sets the state of the event to signaled, allowing one waiting continuation to proceed.
    /// </summary>
    public void Set() {
        if (!this.TrySet())
            return;

        TaskCompletionSource<bool> handler;

        // Notify first alive handler
        while (this.handlers.TryDequeue(out handler))
            if (CheckIfAlive(handler)) // Flag check
                lock (handler) {
                    if (!CheckIfAlive(handler))
                        continue;

                    if (this.TryReset())
                        handler.SetResult(true);
                    else
                        this.handlers.Enqueue(handler);

                    break;
                }
    }

    /// <summary>
    ///     Try to switch the state to signaled from not signaled
    /// </summary>
    /// <returns>
    ///     true if suceeded, false if failed
    /// </returns>
    private bool TrySet() {
        return Interlocked.CompareExchange(ref this.isSet, 1, 0) == 0;
    }

    /// <summary>
    ///     Waits for a signal asynchronously
    /// </summary>
    public Task WaitAsync() {
        return this.WaitAsync(CancellationToken.None);
    }

    /// <summary>
    ///     Waits for a signal asynchronously
    /// </summary>
    /// <param name="cancellationToken">
    ///     A <see cref="P:System.Threading.Tasks.TaskFactory.CancellationToken" /> to observe while waiting for a signal.
    /// </param>
    /// <exception cref="OperationCanceledException">
    ///     The <paramref name="cancellationToken" /> was canceled.
    /// </exception>
    public Task WaitAsync(CancellationToken cancellationToken) {
        // Short path
        if (this.TryReset())
            return Completed;

        cancellationToken.ThrowIfCancellationRequested();

        // Wait for a signal
        var handler = new TaskCompletionSource<bool>(false);

        this.handlers.Enqueue(handler);

        if (CheckIfAlive(handler)) // Flag check
            lock (handler)
                if (CheckIfAlive(handler) && this.TryReset()) {
                    handler.SetResult(true);
                    return handler.Task;
                }

        cancellationToken.Register(() => {
            if (CheckIfAlive(handler)) // Flag check
                lock (handler)
                    if (CheckIfAlive(handler))
                        handler.SetCanceled();
        });

        return handler.Task;
    }

    private static bool CheckIfAlive(TaskCompletionSource<bool> handler) {
        return handler.Task.Status == TaskStatus.WaitingForActivation;
    }

    private bool TryReset() {
        return Interlocked.CompareExchange(ref this.isSet, 0, 1) == 1;
    }
}

Any suggestions?

At first I tried to make it completely lock-less, but it turned out to be impossible. This implementation contains a lock however the lock isn't an instance wide.

It may shock you to hear that lock-free code may be slower than code using locking.

Lock-free code is usually longer and is definitely much more complex. You should not attempt to write lock-free code until you fully understand the .NET memory model. Joe Duffy's book would be a good starting point after reading those articles. I would say you are ready to write lock-free code when you can describe why double-checked locking is broken in Java and correctly answer this question: is it also broken in C#?

But back to the point: lock-free code is easily slower than regular locking in this instance because lock-free code is only faster when there's a lot of contention. When you're writing async-compatible primitives, any locks you take are only going to last for the synchronous portion of that method call - an extremely short time. So, unless you have literally hundreds of different threads all calling Set or WaitAsync on the same instance at the same time, you won't have a problem. In other words, async primitives kind of "lift" you to a higher level of scheduling - you actually build your own queue of waiters. And any lock you have isn't going to affect the real contention, which will be represented by that queue.

So, on with the actual code review...

As @svick correctly pointed out, you have a (benign) race condition in your code that may cause starvation, when your Set chooses to re-enqueue a TCS. You are also holding onto resources longer than necessary by keeping "dead" TCS instances in your queue. Remember that each TCS has a Task along with all its continuations, and any local variables captured by their lambdas, etc.

But that's not a deal-breaker, it's just somewhat unfair (starvation) and inefficient (holding references). There's a more sinister and subtle problem with this implementation.

You are calling back to end-user code while holding a lock. This is violating one of the central laws of multithreaded programming. Whenever you do this, there is a possibility of deadlock.

It's very subtle because the callback is not obvious, but it's there in both Set and Reset: SetResult and SetCanceled both (synchronously) invoke any task continuations that were scheduled with the ExecuteSynchronously flag.


Sort files in a given folders and provide as a list I have two folders query and subject. The following function sorts alphabetically and provides the query and subject as a separate list. The file names are mixed of numbers and I found the sort function works perfectly well. Any comments to improve?

import os
import re

subject_path = "/Users/catuf/Desktop/subject_fastafiles/"
query_path = "/Users/catuf/Desktop/query_fastafiles"

def sorted_nicely(l):

    """ Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(l, key = alphanum_key)

def subject_list_fastafiles():

    subject_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))])

    return subject_fastafiles

def query_list_fastafiles():

    query_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(query_path) if os.path.isfile(os.path.join(query_path, fastafile))])

    return query_fastafiles

def filter_files_ending_with_one(sorted_files):

    """ The function filters the files end with 1 """

    files_end_with_one = [name for name in subject_fastafiles if name[-1].isdigit() and not name[-2].isdigit() == 1]

    return files_end_with_one

subject_fastafiles = subject_list_fastafiles()

query_fastafiles = query_list_fastafiles()

subject_files_ending_with_one = filter_files_ending_with_one(subject_fastafiles)

Docstrings

You should include a docstring at the beginning of every function, class, and module you write. This will allow documentation to identify what your code is supposed to do. This also helps other readers understand how your code works. I see that you already have a couple for your functions, but stay consistent.

Parameter Names

Parameter names should be descriptive enough to be able to tell what should be passed. While l might be obvious to some programmers as an iterable, to others it might not. Since you're passing a list, renaming it to list_ (to avoid using reserved word list) makes it more obvious what you're passing, and accepting.

Constant Variables

When you have a constant in your program, it should be UPPER_CASE to identify it as such.

Code Reduction

You want as little code as possible in your program. So, instead of:

def subject_list_fastafiles():
    """ Method Docstring """
    subject_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(subject_path) if os.path.isfile(os.path.join(subject_path, fastafile))])
    return subject_fastafiles

def query_list_fastafiles():
    """ Method Docstring """
    query_fastafiles = sorted_nicely([fastafile for fastafile in os.listdir(query_path) if os.path.isfile(os.path.join(query_path, fastafile))])
    return query_fastafiles

def filter_files_ending_with_one(sorted_files):
    """ Method Docstring """
    files_end_with_one = [name for name in subject_fastafiles if name[-1].isdigit() and not name[-2].isdigit() == 1]
    return files_end_with_one

You can simply return the function call, instead of assigning it to a variable and returning the variable, like so:

def subject_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(SUBJECT_PATH) if os.path.isfile(os.path.join(SUBJECT_PATH, fastafile))])

def query_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(QUERY_PATH) if os.path.isfile(os.path.join(QUERY_PATH, fastafile))])

def filter_files_ending_with_one():
    """
    The function filters the files end with 1
    """
    return [name for name in SUBJECT_FASTAFILES if name[-1].isdigit() and not name[-2].isdigit() == 1]

Main Guard

This is an excerpt from this fabulous StackOverflow answer.

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed.  Functions and classes that are defined are, well, defined, but none of their code gets run.  Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block.  __name__ is a built-in variable which evaluates to the name of the current module.  However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__".  Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won't get run as the condition is not met.

Updated Code

"""
Module Docstring (A description of your program goes here)
"""

import os
import re

SUBJECT_PATH = "/Users/catuf/Desktop/subject_fastafiles/"
QUERY_PATH = "/Users/catuf/Desktop/query_fastafiles"

def sorted_nicely(list_):
    """
    Sort the given iterable in the way that humans expect. https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
    """
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(list_, key=alphanum_key)

def subject_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(SUBJECT_PATH) if os.path.isfile(os.path.join(SUBJECT_PATH, fastafile))])

def query_list_fastafiles():
    """
    Method Docstring
    """
    return sorted_nicely([fastafile for fastafile in os.listdir(QUERY_PATH) if os.path.isfile(os.path.join(QUERY_PATH, fastafile))])

def filter_files_ending_with_one():
    """
    The function filters the files end with 1
    """
    return [name for name in SUBJECT_FASTAFILES if name[-1].isdigit() and not name[-2].isdigit() == 1]

if __name__ == '__main__':

    SUBJECT_FASTAFILES = subject_list_fastafiles()
    QUERY_FASTAFILES = query_list_fastafiles()
    SUBJECT_FILES_ENDING_WITH_ONE = filter_files_ending_with_one()


Tips on projecteuler code optimization I am working on projecteuler # 14, http://projecteuler.net/problem=14 and my code takes too long to run. Any tips, or hints for a beginner?

Code:

////////////////////////
/// ProjectEuler # 14///
////////////////////////

#include <iostream>
#include <tuple>           //New, shaky on tuple
using namespace std;

bool tester(int n)      //Even number tester//It works 100%
{
    bool result = false;
    if (n%2 == 0) result = true;
    return result;
}

int collatz_counter (int collatz_number)    //Collatz sequence counter//It works 100%
{
    int j = collatz_number;
    int total = 0;
    do
    {
        if (tester(j))
        {
            j /=2;
            total ++;
        }
        else
        {
            j = 3*j +1;
            total ++;
        }
    }while (j!=1);
    total +=1;          // To account for the original number itself
    return total;
}

pair <int n, int m> value_finder (int n)
{
    int max = 0;
    int max_number = 0;
    for (int i = n; i>1; i--)
    {
        if(collatz_counter(i) > max)
        {
            max_number = i;
            max = collatz_counter(i);
        }
    }
    max_number++;
    return{max, max_number};
}

int main (void)
{
    int starter;
    int x;
    cout<<"Enter value :"<<endl;
    cin>>starter;
    cout<<endl;
    int Max = 0;
    int Max_Number = 0;
    for (x = starter; x>= starter/2 ; x--)
    {
        int m, n;
        tie(m, n) = value_finder(x);
        if ( m> Max)
        {
            Max_Number = n;
            Max = m;
        }
    }

    cout<<" The maximum numbers in the collatz sequence is "<<m<<endl;
    cout<<" The starting number of the collatz sequence is "<<n<<endl;
    system ("pause");
    return 0;
}

Hint

Taking the example from the Project Euler page, if you have computed the Collatz number for 5 in the past and you know it's 6, then when computing Collatz number for 10, you probably don't need to go through the whole chain. You can stop when you reach 5.

It might be interesting to cache the computed value to be able to reuse them.

(Disclaimer : I solved this problem a long time ago and cannot really remember how I did it)


Send an inbound Enquiry to a Users registered Twitter Account to notify them of its arrival This follows on from an earlier CR Question. - The reasoning behind which suggestions were taken on / which were not taken on board are no longer relevant as this is supposed to be, from my understanding, a distinct question that is capable of standing alone should anyone come across it.

Background

An enquiry is posted from a "Contact Me widget" on a registered user's 3rd party domain to a processing queue, this is one of the jobs that is triggered via an event handler that batch processes the queue and spawns events containing any new Enquiry Identifiers since the last time the queue was processed.

<?php

namespace App\Listeners\Enquiry;

use App\Events\NewEnquiryEvent;
use App\Models\Stores\Enquiry;

class TweetNewEnquiry
{
    /**
     * On enquiry event send tweet notifying the Enquiry target,
     * if applicable.
     *
     * @param NewEnquiryEvent
     *   The new enquiry event object.
     */
    public function handle(NewEnquiryEvent $event) : void
    {
        $enquiry_ids = (array) $event->body->id;

        $enquiries_to_tweet = Enquiry::find($enquiry_ids)->filter(function($enquiry) {
            return $enquiry->canTweet() && $enquiry->shouldTweet();
        });

        $enquiries_to_tweet->each->tweet();
    }
}

Context:

  This answer was originally supplied in context as part of a larger
  answer, when the question was split here I've also split the answer here

Updated code

The updated code does create a better signal to the reader of what is going on, I particularly like the variable name coming out one of the operations. You are trying to write Laravel code so I'll skip over framework coupling issues

Had a look at Laravel's docs and there is a filter method on the collection class so we could change the code to this:

filter(function (Enquiry $enquiry) : bool {
  return $enquiry->canTweet() || $enquiry->shouldTweet();
));

The reason to inverse the check from reject to filter is that I find it hard personally to read negative code, With !$something, first your brain has to parse what $something is, and then it has to flip it, I would advise as much as possible to write code that talks about the situation from the "positive" prospective.

I've also added type hinting again, seems like you agree that type hinting is overall good but just not in the habit of doing so? Remember anonymous functions can be type hinted too.

I would also suggest moving that anonymous function out into it's own function not necessarily just for code reuse (although that's a nice side effect) but because it forces you to create a semantic name for what the combination of canTweet() and shouldTweet() is.

I definitely appreciate it doesn't look necessary now to create a new function but if you default to doing so you encourage other developers to not lump all their changes at this particular call point (good if this eventually gets reused elsewhere).

Also you tell them the intent of the code so hopefully they won't dump unrelated stuff into your function, code always grows in active projects, decisions you make now will affect future code more than you know, variable names/function names that you decide now will be replicated in other parts of the code and particularly classes they get sticky to everything because they are a natural clumping mechanism

Alternatively (or additionally) I personally often assign the result of a condition to variable before return to force myself to name it and it also helps when using xdebug, because you can then see the result of the return inside the function itself, this makes stepping over/debugging easier because xdebug cannot go in reverse see: https://bugs.xdebug.org/view.php?id=888 :(

We can also stop our coupling to the structure of NewEnquiryEvent by changing the signature of the handle method to array $enquiry_ids

Feels like the OOP way to do this would be to create a method that does this:

class NewEnquiryEvent
{
  public function getIds() : array
  {
    return $this->body->id;
  }
}

Personally I would prefer to do this:

namespace NewEnquiryEvent;
function getIds(NewEnquiryEvent $event) : array
{
  return $event->body->id;
}

This is because I prefer to take responsibly away from classes they're usually already doing too much

I find OOP developers typically set things to private or protected for one of these reasons:

They think it makes the property immutable
They think know better than the callee about how the object should be used, and they think they can dictate that
They do it because they were taught to do so by default without really questioning why

Let's assume that's happened and we can't edit their class because we don't want to debug their class or its a third party code that we want are not interested in maintaining our own fork of then use the following:

namespace NewEnquriyEvent;
function getIds(NewEnquiryEvent $event) : array
{
  return (function () : array {
    return $this->body->id;
  })->call($event);
}

I imagine this won't be consistent with your current project structure or in particular your autoloader and sometimes consistency should trump logic or programming style, but either way I think it's interesting to explain the train of thought.


Chain of Responsibility design I'm trying to design a chain of responsibility pattern.
It slightly differ from traditional way when handler does only one action on a request, f.e. handles http response considering status code.
But my handlers have to do two actions. Below is an (dummy) example where handler asks a question first and then writes the user response to some store:
# some object where we keep surname and name
class Request:
    pass

# some outer storage
store = {}

# chain of responsibility implementation

class PersonIdentifier:

    def __init__(self) -> None:
        self.handlers = []

    def add_handler(self, handler):
        if self.handlers:
            self.handlers[-1].set_next_handler(handler)
        self.handlers.append(handler)

    def handle(self, request):
        return self.handlers[0].handle_request(request)

# handlers for chain of responsibility

class BaseHandler:
    handler_name = None

    def __init__(self) -> None:
        self.next_handler = None

    def set_next_handler(self, handler):
        self.next_handler = handler

class SurnameHandler(BaseHandler):
    handler_name = 'surname'
    handler_name_answer = 'surname-answer'
    question = 'Type your surname: '

    def handle_request(self, request):
        if request.handler_name == self.handler_name:
            return self.question
        elif request.handler_name == self.handler_name_answer:
            global store
            store['surname'] = request.surname
            del request.surname
            request.handler_name = 'name'
            return self.next_handler.handle_request(request)
        else:
            return self.next_handler.handle_request(request)

class NameHandler(BaseHandler):
    handler_name = 'name'
    handler_name_answer = 'name-answer'
    question = 'Type your name: '

    def handle_request(self, request):
        if request.handler_name == self.handler_name:
            return self.question
        elif request.handler_name == self.handler_name_answer:
            global store
            store['name'] = request.name

user_request = Request()

chain = PersonIdentifier()
chain.add_handler(SurnameHandler())
chain.add_handler(NameHandler())

# first ask for surname
user_request.handler_name = 'surname'
surname = input(chain.handle(user_request))
user_request.handler_name = 'surname-answer'
user_request.surname = surname

# then ask for name
name = input(chain.handle(user_request))
user_request.name = name
user_request.handler_name = 'name-answer'
chain.handle(user_request)

print(store)

It looks ugly for me. What do I dislike more is using handler_name and handler_name_answer.
May be you could offer nicer way to solve my task?

Chain of Responsibility pattern (hereby "CORP") includes two things: iteration and "handling".
IMO, the iteration part, at least in modern programming languages such as Python and Java, can be easily "extracted" to an external iteration. So eventually the code could look like:
result = None
for handler in handlers:
  temp_result = handler.handle(request)
  if temp_result is not None:
    result = temp_result
    break
if result is not None:
  # handled!

I think this approach is simpler than maintaining the inner chain, and it has the same impact.
In CORP, once a handler was found, and it can handle the input, no additional handlers should be executed. It's quite similar to filtering.
However, I think that the code we have in your question tries to execute as many handlers as it can (as it tries to enrich a wider context). So maybe CORP is not really needed here.
Perhaps you can have enriching classes, that have a method enrich that accepts a request and a context, so that every enriching class could either change the state of the context object, or leave it as is:
class BaseEnricher:
  def enrich(request, store):
    pass


Compute and Display Engineering Information I am updating a class in legacy code and having some issue with my calcPressure method.   I want to make it nice and clean but there is some convolution in the process.

Namely the calcPressure method I have does this:

computes a value from existing values
writes that value into an in-class parameter
returns the value to the caller
prints debug output while computing
prepares output for View (JSON, document...innerHtml)

Issues

In general, the code is all interconnected and it works, so part of me feels "why do I want to mess with it".  But part of me feels that Separation of Concerns (SOC) is super-broken.  After all, the same internal pressure parameter that originates inside PHP class goes all the way into JS view, from being computed in PHP, transferred to JS and displayed in the browser.  So if I make pressure private for example, or rename it, my view will become broken, since it depends on having the same parameter name in JS as in PHP for it to work.

More specifically my method seems to do an awful lot.  I'm questioning whether I should only have it compute data and return it without assigning the in-class parameter.  Or if I should only assign the in-class parameter and not return anything.  Right now it does both.  I wonder if I should redirect debugging information to be a part of view and not be a part of the method somehow (computation/debug output separation).

Code

class Spec
{

    function load()
    {
         $result = db_query("SELECT * from spec where id = {$this->id}");
         $row = db_fetch_array($result);
         $this->n = $row['n'];
         $this->sg = $row['sg'];
         $this->q = $row['q'];
    }

    /**
     * Computes and returns Pressure
     * Outputs debug info
     * Assigns internal parameter
     *
     * @return number
     */
    function calcPressure()
    {
        $res = abs($this->n * sqrt($this->q) / 15164.93 * $this->sg);
        dump("  *** Pressure = $res");
        $this->pressure = $res;
        return $res;
    }

    public $pressure;

    public $sg;

    public $q;

    public $n;

    public $id;
}

PHP side

$spec = new Spec();

/*
 * Load of static parameters ($q, $sg, $n) from DB omitted for clarity
 */
$spec->id = 5;
$spec->load();
$spec->calcPressure();
$json = json_encode($spec);

JS/View side

Dump

function dump($sql){print "
";print_r($sql);print"
" . PHP_EOL;}

This is a pretty incomplete code example, but let me give you some initial thoughts:

Use meaningful class and variable names. Spec seems very indeterminate as to what the class does. $sg, $q, and $n also convey little value (though perhaps that is because these are common scientific formula names that I am not fully familiar with.
Don't have the class output directly to standard output (which is what I assume the dump() function does.  Consider actually logging to server logs, or have it returned as part of the method return value so that caller can determine how to display it.
I almost question the need for this to be a class at all if this is only going to have a single method. It is very unclear how class properties are set. If all you are going to do is instantiate an object, use several methods to set properties (or directly set since these are public), and then call a single method, I don't see why this could not just be a function, or just static class method, as I do not understand what value you get by instantiating the class.  Perhaps if you had a constructor where you passed in and validated the variable values or, better yet, interacted with the DB to set these values, there would be value in having a class.
Do you really want to directly json_encode the object?  If you do, you might consider implementing the JSONSerializable interface, which would allow you to implement a jsonSerialize() method where you could specifically control the data structure that is sent to json_encode() for serialization. For example, if you wanted to make properties protected/private but still be able to see them in JSON output, you could build a stdClass object or associative array with key-value pairs describing the object, which would then be serialized.
If your code needs to be compatible with potentially older versions of PHP (i.e. < 5.4), you should probably not use short echo tag syntax (i.e. <?=$json?>)

Since you know have complete class information, I have updated my answer to give more specific review comments on your code below.  My comments are within multi-line comments.

/*
Class name seems non-specific
*/
class Spec
{
/*
Typical style guides would have class properties defined before class methods.
All methods should have visibility (i.e. public, protected, private) explicitly
defined.
Consider using a constructor such that you could do something like:
$spec = new Spec($id);
Where the constructor could call the load method. This would allow you to make
load method private, meaning calling code couldn't destructively reload
the object.  This will also allow you to validate the id input as integer
value greater than zero before trying to do any further work in instantiating
the class.
If you are going to use PHPDoc, use it on every method and property as well as
class itself. Don't partially use documentation.
*/
    function load()
    {
/*
Consider working with DB in an object-oriented fashion, with database object
dependency being passed to this class on instantiation.
Consider using parametrized prepared statements here rather than string
interpolation.  String interpolation raises question as to whether you might
be opening up an SQL injection vulnerability.
Don't use 'SELECT *'. It makes expected return results unclear to the code
reader and also potentially negatively impacts performance if you end up
retrieving more fields than necessary.
This DB interaction only considers happy path. What if query fails for some
reason?  What if an empty result set is returned?
*/
         $result = db_query("SELECT * from spec where id = {$this->id}");
         $row = db_fetch_array($result);
         $this->n = $row['n'];
         $this->sg = $row['sg'];
         $this->q = $row['q'];
    }

    /**
     * Computes and returns Pressure
     * Outputs debug info
     * Assigns internal parameter
     *
/*
"number" is not a valid @return type. It looks like you should be using "float".
*/
     * @return number
     */

/*
I really don't understand why you would need to make this method publicly
available. If you had a constructor, you could pass that constructor the id
(as well as a valid DB object if you choose to work with DB in OO fashion)
and then execute private load and calcPressure methods, setting up the object
for its intended use directly upon instantiation.
*/
    function calcPressure()
    {
        $res = abs($this->n * sqrt($this->q) / 15164.93 * $this->sg);
/*
Don't output from this class.
*/
        dump("  *** <u>Pressure</u> = $res");
        $this->pressure = $res;
/*
You would probably not need a return if you made this private method called
from constructor.
*/
        return $res;
    }
/*
Consider whether these should be public.  My guess is that they shouldn't be
unless you REALLY want the object to be mutable since you are reading this
information from a database and haven't shown an update method.
If you do intend to make the object mutable, then it still probably makes sense to make these private so that you can have proper setters that can trigger
methods to update the database and recalculate pressure.
If you make them private, you would obviously need to implement getters or
__get() magic method to allow caller to get to the information.
As you begin to work more with OOP, you will likely find that the use cases
for truly public properties are fairly limited.
*/
    public $pressure;

    public $sg;

    public $q;

    public $n;

    public $id;
}


Merging cells in multiple columns on multiple sheets This code merges cells in multiple columns on multiple sheets, and it's too slow.

I'm hoping for any help at all to speed this up. Unfortunately, I'm not able to get around the fact that the cells must be merged.

I broke up the for statements - it helped a bit, but it's still very, very slow.

Also, I turned off screenupdating, events, calculation, displaypagesbreaks, etc.; it didn't seem to help.

Function MergeCells()

    Dim WS_Count As Integer
    Dim i As Integer
    Dim ShName As String

    WS_Count = ActiveWorkbook.Worksheets.Count

    PIS.Activate

    For i = 1 To WS_Count
        Select Case ActiveWorkbook.Worksheets(i).Name
            Case "Med Curr", "Med Ren", "Med RevRen", "Med Prop", "Med Renewal Alts A", "Med Renewal Alts B", _
                "Med Renewal Alts C", "Med Prop Other Markets 1A", "Med Prop Other Markets 1B", "Med Prop Other Markets 1C", _
                "Med Prop Other Markets 2A", "Med Prop Other Markets 2B", "Med Prop Other Markets 2C", _
                "Med Prop Other Markets 3A", "Med Prop Other Markets 3B", "Med Prop Other Markets 3C"
                    ActiveWorkbook.Worksheets(i).Activate
                    ShName = ActiveSheet.Name
                MergeCellsx (ShName)
        End Select
    Next i

End Function

Function MergeCellsx(ShName)

    Dim RngB As Range
    Dim row As Integer

    With Sheets(ShName)
        For row = 6 To 12
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 14 To 18
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 20 To 22
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 24 To 25
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
        For row = 27 To 34
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 3))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 5), .Cells(row, 6))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

            Set RngB = .Range(.Cells(row, 8), .Cells(row, 9))
            RngB.Merge
            RngB.HorizontalAlignment = xlCenter

        Next row
    End With
End Function

Some notes -
Sub or Function
Functions should be used when something is returned and subs should be used when something happens. In this case they are actually both Subs.

Naming
So I think PIS is the actual name of the sheet, not a variable. But, it's all uppercase and not very descriptive. In this case I would think it's a constant because
Standard VBA naming conventions have camelCase for local variables, UPPER_CASE for constants and PascalCase for other variables and names.

Variables
You did a good job declaring all of your variables, but it's always a good idea to turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know.
Names - names are cheap and characters are free. You can use this to your advantage by giving all of your variables descriptive names. For instance - RngB tells me nothing about what that range is supposed to be doing.
Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Select Case
Why do you have a select case given you're basically using it like an IF? It looks pretty messy, to me. You could fix that up with a constant. Personally, I'd pull it out as its own function -
Private Function IsTargetSheet(ByVal sheetName As String) As Boolean
    Const SHEET_NAMES As String = "Med Curr, Med Ren, Med RevRen, Med Prop, Med Renewal Alts A, Med Renewal Alts B, Med Renewal Alts C, Med Prop Other Markets 1A, Med Prop Other Markets 1B, Med Prop Other Markets 1C, Med Prop Other Markets 2A, Med Prop Other Markets 2B, Med Prop Other Markets 2C, Med Prop Other Markets A, Med Prop Other Markets 3B, Med Prop Other Markets 3C"
    If InStr(1, SHEET_NAMES, sheetName) > 0 Then
        IsTargetSheet = True
    Else: IsTargetSheet = False
End Function

And now you just need this in the main sub -
For i = 1 To sheetCount
    sheetName = ActiveWorkbook.Sheets(i).Name
    If IsTargetSheet(sheetName) Then MergeCellsx sheetName
Next i

MergeCellsx
In case you didn't know, a Sub can take an argument the same way as a function -
Sub MergeCells(ByVal sheetName as String)

I see you are targeting columns 2 and 3, 5 and 6, 8 and 9. When you have something like that, it might be better to put those number in a variable or constant so that if they change, you can just change the initial value of the variable. -
Const FIRST_NAME_COLUMN As Long = 2
Const SECOND_NAME_COLUMN As Long = 3

Now every time you type in the columns, you can use the constant which will tell you what the column is supposed to contain.
Also, in this instance, you would probably be better with a long if instead of 15 conditional loops. Maybe even the select case would belong here. When you see repeated code like that, it's an indication you can refactor it.


Computation of Prefix Free Codes with many repeated weight values in reduced space Does the code below respect Python programming conventions? (and if not, which one does it disrespect?) The objective would be to publish this code as part of a scientific article, as "reproducible research".

In 1998, Moffat and Turpin described in "Efficient Construction of Minimum Redundancy Codes for Large Alphabets" (which I reviewed here) how to compute prefix free codes from sorted weights with many repeated weight values in reduced space and time (once the weights are sorted). I am planning to reproduce and describe their first experiment (compressing some TREC data set) in a fully reproducible way, as an exercize in reproducible research. Their algorithm should be implementable (they did implement it and ran it for their experiment but did not share their code) but I found that I needed to make large modifications when programming it in Python, and I wonder if I am doing it properly (I am more of a mathematician than a programmer).

def assertEqual(x,y):
   assert x==y, str(x)+" should be "+str(y)

# A function to simulate one sorted list from two:
def sourceOfFirstOfTwo(leaves,graphs):
   """Given two lists of 4-uple, returns a pointer to the one with the list with the smallest first element, sorted by first value."""
   assert(len(leaves)>0 or len(graphs)>0)
   if len(leaves)==0:
      return graphs
   elif len(graphs)==0:
      return leaves
   else:
     (firstLeafWeight,firstLeafFrequency,firstLeafLeft,firstLeafRight) = leaves[0]
     (firstGraphWeight,firstGraphFrequency,firstGraphLeft,firstGraphRight) = graphs[0]
     if firstLeafWeight<firstGraphWeight:
        return leaves
     else:
        return graphs
assertEqual(sourceOfFirstOfTwo([(1,1,0,0)],[]),[(1,1,0,0)])
assertEqual(sourceOfFirstOfTwo([],[(2,1,0,0)]),[(2,1,0,0)])
assertEqual(sourceOfFirstOfTwo([(1,1,0,0)],[(2,1,0,0)]),[(1,1,0,0)])
assertEqual(sourceOfFirstOfTwo([(2,1,0,0)],[(1,1,0,0)]),[(1,1,0,0)])

def Meld(leaves):
   assert(len(leaves)>0)
   graphs = []
   source = leaves
   first = (firstWeight,firstFrequency,firstLeft,firstRight) = source[0]
   while firstFrequency>1 or len(leaves)+len(graphs)>1:
      assert(len(graphs)<5)
      if firstFrequency>1:
         if firstFrequency %2 == 1:
            source[0] = (firstWeight, 1, firstLeft, firstRight)
         else:
            source.remove(first)
         graphs.append((2*firstWeight,firstFrequency // 2,first,first))
      else: #firstFrequency == 1 but len(leaves)+len(graphs)>1
         source.remove(first)
         secondSource = sourceOfFirstOfTwo(leaves,graphs)
         second = (secondWeight,secondFrequency,secondLeft,secondRight) = secondSource[0]
         assert(secondFrequency>0)
         if secondFrequency==1:
            secondSource.remove(second)
         else:
            secondSource[0] = (secondWeight,secondFrequency-1,secondLeft,secondRight)
         graphs.append((firstWeight+secondWeight,1,first,(secondWeight,1,secondLeft,secondRight)))
      source = sourceOfFirstOfTwo(leaves,graphs)
      first = (firstWeight,firstFrequency,firstLeft,firstRight) = source[0]
   return(sourceOfFirstOfTwo(leaves,graphs)[0])
assertEqual(Meld([(1,1,0,0)]),(1, 1, 0, 0))
assertEqual(Meld([(1,2,0,0)]),(2,1,(1, 2, 0, 0),(1, 2, 0, 0)))
assertEqual(Meld([(1,4,0,0)]),(4,1,(2,2,(1, 4, 0, 0),(1, 4, 0, 0)),(2,2,(1, 4, 0, 0),(1, 4, 0, 0))))
assertEqual(Meld([(1,2,0,0),(3,1,0,0)]),(5,1,(2,1,(1,2,0,0),(1,2,0,0)),(3,1,0,0)))

1. Comments on your code

The Python style guide (PEP8) recommends using 4 spaces for each indentation step, and lowercase_words_with_underscores for variable names and function names. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers if you do.
In answer to your question in comments, assert statements are fine. It's usually a good sign when code includes them, because it shows that the programmer has thought about what needs to be true at each step of the algorithm.
The assertEqual calls, on the other hand, are not quite in the right place. It's a good sign to see test cases. However, it's not a good idea to intermix the test suite with the code like this, because it means that every time your program gets run or your module gets loaded, the test suite gets run. That's harmless here because the test cases are so short, but if the test suite took a lot of time to run, you'd normally prefer not to run it every time.

So I would suggest reorganizing the test code so that it uses the facilities in the unittest module. Which includes its own assertEqual method, saving you the need to write your own. See below for how you might do this.
The docstring of sourceOfFirstOfTwo seems confused. Python doesn't have "pointers" and it's best not to think in terms of pointers, but in terms of values. You should have written:

"""Given two lists of 4-tuples, return the one with the smallest first element."""

but in fact this doesn't completely describe the behaviour of the function because it doesn't say what happens if one of the lists is empty.
A confused or complicated docstring is often an indication that a function would profit from being simplified or generalized, and that's definitely the case here. The first thing to note is that sequences test true if they are non-empty, and false if they are empty, so the initial tests can be rewritten:

assert(leaves or graphs)
if not leaves:
    return graphs
elif not graphs:
    return leaves

Next, Python already compares tuples element-wise:

>>> sorted([(2,3), (1,4), (2,1)])
[(1, 4), (2, 1), (2, 3)]

so there is no need to split up your 4-tuples into their components. Instead you can write:

if leaves[0] < graphs[0]:
    return leaves
else:
    return graphs

which can be simplified to:

return min(leaves, graphs)

since lists compare element-wise too. But now that we've made these simplifications, there's nothing in this function that needs to know about leaves and graphs. Really, it's a function that takes two sequences, discards empty ones, and returns the smaller among the remaining ones. But you can see that there's nothing special about the number two here. So I would generalize this function in order to further simplify it, like this (just one line!):

def min_non_empty(*sequences):
    """Return the smallest of the non-empty sequences.
    Raise ValueError if all sequences are empty.

        >>> min_non_empty([1,2],[2,3],[])
        [1, 2]
        >>> min_non_empty([1,2],[1],[])
        [1]
        >>> min_non_empty([], [])
        Traceback (most recent call last):
        ...
        ValueError: min() arg is an empty sequence

    """
    return min(s for s in sequences if s)

Notice how I've used the docstring to provide examples of how the function can be called. Python's doctest module is capable of running these mini-tests and checking their output. (This feature doesn't substitute for a proper test suite, but it's a useful way to check examples in documentation.)

Note also that there's no need for an assertion any more because min raises ValueError if you don't give it any arguments.

But having done all that, I don't think we actually need this function at all. See below.
A data structure with more than a couple of elements becomes unwieldy to manipulate if you represent it as a tuple. You have to refer to its elements by index (like x[1]) in which case it is not clear what that element means, or else you have to break it down into its components.

It would be better to refer to the elements of your data structure by name. You could do this by creating a class, but the simplest thing to do here is to use a named tuple:

Graph = namedtuple('Graph', 'weight frequency left right'.split())

Instead of using 0 as a placeholder meaning "no left/right child", it's conventional in Python to use None. That way there's no risk of confusing it for a weight or a frequency.
Your Meld function lacks a docstring. What does it do and how to call it?
Your Meld algorithm isn't the same as the one in your blog. (The original paper is hidden behind a paywall and IEEE want to charge me $31 just to read it, so I am basing this on your blog instead.) The differences are as follows: (i) you separate the graphs into two lists, leaves and graphs, whereas Moffat and Turpin just maintain a single list A; (ii) you set first to be the smaller of the initial elements of leaves and graphs, whereas Moffat and Turpin set t to be the first element of A; (iii) similarly for second and u.

This causes some of the prefix trees to come out in a different order. For example, you have

>>> Meld([(1,2,0,0),(3,1,0,0)])
(5, 1, (2, 1, (1, 2, 0, 0), (1, 2, 0, 0)), (3, 1, 0, 0))

but I believe that Moffat and Turpin's algorithm would go through these steps:

A = [(1, 2), (3, 1)]
A = [(3, 1), (2, 1, (1, 2), (1, 2))]
A = [(5, 1, (3, 1), (2, 1, (1, 2), (1, 2)))]

I don't know if this difference is significant, but I thought I ought to mention it.

Update: you noted in comments that the reason for this difference is that the description of Moffat and Turpin's algorithm in your blog was incomplete in that the list A needs to be maintained in sorted order (or rather, it needs to be possible to efficiently fetch the smallest element from the list).

Maintaining a priority queue can be done efficiently in Python using the heapq module. I've revised my code below to show how to do this.
In the course of the algorithm you need to manipulate the list graphs by adding items at the right and removing items from the left. The latter operation is not efficient for ordinary Python lists: if you look at the TimeComplexity page on the Python Wiki you'll see that deleting an item from a list is O(n).

In order to modify a sequence at both ends efficiently, you need to use some other data structure. In many cases you could use the double-ended queue class collections.deque, but here since you need to be able to efficiently fetch the smallest item in the sequence, the heapq module is the one to use.
The meld function is not very useful by itself. As you comment in your blog post, any actual user will need a function that converts the list of weights into the (weight, frequency) pairs (collections.Counter would be a convenient and efficient tool to do this in Python), and a function that processes the resulting prefix tree into the codes. You'd probably want to add these functions to your code.

2. Rewrite

Putting all this together, here's how I'd write this code:

from collections import namedtuple
from heapq import heapify, heappush, heappop
from unittest import TestCase

Graph = namedtuple('Graph', 'weight frequency left right'.split())

def meld(graphs):
    """Given a non-empty list 'graphs' of Graph objects, return a
    minimum-redundancy prefix tree constructed using the algorithm of
    Moffat and Turpin (1998).

    """
    heapify(graphs)
    while True:
        t = graphs[0]
        if t.frequency > 1:
            if t.frequency % 2 == 0:
                heappop(graphs)
            else:
                graphs[0] = Graph(t.weight, 1, t.left, t.right)
            heappush(graphs, Graph(2 * t.weight, t.frequency // 2, t, t))
        elif len(graphs) > 1:
            assert(t.frequency == 1)
            heappop(graphs)
            u = graphs[0]
            if u.frequency == 1:
                heappop(graphs)
            else:
                graphs[0] = Graph(u.weight, u.frequency - 1, u.left, u.right)
            heappush(graphs, Graph(t.weight + u.weight, 1, t, u))
        else:
            assert(len(graphs) == 1 and t.frequency == 1)
            return t

class MeldTest(TestCase):
    def test(self):
        t = Graph(1, 1, None, None)
        self.assertEqual(meld([t]), t)

        u = Graph(1, 2, None, None)
        self.assertEqual(meld([u]), Graph(2, 1, u, u))

        v = Graph(1, 4, None, None)
        w = Graph(2, 2, v, v)
        self.assertEqual(meld([v]), Graph(4, 1, w, w))

        x = Graph(3, 1, None, None)
        self.assertEqual(meld([u, x]), Graph(5, 1, Graph(2, 1, u, u), x))

Notes:

There turned out to be no need for the sourceOfFirstOfTwo function.
The unit tests have been moved to a unittest.TestCase class. You can run all the unit tests from the command line like this:

$ python -munittest mymodule.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


Use filename to determine file type This is legacy, so I'm not really looking for improvements on architectural approach.

Here's what the method does:

Extracts filename from a string containing full file path (passed in as parameter)
Checks to see if the filename extracted is not null or empty or just white spaces
If check in step 2 passes, then it uses naming conventions in the filename, to determine the logical "Type" for the file as follows:

If filename contains __Import__, then setType to Source Data
If filename contains __Export__, then setType to Destination Data
If filename contains __Transform__, then setType to Transformational Data
If none of the conditions from 3.1 through 3.3 are met, then default the "Type" to General.

Is there a way to make the if...else if... else if... block more concise, and elegant without loss of functionality?

private static string GetFileDataType(string fullFileNameWithPath)
{
    // extract filename only
    var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
    var fileDataType = string.Empty;

    // if filename is not empty
    if (!string.IsNullOrWhiteSpace(fileName))
    {
        // if... else... to determine type of file contents based on file name convention
        // legacy code, so not looking for architectural improvements etc... :)
        if (fileName.Contains("__Import__"))
        {
            fileDataType = "Source Data";
        }
        else if (fileName.Contains("__Export__"))
        {
            fileDataType = "Destination Data";
        }
        else if (fileName.Contains("__Transform__"))
        {
            fileDataType = "Transformational Data";
        }
        else
        {
            fileDataType = "General";
        }
    }

    return fileDataType;
}

I find the cleanest way is to replace the ugly if/else if/else with a dictionary:

private static IDictionary<string, string> FileDataTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["Import"] = "Source Data",
    // ..
}

The also not so pretty Contains can be replaced with a nice regex that will grow or shirnk automatically if you add/remove mappings:

private static string GetFileDataType(string fullFileNameWithPath)
{
    var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
    var fileContentsMatch = Regex.Match(fileName, $"__(?<Type>{string.Join("|", FileDataTypes.Keys)})__", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
    return
        fileContentsMatch.Success && FileDataTypes.TryGetValue(fileContentsMatch.Groups["Type"].Value, out var fileDataType)
            ? fileDataType
            : FileDataTypes[string.Empty];
}

Notice that both the dictionary and the regex are case insensitive. You should always make paths case insensitive in Windows. You are lucky that this worked for so long.

(Dislaimer: It's just an example so I was to lazy to implement all the empty/null checks)


Method to close a lot of closeable objects I wrote a method that closes 3 closeable types:

java.sql.Connection
java.sql.PreparedStatement
java.sql.ResultSet

   public static void closeAll(final Connection connection,
                            final PreparedStatement statement,
                            final ResultSet rs)
         throws SQLException
   {
      try
      {
         if (rs != null)
         {
            rs.close();
         }
      }
      finally
      {
         try
         {
            if (statement != null)
            {
               statement.close();
            }
         }
         finally
         {
            if (connection != null)
            {
               connection.close();
            }
         }
      }
   }

Is there a way to simplify it in Java 6?

In Java 7 I can use an AutoCloseable interface:

   public static void closeAll(final AutoCloseable ... closeables)
   {
      if (closeables != null && closeables.length > 0)
      {
         for (final AutoCloseable closeable: closeables)
         {
            try
            {
               closeable.close();
            }
            catch (final Exception ex)
            {
               // log it
            }
         }
      }
   }

Is this a better solution?

A ResultSet is closed automatically when the Statement that created it is closed.
A Statement is closed automatically when the Connection that created it is closed.

If you want to close everything, just close the Connection.


The Odin Project - Project Ruby: Translating from English to Pig Latin I just finished the pig latin translator for The Odin Project and I would appreciate some honest feedback for my code. The code is intended to be "test-driven learning", and therefore emulates test driven development.

Here is the prompt:

Pig Latin is a made-up children's language that's intended to be confusing. It obeys a few simple rules (below) but when it's spoken quickly it's really difficult for non-children (and non-native speakers) to understand.

Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.

Rule 2: If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.

(There are a few more rules for edge cases, and there are regional variants too, but that should be enough to understand the tests.)

Here is the test spec:

require "pig_latin"

describe "#translate" do

  it "translates a word beginning with a vowel" do
    s = translate("apple")
    expect(s).to eq("appleay")
  end

  it "translates a word beginning with a consonant" do
    s = translate("banana")
    expect(s).to eq("ananabay")
  end

  it "translates a word beginning with two consonants" do
    s = translate("cherry")
    expect(s).to eq("errychay")
  end

  it "translates two words" do
    s = translate("eat pie")
    expect(s).to eq("eatay iepay")
  end

  it "translates a word beginning with three consonants" do
    expect(translate("three")).to eq("eethray")
  end

  it "counts 'sch' as a single phoneme" do
    s = translate("school")
    expect(s).to eq("oolschay")
  end

  it "counts 'qu' as a single phoneme" do
    s = translate("quiet")
    expect(s).to eq("ietquay")
  end

  it "counts 'qu' as a consonant even when it's preceded by a consonant" do
    s = translate("square")
    expect(s).to eq("aresquay")
  end

  it "translates many words" do
    s = translate("the quick brown fox")
    expect(s).to eq("ethay ickquay ownbray oxfay")
  end

  # Test-driving bonus:
  # * write a test asserting that capitalized words are still capitalized (but with a different initial capital letter, of course)
  # * retain the punctuation from the original phrase

end

Finally, here is my code:

def translate(phrase) #translates individual words or multiple words into pig latin
  new_phrase = []
  if phrase.include? " "
    new_phrase = phrase.split(" ").map do |word|
      rearrange(word)
    end
    new_phrase = new_phrase.join(" ")
  else
    new_phrase = rearrange(phrase)
  end
  new_phrase
end

def rearrange(word) #rearranges individual words into pig latin
  vowels = ["a", "e", "i", "o", "u", "y"]
  new_word = word
  word.each_char do |char|
    if char == "u" && new_word[-1] == "q"
      new_word << "u"
      new_word.slice!(0)
      next
    elsif vowels.include? char
      new_word << "ay"
      break
    else
      new_word << char
      new_word.slice!(0)
      next
    end
  end
  new_word
end

Some notes:

expect(translate("three")).to eq("eethray"). Be consistent, use always a local variable or don't. I think this way looks pretty cool.
Isn't the code inside a module/class?
translate. This methods is unnecessarily verbose. You don't need to check if there is a space or not, since the algorithm works just the same if there is not.
Those two nexts are redundant.
rearrange: This method would look so much nicer if you don't use imperative style.
If a regular expression can express the rules, you should consider using it. It will be easier to read and much more compact.
Side note: The rules are pretty simple. If they ever get more complex, a manual processing will be undecipherable and regexps will come short. Then you'll need something more sophisticated, like a parser (i.e. grammy).

I'd write:

def translate(phrase)
  phrase.split(" ").map { |word| rearrange(word) }.join(" ")
end

def rearrange(word)
  match = word.match(/^((?:qu|[bcdfghjklmnpqrstvwxz])*)(.*)$/)
  match ? match[2] + match[1] + "ay" : word
end

If you have trouble reading that regular expressions, consider using multi-line regexps with named captures:

def rearrange(word)
  match = word.match(%r{
    ^
    (?<leading_consonants>(?:qu|[bcdfghjklmnpqrstvwxz])*)
    (?<rest>.*)
    $)
  match ? match[:rest] + match[:leading_consonants] + "ay" : word
end


Convert array of u32 to Vec in Rust In Rust, I want to take an array of u32 values, convert each to four bytes in big endian, and concatenate them to yield a Vec<u8> result. Example:
let input: [u32; 5] = [
    0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];

(... Do some data conversion work ...)

let output: Vec<u8> = vec![
    0x67, 0x45, 0x23, 0x01,
    0xEF, 0xCD, 0xAB, 0x89,
    0x98, 0xBA, 0xDC, 0xFE,
    0x10, 0x32, 0x54, 0x76,
    0xC3, 0xD2, 0xE1, 0xF0,
];

I have several pieces of working code that all give the same answer.
Algorithm A (for-loop):
let mut output = Vec::<u8>::new();
for val in &input{
    output.extend_from_slice(&val.to_be_bytes());
}

Algorithm B (for-each):
let mut output = Vec::<u8>::new();
input.iter().for_each(|val| output.extend_from_slice(&val.to_be_bytes()));

Algorithm C (fold-append):
let output = input.iter().fold(Vec::<u8>::new(),
    |mut acc, val| {acc.extend_from_slice(&val.to_be_bytes()); acc});

Algorithm D (flat-map):
let output: Vec<u8> = input.iter().flat_map(|val| val.to_be_bytes().to_vec()).collect();

Is there an even shorter, clearer way to accomplish the task? Maybe algorithm D's to_vec() could be avoided somehow?
Speed is not a concern because this code only executes a few times, and the input array length is fixed at 5.

Algorithm A seems the clearest to me.  An improvement might be to use Vec::with_capacity to avoid the allocation.  Indeed, arrays in Rust are currently somewhat cumbersome to use.
My advice would be to wrap it in a function and not worry about it later on:
pub fn to_bytes(input: &[u32]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(4 * input.len());

    for value in input {
        bytes.extend(&value.to_be_bytes());
    }

    bytes
}

#[cfg(test)]
mod tests {
    #[test]
    fn to_bytes() {
        use super::*;

        assert_eq!(to_bytes(&[]), &[]);

        let input = &[0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
        let output = &[
            0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, 0x89, 0x98, 0xBA, 0xDC, 0xFE, 0x10, 0x32,
            0x54, 0x76, 0xC3, 0xD2, 0xE1, 0xF0,
        ];

        assert_eq!(to_bytes(input), output);
    }
}

(playground)


Adding an attribute to a class after the documentation comment trivia I am trying to turn

namespace DevComponents.WpfEditors.Primitives
{
    /// <summary>
    /// Interaction logic for EditorFreeTextButton.xaml
    /// </summary>
    public partial class EditorFreeTextButton : EditorButton
    {
        public EditorFreeTextButton()
        {
            InitializeComponent();
        }
    }
}

into

namespace DevComponents.WpfEditors.Primitives
{
    /// <summary>
    /// Interaction logic for EditorFreeTextButton.xaml
    /// </summary>
    [System.Reflection.Obfuscation(Exclude = true)]
    public partial class EditorFreeTextButton : EditorButton
    {
        public EditorFreeTextButton()
        {
            InitializeComponent();
        }
    }
}

through Roslyn. I have the following code that works

private static SyntaxNode AddAnnotation(ClassDeclarationSyntax classNode, SyntaxNode rootNode)
{
    var name = SyntaxFactory.ParseName("System.Reflection.Obfuscation");
    var arguments = SyntaxFactory.ParseAttributeArgumentList("(Exclude = true)");
    var attribute = SyntaxFactory.Attribute(name, arguments);
    var leadingTrivia = classNode.GetLeadingTrivia();
    var whitespace = leadingTrivia.LastOrDefault(x => x.Kind() == SyntaxKind.WhitespaceTrivia);

    var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attribute))
        .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);
    var newClassNode = classNode.WithoutLeadingTrivia()
        .WithLeadingTrivia(whitespace)
        .AddAttributeLists(attributeList)
        .WithLeadingTrivia(leadingTrivia);

    rootNode = rootNode.ReplaceNode(classNode, newClassNode);
    return rootNode;
}

However I feel like I am coding in circles to get all the leading Trivia right.

Is there a easier way to insert an attribute to be after the SingleLineDocumentationCommentTrivia and be formatted correctly with the correct leading whitespace trivia?

Look into the WithAnnotation(Formatter.Annotation) member.  This should create a new node with the correct leading indentation.

var newClassNode = classNode.AddAttributeLists(attributeList)
                            .WithAnnotation(Formatter.Annotation)


Creating a dictionary of all prefixes of a string in Python 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?

It's hard to tell what is making the error occur without giving us the input, but it's certainly possible the input is too large for the system to store.

prefix_dict will contain len(a) entries so if your input is larger than 32-bit python allows for dictionary size on your machine, then that could be the issue.

I will note that instead of having prefix_dict[prefix] = len(prefix) you could just have prefix_dict[prefix] = j which would stop you from needing to do an extra length calculation each time (not that this would be the cause of the memory issue).

Take a look at the sample output (I modified the print statement and used an example string):

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

1 1 {'h': 1}
2 2 {'h': 1, 'he': 2}
3 3 {'hel': 3, 'h': 1, 'he': 2}
4 4 {'hel': 3, 'h': 1, 'hell': 4, 'he': 2}
5 5 {'hel': 3, 'h': 1, 'hell': 4, 'hello': 5, 'he': 2}


Python Text-To-Speech program I have some code that asks for a user input, and then uses TTS to convert that into speech and play the file. It then asks the user whether they want to repeat it and convert another input into speech, or whether they want to exit the program. Are there any improvements that I could make to the code?

import webbrowser
import os
import time
import sys
import getpass
from gtts import gTTS
from mutagen.mp3 import MP3

my_file = "C:/Users/%USERNAME%/Desktop/TTS/bob.mp3" #Sets a variable for the file path.

username = getpass.getuser() #Gets the username of the current user.

def repeat():
    while True:
        if os.path.isfile(my_file): #Checks to see whether there is a file present and, if so, removes it.
            os.remove(my_file)
        else:
            None

        tts = gTTS(text = input("Hello there " + username + """. This program is
used to output the user's input as speech.
Please input something for the program to say: """)) #Takes the user's input and uses it for the Text-To-Speech
        tts.save('bob.mp3') #Saves a .mp3 file of the user's input as speech.
        webbrowser.open(my_file) #Opens the .mp3 file

        audio = MP3(my_file) #Sets a variable so that the Mutagen module knows what file it's working with.
        audio_length = audio.info.length #Sets a variable of the length of the .mp3 file.
        time.sleep((audio_length) + 0.25) #Waits until the file has finished playing.
        os.system('TASKKILL /F /IM wmplayer.exe') #Closes Windows Media Player.
        time.sleep(0.5) #Waits until Windows Media Player has closed.

        while True:
            answer = input("Do you want to repeat? (Y/N) ")
            if answer == "y" or answer == "Y":
                return repeat() #Goes back to the beginning of the function if the user wants to try again.
            elif answer == "n" or answer == "N":
                if os.path.isfile(my_file): #Checks to see whether there is a file present and, if so, removes it.
                    os.remove(my_file)
                else:
                    None
                sys.exit() #Exits the program.
            else:
                print("Sorry, I didn't understand that. Please try again with either Y or N.")
                continue #Goes back to the beginning of the while loop.

repeat() #Calls the function.

DRY

Apply the DRY (Do not Repeat Yourself) method. For instance, the check to remove the file. Since it's being called in two places, we can make this a function. I've re-written your code in a more functional style. This is also easier to read what's occurring.

else

Your else: None statements are not doing anything.

continue

Same goes for this in the while loop. This happens anyway.

if

When you check the user's answer, just assume it's going to be varying. Instead of checking for an UPPERCASE 'y' and lowercase, just lower it. Also stripping it to make sure to remove erroneous spaces.

answer = input("Do you want to repeat? (Y/N) ").strip().lower()
if answer in ['yes', 'y']:
# instead of
answer = input("Do you want to repeat? (Y/N): ")
if answer == "y" or answer == "Y":

Exceptions

Since you're interacting with the user from the interpreter, you can catch if the user exits the program and run any cleanup code before cleanly exiting. I've wrapped the loop of the interaction in a try/except statement so that this can be caught.

if name == 'main':

Check this SO post out.

Rewritten

import webbrowser
import os
import time
import getpass
from gtts import gTTS
from mutagen.mp3 import MP3

my_file = "C:/Users/%USERNAME%/Desktop/TTS/bob.mp3" #Sets a variable for the file path.

username = getpass.getuser() #Gets the username of the current user.

def remove_file():
    """Checks if myfile exists and if so, deletes."""
    if os.path.isfile(my_file):
        os.remove(my_file)

def play_tts():
    webbrowser.open(my_file)  # Opens the .mp3 file
    audio = MP3(my_file)  # Sets a variable so that the Mutagen module knows what file it's working with.
    audio_length = audio.info.length  # Sets a variable of the length of the .mp3 file.
    time.sleep(audio_length + 0.25)  # Waits until the file has finished playing.
    os.system('TASKKILL /F /IM wmplayer.exe')  # Closes Windows Media Player.
    time.sleep(0.5)  # Waits until Windows Media Player has closed.

def ask_and_play():
    # Takes the user's input and uses it for the Text-To-Speech
    tts = gTTS(text=input(
        "Hello there " + username + ". This program isn\n"
        "used to output the user's input as speech.\n"
        "Please input something for the program to say: ")
    )
    tts.save('bob.mp3')  # Saves a .mp3 file of the user's input as speech.
    play_tts()

def check_continue():
    """Checks if the user wants to continue.
    Returns a boolean value."""
    while True:
        answer = input("Do you want to repeat? (Y/N) ").strip().lower()
        if answer in ['yes', 'y']:
            return True
        elif answer in ['no', 'n']:
            return False
        else:
            print("Sorry, I didn't understand that. Please try again with either Y or N.")

def repeat():
    """Repeatedly ask the user to type text to play,
    and check if the user wants to repeat or exit."""
    while True:
        remove_file()
        ask_and_play()
        if not check_continue():
            raise KeyboardInterrupt

if __name__ == '__main__':
    try:
        repeat() #Calls the function.
    except KeyboardInterrupt:
        # clean up
        remove_file()
        print('Goodbye!')