"Ease the Array" challenge I'm working on this challenge:

  Given an array of integers of size N. Assume ‘0’ as invalid number and all other as valid number. Write a program that modifies the array in such a way that if next number is  valid number and is same as current number, double the current number value and replace the next number with 0. After the modification, rearrange the array such that all 0’s are shifted to the end and the sequence of the valid number or new doubled number is maintained as in the original array.

  Examples:

Input : arr[] = {2, 2, 0, 4, 0, 8}
Output : 4 4 8 0 0 0

Input : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}
Output :  4 2 12 8 0 0 0 0 0 0

  Input:

  The first line of the input contains an integer T, denoting the number of test cases. Then T test case follows. First line of each test contains an integer N denoting the size of the array. Then next line contains N space separated integers denoting the elements of the array.

  Output:

  For each test case print space separated elements of the new modified array on a new line.

  Constraints:

  1 ≤ T ≤ 10³

  1 ≤ N ≤ 10⁵

  Example:

  Input:

2
5
2 2 0 4 4
5
0 1 2 2 0

  Output:

4 8 0 0 0
1 4 0 0 0

I managed to get my code to work for the given input and output cases. However, when I submit it, I get a "time limit exceeded" message.

#include <stdio.h>

int main() {
    //code
    int x,q,n,i,j,k,m,arr[100000],d,t;
    scanf("%d",&x);
    for(q=0;q<x;q++)
    {
        scanf("%d",&n);
        for(t=0;t<n;t++)
        {
            scanf("%d",&arr[t]);
        }
        for(i=0;i<n;i++)
        {
            if(i>0)
            {
                if(arr[i]==arr[i-1])
                {
                    arr[i-1]=arr[i]+arr[i-1];
                    arr[i]=0;
                }
            }
        }
        j=n-1;
        k=0;
        while(k != j)
        {
            if(arr[k]==0)
            {

                for(m=0;k+m+1<=j;m++)
                {
                    arr[k+m]=arr[k+m+1];
                }
                arr[j]=0;
               j--;

            }
            else
            {
                k++;
            }
        }
        for(d=0;d<n;d++)
        {
            printf("%d",arr[d]);

            printf(" ");
        }
        printf("\n");

    }
    return 0;
}

This is a decent start. Here are some things that could be improved.
Naming
Your variable names are single letters that as far as I can tell have no relationship to what they represent. The variable x is the number of test cases to run. You should name it numTestCases or testCases. q is the specific test case you're currently running, so testCase or testCaseIndex would be a better name. n is the number of inputs to read, so numInputs would be a good name. And arr tells us very little other than that it is an array. How about inputs? I would rename i to inputIndex, as it's for iterating over the inputs. d could be outputIndex.
Functions
There are 4 different things your code does:

Reads the inputs from the user (or stdin)
Finds duplicate items in the array and combines them
Moves 0s to the end of the array
Prints the results

Each of those should be a different function with a clear name.
Space Efficiency
You have an array declared as int arr[100000]. Assuming a typical 32-bit int implementation, that's ~400k. On my system, the default stack size is 1MB. That means that single array takes up half the stack. If had just two more of those, you'd get a stack overflow just running the app. Since it's only 1 allocation at the start of the program and not a repeating allocation, I recommend using malloc() to allocate the array and freeing it after you've finished.
Time Efficiency
The main slowdown in your code is the part that copies the remaining elements when you find a 0 in the array. There are built-in functions in the standard library to do this task for you. In this case, this loop:
            for(m=0;k+m+1<=j;m++)
            {
                arr[k+m]=arr[k+m+1];
            }

can be replaced with a single line:
            memmove(&arr[k], &arr[k+1], sizeof(arr[0]) * (j - (k + 1) + 1));

This is significantly more efficient. The library function (which is sometimes not even a function), can use SIMD instructions, and other speedups to make it much faster than you're likely to do on your own. And it's portable. When I run the test with just that single change, it passes.
There are other ways you could speed this up, too. Instead of copying the remaining portion of the array at every 0, you could read up to the first 0. Mark that index. Read up to the next 0. Move only the values between those 2 indexes back, and repeat. This way you never move any element in the array more than once.


Rails controller method that conditionally filters results This code for my blog checks to see if tags are in the params hash. If they are, then only posts that are tagged will be paginated. Otherwise, all of the posts are paginated.

class PostsController < ApplicationController
  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
    else
      @posts = Post.all.paginate(page: params[:page])
    end
  end
end

I feel like this checking of params shouldn't be the concern of the controller, but of some other model like PostParameterChecker. How do you feel about this? Where does this code actually belong?

Creating a model just to check the parameters is overkill and not idiomatic in Rails. If you need some extra logic, use the existing model. In this case, I'd make Post#tagged_with accept a nil value which wouldn't filter anything:

def Post
  scope :tagged_with, ->(tag) { tag ? <code to filter> : all }
end

class PostsController < ApplicationController
  def index
    @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
  end
end


jQuery tooltip optimization This is my second jQuery script: a universal tooltip for my entire web page. It took me a couple of days to research and make it work.

Now, I need help from the experts to optimize my newbie code.

This is one of the ways I can show the tooltip:

My tooltip

jQuery:

$('.tooltip').hover(function(){
    var text = $(this).attr('data-tooltip');

    // get coordinates (top, left) of clicked element
    var offset = $(this).offset();

    // append tooltip to body, hide it, insert text
    // center the tooltip to the clicked element and display it 3 pixels above the clicked element
    $('

')
    .hide()
    .text(text)
    .appendTo('body')
    .css("left", offset.left - (($(".tooltipbox").outerWidth() - $(this).width()) / 2 )) // center the tooltip
    .css("top", offset.top - $(".tooltipbox").outerHeight() - 3)
    .fadeIn(200);
}, function() {
    // hover out the tooltip box
    $('.tooltipbox').remove();
});

Something simple that works ok. Any way to improve my second jQuery script?

You don't really need a tooltip class on your target element. Since you already have a data-tooltip attribute, that's enough to find the relevant elements:

$("[data-tooltip]") // find all elements with a data-tooltip attribute

This will also let you use the tooltip class for the actual tooltip, which makes more sense, given the name.

You call $(this) multiple times instead of calling it once and storing it a variable, e.g.

var target = $(this);

You're also creating an element in your code, yet you're fetching it back through jQuery. That really isn't necessary, since that can go in a variable too. And you can use jQuery to your advantage a bit more.

var tooltip = $("

")
  .hide()
  .addClass("tooltipbox")
  .appendTo(document.body);

then, when positioning it, it might be nice with yet more variables, just to improve clarity a bit

var top  = offset.top - tooltip.outerHeight() - 3,
    left = offset.left - (tooltip.outerWidth() - target.width()) / 2;

tooltip.css({
  left: left,
  top:  top
});

Also, you may want to not hide the tooltip, if the user mouses over it. Doing so will require more trickery, though, so it's a bit out-of-scope for this answer. But the point is that right now, moving over the tooltip causes it to disappear, which can cause a bunch of flickering, since it's being displayed practically where the cursor already is.

Lastly, it'd be better to use a div or span for the tooltip. While not strictly necessary, the div element is a better fit, because it's semantically neutral, and span just means "a run of text". A p element means paragraph, but a tooltip is usually just a tiny snippet; not really a paragraph in and of itself. There's nothing preventing you from using a p or any other element, but that also means you might as well use a more appropriate element than p.


First steps in Scala: does this look idiomatic? I an a newcomer in the Scala world, and I would like some advice from more experienced people to find out whether what I am writing goes in the direction of idiomatic code.

In particular, I have to write a simple algorithm that will do the following. We are given an integer number of, say, candies to be distributed, and a list of proportions, which are also integers. We should split the candies into groups, such that the proportions are respected as accurately as possible, given that a single candy cannot be broken up.

For instance, given 17 candies to distribute in proportions of (3, 2, 5) we should obtain (5, 4, 8).

Here is my code, including a quick ScalaCheck test.

import org.scalacheck.Prop._
import org.scalacheck.Gen

object Distribution {
    private class IntWithDivision(val self: Int) {
        def @/(other: Int): Float = self.toFloat / other
    }

    private implicit def divisibleInt(int: Int) = new IntWithDivision(int)

    def distribute(amount: Int, proportions: Seq[Int]): Seq[Int] = {
        val sum = proportions.sum
        val byDifect = proportions map { x => (amount * x @/ sum).toInt }
        val approximations = (byDifect, proportions).zipped map { (x, y) => x @/ y }
        val lowValuesIndices = (
            approximations.view.zipWithIndex
            sortBy { _._1 }
            take (amount - byDifect.sum)
            map { _._2 }
        ).force
        val remainders = (
            approximations.view.zipWithIndex
            map { x => if (lowValuesIndices contains x._2) 1 else 0 }
        ).force

        (byDifect, remainders).zipped map { _ + _ }
    }

    def main(args: Array[String]) {
        val pos = Gen.choose(1, 50000)
        val posList = Gen.containerOf[List, Int](pos)
        val propSum = forAll(pos, posList) { (amount: Int, proportions: List[Int]) =>
            (proportions.size > 0) ==> (amount == distribute(amount, proportions).sum)
        }
        propSum.check
    }
}

In particular, I would like advice on the following points:

The algorithm goes over the list of proportions and derived lists a few times. I would like to use more laziness, but using proportions.view at the beginning and then returning a force gives a type error.
The code is more convoluted than I would like. I think it may be simplified knowing the Collections API better.

Any help or suggestion is welcomed.

Ok, I'm changing the answer now that I understand what you are doing.

The main problem here is @/ -- while Scala people, in general, don't mind special operators, they don't add operators just because they can either. You can replace @/ with the existing / just by adding .toFloat to any one of the terms.

Views aren't often used either, and it's important to have a very good understanding of how they work if you are going to use them, and it's not that easy to gain performance with them, since the machinery they use to support non-strictness is quite heavy, and not everything takes advantage of it. For example, sortBy will create a new collection before take and map are applied.

Views can gain when you have many mapping/slicing steps, and few elements of it are ever used. Most of the time, iterators will gain you much more performance, at the cost of the mutability problems iterators have.

If you want to reduce the number of times you iterate through the list of proportions, there's at least one place where you can simplify:

    val remainders = (
        approximations.view.zipWithIndex
        map { x => if (lowValuesIndices contains x._2) 1 else 0 }
    ).force

    (byDifect, remainders).zipped map { _ + _ }

Can be reduced to

    byDifect.zipWithIndex map {
      case (bd, i) => bd + (if (lowValuesIndices contains i) 1 else 0)
    }

One could also keep byDifect a Float, then either use it alone when computing approximation (instead of zipping stuff), or skip that altogether and put that computation on sortBy -- incurring the cost of computation O(nlogn) times instead of O(n) times. It would make the code shorter, but whether it would be faster or not is something I'd leave to a benchmark with a real application -- I'm guessing it would depend on actual sizes for proportions.

So, let's talk a bit about performance. Before Scala 2.10, if you want performance you should avoid methods added through implicits on critical paths. The code you wrote will probably get inlined by JIT. You can also reduce the number of computations by pre-computing amount / sum, and if you make that amount.toFloat / sum, then you don't need /@.

More specifically, views are not guarantees of speed, particularly if the computations are light, such as here. I'd not use them at all, unless I'm specifically optimizing the code.

Doing a fixed size of multiple passes on small data structures is often not a problem. You are not changing the complexity, just losing memory locality. If the data is bigger, you can incur in gc overheads, which are more substantial. If maximum performance is required, just drop immutability and go to mutable arrays.

Finally, contains is faster on Set than Seq -- and, in this particular case, a BitSet would be way faster. Call it apply, however, since contains is a general method on traversables, while set's apply is a fundamental operation. If one of them is less than optimized, it will be contains.

This is the most idiomatic beginner's code I have ever seen... do you come from another functional language?


Factory pattern along with DI using Unity container I am learning design patterns and this is my sample code where I have implemented Factory pattern and instance creation I have delegated to Unity container Framework(DI) to build the loosely coupled system.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace DesignPatternsDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            iPaymentGateway gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.SHIFT4);
            gateway.CreatePaymentGateway();
            gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.WELLSFARGO);
            gateway.CreatePaymentGateway();
            gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.PROTOBASE);
            gateway.CreatePaymentGateway();
            Console.ReadLine();
        }

        enum GateWay
        {
            PROTOBASE = 1,
            SHIFT4 = 2,
            WELLSFARGO = 3
        }

         //Factory class
        class PaymentGatwayFactory
        {
            public static iPaymentGateway NewPaymentGatway(GateWay GateWayType)
            {
                 //Dependency injection using unity container
                var container = new UnityContainer();
                iPaymentGateway result = null;
                switch (GateWayType)
                {
                    case GateWay.SHIFT4:
                        container.RegisterType<iPaymentGateway, SHIFT4Gateway>();
                        result = container.Resolve<SHIFT4Gateway>();
                        break;
                    case GateWay.WELLSFARGO:
                        container.RegisterType<iPaymentGateway, WellsFargoGateway>();
                        result = container.Resolve<WellsFargoGateway>();
                        break;
                    default:
                        container.RegisterType<iPaymentGateway, ProtobaseGateway>();
                        result = container.Resolve<ProtobaseGateway>();
                        break;
                }

                return result;
            }
        }

        class WellsFargoGateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement Wells Fargo logic");
            }
        }

        class SHIFT4Gateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement SHIFT4 logic");
            }
        }

        class ProtobaseGateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement Protobase logic");
            }
        }

        interface iPaymentGateway
        {
            void CreatePaymentGateway();
        }
    }
}

Is this is the right way of implementing Factory pattern and using the Unity framework?

The following code should tell a story as it is reviewed. There are not many comments as the code has been simplified to be easy to understand as it speaks for itself. I suggest comparing it to what you had before and observe the difference in strategy taken to achieve the factory pattern with DI.

Apart from the composition root, note the separation of concerns and loose coupling of all members involved. The factory in the original post was tightly coupled to the UnityContainer and was also creating an instance every time the factory method was called. The container should only be created once in the composition root of the application.

public interface IPaymentGateway {
    void Invoke();
}

public class WellsFargoGateway : IPaymentGateway {
    public void Invoke() {
        Console.WriteLine("Implement Wells Fargo logic");
    }
}

public class SHIFT4Gateway : IPaymentGateway {
    public void Invoke() {
        Console.WriteLine("Implement SHIFT4 logic");
    }
}

public class ProtobaseGateway : IPaymentGateway {
    public void Invoke() {
        Console.WriteLine("Implement Protobase logic");
    }
}

internal class NullGateway : IPaymentGateway {

    static Lazy<IPaymentGateway> nullObject = new Lazy<IPaymentGateway>(() => new NullGateway());

    public static IPaymentGateway Empty {
        get { return nullObject.Value; }
    }

    private NullGateway() {

    }

    public void Invoke() {
        //No-op
    }
}

public enum GateWay {
    PROTOBASE = 1,
    SHIFT4 = 2,
    WELLSFARGO = 3
}

public interface IPaymentGatewayFactory {
    IPaymentGateway Create(GateWay GateWayType);
}

public class DefaultPaymentGatewayFactory : IPaymentGatewayFactory {

    readonly Func<GateWay, IPaymentGateway> factoryFactory;

    public DefaultPaymentGatewayFactory(Func<GateWay, IPaymentGateway> factoryFactory) {
        this.factoryFactory = factoryFactory;
    }

    public IPaymentGateway Create(GateWay GateWayType) {
        return factoryFactory(GateWayType);
    }
}

public static class CompositionRoot {
    public static IUnitContainer Configure() {
        //Dependency injection using unity container
        var container = new UnityContainer();
        //Register the gateways using named mappings
        container.RegisterType<IPaymentGateway, WellsFargoGateway>(GateWay.WELLSFARGO.ToString());
        container.RegisterType<IPaymentGateway, SHIFT4Gateway>(GateWay.SHIFT4.ToString());
        container.RegisterType<IPaymentGateway, ProtobaseGateway>(GateWay.PROTOBASE.ToString());
        //create the strategy
        Func<GateWay, IPaymentGateway> factoryFactory = (gatewayType) =>
            container.Resolve<IPaymentGateway>(gatewayType.ToString()) ?? NullGateway.Empty;
        //register factory
        var factory = new DefaultPaymentGatewayFactory(factoryFactory);
        container.RegisterInstance<IPaymentGatewayFactory>(factory);

        return container;
    }

}

class Program {
    static void Main(string[] args) {
        var container = CompositionRoot.Configure();
        var factory = container.Resolve<IPaymentGatewayFactory>();
        IPaymentGateway gateway = factory.Create(GateWay.SHIFT4);
        gateway.Invoke();
        gateway = factory.Create(GateWay.WELLSFARGO);
        gateway.Invoke();
        gateway = factory.Create(GateWay.PROTOBASE);
        gateway.Invoke();
        Console.ReadLine();
    }
}


Let's play Rock, Paper, Scissors with Ruby I'm just looking for any tips to improve the code, particularly easier ways to change the main logic of the code so that it's shorter.

puts "Let's play rock, paper, scissors"

#scores
compScore = 0
humanScore = 0

until compScore == 5 || humanScore == 5

    puts "Select your weapon. Rock, paper or scissors?"

    human = gets.chomp.downcase
    comp = ["rock", "paper", "scissors"].sample

    #human wins
    if (human == "rock" && comp == "scissors") || (human == "scissors" && comp == "paper") || (human == "paper" && comp == "rock")
        p "You won!"
        humanScore += 1

    #draws
    elsif (human == "rock" && comp == "rock") || (human == "paper" && comp == "paper") || (human == "scissors" && comp == "scissors")
        p "Draw! No point awarded"

    #computer wins
    else compScore += 1
        p "You lose."
    end

    #Resulted Scores
    p "Human Score: #{humanScore}"
    p "Computer Score: #{compScore}"

    #Resulted Choices
    p "Human chose: #{human}"
    p "Computer chose: #{comp}"
end
    #Tell who wins
    p humanScore > compScore ? ("YOU WIN!") : ("COMPUTER WINS!.")

Fix your formatting. While the computer doesn't care about indentation, humans do. And code is read (by humans) many more times than it's written. And this code is hard to read.

The whole "draws" logic can be replaced with a simple check: human == comp.

Determining the winner of a "hand" in rock-paper-scissors can be done in many, many, many ways. You're checking it "manually" in a sense, by writing out all the possible combinations. But you could also assign numeric values to the choices (for instance, their index in an array), and compare those numbers instead. Or so something like this, where the player's choice is used to determine what the winning response would be and see if the computer picked that:

choices = %w(rock paper scissors).reverse

index = choices.index(player_choice)
winning_choice = choices[index - 1]

if computer_choice == winning_choice
  # computer wins
else
  # human wins
end

(this assumes that player_choice and computer_choice have already been set and that you've checked for draws.)


Fairly Simple Hangman in Python This is my take on a simple hangman game, which is played from command prompt.

import random

wordlist = []

word =  random.choice(open("words.txt").readlines())
#word.txt is a list of words, in the same directory with the game file.

length  = len(word)

mock_word = "_ " * length
#The underscores presented to the player

mock_word =  mock_word.split()
#making it a list, since strings can't be assigned

used_lets = []

lives = 7

while True:
    print " ".join(mock_word) #Needs space in join, so the underscores are separated.
    let = raw_input("Give a letter: ")

    if len(let) > 1: #User can only give one letter
        print "Only one!"

    elif (let not in word):
        if let not in used_lets:
            lives = lives - 1
            if lives == 0:
                print "Sorry you lost, the word was:", word
                break
            print "Try again, you have only %r lives left!" % lives
            used_lets.append(let)
            print "So far you have used:"
            print used_lets

    else:
        for i in range(length):
            if let == word[i]:
                mock_word[i] = let

    if "".join(mock_word) == word: #Making it a string again
        print word + " You won!"
        break

If you want to test, just set word to something. That is how I tested the loop.
I would appreciate criticisms of my coding technique, and perhaps the suggestion of an alternative of the while loop use, which feels wrong.

tl;dr: This is pretty good for a beginner. It’s robust to bad input and plays smoothly. To improve it, you could use functions to make it more reusable, and I’ve suggested a bunch of small ways to tidy up your Python. But a high level it works well.

I’m just going to dive in, run the script, and see what happens. You didn’t provide a words.txt file, so I just used this small sample:

american
captain
dictionary
fish
hangman
letter
list

Comments:

Overall, it seems pretty robust. I was unable to cause a traceback or exception by passing in dodgy input – kudos!

(And yes, I passed in an emoji thumbs-up, and it handled it fine.)
At the risk of getting bludgeoned to death by Jeff Atwood, I found a pluralisation bug:

Try again, you have only 1 lives left!
So far you have used:
['b', 'c', 'd', 'e', 'f', 'i']

Should be “lives”.
The program treats uppercase and lowercase letters as distinct. That’s not what I expect when I play Hangman – at least whenever I’m played it, I’m just guessing letters, not their associated case as well.
There are a few cases where the program just asks for the next letter, and doesn’t give a helpful message. When I guess a letter that I’ve already guessed (correct or not), it goes straight to prompting me for a new letter without explaining why.

That’s more adding polish than fixing a bug – but it would be nice.
I think a newline between guesses would make the output much easier to read. That’s a personal preference though, not a bug.

At a high-level, the problem with this code is that it isn’t very reusable. It’s good to break your code down into functions – that allows it to be reused within the same file, or across other files.

For example, this script only allows me to play a single game of Hangman. Having a play_hangman() function would allow you to keep playing Hangman until the player got bored. Here are some suggestions to get you started:

play_hangman(word, number_of_lives)
get_random_word_from_file(file_path) – letting me specify the file path means I could drop in another word list easily

I think the while loop is fine for this purpose.

Once you have some functions in the file, you should use the if __name__ == '__main__' construction, which allows the same file to be used both as a module and a script. Like so:

if __name__ == '__main__':
    play_hangman('pomegranate', number_of_lives=8)

The code inside that if block only runs if the script is run directly; if you access part of the file via an import statement, it doesn’t run. That means you can import from the file without having to play a game of Hangman first.

Finally, here are some minor line-by-line comments and/or nitpicks:

You’re pretty good for PEP 8 compliance. One line is a bit long, and you need a bit of extra spacing around your comments, but otherwise fine.
The wordlist variable is unused.
When you choose the word, you open the words.txt file, but don't close it again. You could add an explicit close, but a better approach is to use the with keyword when opening files, like so:

with open("words.txt") as wordsfile:
    word = random.choice(wordsfile.readlines())

The length variable is only used twice (and I’m going to get rid of the second usage shortly), so I’d remove it and just use it directly.
The way you’ve constructed the mock_word list is a little strange. You could go straight to it in one line:

mock_word = ['_'] * len(word)

Also note that the word “mock” has a special meaning in programming, so I’d suggest picking a different name for this variable – perhaps player_guess?
Don’t be stingy with variable names – characters are cheap. Names like used_lets and let can become used_letters and guessed_letter. It makes your program easier to read.

Now I’m diving into the heart of the program: the while loop that processes the player guess.

The first if branch is fine. However, you’re only checking that I don’t enter too many characters; you don’t check that I enter enough characters. This loop could be improved by checking for an incorrect number of characters, and printing a generic message:

if len(letter) != 1:
    print("Please enter a single character.")

In the elif branch, a common way to decrement a variable is to write lives -= 1. That’s a bit more compact.

In the print statement telling me how many lives I have left, you’re using the %r token. That’s fairly generic – it just prints the string representation of whatever gets passed in. Since you know that the lives variable is an integer, I think it’s better to use the more explicit token %d. As I read the string, I know what sort of data will appear here.
In the else branch, a more Pythonic approach than iterating over the indexes is to use enumerate(), which iterates over the index and the array element together. Like so:

for i, letter in enumerate(word):
    if guessed_letter == letter:
        player_guess[i] = letter


Closing a ResultSet and rethrowing an Exception Is this an acceptable way to make sure a java.sql.ResultSet is always closed, and also make sure that an Exception caught is propagated to the caller?

Please don't hesitate to review other aspects of this sample as well.

public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws Exception {
    String strSelect = this.createReplicationSelectStatement(taskBean);
    ResultSet resultSet = null;
    try {
        resultSet = DerbyDog.getResultSet(strSelect);
        if (resultSet.next()) {
            resultSet.updateString(COLUMN_STATUS, strStatus);
            resultSet.updateRow();
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}

Close a ResultSet/Resource

If you are using java 7 then I would recommend to use try with resources

it will take care of closing ResultSet for you and make your code a little cleaner.

public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws Exception {
    String strSelect = this.createReplicationSelectStatement(taskBean);
    try (ResultSet resultSet = DerbyDog.getResultSet(strSelect) {
        if (resultSet.next()) {
            resultSet.updateString(COLUMN_STATUS, strStatus);
            resultSet.updateRow();
        }
    } catch (Exception e) {
        throw e;
    }
}

Exception Handling

personal I prefer to wrap my own exceptions around generic exceptions.

That way I can throw a more precise exception with a comment to help myself when debugging

public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus)   throws ReplicationStatusException {
    String strSelect = this.createReplicationSelectStatement(taskBean);
    try (ResultSet resultSet = DerbyDog.getResultSet(strSelect) {
        if (resultSet.next()) {
            resultSet.updateString(COLUMN_STATUS, strStatus);
            resultSet.updateRow();
        }
    } catch (SqlException e) {
        throw new ReplicationStatusException("update ReplicationStatus failed because of a SQLException", e);
    } catch (Exception e) {
        throw new ReplicationStatusException("update ReplicationStatus failed because of an unexpected exception", e)
    }
}

that's about my 2 cents


Deep pick using lodash/underscore Use Case

_.pick creates a shallow clone of an object given a predicate that identifies which keys to keep. pickDeep would perform a deep clone of the object and would "pick" up all nested objects containing the given keys. All containers containing the nested objects would remain and would not be removed.

Requirements

Recursively apply a pick to each level in an object.
If a property is an object/array, then apply a pick.
Keep all object/array only if the descendant properties fulfill the pick.

Improvements

I'd like any constructive criticism to improve this code, but I'm mainly interested in advice pertaining to:

Readability
Flexibility
Performance
Implementing this with _.pick and _.cloneDeep

Function

(jsfiddle)

function pickDeep(collection, identity, thisArg) {
    var picked = _.pick(collection, identity, thisArg);
    var collections = _.pick(collection, _.isObject, thisArg);

    _.each(collections, function(item, key, collection) {
        var object;
        if (_.isArray(item)) {
            object = _.reduce(item, function(result, value) {
                var picked = pickDeep(value, identity, thisArg);
                if (!_.isEmpty(picked)) {
                    result.push(picked);
                }
                return result;
            }, []);
        } else {
            object = pickDeep(item, identity, thisArg);
        }

        if (!_.isEmpty(object)) {
            picked[key] = object;
        }

    });

    return picked;
}

Test Data

var data = {
    a: 5,
    b: 6,
    c: 7,
    d: {
        a: 65,
        z: 6,
        d: {
            a: 65,
            k: 5
        }
    },
    e: [
        {a : 5},
        {b : 6},
        {c : 7}
    ],
    f: [
        {
            b : [  { a: 5, z: 5 } ],
            c : 6
        },
        {
            g: 0
        }
    ]
};

Test Cases

var testCase1 = { a: 5, b: 6};
pickDeep(testCase1, 'a'); // {a : 5}
var testCase2 = { a: 5, b: { a: 1}, c: { b: 3}};
pickDeep(testCase2, 'a'); // {a: 5, b: {a: 1}}
var testCase3 = { a: 5, b: [ { a: 1}, { c: 2}, {d: 3} ], c: [ {c: 2}, {d : 3}]}
pickDeep(testCase3, 'a'); //{ a: 5, b: [ {a: 1} ]}
var testCase4 = [ {a: 5}, {b: 2}, {c: {a :3 }}, {d: [ {a: 4}] }, z: [ { f: 34}] ];
pickDeep(testCase4, 'a'); // [ {a:5}, {c: {a:3}}, {d: [ {a:4}]}];

Execution Code

function isIn(collection) {
    return function(value, key) {
        return _.contains(collection, key);
    }
}

console.log(pickDeep(data, isIn(['a', 'c'])));

Here's the most elegant way I can think of writing this. I use transform to handle both Arrays and Objects as your tests showed you wanted to support them, though as pointed out in comments your code didn't.

These changes also allow you to use more than 2 pick properties (pickDeep(set, 'a', 'b', 'c', ['d', 'e'])) as you can with the normal pick/omit.

For lodash 3 and underscore 1.8? you'll need to change _.createCallback to _.iteratee the rest of the code should remain the same.

function pickDeep(collection, predicate, thisArg) {
    if (_.isFunction(predicate)) {
        predicate = _.createCallback(predicate, thisArg);
    } else {
        var keys = _.flatten(_.rest(arguments));
        predicate = function(val, key) {
            return _.contains(keys, key);
        }
    }

    return _.transform(collection, function(memo, val, key) {
        var include = predicate(val, key);
        if (!include && _.isObject(val)) {
            val = pickDeep(val, predicate);
            include = !_.isEmpty(val);
        }
        if (include) {
            _.isArray(collection) ? memo.push(val) : memo[key] = val;
        }
    });
}

This also fixes a the need to check pickDeep({a: [{a: 1}]}) twice to add it to the picked object


Dynamic Official Receipt increment algorithm I made a function that would automatically generate official receipt for POS. it is able to accept format such as xxx, xxx-xxx, xx-xx.

But my code is really messy and horrible and it needs review. I would really appreciate for corrections, recommendations and critiques to improve this.

The flow would be:

Get the last official receipt number OR, if none use specified system default.
If there is a provided format, use it. and read the last number according to its format
Split it, convert it to int and increment it.
Check it doesn't exist yet.
Return the next official receipt number

I'm using Django/Python. If it needs explanation please comment and I will explain the best way I can.

try:
    user = request.user.id
    official_receipt = {}
    default = {}
    company = get_current_company(request)

    or_from_last_transaction = ""
    or_from_default_company = ""

    try:
        try:
            official_receipt = Pointofsale.objects.filter(company=company,is_or_manual=False).values('official_receipt').order_by('-official_receipt').first()
        except Exception as e:
            or_from_last_transaction = '10000'
        else:
            pass
        finally:
            or_from_last_transaction = official_receipt['official_receipt']
        try:
            POS_settings.objects.filter(company=company).exists()
        except POS_settings.DoesNotExist:
            pass
        else:
            or_from_default_company = '00000'
        finally:
            default_company = POS_settings.objects.filter(company=company).values().first()
            if default_company['is_or_per_company']:
                or_from_default_company = default_company['pos_official_receipt']
            else:
                or_from_default_company = None

    except Exception as e:
        official_receipt = '30000'
    else:
        pass
    finally:
        official_receipt = or_from_default_company if or_from_default_company else or_from_last_transaction

    stop = True
    duplicate_add = 0

    if any(c.isalpha() for c in official_receipt):
        return 'Incorrect OR Format'

    while stop:
        str_group = official_receipt.split("-")
        str_length = len(official_receipt)
        group_length = int(len(str_group))

        for index, group in reversed(list(enumerate(str_group))):
            limit = len(group)
            group = int(group)
            group += 1
            if len(str(group)) > limit:
                if index == 0:
                    str_group[index] = group
                else:
                    str_group[index] = 0
            else:
                str_group[index] = int(str_group[index]) + (1 + duplicate_add)
                str_group[index] = str(str_group[index]).zfill(limit)
                break

        next_official_receipt = ''
        for group in str_group:
            next_official_receipt += str(group)
            next_official_receipt += '-'

        next_official_receipt = next_official_receipt[0:len(next_official_receipt)-1]
        if Pointofsale.objects.filter(official_receipt=next_official_receipt,company=company).exists():
            stop = True
            duplicate_add += 1
        else:
            stop = False
    return next_official_receipt
except Exception as e:
    print(e)
    return e

A few notes on the use of exceptions:

You're catching the non-specific Exception. That's bad, because it hides real programming errors. You should be specific what exception to catch (like except POS_settings.DoesNotExist:).
There are too many try-except blocks overall. You may need to rethink what you're trying to do, and with the previous point in mind, what exceptions you're trying to catch. Django queries may often return an empty queryset instead of raising an exception, which may be better suited.
The overarching try-except is really bad. Firstly, that catches anything that isn't caught in the inner block, and secondly, it makes it hard to read where it starts and ends. Try-except blocks should be short, concentrated around the code code (one or a few lines at most) that might raise the exception
If you use else: pass in an try-except clause (or in an if-clause), it's cleaner to just leave off the else branch. There's no use for it. The same goes for finally: pass.
You're catching the overarching exception, then printing it, then returning it. That has two problems:

when run inside a proper server, print very likely causes problems (from my experience using Apache). Use the Django logging provided.
there is absolutely nothing to gain by returning an exception. Re-raise it, or perform a cleanup action (and possibly still re-raise it after that). Return is for actual values, not exceptions.


UniqueList Class in VBA I often find myself abusing dictionary objects just for the exist method like this,

For Each x in Something
    If Not dict.Exists(x) Then dict.Add x, False
Next x

Then just exploit the .Exists(x) method.  It happens often enough that I thought it merited it's own class.

Instead of composing Scripting.Dictionary, I decided to just maintain a sorted list of unique items.  Usage is simple; unique items are inserted into the collection sorted.  Non-unique items are not added.

Attributes

Let's just get this out of the way.  Attribute VB_PredeclaredId must be set to True and NewEnum allows the class to be iterable.  I still haven't found a way to replicate this using an array instead of a collection.  With an array I could offload some of my code to my standard library, but then this wouldn't be standalone or portable.

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1
END
Attribute VB_Name = "UniqueList"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Option Explicit

Private list As Collection

Public Sub Class_Initialize()
    Set list = New Collection
End Sub
Public sub Class_Terminate()
    Set list = Nothing
End Sub
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4

    Set NewEnum = list.[_NewEnum]

End Property

Data Manipulation

Public Sub Add(ByVal element As Variant)

    If IsEmpty Then

        list.Add element
        Exit Sub

    End If

    Dim index As Long
    index = LocateIndex(element)

    If (list(index) > element) Then
        list.Add element, Before:=index
    ElseIf list(index) < element Then
        list.Add element, After:=index
    End If

End Sub
Public Sub Merge(ByVal list_ As Variant)

    Dim element As Variant
    For Each element In list_
        Add element
    Next element

End Sub
Public Sub Remove(ByVal element As Variant)

    Dim index As Long
    index = LocateIndex(element)

    If (list(index) = element) Then list.Remove index

End Sub
Public Sub Clear()

    Set list = Nothing
    Set list = New Collection

End Sub

Introspection

Note I don't implement an Item(x) method.  I don't want users to be able to scramble the data.

Public Function Exists(ByVal element As Variant) As Boolean
    Exists = (element = list(LocateIndex(element)))
End Function
Public Function Count() As Long
    Count = list.Count
End Function
Public Function IsEmpty() As Boolean
    IsEmpty = (Count = 0)
End Function

Searching

The only private method is a binary search that returns where the element is or where it should be.

Private Function LocateIndex(ByVal element As Variant) As Long

    Dim upper As Long
    upper = Count

    Dim lower As Long
    lower = 1

    While lower < upper

        Dim middle As Long
        middle = (lower + upper) \ 2

        If list(middle) >= element Then
            upper = middle
        Else
            lower = middle + 1
        End If

    Wend

    LocateIndex = upper

End Function

Just a couple of notes. The biggest of which is that I think you've misunderstood what VB_PredeclaredId does. It creates a default instance of the class. Which allows you to do things like this

UniqueList.Add someItem

Without declaring and setting a new instance of the class. It's a cool feature, but it's not what allows the list to be iterable and you don't need it here. The [_NewEnum] is what allows the For Each syntax.

The Clear method doesn't need to Set list = Nothing. Drop that line and just set it to a new instance of Collection.

Lastly, I find it really odd that you have a list with no way to get an element back out of the list. We can add and remove items, but not retrieve them. I would rethink implementing an Item method.


Bare bones painter app in Java See the next iteration: Bare bones painter app in Java - follow-up.

I have this tiny program for drawing:

PaintCanvas.java:

package net.coderodde.javapaint;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;

/**
 * This class implements a GUI component for drawing.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Jun 8, 2016)
 */
public class PaintCanvas extends Canvas {

    /**
     * The actual image being drawn to.
     */
    private final BufferedImage image;

    /**
     * The graphics context of the above.
     */
    private final Graphics2D imageGraphics;

    public PaintCanvas(final int width, final int height) {
        super();
        super.setBounds(0, 0, width, height);

        this.image  = new BufferedImage(width,
                                        height,
                                        BufferedImage.TYPE_INT_RGB);
        this.imageGraphics = this.image.createGraphics();
        this.imageGraphics.setColor(Color.WHITE);
        this.imageGraphics.fillRect(0, 0, width, height);
        this.imageGraphics.setColor(Color.BLACK);

        final PaintCanvasMouseListener listener =
                new PaintCanvasMouseListener();

        this.addMouseListener(listener);
        this.addMouseMotionListener(listener);
    }

    @Override
    public void paint(final Graphics g) {
        update(g);
    }

    @Override
    public void update(final Graphics g) {
        g.drawImage(this.image, 0, 0, null);
    }

    private class PaintCanvasMouseListener
    extends MouseAdapter implements MouseMotionListener  {

        @Override
        public void mouseClicked(final MouseEvent event) {
            processEvent(event);
        }

        @Override
        public void mouseDragged(final MouseEvent event) {
            processEvent(event);
        }

        private void processEvent(final MouseEvent event) {
            PaintCanvas.this.imageGraphics.fillOval(event.getX(), event.getY(), 5, 5);
            PaintCanvas.this.repaint();
        }
    }
}

App.java:

package net.coderodde.javapaint;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

/**
 * This class implements an application for simple drawing.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Jun 8, 2016)
 */
public class App {

    private final JFrame frame = new JFrame("JavaPaint");

    public App() {
        frame.getContentPane().add(new PaintCanvas(640, 480));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        setFrameLocationToCenter();
        frame.setVisible(true);
    }

    private void setFrameLocationToCenter() {
        final Dimension screenDimension = Toolkit.getDefaultToolkit()
                                                 .getScreenSize();
        final int screenWidth  = screenDimension.width;
        final int screenHeight = screenDimension.height;

        frame.setLocation((screenWidth - frame.getWidth()) / 2,
                          (screenHeight - frame.getHeight()) / 2);
    }

    public static void main(final String... args) {
        final App app = new App();
    }
}

It allowed me to draw the following masterpiece:

I am most interested to hear about the internals, yet feel free to tell me anything that comes to mind.

A few notes:

Is there a reason you aren't using JavaFX?  See this answer as
to why you should be using it.
Since I mostly rewrote your code, I'll do the best I can to explain all the components of implementing an app in JavaFX:

There are a few layers within a JavaFX app; the application, the stage, the scene, and the canvas.  I'll let you do more reading on your own about all of those if you wish to learn more, but these are the basic components for creating a GUI.
Within the canvas, we add the event handlers to handle all the different mouse events.  These are pretty self-explanatory, since you have them in your app as well.
Now we have to handle the actual painting on the canvas.  Again, you have a similar approach in your code, so I don't have to cover this in depth.

Small user-experience quip: don't start the program in the middle of the screen.  Often comes across as adware-like.

Final Code:

package javafx_drawoncanvas;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFX_DrawOnCanvas extends Application {

    @Override
    public void start(Stage primaryStage) {

        Canvas canvas = new Canvas(400, 400);
        final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
        initDraw(graphicsContext);

        canvas.addEventHandler(MouseEvent.MOUSE_PRESSED,
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.beginPath();
                graphicsContext.moveTo(event.getX(), event.getY());
                graphicsContext.stroke();
            }
        });

        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED,
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                graphicsContext.lineTo(event.getX(), event.getY());
                graphicsContext.stroke();
            }
        });

        canvas.addEventHandler(MouseEvent.MOUSE_RELEASED,
                new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {

            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(canvas);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setTitle("Paint");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initDraw(GraphicsContext gc){
        double canvasWidth = gc.getCanvas().getWidth();
        double canvasHeight = gc.getCanvas().getHeight();

        gc.setFill(Color.LIGHTGRAY);
        gc.setStroke(Color.BLACK);
        gc.setLineWidth(5);

        gc.fill();
        gc.strokeRect(
                0,              //x of the upper left corner
                0,              //y of the upper left corner
                canvasWidth,    //width of the rectangle
                canvasHeight);  //height of the rectangle

        gc.setFill(Color.RED);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(1);
    }

    public static void main(String... args) {
        launch(args);
    }

}


Handling objects and arrays simply in this tagging library I have written this little tagging module to make it easier to generate small html snippets on the fly. The examples below show how this make things a bit easier. My question is about the handling of tags that contain either a single element like text or a list of other elements, like the tr element in the second example. At the moment, the code has to jump though some unpythonic loops to handle the different cases. How do I write code that handles either a single thing or a list of those things with one function in an elegant way?

""" Supplies some utilities for creating html documents manually

>>> print(h1('test'))

test

>>> print(table([tr([td('d1'), td('d2')]), tr()]))

d1

d2

"""
from __future__ import print_function

class tag:
    """ represents an html tag - specifically used to create outputs for web pages

    Basic usage - create a "test" tag:

    >>> print(tag('test'))
    <test />

    Attributes can be specified as a dictionary

    >>> print(tag('test', attributes={'prop': 'value'}))
    <test prop='value' />

    The real benefit - tags can be nested, allowing the python interpreter to track closing tags:

    >>> print(tag('test', tag('inner')))
    <test>
    <inner />
    </test>
    """
    def __init__(self, name, contents=[], attributes={}):
        self.name = name
        self.contents = contents
        self.attributes = attributes
    def __str__(self):
        tagcontents = self.name
        if len(self.attributes) > 0:
            attrstring = " ".join("%s='%s'" % kv for kv in self.attributes.items())
            tagcontents += " " + attrstring

        if self.contents:
            if hasattr(self.contents, '__iter__') and not hasattr(self.contents, 'strip'):
                contentstring = "\n".join(str(i) for i in self.contents)
            else:
                contentstring = str(self.contents)
            return "<%s>\n%s\n</%s>" % (tagcontents, contentstring, self.name)
        else:
            return "<" + tagcontents + " />"
    def __repr__(self):
        return "tag(%s, contents=%s, attributes=%s)" % (self.name, self.contents, self.attributes)

def namedtag(t):
    """ create a named tag class - useful for standard html tags

    >>> mytag = namedtag('mytag')
    >>> print(mytag())
    <mytag />

    """
    class n(tag):
        def __init__(self, contents=[], attributes={}):
            tag.__init__(self, t, contents, attributes)
    return n

h1, h2, p, table, td, th, tr, a = (namedtag(t) for t in ("h1", "h2", "p", "table", "td", "th", "tr", "a"))

The solution is to have contents always be a list. If we don't want to impose this onto the caller of the constructor, we have to use a variable number of arguments:

def __init__(self, name, *contents, **attrs):
   ...

Now the functions can be called as table(tr(td('d1'), td('d2')), tr()) or more generally:

foo("name", child1, child2, ... attr1=value, attr2=value, ...)

Then inside the function, contents will be a tuple and attrs a dictionary.

Otherwise, I find your inappropriate usage of OOP unnecessary. For example, the class n does not really add value, and violates the Liskov Substitution Principle – the constructor signature is incompatible with the parent class. Instead, use closures to provide a default argument:

def namedtag(name):
    return lambda *contents, **kws: tag(name, *contents, **kws)


Unit testing IValueConverter I am just starting to implement unit testing into my project and familiarizing myself with NUnit.  I have added unit tests for encryption/decryption methods that I have implemented, and am looking for more things to start testing for in my existing code before moving forward.

The most basic classes that I have are my IValueConverters, so I thought it would be a good place to start.

Here is my first test:

[TestFixture]
public class ConverterUnitTest
{
    [TestCase]
    public void BooleanToVisibilityConverterTest()
    {
        var btvConverter = new BooleanToVisibilityConverter();

        Assert.That(btvConverter.Convert(true, typeof(Visibility), null, "en-us").Equals(Visibility.Visible));
        Assert.That(btvConverter.Convert(false, typeof(Visibility), null, "en-us").Equals(Visibility.Collapsed));
    }
}

As you can see, this test is just ensuring that true returns Visibility.Visible and false returns Visibility.Collapsed.  What I am wondering is, does it make sense to have multiple Asserts in one test, or should I split them up into multiple tests even though they are both testing the same converter? Also, is it a good practice to test converters?

This is a good unit test. It may seem like a trivial case to test a boolean response, but wrapping this in a test ensures that you always get the correct response. What if you decide to refactor the internals of BooleanToVisibilityConverter down the road? With this test, you can always be confident that it's behaving correctly.

To me, the two assertions look like they belong together. As a matter of style, you could split the test up so that you have two tests with a straight AAA (Arrange, Act, Assert) pattern - one for true, one for false. In my opinion, that would be a little excessive. I like a test that looks like this because it is clear and quick.

If you were writing a test of a converter that had many possible outputs and multiple input conditions (for example), then you definitely should consider splitting it up and testing each condition separately. For now, you're on the right track.


Complexity Of Determining Tree is balanced? boolean isBalance(Node root) {
    if (root == null )
        return true;
    return Math.abs(getHeight(root.left)-getHeight(root.right)) <=1;
}

int getHeight(Node N) {
    int L = 0;
    int R = 0;
    if (N.L!=null) L = getHeight(N.L);
    if (N.R!=null) R = getHeight(N.R);
    return 1 + Max(L,R);
}

I believe that the run time of my algorithm is O(N); But one of my friend told this runs for O(N^2);

My question is whether I am wrong or right since I believe I visit each node once. SO for that its O(N)...

Your getHeight method could be simpler (and more correct) if it was handling the null case.

int getHeight(Node N) {
    if (N==null) return 0
    return 1 + Max(getHeight(N.L),getHeight(N.R));
}

Also, I think you should have a read at this quite similar question.


get-release npm module Solved, question with improved code
I've created a simple npm module and CLI program to get the latest GitHub and Bitbucket release from their APIs using Node.js. Please tell me if there's anything to improve!
Module code:
#!/usr/bin/env node
const fetch = require("node-fetch");

/**
 * @param {string} string
 * @return {string}
 */
const normalize = (string) => {
    try {
        return string.toUpperCase().trim()
    } catch (e) {
        return string
    }
}

/**
 * @param {string} provider
 * @param {string} user
 * @param {string} repo
 * @param {string} part
 */
module.exports.getRelease = async ({provider, user, repo, part = ""}) => {
    if (normalize(provider) === normalize("github")) {
        let json = (await (await fetch(`https://api.github.com/repos/${user}/${repo}/releases/latest`)).json())
        if (json.message === "Not Found") throw "Invalid repository"
        if (!("assets" in json)) throw "Rate limit exceeded"
        let browser_download_urls = json.assets.map(asset => asset.browser_download_url)
        return browser_download_urls.filter(url => url.includes(part))
    } else if (normalize(provider) === normalize("bitbucket")) {
        let json = (await (await fetch(`https://api.bitbucket.org/2.0/repositories/${user}/${repo}/downloads/`)).json())
        if (json.type === "error") throw "Invalid repository"
        let links = json.values.map(value => value.links.self.href)
        return links.filter(url => url.includes(part))
    } else {
        throw "Invalid provider"
    }
}

const usage = _ => {
    console.log(
        `Usage: get-release (github|bitbucket) user repo [partofreleasefile]
   Ex: get-release github phhusson treble_experimentations
       get-release github phhusson treble_experimentations arm64-ab-gapps
       get-release bitbucket JesusFreke smali
       get-release bitbucket JesusFreke smali baksmali`
    )
    process.exit(1)
}

// If via CLI
if (require.main === module) {
    let args = process.argv.slice(2)
    if (args.length !== 3 && args.length !== 4) {
        usage()
    }
    module.exports.getRelease({
        provider: args[0],
        user: args[1],
        repo: args[2],
        part: args[3]
    }).then(result => {
        if (result.length !== 1) {
            console.log(result)
        } else {
            console.log(result[0])
        }
    }).catch(error => {
        console.log(error)
        usage()
        process.exit(1)
    })
}

Called using:
const { getRelease } = require("get-release")
;(async _ => {
  let url = await getRelease(
      {
          provider: "github",
          user: "phhusson",
          repo: "treble_experimentations",
          part: "arm64-ab-gapps"
      }
  )
  console.log(url[0])
})()

Consider using a hashmap of provider -> process. This will enable you to register new providers with relative ease.
async function githubRelease({user, repo, part = ""}) {
  let json = (await (await fetch(`https://api.github.com/repos/${user}/${repo}/releases/latest`)).json())
  if (json.message === "Not Found") throw "Invalid repository"
  if (!("assets" in json)) throw "Rate limit exceeded"
  let browser_download_urls = json.assets.map(asset => asset.browser_download_url)
  return browser_download_urls.filter(url => url.includes(part))
}

It will then be mapped inside the getRelease function as follows:
module.exports.getRelease = async ({provider, user, repo, part = ""}) => {
    if !(providerMethods[normalise(provider)]) {
        throw "Invalid provider"
    }
    return providerMethods[normalise(provider)](user, repo, part)
}

where providerMethods would be:
let providerMethods = {
    normalise("github"): githubReleases
}

This will enable users of your module to register new (or private) registry providers. They can add a new provider to the providerMethods object (gitlab etc) and don't have to wait for you to update the library first for supporting any extra providers (you can add providers if popular).
The await (await fetch()).json() can be extracted to another function. Although, I'd prefer using the promise.then(r => r.json()).catch() chain over multiple awaits, it is entirely dependent on your comfort with the language.


Simple prime number search with trial division I made a primality tester with trial division. I'm trying to make it as fast as possible and have reached the point now where I'm out of ideas.

I use the generator approach and not lists because I found out that it's awfully slow to generate and checklists for big ranges.

Does someone have ideas on how to improve the is_prime_td() and seeker() functions? I left some comments in the code to explain why I did it like this.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
    Made for Python 2.7.x
    See __main__ block at the end of this
    script to change the range to be searched.
'''

from math import sqrt as math_sqrt

def is_prime_td(num):
    ''' Test if a number is a prime with Trial Division.

        num: The number to be tested.

        Returns True if num is a prime and False if not.
    '''
    # No prime if smaller than 2
    if num < 2:
        return False

    # 2 is the only even prime
    if num == 2:
        return True

    # No prime if if num can be divided by 2 w/o a remainder except 2 itself
    if num % 2 == 0:
        return False

    # Check if num is divisible by any odd number (except 1) up two
    # ceil'ed square root of num. I didn't want to call math.ceil()
    # so i added just "+ 1"
    i = 3
    while i <= int(math_sqrt(num) + 1):
        # No prime if if num can be divided by i w/o a remainder
        if num % i == 0:
            return False
        # Go test with the next odd divisor
        i += 2

    # It's a prime if not proven false until here
    return True

def seeker(num_start, num_end):
    ''' Search for primes from and including num_start to num_end.
        Uses 'is_prime_td()'.
    '''
    # The smallest prime number is two. So, always skip if num's < 2.
    # We could add this check also to the loop below where we Increment
    # accordingly, but this would just add a useless extra check each
    # iteration.
    if num_start >= 2:
        num = num_start
    else:
        num = 2

    try:
        while num <= num_end:
            if is_prime_td(num):
                yield num
            # Since there are no even primes except 2, we only want to
            # test odd numbers in the loop. Increment accordingly so we never
            # test even numbers and thus saving some time.
            if num % 2 == 0:
                num += 1
            else:
                num += 2
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    # Define the range to be searched here.
    num_start = 0
    num_end   = 100

    # Print only positive findings.
    for num in seeker(num_start, num_end):
        print num

Instead of doing this you should instead use a sieve, where you filter the output. It would make the code much simpler, and would make it much faster.

Your comments are useless at best. If you know two languages it'd not make sense to say the same thing in both. Which is what you are doing here. Instead what you want to use comments for, is for high-level overviews of your code.

Say you create a primality test which is heavily optimized, you would want to put a comment on the hard to read parts. Such as your sqrt part.

To improve the actual code, I'd:

Remove unneeded comment.
Change the while to not square root num each iteration.
Change the code to use the less accurate ** operator, rather than math.sqrt. You're using int and adding by 1 anyway, so it won't make a difference.
Change seeker to yeild 2 if it's within the domain.
Change seeker to use a for loop, to simplify the code. As with the above you don't need to increment by one ever.
Move the keyboard interrupt code out of the function, into the main. As functions are meant to do one thing, not two.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Made for Python 2.7.x
See __main__ block at the end of this
script to change the range to be searched.
"""

def is_prime(num):
    """
    Test if a number is a prime with Trial Division.

    num: The number to be tested.
    Returns True if num is a prime and False if not.
    """

    if num < 2:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False

    # Check if number is divisible by any odd number,
    # from one to the square root of the number.
    # as one of a or b will be in this range,
    # for all a and b that are `a * b = num`.
    for i in range(3, int(num ** 0.5) + 2, 2):
        if num % i == 0:
            return False
    return True

def seeker(num_start, num_end):
    """
    Search for primes from and including num_start to num_end.
    Uses 'is_prime_td()'.
    """
    # Force `num_start` to be odd with xor, ^. And go up in twos.
    if num_start <= 2 <= num_end:
        yield 2
    for i in range(max(3, num_start ^ 1), num_end + 1, 2):
        if is_prime_td(num):
            yield num

if __name__ == '__main__':
    num_start = 0
    num_end   = 100
    try:
        for num in seeker(num_start, num_end):
            print num
    except KeyboardInterupt:
        pass


Sequence of numbers which follow a rule I have a sequence of numbers: 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, 7, 4,... I have to guess the rule which the sequence follow and to:

Compute the sum of all prime numbers smaller than n
Find how many times the digit k appears in the element of the sequence
The number on the position p in the sequence.

Input:
n, k, p

I have written the next code: it serves it's purpose, but I would like you to give me some tips on code style and performance(and I am thinking specifically to speed).

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

int prime(int n)
{
    if(n < 2) return 0;
    if(n == 2) return 1;
    if(n % 2 == 0) return 0;
    int i;
    for(i = 3; i <= sqrt(n); i += 2)
    {
        if(n % i == 0)
            return 0;
    }
    return 1;
}

int main()
{
    int n;
    int p;
    int k;
    scanf( "%d", &n );
    scanf( "%d", &k );
    scanf( "%d", &p );

    int primeSumPerSubSequence = 128;
    int nAux = n;
    int primeSum = 0;
    int subSequences = 0;

    if( n > 60 )
        subSequences = n / 60;
    if( n > 60 )
    {
        nAux = n % 60;
        primeSum = primeSum + primeSumPerSubSequence * subSequences;
    }

    int i = 2;
    int firstNumber = 1;
    int secondNumber = 2;
    if( !nAux ) secondNumber = 0;
    int thirdNumber = 3;
    int kFound = 0;

    switch( k )
    {
        case 0: kFound = 4 * subSequences;break;
        case 1: kFound = 8 * subSequences;break;
        case 2: kFound = 4 * subSequences;break;
        case 3: kFound = 8 * subSequences;break;
        case 4: kFound = 4 * subSequences;break;
        case 5: kFound = 8 * subSequences;break;
        case 6: kFound = 4 * subSequences;break;
        case 7: kFound = 8 * subSequences;break;
        case 8: kFound = 4 * subSequences;break;
        case 9: kFound = 8 * subSequences;break;
    }

    if(( kFound == 1 ) || ( kFound == 2 )) kFound++;
    int pNumber = -1;
    if( !p ) pNumber = 0;
    else if( p % 60 == 0) pNumber = 1;
    else if( p > 60 ) p %= 60;

    while( i <= nAux )
    {
        if( nAux && prime( secondNumber ) )
        {
            primeSum += secondNumber;
        }
        if(( i == p ) && ( pNumber != 1)) pNumber = secondNumber;
        firstNumber = secondNumber;
        secondNumber = thirdNumber;
        thirdNumber = firstNumber + secondNumber;
        if( thirdNumber > 9 )
            thirdNumber %= 10;
        if(( secondNumber == k ) && ( i < n )) kFound++;
        i++;
    }

    firstNumber = 1;
    secondNumber = 2;
    thirdNumber = 3;

    if( pNumber == -1 )
    {
        for( i = 3; i <= p; i++ )
        {
            firstNumber = secondNumber;
            secondNumber = thirdNumber;
            thirdNumber = firstNumber + secondNumber;
            if( thirdNumber > 9 )
                thirdNumber %= 10;
            if( i == p ) pNumber = secondNumber;
        }
    }

    if( pNumber == -1) pNumber = 0;

    printf( "\n%d", primeSum );
    printf( "\n%d", kFound );
    printf( "\n%d", pNumber );

    return 0;
}

Should I edit the question and add how I thought the algorithm?
Thank you and please excuse my bad english.

This is a rare case where the comment is absolutely necessary, along the lines of

/* The sequence is Fibonacci numbers modulo 10. It is periodic with a
   period of 60. Each even digits appears for 4 times, and each odd
   digit for 8 times, per period. The sum of primes per period is 128.

           Reviewer's note: are you sure? Looks like you consider 1 as prime.

   To get the desired results, compute the number of entire periods,
   and process the last incomplete part separately. */

Rename subSequences toperiods
Collapse the switch to

kFound = ((k & 0x01)? 8: 4) * periods;

I don't see how kFound can be 1 or 2, so

if(( kFound == 1 ) || ( kFound == 2 )) kFound++;

seems to serve no purpose. Correct me if I am wrong.
Working with the incomplete part should be split into functions. Precompute the period once, and pass it to separate functions (computing sum of primes, counting occurrences, and returning number at position).


Slicing a string into three pieces, and also controlling/manipulating through loops # Filename: P05_Strings.py
# Author: Joseph Chua
# Date: 10/18/2016
# Purpose: Slicing a string into THREE pieces.
# Other: http://repeatercreeper.me

#=======================================================================
# Logic - Assignment #1
#=======================================================================
userInp = input("Enter Here: ")

while (len(userInp) % 3) != 0: # Keep adding whitespace until divisible by 3
    userInp += " " # Concatenation of whitespace

def split(str, num):
    return [ str[i:i+num] for i in range(0, len(str), num) ]

print ("Original String: " + userInp)
# Creates 3 variables to store each slices. Sliced using 'split' function.
slice1, slice2, slice3 = split(userInp, int(len(userInp) / 3))

# Prints the results in THREE slices.
print("Slice #1: " + slice1)
print("Slice #2: " + slice2)
print("Slice #3: " + slice3)

#=======================================================================
# Logic - Assignment #2
#=======================================================================
quote = input("Enter a quote: ")
i = 0

if (len(quote.split(' '))) >= 2:
    splitQuote = quote.split(' ')
    while i != 3:
        if i == 0:
            print("Split: ", splitQuote)
        elif i == 1:
            ccString = ""
            for j in range(0, len(splitQuote)):
                ccString += splitQuote[j]
            print("Concatinate: ", ccString)
        else:
            charUse = ","
            print("Join: ", charUse.join(splitQuote))

        i += 1
else:
    print("You entered an invalid quote!")

I'm mostly looking at my Assignment #2. It looks like it has plenty of room for improvements, but if you find something to improve on Assignment #1 to make it more concise that would be amazing.

So for Assignment #2 objective was as follows (copy & paste directly from the book):

  Activity 2: Write the Python code to split, join, and concatenate a string.

  a)  Allow the user to input a string (a famous quote) that will be manipulated within a While loop.a.   Print the string that was entered.

  b)    Within a WHILE loop that iterates three (3) times, manipulate the string.

  If the loop iteration is the first time, split the quote into separate words and print the result of the split operation.
  If the loop iteration is the second time, concatenate the split string (list of words) in an order you choose and print the result of the concatenation operation.
  If the loop iteration is the third time, join the split string content (list of words) with a character(s) of your choosing and print the result of the join operation.

I concur with @200_success, looping three times and doing something different every loop is totally pointless. Regardless, if I had to use a loop for it, I would use for i in range(3) and not a while loop to do it.
I do not agree with your if (len(quote.split(' '))) >= 2:. For me this is a totally legit quote:

Awesome!
-- Barney Stinson, How I Met Your Mother

Also, the split is done twice here, at least do it before the check.
And actually, all of your code does not care if the length is 1 or even 0:
# Length 1
>>> "Awesome!".split()
["Awesome!"]
>>> " ".join(["Awesome!"])
"Awesome!"
#Length 0
>>> "".split()
[]
>>> " ".join([])
''

Note that str.split splits on white-space by default, so there is no need to do split(" "), unless you specifically do not want to also split on newlines. Incidentally, I would consider this a bug in your code. The quote Awesome\nSuit! would be recognized as one word by your code.
The only part where it is not obvious that a length 0 quote is fine is
ccString = ""
for j in range(0, len(splitQuote)):
     ccString += splitQuote[j]
print("Concatinate: ", ccString)

But range(0, 0) returns [] and a for loop over an empty list does nothing. So this is also safe. And I would suggest a different approach here, anyways.
This code is equivalent to print("Concatinate: ", "".join(splitQuote). But that's really boring and just a special case of the next loop, with an empty character. I think using random.sample would be slightly more interesting:
import random
...
print("Concatinate: ", "".join(random.sample(splitQuote, len(splitQuote))`

To improve maintainability and readability, I would put the two assignments into separate functions, where the docstring describes what the assignment was. Then I would add:
if __name__ == '__main__':
    assignment1()
    assignment2()

Last, but not least, you should have a look at PEP8, Python's official style-guide. One thing it recommends is using lower_case for variables (and functions) and not camelCase.


Generating permutations with repetitions of string I have written the below code which generates all possible permutations with repetitions of a string.

I want to make this program shorter and much faster, but I don't know how to do that.

Imports System.Text

Public Class Form1

    Private blkRpt As Integer
    Private perm As Double

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim textlen As Double = TextBox1.Text.Length
        Dim rtb As Double = TextBox2.Text
        perm = textlen ^ rtb
        permutate()
    End Sub

    Private Sub permutate()

        For a As Integer = 0 To 1 Step 0
            Dim s As String = TextBox1.Text
            Dim len As Integer = TextBox2.Text
            Dim r As New Random
            Dim sb As New StringBuilder

            For i As Integer = 1 To len
                Dim idx As Integer = r.Next(0, s.Length)
                sb.Append(s.Substring(idx, 1))
            Next

            Dim sring As String = sb.ToString

            If RichTextBox1.Text.Contains(sb.ToString) Then
                blkRpt = blkRpt + 1
            Else
                RichTextBox1.AppendText(sring & vbNewLine)
           End If

           Dim s1 As String = TextBox1.Text
           Dim len1 As Integer = TextBox2.Text
           Dim r1 As New Random
           Dim sb1 As New StringBuilder

           For i As Integer = 1 To len1
               Dim idx1 As Integer = r1.Next(0, s1.Length)
               sb1.Append(s1.Substring(idx1, 1))
           Next

           Dim sring1 As String = sb1.ToString

           If RichTextBox1.Text.Contains(sb1.ToString) Then
                blkRpt = blkRpt + 1
           Else
                RichTextBox1.AppendText(sring1 & vbNewLine)
           End If

           Dim s2 As String = TextBox1.Text
           Dim len2 As Integer = TextBox2.Text
           Dim r2 As New Random
           Dim sb2 As New StringBuilder

           For i As Integer = 1 To len2
               Dim idx2 As Integer = r2.Next(0, s2.Length)
               sb2.Append(s2.Substring(idx2, 1))
           Next

           Dim sring2 As String = sb2.ToString

           If RichTextBox1.Text.Contains(sb2.ToString) Then
               blkRpt = blkRpt + 1
           Else
               RichTextBox1.AppendText(sring2 & vbNewLine)
           End If

           Dim s21 As String = TextBox1.Text
           Dim len21 As Integer = TextBox2.Text
           Dim r21 As New Random
           Dim sb21 As New StringBuilder

           For i As Integer = 1 To len1
               Dim idx21 As Integer = r21.Next(0, s2.Length)
               sb2.Append(s2.Substring(idx21, 1))
           Next

           Dim sring21 As String = sb21.ToString

           If RichTextBox1.Text.Contains(sb21.ToString) Then
               blkRpt = blkRpt + 1
           Else
               RichTextBox1.AppendText(sring21 & vbNewLine)
           End If

           If RichTextBox1.Lines.Length - 1 >= perm Then
               Exit For
           End If

           Label6.Text = blkRpt.ToString
           Label5.Text = RichTextBox1.Lines.Length - 1 & "/" & perm
       Next
    End Sub
End Class

I'm not going to rewrite this code right now, but I can highlight a few points:

Naming.

Identifiers should have a meaningful name.
Disemvoweling is evil.
Adding a 1 after an identically-named variable is bad.
Adding a 2 after an identically-named variable is terrible.
Adding 21 instead of a 3 after an identically-named variable is careless.
If you think you need the same variable 3 times in one function, something's not right. Right? I think Tim's comment on your original post has a huge golden clue on that matter.

UI is for presentation. Logic that isn't presentation logic shouldn't need to know there's a UI involved.

Decoupling your logic from the UI helps making your code testable.
Learn to pass parameters into your functions.
Knowing exactly what's involved is very hard to tell, we need to puzzle out the whole thing just to figure out what RichTextBox1 is supposed to contain; your naming isn't helping.

Implicit string-to-numeric conversion is ugly and bug-prone, especially with user input.

Assume the user is a 3 year old that could click anywhere and enter anything in any TextBox.

You have many, many, many things to worry about before you can think of improving performance.

Using Random isn't making it any faster. I don't think Random is warranted here.
Access the UI once to get the values you need, once to write the values you've computed; pass the values as parameters (I said that before, I'll say it again - here, done).
It's not the job of a permutation function to access the UI. Ever. Take values in (as parameters), do your thing, spit out a result (as a return value).
perm (bad name) shouldn't be an instance variable. Not even a parameter. It's only meaningful within the permutate function: that's where it belongs.

That's all folks! I might edit this post later with actual code.


Check string is permutation of palindrome I assume there can be space in between and I have ignored that. Also, there will be only lower case characters in the string.

My logic: There can be only one occurrence of odd number of character in palindrome string.

#include <iostream>
#include <algorithm>
#include <unordered_map>

using std::cout;
using std::endl;

int main(int argc, const char * argv[]) {

    char arr[] = "tact coa";

    std::unordered_map<char, int> m;

    size_t len = strlen(arr);

    for (int i = 0; i<len; i++) {

        if(arr[i] == ' ') continue; //ignoring space

        if(m.find(arr[i]) == m.end())
        {
             m[arr[i]] = 1;

        }
        else{
            m[arr[i]]++;
        }
    }

    int count = 0;

    for (int i = 0; i<len; i++) {

        if((m[arr[i]] % 2) == 1)count++;

    }
    if(count > 1) {cout<<"Not Palindrom"<<endl;}
    else {cout<<"Palindrom"<<endl;}

    return 0;
}

I would separate the algorithm from the main so that you can reuse your algorithm later.

The idea of using a hash-table based unordered_map is going into the right direction. However...

if(m.find(arr[i]) == m.end())
{
     m[arr[i]] = 1;
}

you don't need that initialization; you can think that each integer key is zero by default.

What comes to this:

for (int i = 0; i<len; i++) {
    if((m[arr[i]] % 2) == 1)count++;
}

In the loop, you can check whether the counter gets the value of 2, and exit as soon as you detect this, which adds to the efficiency of the routine.

All in all, I had this in mind:

bool is_palindrome_permutation(char* p)
{
    std::unordered_map<char, size_t> m;

    while (*p)
    {
        if (std::isalpha(*p))
        {
            m[*p]++;
        }

        p++;
    }

    size_t count = 0;

    for (auto& p : m)
    {
        if (p.second % 2 == 1)
        {
            if (++count == 2)
            {
                return false;
            }
        }
    }

    return true;
}

Hope that helps.

Edit 1

As additional fun, you can consider having a template, which allows you to abstract away the actual sequence implementation:

template<typename ForwardIter>
bool is_palindrome_permutation(ForwardIter begin, ForwardIter end)
{
    using value_type = typename std::iterator_traits<ForwardIter>::value_type;
    std::unordered_map<value_type, size_t> m;

    while (begin != end && *begin) // *begin: a dirty hack for correctness
    {                              // on zero-terminated C strings.
        m[*begin]++;
        ++begin;
    }

    size_t count = 0;

    for (auto& pair : m)
    {
        if (pair.second % 2 == 1)
        {
            if (++count == 2)
            {
                return false;
            }
        }
    }

    return true;
}

template<typename Sequence>
bool is_palindrome_permutation(const Sequence& seq)
{
    return is_palindrome_permutation(std::begin(seq), std::end(seq));
}

int main() {
    char str[] = "tacoota";
    cout << "Palindrome permutation: "
         << std::boolalpha
         << is_palindrome_permutation(str,
                                      str + sizeof(str) / sizeof(str[0]))
         << endl;

    std::string str2{"tacoota"};
    cout << "Palindrome permutation: "
         << is_palindrome_permutation(str2)
         << endl;

    std::vector<char> vec;
    std::copy(str2.begin(), str2.end(), std::back_inserter(vec));
    cout << "Palindrome permutation: "
         << is_palindrome_permutation(vec)
         << endl;
    return 0;
}


Utilizing HTML5 Canvas to apply color theme to .png icons Because we have a mix of both icons for core items and .png icons for custom items, I've developed an easy way to theme them (alter the color) all of them easily that will work across all browsers.

Prior to this, I tried CSS and SVG options and they just weren't as simple as this option (but probably less overhead of course). I have to call this after load because of course can't start any canvas work until the items actually hit the DOM and they're parsing through via PHP. There's about 50 of these icons max, more like 25 of them to iterate thought on 90% of users.

Any suggestions on how to streamline this or possibly simplify it? Also I would have posted a test (fiddle or bin) but canvas has a strict cross domain policy.

Update: Found an image on the jsfiddle shell I can use for an example that adheres to the cross-domain policy.

JSFiddle: http://jsfiddle.net/d3c0y/6BSsy/

function changeColor(imgObject, imgColor) {
    // create hidden canvas
    var canvas = document.createElement("canvas");
    canvas.width = 40;
    canvas.height = 40;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgObject, 0, 0, 40, 40);

    var map = ctx.getImageData(0, 0, 40, 40);
    var imdata = map.data;

    // convert image to grayscale first
    var r, g, b, avg;
    for (var p = 0, len = imdata.length; p < len; p += 4) {
        r = imdata[p]
        g = imdata[p + 1];
        b = imdata[p + 2];

        avg = Math.floor((r + g + b) / 3);

        imdata[p] = imdata[p + 1] = imdata[p + 2] = avg;
    }

    ctx.putImageData(map, 0, 0);

    // overlay using source-atop to follow transparency
    ctx.globalCompositeOperation = "source-atop"
    ctx.globalAlpha = 0.3;
    ctx.fillStyle = imgColor;
    ctx.fillRect(0, 0, 40, 40);

    // replace image source with canvas data
    return canvas.toDataURL("image/png", 1);
}

jQuery(window).load(function () {
    $('.custom-module').each($.proxy(function () {
        $(this).attr('src', changeColor(this, '#33CC33'));
    }), this).promise().done(function () {
        $('.module-li').removeClass('hidden');
    });
});

Pretty nice overall. You're missing a semi-colon or two, but otherwise it's a nice solution.

The only real criticism I have are the "magic numbers" in there, like the 40x40 size that's hardcoded everywhere. Technically, you could derive the canvas dimension from the image, or pass the width/height as arguments. (Incidentally, setting a canvas's size will also clear its contents, which is helpful if there's one shared canvas that needs to be cleared between uses.) In either case, though, you'd have to get rid of the hardcoded "40".

Optimization-wise, the only addition I've made is to simply skip pixels with a zero alpha component; if they're transparent anyway, there's no need to bother with them.

Other than that, I've just broken the code into a couple of functions; nothing special (Note, haven't tested this yet.)

var changeIconColor = (function () {
  var canvas  = document.createElement("canvas"), // shared instance
      context = canvas.getContext("2d");

  // only place the dimensions are hardcoded
  // everything else just references canvas.width/canvas.height
  canvas.width  = 40;
  canvas.height = 40;

  function desaturate() {
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height),
        pixels    = imageData.data,
        i, l, r, g, b, a, average;

    for(i = 0, l = pixels.length ; i < l ; i += 4) {
      a = pixels[i + 3];
      if( a === 0 ) { continue; } // skip if pixel is transparent

      r = pixels[i];
      g = pixels[i + 1];
      b = pixels[i + 2];

      average = (r + g + b) / 3 >>> 0; // quick floor
      pixels[i] = pixels[i + 1] = pixels[i + 2] = average;
    }

    context.putImageData(imageData, 0, 0);
  }

  function colorize(color) {
    context.globalCompositeOperation = "source-atop";
    context.globalAlpha = 0.3; // you may want to make this an argument
    context.fillStyle   = color;
    context.fillRect(0, 0, canvas.width, canvas.height);
    // reset
    context.globalCompositeOperation = "source-over";
    context.globalAlpha = 1.0;
  }

  return function (iconElement, color) {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(iconElement, 0, 0, canvas.width, canvas.height);
    desaturate();
    colorize(color);
    return canvas.toDataURL("image/png", 1);
  };
}());

As for invoking it, I don't think you need the $.proxy and promise stuff. I would think it'd be enough to just do

$('.custom-module').each(function () {
    this.src = changeIconColor(this, '#33CC33');
});
$('.module-li').removeClass('hidden');


Clean way to get size of directory I'm working on a Unix machine where I can't use more than vanilla Perl, and I'm using Perl5.8.  This script exits with a 1 if the current directory size is smaller than 1 GB (the character after -d is a literal "tab" character).

my $du = `du --si | tail -1 | cut -d"   " -f1`;
chomp $du;
if (substr($du, -1) ne "G") {
    exit 1;
}
exit 0;

This is gross, but I know the data is in du --si so I can write it in 30 seconds.  Is there a cleaner, more robust way?

I agree with @rolfl that this would be much simpler as a one-line shell pipeline.  The -s option to du makes it produce a total.  awk is a good tool to use for processing multi-column text.

du -s --si | awk '$1 ~ /G/ { exit 1 }'

However, the --si option seems to be a non-portable GNU extension.  A more portable version would look at the number of 512-byte blocks.  The magic number 1953125 is \$\dfrac{10^9}{512}\$.

du -s | awk '$1 < 1953125 { exit 1 }'

The second version also works even if the total is in the terabyte or exabyte range.

There is an inefficiency, though: you should be able to exit early as soon as you find that the total exceeds 1 GB.  For that, you would go back to Perl, but with a proper Perl program instead of a wrapper around du.

use File::Find;
use strict;

my $sum = 0;
my %seen_inodes;
find(sub {
    my ($inode, $blocks) = (stat)[1, 12] or die "${File::Find::name}: $!";

    # Do not double-count hard links
    if (!$seen_inodes{$inode}) {
        $seen_inodes{$inode} = 1;
        $sum += 512 * $blocks;
        exit 0 if $sum >= 1_000_000_000;
    }
}, ".");
exit 1;


Simple Bash backup script - follow-up As a follow up to a previous question, linked here, I have revised the code and developed what I believe to be a better solution.

In summary, the script should backup all files in a particular directory, and assign them to a particular zip file based on their modification dates. This should only occur for files modified yesterday and older, and skip files with the ".zip" extension.

Please let me know if their are any improvements that you would make? From testing the code, it has been working with no issues:

#!/bin/bash

yestdayend=$(date --date="yesterday" +"%Y-%m-%d 23:59:59")

path=/path/to/dir
filelist=$(find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend")

for file in $filelist
do
        moddate=$(stat -c %y $file | cut -d " " -f 1)
        if zip -rv $path/"logbackup-"$moddate.zip $file; then
           rm $file
        fi
done

Saving the output of find in a variable and looping over it is not a good idea in general: filenames with white-space (space, tab, newline) will be split, so the loop will not work on them.

It would be a little bit better to use a while loop instead:

find ... | while read file
do
        # ...
done

But this is still not great, as it won't protect you from newlines.
But for your use case, it might be good enough.
For a more robust solution,
see this other post.

The \( ... \) is pointless here:

find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend"

This is the same, but shorter and simpler:

find $path -maxdepth 1 ! -name "*.zip" -type f ! -newermt "$yestdayend"

It's a bit odd to quote "logbackup-" here:

if zip -rv $path/"logbackup-"$moddate.zip $file; then

Literal strings like that don't need quoting in Bash.
On the other hand, it would be good to quote $path:

if zip -rv "$path"/logbackup-$moddate.zip $file; then


Unix tail in haskell I am trying to write a simple version of the unix tail utility in haskell to improve my understanding of monads. Here is what I have now. I am pretty sure that this is not quite "Haskell enough" yet. Can you please help me improve my code?

import System.Environment
import System.Exit
import Control.Monad

main = getArgs >>= (parse' (10, [])) >>= \ (n_lines, ss) ->
        putStr $ concatMap (tailFile n_lines) ss

tailFile :: Int -> (FilePath, String) -> String
tailFile n_lines (f, c) =
    "==> " ++ f ++ " <==\n" ++
    (unlines.reverse.(take n_lines).reverse.lines) c

parse' :: (Int, [(FilePath, String)])
            -> [String]
            -> IO (Int, [(FilePath, String)])
parse' _ ("-h":_) = putStrLn "usage: " >> exit
parse' _ ("-v":_) = putStrLn "version: 0.1" >> exit
parse' (_, ss) ("-n":num:f) = parse' (read num, ss) f
parse' (n, ss) (f:fs) = do
                            contents <- readFile f
                            parse' (n, ss ++ [(f,contents)]) fs
parse' (x, ss) [] = return (x, ss)

exit = exitWith ExitSuccess
die = exitWith (ExitFailure 1)

My first approach is to map the arguments to a list of IO actions and then execute them:

import Control.Monad
import System.Environment

lastLines :: Int -> String -> [String]
lastLines n = reverse.take n.reverse.lines

printLines :: [String] -> IO ()
printLines = flip forM_ $ putStrLn

readLastLines :: Int -> FilePath -> IO [String]
readLastLines n f = readFile f >>= return . (++) ["==>" ++ f ++ "<=="] . lastLines n

argsToActions :: [String] -> [IO ()]
argsToActions ("-h":_) = [print "Usage"]
argsToActions ("-v":_) = [print "V 1.0"]
argsToActions ("-n":n:f:_) = [readLastLines (read n) f >>= printLines]
argsToActions (f:fs) = [readLastLines 10 f >>= printLines] ++ argsToActions fs
argsToActions [] = []

main :: IO ()
main = getArgs >>= sequence_ . argsToActions