follow-up - caesar-cipher - java I now processed the suggestions you can find here. I've deleted some duplications and corrected some other minor mistakes.

Here's the code:

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
public class caesar {

    public static void main(String[] args) {
        String field, text;

        field = JOptionPane.showInputDialog("Please enter text:");
        field = field.replaceAll("[^a-zA-Z]+", "");
        field = field.toUpperCase();

        int shift;

        String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:");
        shift = Integer.parseInt(shift_String);

        String d = JOptionPane.showInputDialog("Encrypt (1) or decrypt (2):");
        int decision = Integer.parseInt(d);

        String out = "";

        if(decision == 1) {
            boolean test = true;
            out = operation(field, shift, test);

        }
        else if(decision == 2) {
            boolean test = false;
            out = operation(field, shift, test);

        }
        else if(decision != 1 && decision != 2) {
            out = "Invalid choice!";
        }
        JTextArea msg = new JTextArea(out);
        msg.setLineWrap(true);
        msg.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(msg);
        scrollPane.setPreferredSize(new Dimension(300,300));
        JOptionPane.showMessageDialog(null, scrollPane);
    }

    //Encryption
    public static String operation(String text, int n, boolean test) {
        int x = 0;
        int y = 0;
        int z = 1;

        if(!test) {
            z = -1;
        }

        StringBuilder out = new StringBuilder(); //Empty string for result.
        while (x < text.length()) {
            final char currentChar = text.charAt(x);
            if (currentChar > 64 && currentChar < 91) {
                if (currentChar + n > 90) {
                    y = 26;
                }
                out.append((char)(currentChar + (n*z) - (y*z)));
            }
            else {
                out.append(currentChar);
            }
            x++;
            y = 0;
        }
        return out.toString();
    }

}

Are there anymore suggestions to improve the code?

Naming

Give your class a more meaningful name, that begins with a capital letter -as all classes should in Java-, e.g. CaesarCipher.

The operation() method's name doesn't tell us anything about what it actually does. If it weren't for the //Encryption comment, there would be no indication that this class does something even related to encryption/decryption.

The variable shift_String uses snake_case while all the other ones use camelCase; pick one and stick to it (and since this is Java, I'd recommend camelCase as it is the accepted standard).

More generally, try using names that actually describe what the variable/method/class represents or does (what is d? what about test?). You could for example declare one String, say userInput, and reuse it whenever you want to store the user's input, that way you don't need to declare two variables where one has the same name as the other appended with String everytime.

Also, shortened names like out or d don't really have any benefit over slightly longer, clearer ones, other than making the very first time you type the name a tiny bit shorter. Giving them more meaningful names will make the code easier to read later, and you shouldn't be worried about typing a few more characters each time; let your IDE do its job!

final keyword

This recommendation is more based on my own opinions, but I think it's justified here since you've made use of it yourself.

Mark all method arguments as final; this will prevent you from accidentally reassigning them (which you really shouldn't do anyways).

Make all your instance & local variables final when appropriate; this simply indicates that once they are assigned a value, that value should not and will not change in the future. It may seem like you're simply adding more unnecessary fluff to an already very verbose language, but I personally think it helps writing clearer code as well as making it easier to debug.

If you want to read more about Java's use of the final keyword, I recommend this answer : https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java.

Code Optimization & Reusability

The text variable is declared but never used.

Redundant checks in main() :

if(decision == 1) {
    boolean test = true;
    out = operation(field, shift, test);
}
else if(decision == 2) {
    boolean test = false;
    out = operation(field, shift, test);
}
else if(decision != 1 && decision != 2) {
    out = "Invalid choice!";
}

Your last else if could be replaced by a simple else, since the only way you'll get there is if decision is neither equal to 1 nor to 2. In this same snippet, you could also get rid of the test variable altogether, or maybe declare it before those conditionals and place the out = operation(field, shift, test); at the end. Additionnaly, what does test mean? What is it testing for?

You may want to implement another cipher later; if that's the case, then creating a simple Cipher interface might be worthwhile. You should also make caesar a separate class from main() and decouple it from all the user interface stuff, that way you can use it whenever you want, wherever you want. The interface might look something like this :

public interface Cipher {
    public String encrypt(final String text);

    public String decrypt(final String cipherText);
}

Use an enum to represent the two choices given to the user. This might be overkill for this case as you'd only have two possible values (ENCRYPT and DECRYPT, for example), but it would certainly make the code even more readable.

There's more that could be said, about user input validation, or using magic numbers in operation(), and more, but I'll leave it to other users.

Exception Handling & User Input

What happens if the user decides to type "oiuahffduht$$$" when you ask them for the shift value? Your program breaks and the user has to manually start it again! Always assume the worst from the user. Ideally, you'd want to handle such cases in your code via exception handling. If you're not familiar with the concept, you can take a look at this link which covers all the basics of EH in Java : https://stackify.com/specify-handle-exceptions-java/.

So what can we do here? If you look at the Java documentation for Integer.parseInt() -or check its signature from your favorite IDE, you'll see that it can throw a NumberFormatException, so let's catch it. Keeping the same logic and syntax as your original code, it might look something like this :

String shift_String = JOptionPane.showInputDialog("Please enter shift to the right:");

try {
    shift = Integer.parseInt(shift_String);
}
catch (NumberFormatException e) {
    // Handle the exception
}

There's lots of different ways you can handle the exception; you could simply show the user the contents of the exception or the stack trace, you could end the program... Personally, I think the best way to handle this case would be to show a new dialog that says something along the lines of "Error, you must enter a number", then show that previous input box and asks for the same thing again. That way the user won't have to close/reopen the program and they'll know what went wrong.

Magic Numbers

In your operation() method, you use a bunch of "magic numbers" (64, 90, 26...). So what's a magic number? It's basically a hardcoded value (not necessarily a 'number') that is present in your code without any explanation of why it's there or what it means.

Imagine if someone who's not familiar with ASCII were to read your code (though maybe they shouldn't be writing code in the first place). They might think you're using some crazy voodo magic to turn numbers into letters, who knows? So give these numbers names!

Or, maybe try a different approach entirely, where you would store all the possible characters in a String, then make use of the wonderful modulo operator like so :

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encrypt(final String text, final int shift) {
        final String lowerCaseText = text.toLowerCase();
        String cipherText = "";

        for (int i = 0; i < lowerCaseText.length(); i++) {
            final int charPosition = ALPHABET.indexOf(lowerCaseText.charAt(i));
            final int newCharPosition = (shift + charPosition) % 26;
            final char newChar = ALPHABET.charAt(newCharPosition);

            cipherText += newChar;
        }

        return cipherText;
    }

Now you don't even have to deal with those annoying numbers anymore!

By the way, I haven't tested this, and I don't claim it to be more efficient or readable.


Box data structure in Go Would the following be considered idiomatic Go code?

My main concerns are:

The use of maps for this purpose.  I basically want the data structure to be completely dynamic in size and have easy access to elements by id.  This is because I will want to retrieve specific items on demand lots of times, so I don't want to loop each time.
The check for the map element
My use of pointers
General flow and structure

package main

    import (
        "fmt"
    )

    type BoxItem struct {
        Id  int
        Qty int
    }

    func NewBox() *Box {
        return &Box{make(map[int]*BoxItem), 0}
    }

    type Box struct {
        BoxItems map[int]*BoxItem
    }

    func (this *Box) AddBoxItem(id int, qty int) *Box {

        i, ok := this.BoxItems[id]

        if ok {
            i.Qty += qty
        } else {
            boxItem := &BoxItem{id, qty}
            this.BoxItems[id] = boxItem
        }

        return this
    }

    func main() {

        box := NewBox()
        box.AddBoxItem(1, 1)

        fmt.Printf("There are %d items in the box", len(box.BoxItems))
    }

Instead of

i, ok := this.BoxItems[id]
if ok {
    i.Qty += qty
}

a more idiomatic usage is

if i, ok := this.BoxItems[id]; ok {
    i.Qty += qty
}

Calling the receiver this doesn't seem like a good practice to me. Calling it box would be clearer.

You seem to want to make your method chainable. I'm not sure this is a frequent practice in Go but it's probably more a matter of style and experience than a question of idiomatic code or not.

The rest could be condensed a little but that's not a matter of idiom. I have nothing to say regarding your use of pointers.


App for allowing the user to type in chemistry formulas using a custom keyboard Essentially, I am making an app that allows the user to type in chemistry formulas using a custom keyboard.

The keyboard will have several keys, for example, "Na", "H", and "O". Pressing them in different combinations will result in different formulas. For example, Na + O will result in NaO. Pressing any key consecutively will increase the subscript of that given element. For example, H + H + O will result in H2O.

The code below determines how the textfield combines the different elements to make the formulas. I'm wondering if it's too confusing. Also, I'm not sure if I'm correctly managing the memory.

consecutiveElementCount = 0;
formula = [[NSMutableString  stringWithString:@""] retain]; // released in dealloc

^^^ declared in the init method.

- (void)addElement:(NSString *)currentElement {

    if (![currentElement isEqualToString:lastElementPressed])  {

        // when new element is pressed

        [formula appendString:currentElement];
        lastElementPressed = currentElement;
        consecutiveElementCount = 1;

    }

    else if ([currentElement isEqualToString:lastElementPressed]) {

        // when element is pressed consecutively

        if (consecutiveElementCount == 1) {

            // since there is no '1' subscript, nothing needs to be deleted

            [formula appendString:@"₂"];
            subscriptLength = 1;

        }

        if (consecutiveElementCount > 1) {

            // deletes last subscript and replaces it with new subscript

            NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil] autorelease];

            NSRange range = NSMakeRange (([formula length] - subscriptLength), subscriptLength);

            [formula deleteCharactersInRange:range];

            NSString *tempSubscript = [[subscriptList objectAtIndex:consecutiveElementCount - 1] autorelease];
            [formula appendString:tempSubscript];

            subscriptLength = [tempSubscript length];

        }

     // don't increase subscript after 12
        if (consecutiveElementCount < 11)
            consecutiveElementCount ++;

    }

    NSLog(@"%@", formula);
}

You can use some if else statement, where u use several independent ifs. This will lead to a slightly faster code, because in the case, where the previous if is try, no further testing is needed. Personally I also find it more readable for short and medium sized code block.

if (![currentElement isEqualToString:lastElementPressed])  {
    //…
} else {
    if (consecutiveElementCount == 1) {
         //…
    } else if (consecutiveElementCount > 1) {
        //…
    }
    if (consecutiveElementCount < 11) {
        //…
    }
}

But beside that, I don't think, that you are using to many if-statements. But you should use proper indention, as it will build visual block of your code and helps you, to understand the structure.

There is a rule of thumb: If a method/function does not fit on your screen, it becomes to long, and you should use well-named helper functions to break it into several logical blocks.


Optimizing numpy gmean calculation I'm trying to come up with an alternative to the gmean implementation in scipy, because it is awkwardly slow. To that end I've been looking into alternate calculation methods and implementing them in numpy. My only issue is that a method that in the two methods I'm implementing, the one that I feel ought to be faster is in fact much slower. I feel like this is an issue with my implementation and would love advice on improving it.

def fast_gmean(vector, chunk_size=1000):
    base, exponent = np.frexp(vector)
    exponent_sum = float(np.sum(exponent))
    while len(base) > 1:
        base = np.array_split(base, math.ceil(float(base.size)/chunk_size))
        intermediates = np.array([np.prod(split) for split in base])
        base, current_exponent = np.frexp(intermediates)
        exponent_sum += np.sum(current_exponent)
    return (base[0]**(1.0/vector.size)) * (2**(exponent_sum/vector.size))

def actually_fast_gmean(vector):
    return np.exp(np.mean(np.log(vector)))

While these both outperform scipy's gmean implementation, the second method is about 33% faster than the first.

Note: I'm testing this on arrays of approximately 5000 entries.

1. Checking your claim

You claim that "these both outperform scipy's gmean implementation", but I can't substantiate this. For example:

>>> import numpy
>>> data = numpy.random.exponential(size=5000)
>>> from timeit import timeit
>>> timeit(lambda:fast_gmean(data), number=10000)
5.540040018968284
>>> timeit(lambda:actually_fast_gmean(data), number=10000)
1.4999530320055783
>>> from scipy.stats import gmean
>>> timeit(lambda:gmean(data), number=10000)
1.4939542019274086

So as far as I can tell, there's no significant difference in runtime between your actually_fast_gmean and scipy.stats.gmean, and your fast_gmean is more than 3 times slower.

So I think you need to give us more information. What's the basis for your claim about performance? What kind of test data are you using?

(Update: in comments it turned out that you were using scipy.stats.mstats.gmean, which is a version of gmean specialized for masked arrays.)

2. Read the source!

If you look at the source code for scipy.stats.gmean, you'll see that it's almost exactly the same as your actually_fast_gmean, except that it's more general (it takes dtype and axis arguments):

def gmean(a, axis=0, dtype=None):
    if not isinstance(a, np.ndarray):  # if not an ndarray object attempt to convert it
        log_a = np.log(np.array(a, dtype=dtype))
    elif dtype:  # Must change the default dtype allowing array type
        if isinstance(a,np.ma.MaskedArray):
            log_a = np.log(np.ma.asarray(a, dtype=dtype))
        else:
            log_a = np.log(np.asarray(a, dtype=dtype))
    else:
        log_a = np.log(a)
    return np.exp(log_a.mean(axis=axis))

So it's not surprising that these two functions have almost identical runtimes.

3. Why fast_gmean is slow

Your strategy is to avoid calls to log by performing arithmetic on the exponent and mantissa parts of the floating-point numbers.

Very roughly speaking, for each element of the input, you avoid one call to each of log and mean, and gain one call to each of frexp, sum, array_split and prod.

>>> from numpy import log, mean, frexp, sum, array_split, prod
>>> for f in log, mean, frexp, sum, prod:
...     print(f.__name__, timeit(lambda:f(data), number=10000))
log 1.0724926821421832
mean 0.3662677980028093
frexp 0.34479621006175876
sum 0.21649421006441116
prod 0.280590218026191
>>> timeit(lambda:array_split(data, 5), number=10000)
2.1635821380186826

So it's the call to numpy.array_split that's costly. You could avoid this call and split the array yourself, like this:

def fast_gmean2(vector, chunk_size=1000):
    base, exponent = np.frexp(vector)
    exponent_sum = np.sum(exponent)
    while base.size > 1:
        intermediates = []
        for i in range(0, base.size, chunk_size):
            intermediates.append(np.prod(base[i:i + chunk_size]))
        base, current_exponent = np.frexp(np.array(intermediates))
        exponent_sum += np.sum(current_exponent)
    return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)

and this is roughly twice as fast as your version:

>>> timeit(lambda:fast_gmean2(data), number=10000)
2.585187505930662

but still about twice as slow as scipy.stats.gmean, and that's because of the Python interpreter overhead. Numpy has a speed advantage whenever you can vectorize your operations so that they run on fixed-size datatypes in the Numpy core (which is implemented in C for speed). If you can't vectorize your operations, but have to loop over them in Python, then you pay a penalty.

So let's vectorize that:

def fast_gmean3(vector, chunk_size=1000):
    base, exponent = np.frexp(vector)
    exponent_sum = np.sum(exponent)
    while len(base) > chunk_size:
        base = np.r_[base, np.ones(-len(base) % chunk_size)]
        intermediates = base.reshape(chunk_size, -1).prod(axis=0)
        base, current_exponent = np.frexp(intermediates)
        exponent_sum += np.sum(current_exponent)
    if len(base) > 1:
        base, current_exponent = np.frexp([base.prod()])
        exponent_sum += np.sum(current_exponent)
    return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)

For arrays of the size we've been testing (about 5000), this is a little slower than fast_gmean2:

>>> timeit(lambda:fast_gmean3(data), number=10000)
2.8020136120030656

But for larger arrays it beats gmean:

>>> bigdata = np.random.exponential(size=1234567)
>>> timeit(lambda:gmean(bigdata), number=100)
3.192410137009574
>>> timeit(lambda:fast_gmean3(bigdata), number=100)
2.3945167789934203

So the fastest implementation depends on the length of the array.

4. Other comments on fast_gmean

There's no docstring. What does this function do and how do I call it? What value should I pass in for the chunk_size argument?
It's critical that chunk_size is not too large, otherwise the call to prod could underflow and the result will be incorrect. So there needs to be a check that the value is safe, and a comment explaining how you computed the safe range of values.


Deal three Poker hands of five cards each in Python I'm a beginner at coding who recently started learning Python, and I think I have grasped the basics. Now I'm working on my first "proper" project in Python.

The problem is to have the program:

Generate a standard Poker deck of 52 cards (no Jokers)
Shuffle said deck
Deal five (5) cards to three (3) hands/"players" (can be altered when calling the 'deal' function)
Analyse the three hands individually for possible Poker hands in each

the analysis must be able to detect at least:

Two pairs
Straight
Flush
Straight Flush
(no harm in detecting any of the other Poker hands as well)

Print all three hands and their respective results/analyses

I've managed 1-3, but stalled at 4 and plan to continue with 4-5 later, but first I want to hear your thoughts on my code so far!

I managed to find several somewhat similar programs all over the Internet, of which I extracted many parts to my own program. I had to make a few adjustments here and there, as none of the existing programs had the exact same approach as mine, but this was a good thing in terms of my learning curve. In case you find a part of your own code in mine, consider it admiration, for I'm truly grateful for all the help and examples I've received from more seasoned coders' work.

My code:

import random

class Card(object):
    def __init__(self, suit, val):
        self.suit = suit
        self.value = val

    # Implementing build in methods so that you can print a card object
    def __unicode__(self):
        return self.show()
    def __str__(self):
        return self.show()
    def __repr__(self):
        return self.show()

    def show(self):
        if self.value == 1:
            val = "Ace"
        elif self.value == 11:
            val = "Jack"
        elif self.value == 12:
            val = "Queen"
        elif self.value == 13:
            val = "King"
        else:
            val = self.value

        return "{} of {}".format(val, self.suit)

class Deck(object):
    def __init__(self):
        self.cards = []
        self.build()

    # Display all cards in the deck
    def show(self):
        for card in self.cards:
            print(card.show())

    # Generate 52 cards
    def build(self):
        self.cards = []
        for suit in ['Hearts', 'Clubs', 'Diamonds', 'Spades']:
            for val in range(1,14):
                self.cards.append(Card(suit, val))

    # Shuffle the deck
    def shuffle(self, num=1):
        random.shuffle(self.cards)

    # Deal n cards to n players
    def deal(self, n_players, n_cards):
        self.hands = [self.cards[i:n_players*n_cards:n_players] for i in range(0, n_players)]

# Test making a Card
# card = Card('Spades', 6)
# print card

# Making a Deck
myDeck = Deck()
myDeck.shuffle()
#myDeck.show() # Print the shuffled deck if needed, to show it is actually shuffled
               # and that the cards are dealt from top of the deck and not randomly

myDeck.deal(3,5) #(No. of hands, no. of cards dealt per hand)
print(*myDeck.hands, sep = '\n')

Please do let me know what you think of the code in general, and if you think there is a more efficient way to have the cards dealt so that they are also easier to analyse later. All help is much appreciated!

You've got a reasonable implementation for steps 1-3.  I see no glaring issues with the code.  Perhaps, we can over-engineer some parts of it.

General

Add docstrings.

class Card

It is mutable.  I can be dealt the '6 of Spades' and by tweaking it card.rank = "Ace" all of a sudden have a better card for my hand than I was dealt.  Trick decks aside, cards should be immutable, so we could change this into a tuple to keep in from changing.  Since we want named fields, we need a namedtuple, and since we want to customize the str(card), we'll derive our own class from the namedtuple.

from collections import namedtuple

class Card(namedtuple("Card", ['rank', 'suit'])):
    __slots__ = ()   # Allows no additional fields, keeps memory footprint small

    def __str__(self):
        return f"{self.rank} of {self.suit}"

# Use like:
ace_of_spades = Card('Ace', 'Spades')

Note: I'm using the Python3.6 f-strings.  If you're not using 3.6+, you'll have to adapt it to .format() ... or upgrade ;-)

Rank & Suit

We only want "Clubs", "Diamonds", "Hearts", and "Spades" as suits.
And we only want "Ace", "2", "3" ... "10", "Jack", "Queen", and "King" as ranks.

Perhaps we might want an Enum for suit, and (maybe) another Enum for rank.

from enum import Enum

Suit = Enum('Suit', 'Clubs Diamonds Hearts Spades')
Rank = Enum('Rank', 'Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King')

card = Card(Rank.Ace, Suit.Spades)
print(card)

Ew.  This prints "Rank.Ace of Suit.Spades".  We can fix this by changing the __str__(self) function of Card to include the .name of the rank and suit fields:

    def __str__(self):
        return f"{self.rank.name} of {self.suit.name}"

Much better.

But do we want to do this?  It restricts the possible ranks and suits of our cards.
If you wanted a Tarot deck, we might want the Cups, Wands, Pentacles and Swords for our suits.  There are other specialty decks too, so maybe this is too restrictive.  In which case, feel free to ignore this whole section.  But if so, then add something like:

SUITS = ['Clubs', 'Hearts', 'Diamonds', 'Spades']

so you can iterate over a named constant, instead of needing to spell out the valid values each time you need them.

class Deck

What is a deck of cards?  Is it always 52 standard playing cards?  You can shuffle a deck and deal from a deck.  But you can also shuffle two decks together and get 104 cards to deal from (perhaps you're playing Kanasta!  No, wait, you'd need the Jokers too).  What would you call two decks of cards mixed together?  Is it still a deck?  Maybe you want to pass some creation function into the Deck initializer, to control how it is created, instead of always building a deck of standard playing cards.  Again, just a thought.

With the Enums created above, Deck.build() can be simplified:

def build(self):
    self.cards = [ Card(rank, suit) for rank in Rank for suit in Suit ]

Shuffling the cards: def shuffle(self, num=1).  What is the num for?  It isn't used.

Dealing the cards.  Ok.  It deal can deal 3 player a hand of 5 cards each.  Good.  Now, player #1 wants to draw a card ... and they get ... uhm ... one of their first cards again???  The deal() method needs to keep track of which cards you've already distributed, and which remain in the deck.

Is a hand of cards just a list of 5 cards?  If so, why isn't a Deck just a list of 52 cards?  Perhaps you need to deal the cards into a Hand class.  The Hand class would be a good container for evaluating the hand, discarding cards and adding additional drawn cards to, etc.


C code to calculate the binary period of an integer A non-empty zero-indexed string S consisting of Q characters is given.
  The period of this string is the smallest positive integer P such
  that:

  \$P ≤ Q/2\$ and \$S[K] = S[K+P]\$ for \$0 ≤ K < Q−P.\$

  So for example, for the integers 955,1651 and 102, convert the numbers
  to binary and the function should return 4,5,-1 respectively.

  The function returns -1 if there is no binary period for the given
  integer.

  The int n can be any value between 1 to 99999999

Here is the original code given in the challenge. The Challenge states that by modifying at most 2 lines, in the function solution, the existing bug should be fixed.

Here is my Solution, Can someone please review this?

int solution(int n)
{
    int d[30];
    int l = 0;
    int p;
    //convert the integer to binary
    while(n > 0)
    {
        d[l]= n %2 ;
        n = n /2;
        l++;
    }
    //compute the length of the resulting binary number
    //and that is stored in the variable l

    for(p = l/2; p >0; p--){
        int ok = 1;
        int i;
        for(i = 0; i < (l - l/2); i++){
            if(d[i] != d[i + p]){
                ok = 0;
                break;
            }
        }
        if(ok){
            return p;
        }
    }
    return -1;
}

 int main(int argc, char** argv) {
         printf("%d\n",solution(102));
         printf("%d\n",solution(955));
         printf("%d\n",solution(1651));
         return 0;
    }

I see some things that may help you improve your program.

Use the appropriate #includes

In order to compile and link, this code requires at least #include <stdio.h>.  For the program to be complete, all appropriate #includes should be listed, too.

Check your assumptions

For this code to work, the int on your platform must be at least 32 bits.  For that reason, this assumption should be checked at compile time:

static_assert(sizeof(int) >= 4), "int must be at least 32 bits");

Format your code consistently

It doesn't matter as much what style you use as it matters that you have a consistent style. In particular, there seems to be inconsistent indenting and inconsistent placement of braces.  Using a consistent style helps readers of the code understand it.

Use better variable names

Generally, single letter variable names other than i and j for loop variables, are best avoided in favor of longer, more descriptive names.  The variable p is not too terrible, but the variable l is definitely a poor choice, not least because it's easily mistaken for the digit 1 or the letter i.  I changed it to len in the rewrite I did.

Fix the bug

Right now, if we have the program calculate solution(8), it returns 1 instead of -1.  That is not correct.  There are other values within the range that also return incorrect values.

Write a test program

Right now the main routine just tries three values.  It would be better to try other values, maybe even every value in the range, and test it for accuracy.  You can do that by creating a function bool verify(int n, int p) that returns true if the condition stated at the beginning of the problem is true.


Links controller in MVC N-layer architecture I have a common issue that I face in my applications (because I don't know any better) and I want to improve.

This is my usual structure:

Project.UI (MVC Project)
Project.BLL (Class Lib)
Project.DAL (Class Lib)

LinksConfigurationController

public class LinksConfigurationController : BaseController
{
    public async Task<ActionResult> Index()
    {
        var config = new LinksConfiguration();
        var result = await config.GetLinksAsync();
        if (result == null) return View(new List<LinksViewModel>());

        var model = result.Select(item => new LinksViewModel
        {
            Id = item.Id,
            LinkEndpoint = new Uri(item.LinkEndpoint),
            LinkName = item.LinkName
        }).ToList();

        return View(model);
    }
}

LinksConfiguration (In Project.BLL)

public class LinksConfiguration
{
    public LinksConfiguration()
    {
        Repo = new LinksConfigurationRepository();
    }

    public LinksConfigurationRepository Repo { get; set; }
    public async Task<IEnumerable<LinksConfigurationDto>> GetLinksAsync()
    {
        var reuslt = await Repo.GetAllAsync();
        var dto = reuslt.Select(r => new LinksConfigurationDto
        {
            LinkEndpoint = r.LinkEndpoint,
            Id = r.Id,
            LinkName = r.LinkName
        }).ToList();

        return dto;
    }
}

LinksConfigurationRepository (In Project.DAL)

public class LinksConfigurationRepository : IRepository<LinksConfiguration>
{
    public LinksConfigurationRepository()
    {
        Db = new NZBDashContext();
    }
    private NZBDashContext Db { get; set; }
    public async Task<IEnumerable<LinksConfiguration>> GetAllAsync()
    {
        return await Db.LinksConfiguration.ToListAsync();
    }
// Rest of the implemented members from the interface
}

IRepo

public interface IRepository<T> where T : Entity
{
    T Find(int id);
    Task<T> FindAsync(int id);
    IEnumerable<T> GetAll();
    Task<IEnumerable<T>> GetAllAsync();
    T Insert(T entity);
    IEnumerable<T> Insert(IEnumerable<T> entity);
    Task<IEnumerable<T>> InsertAsync(IEnumerable<T> entity);
    Task<T> InsertAsync(T entity);
    int Remove(T entity);
    Task<int> RemoveAsync(T entity);
    Task<int> ModifyAsync(T entity);
    int Modify(T entity);
}

As you can see I have fallen into the trap of constant mapping (I could use Automapper or something similar) and it's a pain and time consuming to actually get anything done. I read through this article and while it looks like a good approach, I do not like the idea of all the layers referencing and using the same models (The model used in the view could be completely different to what is actually stored in the DB).

How can I sort this out?

Do you need it?

From your question it seems that you don't and your Data Access Layer simply forward calls to underlying layer/framework and map properties back/forward.

Complexity (paired with flexibility) comes at a cost (as you see) and for unneeded complexity you pay this cost without any benefit. Drop unneeded complexity! EF abstracts many underlying DB access details and you may won't need to reintroduce Repository pattern. See also Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (read more for further details about when - IMO - Repository pattern is needed).

In a different context this kind of refactoring has even a name: Remove Middle Man. When a class (or an entire layer, in your case) is doing nothing but delegation/direct mapping then you should remove it entirely.

You'll then have just your presentation DLL and your model DLL (with EF to hide/abstract database access and mapping). You may want to introduce another level of abstraction in your presentation layer (View Model) when underlying model is too different from model you present to your users (or when interaction model is very complex) but there you should follow common pattern/practice of your UI framework (MVC, MVP, MVVM, MVCVM or whatever else).

If, in your scenario, you start designing model layer then a code-first approach will let you design your domain classes adding little or nothing code for mapping (no ORM is perfect). With this path (requisites, domain model, presentation) I usually add View Model classes to fit presentation needing otherwise using Model classes directly).

Repository Pattern, When?

I'd add a 3rd layer for Data Access only for these (not exhaustive list of) scenarios:

I need to map deeply different storage methods: relational database, XML file(s), file-system, NoSQL database.
I have to switch between different technologies: Entity Framework, LINQ to SQL, NHibernate.

For simpler scenarios (such as adding a Service layer) mediator, proxy and similars will (usually) do the job.

Note About Testing

With an ORM you (usually) have harder time to write tests because it's directly connected to underlying database. In this case to test extreme error conditions and/or to simulate network issues/speed can be harder. If you can't automate these tests elsewhere (for example with dedicated system tests instead of unit testing) you may want to introduce a different DbContext base class to be used for testing however details depends on ORM you're using, designing approach you selected and specific tests you need to perform.


Detecting UI thread hanging and logging stacktrace I have an application that needs to always be responsive. I've written a class that is designed to monitor the UI thread. The goal is to provide useful information in the logs to be able to understand when the UI thread becomes unresponsive and to determine which code is the cause.

To do this I check how long it takes to process something on the UI thread, if its longer than a certain threshold, I log a warning. If this happens multiple times in succession, it prints the stacktrace.

I've had this in production for about 2 weeks now, and so far it is working as expected.  However, given that it uses deprecated methods to get the stacktrace, I'd like to know if this might end up causing more problems than it solves.

 public class ThreadMonitor
 {
    private static readonly ILog Log =  LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    private readonly Thread thread;
    private readonly int pollingFrequency;
    private readonly int delayThreshold;
    private readonly int stackTraceIterations;

    public ThreadMonitor(Thread thread, int pollingFrequency = 500, int delayThreshold = 100, int stackTraceIterations = 4)
    {
        this.thread = thread;
        this.pollingFrequency = pollingFrequency;
        this.delayThreshold = delayThreshold;
        this.stackTraceIterations = stackTraceIterations;
    }

    public void Run()
    {
        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                Thread.Sleep(pollingFrequency);
                var dispatcher = Dispatcher.FromThread(thread);
                var task = dispatcher.InvokeAsync(() => { });

                for (var i = 0; i < stackTraceIterations; i++)
                {
                    Thread.Sleep(delayThreshold);
                    if (task.Status != DispatcherOperationStatus.Completed)
                    {
                        Log.Debug($"{(i + 1) * 100}ms Delay on thread {thread.Name} ({task.Status})");
                    }
                    else
                    {
                        break;
                    }
                }

                if (task.Status == DispatcherOperationStatus.Completed)
                    continue;

                var stackTrace = GetStackTrace(thread);
                Log.Debug($"StackTrace of UI Thread: {stackTrace}");
            }
        });
    }

    #pragma warning disable 0618
    private StackTrace GetStackTrace(Thread targetThread)
    {
        StackTrace stackTrace = null;
        var ready = new ManualResetEventSlim();

        new Thread(() =>
        {
            // Backstop to release thread in case of deadlock:
            ready.Set();
            Thread.Sleep(200);
            try { targetThread.Resume(); } catch { }
        }).Start();

        ready.Wait();
        targetThread.Suspend();
        try { stackTrace = new StackTrace(targetThread, true); }
        catch { /* Deadlock */ }
        finally
        {
            try { targetThread.Resume(); }
            catch { stackTrace = null;  /* Deadlock */  }
        }

        return stackTrace;
    }
    #pragma warning restore 0618
 }

Great idea! That makes it possible to get information about hanging / lacking GUIs. That kind of (probably) valuable information are only available via customer feedback otherwise :). It would be interesting to know if you already use that ThreadMonitor, if you already evaluated the log files and if you got some interesting information out of it ;).

I have just a few small comments to the code:

There is no need to use a Task for the infinity loop. You can just use a Thread here.
However, when using a Task, I would start it with TaskCreationOptions.LongRunning. Otherwise, a thread from the thread pool will be used (and blocked). Thread pool threads are usually hold available for short running actions.
There is no way to get notified if an error occurs within the endless loop. To avoid that, put the endless loop in a try catch block or add a ContinueWith for the failure case to the created task.
The class allows to start the ThreadMonitor multiple times. That is actually not desired, therefore I would throw an exception when trying to call Run twice.
Honestly, I don't understand how your "DeadLockPreventionLogic" works, but it looks kind of adventurous. Probably, the StackTrace may contain some interesting information, but it is also possible that the StackTrace belongs to unproblematic logic that was coincidentally executed when the StackTrace has be caught. Additional to logging the StackTrace, it makes definitely sense to log the entry points of all use workflows.


Buying bunnies, eggs and elections with tax and a discount I have a small problem with the code below. Although it executes the task perfectly, It's supposed to be more "short" and compact according to the assignment feedback. I was wondering if someone can please help me change my code from its longer version to a more short version that completes the same task...

from math import *

ask = input("Would you like to buy bunnies, eggs, or elections?: ")
if ask == 'bunnies':
    bunnies = 30
    print("Bunnies will cost " + str(bunnies) + " dollars each.")
    quantity = int(input("How many would you like to buy?: "))
    cost1 = bunnies * quantity
    tax = (0.089 * cost1)
    final_cost = (cost1 + tax)
    if final_cost == final_cost > 57.89:
        discount1 = (0.13 * final_cost)
        with_discount1 = (final_cost - discount1)
        print("Your total will be " + str(with_discount1) + " with a discount.")
    if final_cost == final_cost < 57.89:
        print("Your total will be " + str(final_cost) + " without a discount")

if ask == 'eggs':
    eggs = 10
    print("Eggs will cost " + str(eggs) + " dollars each.")
    quantity = int(input("How many would you like to buy?: "))
    cost2 = eggs * quantity
    tax = (0.089 * cost2)
    final_cost2 = (cost2 + tax)
    if final_cost2 == final_cost2 > 57.89:
        discount = (0.13 * final_cost2)
        with_discount = (final_cost2 - discount)
        print("Your total will be " + str(with_discount) + " with a discount for eggs.")
    if final_cost2 == final_cost2 < 57.89:
        print("Your total will be " + str(final_cost2) + " without a discount for eggs")

if ask == 'elections':
    elections = 20
    print("Elections will cost " + str(elections) + " dollars.")
    quantity = int(input("How many are you looking to purchase?: "))
    cost3 = quantity * elections
    tax = (0.089 * cost3)
    final_cost3 = (cost3 + tax)
    if final_cost3 == final_cost3 > 57.89:
        discount2 = (0.13 * final_cost3)
        withdiscount = (final_cost3 - discounts)
        print("Your total will be " + str(withdiscount) + " dollars with a discount for elections.")
    if final_cost3 == final_cost3 < 57.89:
        print("Your total will be " + str(final_cost3) + " dollars without a discount for elections.")

Using from math import * is highly discouraged. Please always use either:

from math import sqrt, or
import math and use math.sqrt instead of sqrt.

You are not using math and so the import is not needed.
It is commonly recommended to use either f-strings or str.format to format your strings. This is as they make reading the format easier on more complex formats.

In your case you won't see this benefit too much but it would be a good habit to get now, rather than later.

print("Bunnies will cost {} dollars each.".format(bunnies))
print(f"Bunnies will cost {bunnies} dollars each.")

Please don't use unnecessary parentheses. This is as they add unneeded clutter to your code.
You can simplify the calculation for final_cost

$$
\begin{array}{r l}
c &= bq\\
t &= 0.089c\\
f &= c + t\\
f &= 0.089c + c\\
f &= (0.089 + 1)c\\
f &= 1.089bq
\end{array}
$$
The statement final_cost == final_cost > 57.89 is confusing and only works due to Python splitting the code into two different conditionals connected with an and.

The statement final_cost == final_cost will always be true, and so by all metrics is just bad.
Your ifs are missing if the final cost is 57.89 exactly. I assume this is a mistake.

When you have two ifs like this when one is getting half the options and the other is getting the other half it is better to use an if and an else rather than two ifs.
You don't need to store discount1 in a variable, it's just adding lines with no visible benefit.
Whilst there's nothing inherently wrong with printing the same string with a slight modification twice, you may be inclined to change it so you only define the structure of the print once.

Overall this would get:

bunnies = 30
print(f"Bunnies will cost {bunnies} dollars each.")
quantity = int(input("How many would you like to buy?: "))
final_cost = 1.089 * bunnies * quantity
if final_cost >= 57.89:
    with_discount = final_cost - 0.13 * final_cost
    print(f"Your total will be {with_discount} with a discount")
else:
    print(f"Your total will be {final_cost} without a discount")

From here we can see all the other options have almost exactly the same code. There are only three things that change:

The variable name bunnies.
The value of the variable bunnies
The name of the item you're buying.

From this we can see that a function would be good.

def price_to_buy(item, price):
    print(f"{item} will cost {price} dollars each.")
    quantity = int(input("How many would you like to buy?: "))
    final_cost = 1.089 * price * quantity
    if final_cost >= 57.89:
        with_discount = final_cost - 0.13 * final_cost
        print(f"Your total will be {with_discount} with a discount")
    else:
        print(f"Your total will be {final_cost} without a discount")

ask = input("Would you like to buy bunnies, eggs, or elections?: ")
if ask == "bunnies":
    price_to_buy("Bunnies", 30)
if ask == "eggs":
    price_to_buy("Eggs", 10)
if ask == "elections":
    price_to_buy("Elections", 20)

Advanced changes

Whilst the above is probably what your instructor expects from you, there are more ways to improve the code and make it shorter.

You can store the name and value in a dictionary, allowing you to condense those ifs into two lines of code.

You may want to use a try and except here to get the code to function the same if you don't enter valid input.
You can use str.title() to make the inputted item's name display in title case.
You can use an if __name__ == "__main__": guard to prevent the code from running when imported, normally by accident.
You can use a turnery to apply the discount, this is basically just an if and else but on one line!

By also using tuple unpacking we can get the preposition (with/without) and the discount percentage in one line.
You can use a try and except to display a nice error message.
You can use foo -= ... rather than foo = foo - ....

def price_to_buy(item, price):
    print(f"{item} will cost {price} dollars each.")
    value = input("How many would you like to buy?: ")
    try:
        quantity = int(value)
    except ValueError:
        print(f"{value} is not an integer.")
        return
    cost = 1.089 * price * quantity
    discount, prep = (0.13, "with") if cost >= 57.89 else (0, "without")
    cost -= discount * cost
    print(f"Your total will be {cost} {prep} a discount")

PRICES = {"bunnies": 30, "eggs": 10, "elections": 20}

if __name__ == "__main__":
    item = input("Would you like to buy bunnies, eggs, or elections?: ")
    price_to_buy(item.title(), PRICES[item])


Calculating average value of points around given point in a wider field I need to calculate the average value of points around a given point in a wider field.
For this I have a function:
fn local_average((x,y):(i32,i32),n:i32,(width,height):(i32,i32),space:&[i32]) -> i32 {
    let y_range = cmp::max(y-n,0)..cmp::min(y+n+1,height);
    let x_range = cmp::max(x-n,0)..cmp::min(x+n+1,width);
    println!("y: {:.?}, x: {:.?}",y_range,x_range);

    let size = (x_range.end-x_range.start) * (y_range.end-y_range.start);
    let mut total: i32 = 0;
    for yi in y_range {
        for xi in x_range.clone() {
            let i = yi * width + xi;
            total += space[i as usize];
        }
    }

    println!("{} / {} = {}",total,size,total / size);
    total / size
}

The thing that bothers me here is x_range.clone(), I feel like this is not a good approach.
I could also implement this in a more function manor but I'm unsure if this is  better as I find it to be less readable:
fn local_average_functional((x,y):(i32,i32),n:i32,(width,height):(i32,i32),space:&[i32]) -> i32 {
    let y_range = cmp::max(y-n,0)..cmp::min(y+n+1,height);
    let x_range = cmp::max(x-n,0)..cmp::min(x+n+1,width);
    println!("y: {:.?}, x: {:.?}",y_range,x_range);

    let size = (x_range.end-x_range.start) * (y_range.end-y_range.start);
    let total: i32 = y_range.map(|yl| {
        x_range.clone().map(|xl| {
            let il = yl * width as i32 + xl;
            space[il as usize] as i32
        }).sum::<i32>()
    }).sum();

    println!("{} / {} = {}",total,size,total / size);
    total / size
}

How could I improve this function?
Repl: https://repl.it/@JonathanWoollet/DraftyTautAdware

We don't need an x_range. We need a range of proper indices over space, as it enables us to use space[start..stop].iter().sum(). We need a combination of x_range and y_range.
So let's start by building one from hand:
fn local_average((x, y): (i32, i32), n: i32, (width, height): (i32, i32), space: &[i32]) -> i32 {
    let y_range = cmp::max(y - n, 0)..cmp::min(y + n + 1, height);
    let x_range = cmp::max(x - n, 0)..cmp::min(x + n + 1, width);

    let size = (x_range.end - x_range.start) * (y_range.end - y_range.start);
    let mut total: i32 = 0;

    for yi in y_range {
        let start = (yi * width + x_range.start) as usize;
        let end = start + ((x_range.end - x_range.start) as usize);

        total += space[start..end].iter().sum::<i32>();
    }

    total / size
}

Note that the code above was formatted by rustfmt. The rustfmt-style is very common in Rust projects, and several projects reject contributions until they are properly formatted. For cargo based projects use cargo fmt.
Either way, we now replaced the inner loop by a single sum(), which is more explicit about our goal. This is also a mixture of both your code styles. At this point, we might as well replace x_range by x_size, but that's a question of style.
For an easier use of local_average, we could introduce type Point = (i32, i32) and type Rect = (i32, i32), however, again, that's a matter of preference.


Devise a program that counts the number of characters in its input up to the end of file This is my code:

#include <stdio.h>
#include <ctype.h>

int main()

{
    int ch;
    int numberOfCharacters = 0;
    printf("please enter a word, and ctrl + d to see the resault\n");

    while ((ch = getchar()) != EOF && isprint(ch))

    {
        numberOfCharacters++;
    }

    printf("The number of characters is %d", numberOfCharacters);

    return 0;
}

Is this a good code?

Well, it doesn't do much. But it is not bad. A few issues:

main() should have parameters
excess blank lines (lines 5, 12, 16, 18) spoil the appearance
no \n on the last printf
the spec doesn't say 'printable' characters, just characters.
"please" needs a capital p and "resault" should be "result"


Load fifty million integers as quickly as possible in Java I am working my way through Project Euler. Many of the problems deal with prime number calculations: this is the type of code that can be extracted into a separate class and reused.

While calculating primes can be done quickly using certain methods, I was able to speed up the process of "getting prime numbers" by using a list of primes on disk and loading them. It is an order of magnitude faster than any calculation, but still takes roughly three minutes loading from an SSD.

What I did:

I took a publicly-available list of the first fifty million primes (some problems do use a significant portion of those numbers).
I wrote a program to convert the numbers from their textual representation to binary using Java's DataOutputStream. The file is simply fifty million four-byte integers in a row.
The utility method below loads each integer into an array using DataInputStream. It produces correct results, but it slow.

Is there any way to speed up the process of loading 50,000,000 integers? If I need to preprocess the data differently I am willing to do that.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class Test {

  public static int[] loadByQuantity(int argNumPrimes) {
    int numPrimes = Math.min(argNumPrimes, 50_000_000);
    int[] primes = new int[numPrimes];
    try (DataInputStream in = new DataInputStream(new FileInputStream("primes.bin"))) {
      for (int i = 0; i < primes.length; ++i) {
        primes[i] = in.readInt();
      }
    }
    catch (IOException ex) {
      throw new RuntimeException(ex);
    }
    return primes;
  }

}

Your code is a bit messy, and having the file name hard-coded in to your function is not great. Also, the "Hungarian Notation" (using things like arg to prefix your function parameters - note, it's a parameter, not an argument, by the way)... is not conventional.

On the other hand, I understand this is an exercise to test performance.... and it's not about the resusability (yet) of the code.

Still, I know from experience that reusability will happen, and your code will need some changes.

I also know, from experience, that memory-mapped IO is much faster in Java than other IO forms, so I figured I would have a kick at this problem.

I took my prime generator I had reveiewed here on Code Review previously ( Thread Safe Prime Generator ) and I generated the first 50,000,000 primes in to a file on my own system, then I tested your code against it (and after changing the file name to a parameter, it worked).

Out of interest, generating and writing to file of the primes took about 5 minutes on my computer - 311 seconds - much of which was probably IO time too.

Then, I converted your function to be:

public static int[] loadByQuantity(int argNumPrimes, String fname) {
    int numPrimes = Math.min(argNumPrimes, 50_000_000);
    int[] primes = new int[numPrimes];
    try (DataInputStream in = new DataInputStream(new FileInputStream(fname))) {
        for (int i = 0; i < primes.length; ++i) {
            primes[i] = in.readInt();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return primes;
}

The only difference is the file-name is now a parameter.

Then I wrote a little test system to time how long your code took for me:

public static void time(Supplier<int[]> task, String name) {
    long nanos = System.nanoTime();
    int[] primes = task.get();
    System.out.printf("Task %s took %.3fms\n", name, (System.nanoTime() - nanos) / 1000000.0);
    System.out.printf("Count %d\nFirst %d\nLast %d\n", primes.length, primes[0], primes[primes.length - 1]);
    System.out.println("----");
}

public static void main(String[] args) {
    int count = 50000000;
    time(() -> loadByQuantity(count, "primes.dat"), "OP");
}

I then implemented the same functionality using an NIO mechanism specifically using memory-mapped IO: http://docs.oracle.com/javase/8/docs/api/java/nio/MappedByteBuffer.html

This type of IO is designed to significantly reduce the amount of memory copies are made of the input file. It also means that Java reads the content out of the OS, without first copying it in to Java's memory space.

For the types of sequential IO this problem has, I expected the performance improvements to be significant.

Further, the MappedByteBuffer has methods getInt() which also decodes 4 bytes in to an int for you: http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#getInt--

Here's the code I came up with. Note, I have used the same exception handling that you use, and also the same array initialization. I believe you should be throwing exceptions from these methods, and not just wrapping them in runtime exceptions:

public static int[] loadByNIO(int argNumPrimes, String fname) {
    int numPrimes = Math.min(argNumPrimes, 50_000_000);
    int[] primes = new int[numPrimes];
    try (FileChannel fc = FileChannel.open(Paths.get(fname))) {
        MappedByteBuffer mbb = fc.map(MapMode.READ_ONLY, 0, numPrimes * 4l);
        for (int i = 0; i < numPrimes; i++) {
            primes[i] = mbb.getInt();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return primes;
}

I then ran the process a couple of times in the main method, and compared the results:

public static void main(String[] args) {
    int count = 50_000_000;
    time(() -> loadByQuantity(count, "primes.dat"), "OP");
    time(() -> loadByNIO(count, "primes.dat"), "NIO");
    time(() -> loadByQuantity(count, "primes.dat"), "OP");
    time(() -> loadByNIO(count, "primes.dat"), "NIO");
}

The NIO operation is, as expected, significantly faster... 1500 times faster

Task OP took 214163.250ms
Count 50000000
First 2
Last 982451653
----
Task NIO took 141.511ms
Count 50000000
First 2
Last 982451653
----
Task OP took 214633.128ms
Count 50000000
First 2
Last 982451653
----
Task NIO took 159.571ms
Count 50000000
First 2
Last 982451653
----

I admit, it is far faster than I was expecting too.... but, the results are correct.

Now, I encourage you to experiment with how to put this concept behind a Java stream, instead of populating the full 50,000,000 in to an array. By streaming the results you can start your "real" computation sooner, without the latency of having to read all the primes from the file. For example, consider what you could do with logic like:

primes.stream().....

where primes was reading the values on-demand from the file.

Here's the full code I have been running:

package prperf;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;
import java.util.function.Supplier;

public class PrimeReader {

    public static int[] loadByQuantity(int argNumPrimes, String fname) {
        int numPrimes = Math.min(argNumPrimes, 50_000_000);
        int[] primes = new int[numPrimes];
        try (DataInputStream in = new DataInputStream(new FileInputStream(fname))) {
            for (int i = 0; i < primes.length; ++i) {
                primes[i] = in.readInt();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return primes;
    }

    public static int[] loadByNIO(int argNumPrimes, String fname) {
        int numPrimes = Math.min(argNumPrimes, 50_000_000);
        int[] primes = new int[numPrimes];
        try (FileChannel fc = FileChannel.open(Paths.get(fname))) {
            MappedByteBuffer mbb = fc.map(MapMode.READ_ONLY, 0, numPrimes * 4l);
            for (int i = 0; i < numPrimes; i++) {
                primes[i] = mbb.getInt();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return primes;
    }

    public static void time(Supplier<int[]> task, String name) {
        long nanos = System.nanoTime();
        int[] primes = task.get();
        System.out.printf("Task %s took %.3fms\n", name, (System.nanoTime() - nanos) / 1000000.0);
        System.out.printf("Count %d\nFirst %d\nLast %d\n", primes.length, primes[0], primes[primes.length - 1]);
        System.out.println("----");
    }

    public static void main(String[] args) {
        int count = 50_000_000;
        time(() -> loadByQuantity(count, "primes.dat"), "OP");
        time(() -> loadByNIO(count, "primes.dat"), "NIO");
        time(() -> loadByQuantity(count, "primes.dat"), "OP");
        time(() -> loadByNIO(count, "primes.dat"), "NIO");
    }

}


Async Implementation I'm seeking code review comments for the following implementation.

jsFiddle

/**
* You need to run a number of async tasks, but you're being rate limited.
* Run as many concurrent tasks as you can, queueing the rest for when the
* tasks are complete.
*/

/**
* @param concurrency: number of concurrent tasks that can be run
*/
var ConcurrencyQueue = function (concurrency) {
    this.concurrency = concurrency;
    this.queue = [];
    this.count = 0;
};

/**
* add an asynchronous task to the queue. it will get executed immediately
* until the concurrent task count reaches this.concurrency. then, queue it until
* tasks are complete.
* @param task: function which takes a callback argument (done)
*/
ConcurrencyQueue.prototype.enqueue = function (task) {
    var self = this;
    self.count = self.count + 1;

    var done = function () {
        self.count = self.count - 1;
        if (self.queue.length) {
            self.queue.splice(0, 1)[0](done);
        }
    };

    if (self.count > self.concurrency) {
        self.queue.push(task);
    }

    if (self.count <= self.concurrency) {
        task(done);
    }
};

/**
 * tasks passed to concurrency queue are async and call the callback "done"
 * after they complete.
 */

function exampleTask (done) {
    console.log('started');
    setTimeout(function () {
        console.log('completed');
        done();
    }, Math.floor(Math.random() * 2000));
};

var queue = new ConcurrencyQueue(2);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);
queue.enqueue(exampleTask);

I have very little to say, maybe others will have more.

if (self.count > self.concurrency) {
    self.queue.push(task);
}

if (self.count <= self.concurrency) {
    task(done);
}

Why not if / else? At least it'll be clear it's one or the other.

this.queue.shift() is cleaner than this.queue.splice(0, 1)[0].

There's also a nitpick about self.count = self.count + 1; where += 1 could be used instead, but it really depends on the coding style.

About the callbacks, you could move to the newer Promise which is part of ECMAScript 2015.

ConcurrencyQueue.prototype.enqueue = function (task) {
    this.count += 1;

    if (this.count > this.concurrency) {
        this.queue.push(task);
    } else {
        this.execute(task);
    }
};

ConcurrencyQueue.prototype.execute = function(task) {
    var p = new Promise(task);

    /* `() => {` is a simpler notation for `function() {` in recent JS,
        but `this` refers to the encompassing `this` */
    var done = () => {
        this.count -= 1;
        if (this.queue.length) {
            this.execute(this.queue.shift());
        }
    };

    /* First argument is in case of success, second in case of errors */
    p.then(done, done);
}

jsFiddle


Plotting a vector field in R + ggplot I've written a small program that draws a vector field in R using ggplot for a given differential equation.

There is a topic on the subject here however, the proposed solutions either don't provide the same functionality as the code below or don't use ggplot.

//example differential equation: f_prime = f(x,y)

f_prime <- function(x,y){
  return(x^2/(1-x^2-y^2))
}

//set the min and max for the x and y curves
x <- 4      //change if you like
y <- 4
minX <- -x
maxX <- x
minY <- -y
maxY <- y
len <- 40   //number by which the x,y space will be subdivided by
            //larger number => more points and vice versus

//create an equally spaced grid
data <- data.frame(expand.grid(x = seq(minX, maxX, length.out=len),
                               y = seq(minY, maxY, length.out=len)))

//create a new column for the results of (x,y) applied on f_prime
data$dydx <- mapply(f_prime, data$x, data$y)

A small graphic to visualize the problem:

//The next step is important to understand:
//The goal is have arrows that have approx. the same length (c = const) and
//point to the direction of f_prime at some point (x,y) for all points
//Note: f_prime is the derivative of F(x,y) with respect to x,
//hence f_prime provides the relative change in y as a result of a change in x
//Now the problem to draw the arrows can be formulated using f_prime (= dy/dx)
//and the fact that c^2 = dy^2 + dx^2 (Pythagoras)
//Using basic algebra to solve the problem:
//Solve for dx = dy/f_prime(x,y) and insert into
//c^2 = dy^2 + dx^2 = dy^2 + (dy/f_prime(x,y))^2 and solve for dx
//dx = sqrt(c^2/(1+f(x,y)^2) and
//dy = f(x,y)*dx
//now we can draw the arrows using (x,y) as the start and (x+dx, y+dy) as the end
//translating this into code:

data$dx <- sqrt((1/len)/(1+data$dydx^2))
data$dy <- data$dx*data$dydx
ggplot(data=data, aes(x=x,y=y), environment = environment()) +
  geom_point(size = 1) +
  geom_segment(aes(xend=x+dx, yend=y+dy), arrow = arrow(length = unit(0.1, "cm"))) +
  xlim(minX,maxX) +
  ylim(minY,maxY)

Looks like:

Maybe there is a better/faster more elegant way to do it, if yes please share if not happy to help.

This will not be faster (which would require you move away from ggplot) but could give you ideas about writing better/cleaner code. The code first:

field_vec_plot <- function(fun, xmin = -1,
                                xmax =  1,
                                ymin = -1,
                                ymax =  1,
                                density = 10) {

  data <- expand.grid(x = seq(xmin, xmax, length.out = density),
                      y = seq(ymin, ymax, length.out = density))

  data <- within(data, {
     dydx = fun(x, y)
     dx   = sqrt((1 / density) / (1 + dydx ^ 2))
     dy   = dx * dydx
  })

  library(ggplot2)
  library(grid) # for arrow()
  xmar <- (xmax - xmin) / density # margin for x
  ymar <- (ymax - ymin) / density # margin for y
  ggplot(data = data, aes(x = x, y = y)) +
    geom_point(size = 1) +
    geom_segment(aes(xend = x + dx, yend = y + dy),
                 arrow = arrow(length = unit(0.1, "cm"))) +
    xlim(xmin - xmar, xmax + xmar) +
    ylim(ymin - ymar, ymax + ymar)
}

f_prime <- function(x, y) x ^ 2 / (1 - x ^ 2 - y ^ 2)
field_vec_plot(f_prime, xmin = -4, xmax = 4,
                        ymin = -4, ymax = 4,
                        density = 40)

Some of the recommendations:

Always write a function (with appropriate inputs and outputs)
expand.grid already returns a data.frame
mapply was not needed since f_prime is vectorized. This will be faster but it is probably a drop in the sea compared to plotting.
The use of within to add dependent columns interactively (no need to write data$ over and over and your code is much more readable.)
Make your code (especially the one you posted here) source the packages it requires. I had to look where arrow() was coming from
Do not write code that throws warnings. Read the message carefully and find what the problem is. In this case, it was warning when trying to plot arrows outside the plotting area. Hence I added some margins xmar and ymar to the plotting area.
Personal preference: put some space after commas and on each side of = and binary operators. Also use linebreaks so your lines are never too long and add spaces to make things align when you get a chance.
I have removed your comments because they were not using the R syntax (need # and not //) but that's an easy fix. Yes, comments are good and having a lot of them was great.

Disclaimer: I am not 100% confident that your 1 / density nor my definitions of xmar and ymar are correct, given what you are trying to achieve. Try this for example:

field_vec_plot(f_prime, xmin = -1, xmax = 1, ymin = -1, ymax = 1, density = 10)

where the arrows seem a little too long...


Counting the number of days worked for all commiters to a git repo I wrote this script to collect evidence of the number of days worked for the purpose of claiming some government tax credits.

I'm looking for some ways to clean it up. I'm especially wondering if there is a cleaner way to uniqueify a list than list(set(my_list) and maybe a better way to do:

d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))

import os
from pprint import pprint

lines = os.popen('git log --all').read().split('\n')

author_lines = filter(lambda str: str.startswith('Author'), lines)
date_lines = filter(lambda str: str.startswith('Date'), lines)
author_lines = map(lambda str: str[8:], author_lines)
date_lines = map(lambda str: str[8:18].strip(), date_lines)

lines = zip(author_lines, date_lines)

lines = sorted(list(set(lines)), key = lambda tup: tup[0])

commiters = list(set(map(lambda tup: tup[0], lines)))

d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))

for item in lines:
    d[item[0]] += 1

pprint(d)

For this part:

author_lines = filter(lambda str: str.startswith('Author'), lines)
date_lines = filter(lambda str: str.startswith('Date'), lines)
author_lines = map(lambda str: str[8:], author_lines)
date_lines = map(lambda str: str[8:18].strip(), date_lines)

This might be clearer, not that I have anything against map or filter, but list comprehensions do combine them nicely when you need both:

author_lines = [line[8:] for line in lines if line.startswith('Author')]
date_lines = [line[8:18].strip() for line in lines if line.startswith('Date')]

This:

lines = sorted(list(set(lines)), key = lambda tup: tup[0])

Can become:

lines = sorted(set(lines), key = lambda tup: tup[0])

for slightly less repetition (sorted automatically converts to a list).
And are you sure the key is even necessary? Tuples get sorted by elements just fine, the only reason to sort specifically by only the first element is if you want to preserve the original order of lines with the same author, rather than sorting them by the date line.
... Actually, why are you even sorting this at all? I don't see anything in the rest of the code that will work any differently whether it's sorted or not.

For this:

commiters = list(set(map(lambda tup: tup[0], lines)))

Why are you zipping author_lines and date_lines and then unzipping again? Just do:

commiters = set(author_lines)

or am I missing something?

And this:

d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))
for item in lines:
    d[item[0]] += 1

You're just getting commit counts, right?  Use Counter:

import collections
d = collections.Counter([author_line for author_line,_ in lines])

Or, if your python version doesn't have collections.Counter:

import collections
d = collections.defaultdict(lambda: 0)
for author_line,_ in lines:
    d[author_line] += 1

... Wait, are you even using date_lines anywhere? If not, what are they there for?


Check for similar value with SQL I've two table (t1 and t2) with 3 identical integer columns: c1, c2 and c3. I want to count how many value in t1 are in t2.

SELECT count(t1.value) FROM t1 INNER JOIN t2 ON  (
    t1.c1 = t2.c1 OR t1.c1 = t2.c2 OR t1.c1 = t2.c3 OR
    t1.c2 = t2.c1 OR t1.c2 = t2.c2 OR t1.c2 = t2.c3 OR
    t1.c3 = t2.c1 OR t1.c3 = t2.c2 OR t1.c3 = t2.c3
)

It doesn't seems a good way to write it (I'll have to add some columns). Is there a better solution to write it without enumerated any possibilities?

I'm using MySQL version 5.6.

Your question is not very clear... but, the way I understand it is:

Collect all the unique values in t1, and count how many of those unique values appear in t2.

Interesting problem.... instead of a straight join with all the or conditions, which may lead to an internal cross-product (thousands of joins and results to run comparisons on), I would state the logic as a couple of subselects ... which represent the two sets of data... the unique values in t1, and the unique values in t2.

Note, the 'union' operator does a distinct as part of the union....

select count(*)
from
  (
      select c1 as val from t1
    union
      select c2 as val from t1
    union
      select c3 as val from t1
  ) as t1vals,
  (
      select c1 as val from t2
    union
      select c2 as val from t2
    union
      select c3 as val from t2
  ) as t2vals
where t1vals.val = t2vals.val

The code looks nicer this way, but requires scanning each table three times (which I think will be better than the potentially thousands of times it may have to happen with your query......

I have put together an sqlfiddle for this


Parse input string into vector of i16 in Rust I'm new to Rust and I'm working through the exercises found at the bottom of this page. The following code parses a space deliminated input string from the user into a Vec<i16>. If the input string is invalid, the code loops and prompts again. If the string is valid, it prints out the debug value of the Vec<i16> and prompts again.

The code works, but I feel there is a more idomatic Rust way to deal with this. Particularly, in the get_input function's looping and how its assigning the return value. Behold.

use std::io::Write;

fn main() {
    while let Some(ary) = get_input() {
        println!("{:?}", ary);
    }

    println!("Peace!");
}

fn get_input() -> Option<Vec<i16>> {
    let mut out: Option<Vec<i16>> = None;
    let mut valid = false;
    while !valid {
        // Get user input.
        print!("Enter series-> ");
        std::io::stdout().flush().unwrap();
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();

        // Parse it.
        match input.trim() {
            "q" => {
                valid = true;
                out = None;
            }
            _ => {
                let parsed = parse_input(input);
                if let Ok(_) = parsed {
                    out = Some(parsed.unwrap());
                    valid = true;
                }
            }
        }
    }
    out
}

fn parse_input(input: String) -> Result<Vec<i16>, std::num::ParseIntError> {
    input
        .split_whitespace()
        .map(|token| token.parse::<i16>())
        .collect::<Result<Vec<i16>, _>>()
}

I don't know Rust too well, so take this review with a grain of salt. That being said, your get_input can be heavily simplified if you return. That way we don't need to remember whether the parsed input was valid: if it's valid we just return:

fn get_input() -> Option<Vec<i16>> {
    loop {
        // Get user input.
        print!("Enter series-> ");
        std::io::stdout().flush().unwrap();
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();

        // Parse it.
        match input.trim() {
            "q" => return None,
            _ => {
                let parsed = parse_input(input);
                if let Ok(out) = parsed {
                    return Some(out);
                }
            }
        }
    }
}

Note that this prevents some errors that were possible before. For example you could have missed to set out and accidentally returned None instead of Some, e.g.

    // ...
    _ => {
        let parsed = parse_input(input);
        if let Ok(_) = parsed {
            valid = true;
            // whoops forgot out
        }
    }

This erroneous state cannot happen now.

Also note that we now have a simple loop. We don't have any mut bindings, only a single if let is left. Also note that we don't need to unwrap parsed: if parsed is an Ok(out), we can use that out.

That being said, you should add an error message after the match, e.g.

match input.trim() {
    // same as above
}
println!("Your input could not get parsed. Please write space-separated numbers or 'q' to quit");


Installation script for Mac OS tool I have a bash script I'm trying to distribute to people in my class. The script requires some dependencies to operate, namely wkhtmltopdf and pdfkit. I can install those dependencies with homebrew, but I can't assume users have that. I've written an install/uninstall script for Mac, and my partner made one for Linux, but both of them seem so hacky to me.

I would like a more robust approach for distributing my bash script with its dependencies.

Here is the Mac OS install/uninstall script:

#!/usr/bin/env bash

arg=$1
uninstall="-u"

if [[ ${arg} == *"$uninstall"* ]];
then
    echo "Uninstalling eesubmit..."

    echo "Removing the shortcut..."
    sudo rm /usr/bin/eesubmit
    echo "The eesubmit shortcut has been removed"

    echo "Removing the source code and username file for eesubmit..."
    rm -rf ~/.eesubmit/
    echo "The source code and username file for eesubmit has been removed"

    echo "eesubmit requires other dependencies that may have been installed when eesubmit was installed"
    echo "Some of these dependencies may have already been installed"
    echo "Please review these dependencies and tell us if you want to remove them"

    echo "Do you want to uninstall pdfkit (a Python package that runs on top of wkhtmltopdf)? (y/n)"
    read uninstallPdfkit
    if [ ${uninstallPdfkit} = "y" ];
    then
        pip uninstall pdfkit
    fi

    echo "Do you want to uninstall wkhtmltopdf (a library for converting HTML to PDFs)? (y/n)"
    read uninstallWkhtmltopdf
    if [ ${uninstallWkhtmltopdf} = "y" ];
    then
        brew uninstall pdfkit --force
    fi

    echo "Do you want to uninstall homebrew (a package manager for Mac OS)? (y/n)"
    read uninstallHomebrew
    if [ ${uninstallHomebrew} = "y" ];
    then
        ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
    fi

    echo "Uninstallation complete!"
else
    echo "Installing homebrew (a package manager for Mac OS)..."
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    echo "Homebrew installation complete"

    echo "Installing wkhtmltopdf (a library for converting HTML to PDFs)..."
    brew install wkhtmltopdf
    echo "wkhtmltopdf installation complete"

    echo "Installing pdfkit (a Python package that runs on top of wkhtmltopdf)..."
    pip install pdfkit
    echo "pdfkit installation complete"

    echo "Adding a shortcut for eesubmit (this may require your password)..."
    if [ -f ~/.eesubmit/eesubmit/main/submitting.bash ];
    then
        sudo cp ~/.eesubmit/eesubmit/main/submitting.bash /usr/bin/eesubmit
        echo "The shortcut has been created"
        echo "Installation complete!"
    else
        echo "Error: The main eesubmit script is not installed" 1>&2
        echo "Are you sure you cloned the repository correctly?"
        echo "Try running these commands"
        echo "    mkdir -p ~/.eesubmit"
        echo "    cd ~/.eesubmit"
        echo "    git clone https://github.com/DakotaAndMichael/eesubmit.git"
        echo "Then, run this script again"
    fi
fi

The first thing I can see that should be changed is to add some checks before/after removing files.  As it is currently written, the script will break if it goes to remove a file that isn't there.  So, for instance, if the uninstall is interrupted halfway (computer unplugged, process killed, whatever), then a subsequent run of the script will throw an error and the last part of the script will never be executed.

For simple checks like these, and for that matter for the single-command if checks you already have, you should just use && and || instead.

if [ ${uninstallPdfkit} = "y" ];
then
    pip uninstall pdfkit
fi

and

[ ${uninstallPdfkit} = "y" ] && pip uninstall pdfkit

are exactly equivalent.  Funny thing in this example is that the braces {} are completely unnecessary, as are the double quotes around y, but there should be doublequotes around the variable for safety:

[ "$uninstallPdfkit" = y ] && pip uninstall pdfkit

So instead of:

rm -rf ~/.eesubmit/
echo "The source code and username file for eesubmit has been removed

You should use:

[ -e ~/.eesubmit ] && rm -rf ~/.eesubmit && echo 'The source code and username file for eesubmit has been removed'

This is just scratching the surface; here are some other partial thoughts that could be expanded into further detail:

Why do you echo "Uninstallation complete" if the user decides not to uninstall?
read has a bunch of flags that would be useful; in particular -p to specify a prompt message.  (Use quotes!)
Your big error message has only the first line redirected to stderr.  Consider using single quotes (since you don't need variable expansion) and just have it include multiple lines with one echo command, then redirect to stderr only once for all of it.
You say a shortcut is being created, but you used cp instead of ln -s target linkname.  Also you shouldn't need to use sudo at all.

Hope this helps.


Generating the powerset in C I am solving another problem in leetcode.

  Given a set, generate all the subsets of the set.

  Input: [1,2,3]
  Output: [ [3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]

The solution is accepted but I would like to improve on my C coding style. I have created a node_t type to encapsulate the data related each subset. There could be less verbose ways to do this. Two popular methods of solving this problem seem to be:

backtracking
a subset equals to binary number ≤ n where n is element count.

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

typedef struct node_s {
    int *array;
    int  size;
    struct node_s *next;
} node_t;

node_t* alloc_node()
{
    return (node_t*)malloc(sizeof(node_t));
}

void free_node(node_t *node)
{
    free(node);
}
#define SIZE 3

void print_one(int *one)
{
    printf("%d ", *one);
}
void print_1d_array(int *array, int size)
{
    for(int i = 0; i < size; i++) {
        print_one(&array[i]);
    }
    printf("\n");
}
void print_2d_array(int **array, int *col_sizes, int size)
{
    for (int i = 0; i < size; i++) {
        print_1d_array(array[i], col_sizes[i]);
    }
}
int** create_solution_array(node_t *head, int ans_size, int **column_sizes)
{
    int **ans = (int**)malloc(sizeof(int*)*ans_size);

    node_t *iter;
    iter = head->next;
    int idx = 0;
    while(iter) {
        ans[idx] = iter->array;
        (*column_sizes)[idx] = iter->size;
        idx++;
        iter = iter->next;
    }
    return ans;
}

void gen_powerset(int *num, int num_size, int idx, int cur_size, int *cur, node_t **iter_node, int *ans_size) {
    if (idx == num_size) {
        node_t *new_node = alloc_node();
        if (cur_size) {
            new_node->array = (int *) malloc(sizeof(int) * cur_size);
            new_node->size = cur_size ;
            memcpy(new_node->array, cur, cur_size*sizeof(int));
        }
        (*iter_node)->next = new_node;
        *iter_node = new_node;
        (*ans_size)++;
        return;
    }

    gen_powerset(num, num_size, idx + 1, cur_size, cur, iter_node, ans_size);
    *(cur + cur_size) = num[idx];
    gen_powerset(num, num_size, idx + 1, cur_size + 1, cur, iter_node, ans_size);
}

int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {
    node_t  *head = alloc_node();
    node_t  *iter = head;
    int     *cur = (int*)malloc(sizeof(int)*numsSize);
    gen_powerset(nums, numsSize, 0, 0, cur, &iter, returnSize);
    return create_solution_array(head, *returnSize, columnSizes);
}

int main ()
{
    int *nums = (int*)malloc(sizeof(int)*SIZE);
    for (int i = 0; i < SIZE; i++) {
        nums[i] = i+1;
    }
    int *col_sizes = (int*)malloc(sizeof(int)*SIZE);
    int ans_size;
    int ** ans = subsets(nums, SIZE, &col_sizes, &ans_size);
    print_2d_array(ans, col_sizes, ans_size);
    return 0;
}

I'll just work through this from the top:

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

Looks good; we need these.

typedef struct node_s {
    int *array;
    int  size;
    struct node_s *next;
} node_t;

It's usual to use the same structure tag as the typename we're going to use: struct node_t.

If size is the number of elements in the array, a more natural type might be size_t.

node_t* alloc_node()
{
    return (node_t*)malloc(sizeof(node_t));
}

All this does is to allocate the memory.  Consider initialising the members to sane values, too:

node_t* alloc_node()
{
    node_t *n = malloc(sizeof *n);
    if (n) {
        n->array = NULL;
        n->size = 0;
        n->next = NULL;
    }
    return n;
}

We're writing C, so it's not advised to cast the result of malloc().  But we can't assume it succeeds!

It's a good habit to use the assigned-to variable in the argument of sizeof, rather than its type; that saves us the mental work of having to check that the type actually matches.  That's why I've used sizeof *n in place of sizeof (node_t) here; you'll see just following an example where we're further from the declaration and this idiom has more benefit.

It's possibly a good idea to create the array at the same time:

node_t* alloc_node(size_t array_count)
{
    node_t *n = malloc(sizeof *n);
    if (n) {
        n->array = malloc(sizeof *n->array * array_count);
        n->size = n->array ? array_count : 0;
        n->next = NULL;
    }
    return n;
}

void free_node(node_t *node)
{
    free(node);
}

Assuming that the node owns its array, we need to free that, too:

void free_node(node_t *node)
{
    if (node) {
        free(node->array);
    }
    free(node);
}

Does the node own its next as well?  If so, we need to free that, or perhaps return it.

#define SIZE 3

Why is this in the middle here?  It should be right at the beginning (or perhaps just before main()).

void print_one(int *one)
{
    printf("%d ", *one);
}

I'm not convinced there's much benefit to encapsulating this as a function.

void print_1d_array(int *array, int size)
{
    for(int i = 0; i < size; i++) {
        print_one(&array[i]);
    }
    printf("\n");
}

We should use size_t for the count here:

void print_1d_array(int *array, size_t size)
{
    for (size_t i = 0;  i < size;  ++i) {
        printf("%d ", array[i]);
    }
    printf("\n");
}

void print_2d_array(int **array, int *col_sizes, int size)
{
    for (int i = 0; i < size; i++) {
        print_1d_array(array[i], col_sizes[i]);
    }
}

Another size_t (okay, I'll stop mentioning these now).

int** create_solution_array(node_t *head, int ans_size, int **column_sizes)
{
    int **ans = (int**)malloc(sizeof(int*)*ans_size);

    node_t *iter;
    iter = head->next;
    int idx = 0;
    while(iter) {
        ans[idx] = iter->array;
        (*column_sizes)[idx] = iter->size;
        idx++;
        iter = iter->next;
    }
    return ans;
}

Aside from points from earlier, that while loop has an initialisation and an advancement, so it's really a for loop:

int** create_solution_array(node_t *head, size_t ans_size, size_t **column_sizes)
{
    int **ans = malloc(sizeof *ans * ans_size);

    if (ans) {
        int idx = 0;
        for (node_t *iter = head->next;  iter;  iter = iter->next) {
            ans[idx] = iter->array;
            (*column_sizes)[idx] = iter->size;
            ++idx;
        }
    }
    return ans;
}

void gen_powerset(int *num, int num_size, int idx, int cur_size, int *cur, node_t **iter_node, int *ans_size) {
    if (idx == num_size) {
        node_t *new_node = alloc_node();
        if (cur_size) {
            new_node->array = (int *) malloc(sizeof(int) * cur_size);
            new_node->size = cur_size ;
            memcpy(new_node->array, cur, cur_size*sizeof(int));
        }
        (*iter_node)->next = new_node;
        *iter_node = new_node;
        (*ans_size)++;
        return;
    }

    gen_powerset(num, num_size, idx + 1, cur_size, cur, iter_node, ans_size);
    *(cur + cur_size) = num[idx];
    gen_powerset(num, num_size, idx + 1, cur_size + 1, cur, iter_node, ans_size);
}

*(cur + cur_size) is normally written cur[cur_size].

We need to check whether our allocations succeeded:

/* true if successful, false on any error (e.g. out of memory) */
bool gen_powerset(int *num, size_t num_size, size_t idx,
                  size_t cur_size, int *cur, node_t **iter_node,
                  size_t *ans_size)
{
    if (idx == num_size) {
        node_t *new_node = alloc_node(cur_size);
        if (!new_node || new_node->size != cur_size) {
            return false;
        }
        if (cur_size) {
            memcpy(new_node->array, cur, sizeof *cur * cur_size);
        }
        (*iter_node)->next = new_node;
        *iter_node = new_node;
        ++*ans_size;
        return true;
    }

    cur[cur_size] = num[idx];

    return gen_powerset(num, num_size, idx + 1, cur_size, cur, iter_node, ans_size)
        && gen_powerset(num, num_size, idx + 1, cur_size + 1, cur, iter_node, ans_size);
}

int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {
    node_t  *head = alloc_node();
    node_t  *iter = head;
    int     *cur = (int*)malloc(sizeof(int)*numsSize);
    gen_powerset(nums, numsSize, 0, 0, cur, &iter, returnSize);
    return create_solution_array(head, *returnSize, columnSizes);
}

Again, check that malloc() succeeded, and check that gen_powerset() succeeded.

int main ()
{
    int *nums = (int*)malloc(sizeof(int)*SIZE);
    for (int i = 0; i < SIZE; i++) {
        nums[i] = i+1;
    }
    int *col_sizes = (int*)malloc(sizeof(int)*SIZE);
    int ans_size;
    int ** ans = subsets(nums, SIZE, &col_sizes, &ans_size);
    print_2d_array(ans, col_sizes, ans_size);
    return 0;
}

Having carefully created free_node(), we completely forgot to use it.  Valgrind reveals a substantial leak due to this.  We need to free the other allocated memory, too.


Python guessing game I'd like some feedback.

from random import randint

turns = 1
computer_guess = randint(1, 10)
while True:
    user_guess = raw_input("Guess Number: ")
    print 4-turns, "Turns left"
    if turns == 4:
        print "You lost!, LOOSER!"
        exit()
    else:
        if int(user_guess) == int(computer_guess):
            print "Congratulations, You won!\n"
            play_again = raw_input("Do You Want To Play Again? (Y / N): ")
            if play_again.upper() == 'Y':
                continue
            else:
                exit()
        else:
            turns += 1
            print "Try again - N was ", computer_guess

With some short code like that, I decided I'd run it to get a better feel for the program.  Here's my first session:

Guess Number: 45
3 Turns left
Try again - N was  9
Guess Number: 9
2 Turns left
Congratulations, You won!

Do You Want To Play Again? (Y / N): yes

(end)

You didn't give any rules at the beginning of the file, so how was I to know the number had to be between one and ten?  I know only because I looked at your code.  I typed 45 and there was no indication that it was invalid.  It told me it wasn't the right answer and said I had three turns left, but it also told me what the right answer was.  That made my second guess easy.  I was right, but it still printed 2 Turns left.  I said yes when it asked if I wanted to play again, but it exited the program anyway.  Another minor thing: you want to look professional and that includes more than just how the program works.  It includes how your text is formatted.  Your caPitaliZatioN maKes a diFfErence iN How yOur ProGram LooKs.  You have a lot of unnecessarily capitalized letters.  I would recommend looking up a good style guide on capitalization.

print 4-turns, ...

Why 4?  Well, of course, it's because that's how many turns there are.  It's an arbitrary number (called a magic number) that should instead be defined as a constant at the beginning of the file to be used in all cases instead of typing in magic numbers.  You also shouldn't be printing how many turns are left unless the user did not win or lose.  That means that it should come after the if and else blocks.

exit()

It is unnecessary to exit; you can just use break.

if int(user_guess) == int(computer_guess):

What if the user typed wheeeee!?  It's a common thing to say, right?  Well, anyway, the user might type something invalid and you wouldn't want to have an error if he did.  You'd have a disgruntled user on your hands.  You also don't need to convert computer_guess.  It's already an integer.

if play_again.upper() == 'Y':
    continue
else:
    exit()

You shouldn't just continue.  You also need to reset turns.

You shouldn't use a bare else.  What if the user typed yes as I did?  It still exits.  You should use a loop there that validates the user's input.  If you want to be really fancy, define a function that excepts a bunch of different inputs as positive and a bunch as negative.  I once wrote a function that even counted uh huh as a valid way of saying yes.

print "Try again - N was ", computer_guess

You shouldn't tell the user what the answer is until the game is over.

The new code:

from random import randint

TOTAL_TURNS = 4

turns = 1
computer_guess = randint(1, 10)
while True:
    try:
        user_guess = int(raw_input("Guess number between 1 and 10: "))
    except ValueError:
        print "Please type an integer."
        continue
    if not 1 <= user_guess <= 10:
        print "Please type a number between 1 and 10."
        continue
    if turns == TOTAL_TURNS:
        print "You lost! Loser!"
        break
    else:
        if user_guess == computer_guess:
            print "Congratulations, You won!\n"
            while True:
                play_again = raw_input("Do you Want To Play Again? (Y / N): ").upper()
                if play_again in "YN": break
                print "Please type Y / N"
            if play_again == 'Y':
                turns = 1
                computer_guess = randint(1, 10)
                continue
            else:
                break
        else:
            turns += 1
            print "Try again"
    print TOTAL_TURNS - turns + 1, "Turns left"


Blog & Blog Tags SQL Statements I have three tables for a blog system.

The blog

CREATE TABLE IF NOT EXISTS lm_blog(
        blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        title VARCHAR(80) NOT NULL UNIQUE,
        action VARCHAR(80) NOT NULL UNIQUE INDEX,
        url VARCHAR(80) NOT NULL UNIQUE,
        summary VARCHAR (255) NOT NULL,
        article TEXT NOT NULL,
        created DATE NOT NULL,
        updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        publish TINYINT UNSIGNED DEFAULT 0,
        PRIMARY KEY(blog_id));

The tags

CREATE TABLE IF NOT EXISTS lm_blog_tags(
        tag_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        tag VARCHAR(32) NOT NULL UNIQUE INDEX,
        description TEXT,
        PRIMARY KEY(tag_id)
    );

And the relationships

CREATE TABLE IF NOT EXISTS lm_blog_tag_relationships(
        blog_id INT UNSIGNED NOT NULL,
        tag_id INT UNSIGNED NOT NULL,
        PRIMARY KEY(blog_id, tag_id),
        FOREIGN KEY (blog_id) REFERENCES lm_blog(blog_id),
        FOREIGN KEY (tag_id) REFERENCES lm_blog_tags(tag_id)
    );

I want to search for blogs by a tag name and have all the tags for that blog. I am currently using GROUP_CONCAT to group the tags and filter it with a HAVING LIKE clause.

I.E to search for aticles with a PHP tag

SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T3.tag SEPARATOR ':') AS tags
FROM  lm_blog_tag_relationships AS T1
INNER JOIN lm_blog AS T2 ON T1.blog_id = T2.blog_id
INNER JOIN lm_blog_tags AS T3 ON T1.tag_id = T3.tag_id
GROUP BY T2.blog_id
HAVING tags   LIKE '%:PHP:%' OR tags LIKE '%:PHP' OR tags LIKE 'PHP:%'
ORDER BY T2.blog_id DESC

I'm assuming there is a better way to get the same results.

Using a like with a leading wild card will likely be very slow as no indexes can be used. As such they should be avoided, which should be easy to do when the string you are checking it a concatenation of values from a table.

I would suggest you do another join from the blog table to the blog tag relationship table, and from that another join to the blog tag table but specifying that the tag is php . This should mean any blog with a php tag will be brought back (complete with all its tags concatenated together) while any blog without that tag will be ignored.

Not tested, but something like the following

SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T3.tag SEPARATOR ':') AS tags
FROM  lm_blog_tag_relationships AS T1
INNER JOIN lm_blog AS T2 ON T1.blog_id = T2.blog_id
INNER JOIN lm_blog_tags AS T3 ON T1.tag_id = T3.tag_id
INNER JOIN lm_blog_tag_relationships T4 ON T2.blog_id = T4.blog_id
INNER JOIN lm_blog_tags AS T5 ON T4.tag_id = T5.tag_id AND T5.tag SEPARATOR = 'PHP'
GROUP BY T2.blog_id
ORDER BY T2.blog_id DESC


Amalgamate two toggle functions into one I want to amalgamate these two functions into one, Any ideas?

  function toggleVisibility() {

        document.getElementById('regStart').style.visibility = 'hidden';
        document.getElementById('regPage').style.visibility = 'visible';

        document.getElementById('facebook').src = "/images/js project/FacebookGray.png"
        document.getElementById('google').src = "/images/js project/GoogleGray.png"
        document.getElementById('winlive').src = "/images/js project/WinLiveGray.png"
        document.getElementById('yahoo').src = "/images/js project/YahooGray.png"
}

function toggleSave() {

    document.getElementById('regStart').style.visibility = 'visible';
    document.getElementById('regPage').style.visibility = 'hidden';

    document.getElementById('facebook').src = "/images/js project/FacebookDepressed.ico"
    document.getElementById('google').src = "/images/js project/GoogleDepressed.ico"
    document.getElementById('winlive').src = "/images/js project/WinLiveDepressed.ico"
    document.getElementById('yahoo').src = "/images/js project/YahooDepressed.ico"

  }

function toggleVisibility() {
    var temp = document.getElementById('regStart').style.visibility
    document.getElementById('regStart').style.visibility = document.getElementById('regPage').style.visibility;
    document.getElementById('regPage').style.visibility = temp;

    var suffix = "Gray.png";
    if ( 'hidden' === temp ) {
        suffix = "Depressed.ico";
    }

    document.getElementById('facebook').src = "/images/js project/Facebook" + suffix;
    document.getElementById('google').src = "/images/js project/Google" + suffix;
    document.getElementById('winlive').src = "/images/js project/WinLive" + suffix;
    document.getElementById('yahoo').src = "/images/js project/Yahoo" + suffix;
}

The first insight is that you want to swap the visibility settings for regStart and regPage.  So use the normal swap format with a temp variable.

The second insight is that your image paths have the same start for both cases of each image.  So the beginning can be a constant value for each image.

The third insight is that your image paths have the same ending for all images in a particular case.  So based on the value of temp (arbitrarily chosen as the shortest variable name), change the ending.

I also normalized the indentation.  It was inconsistent in your original functions.