Calculating a Collatz Sequence I've written a small script to calculate Collatz sequences. For background, read here about the Collatz conjecture. Largest number I've tried so far in my implementation is 93571393692802302 (which wikipedia claims is the number requiring most steps below 10e17), which needs 2091 steps. Apparently I count different from Wikipedia, as my len(collatz(93571393692802302)) is 2092 long, but I include the number itself as well as the final 1 .

A Collatz sequence takes a number, and calculates the next number in sequence as following:

If it is even, divide by two
If it is odd, triple and add one.

The Collatz Conjecture claims that all sequences created this way converge to 1. It is unproven, but it seems most mathematicians suspect it's True.

Without further ado, the code:

from typing import List

collatz_cache = {}

def _calc(number: int) -> int:
    """
    Caches this number in the collatz_cache, and returns the next in sequence.
    :param number: Integer > 1.
    :return: Integer > 0
    """
    if number % 2 == 0:
        next_number = number // 2
    else:
        next_number = number * 3 + 1
    collatz_cache[number] = next_number
    return next_number

def collatz(number: int) -> List[int]:
    """
    Returns the collatz sequence of a number.
    :param number: Integer > 0
    :return: Collatz sequence starting with number
    """
    if not isinstance(number, int):
        raise TypeError(f"Collatz sequence doesn't make sense for non-integers like {type(number).__name__}")
    if number < 1:
        raise ValueError(f"Collatz sequence not defined for {type(number).__name__}({number})")
    new_number = number
    result = [number]
    while new_number not in collatz_cache and new_number != 1:
        new_number = _calc(new_number)
        result.append(new_number)
    while result[-1] != 1:
        result.append(collatz_cache[result[-1]])
    return result

I've tried to minimize calculation time in repeated attempts by creating a mapping for each number to the next number in the sequence. First I just mapped to the full list, but that would make the dictionary a bit bigger than I really wanted.

I feel that there should be some gains to be made in the list construction, but I'm at loss as to the how.

Purpose of this code is to basically be a general library function. I want to:

Be fast
Be memory efficient with my cache
Handle multiple equal/partially overlapping sequences
Handle completely different sequences

And all of that at the same time. Any code stylistic improvements are of course welcome, but any suggestions improving the above goals without disproportional disadvantage to the others are also welcome.

I think the handling of the cache could be improved. You add to the cache in _calc, then check the cache in collatz. Why not just let _calc handle the cache? That way collatz doesn't need to know anything about how _calc is getting its results. I'd change it to something like:

def _calc2(number: int) -> int:
    if number in collatz_cache:  # Let it do the lookup
        return collatz_cache[number]

    if number % 2 == 0:
        next_number = number // 2
    else:
        next_number = number * 3 + 1

    collatz_cache[number] = next_number
    return next_number

def collatz2(number: int) -> List[int]:
    if number < 1:
        raise ValueError(f"Collatz sequence not defined for {type(number).__name__}({number})")

    results = [number]

    new_number = number
    while new_number != 1:
        new_number = _calc2(new_number)
        results.append(new_number)

    return results

I also don't think collatz really needs to do an isinstance check on number. You've said via type-hints that it only accepts integers. If you're going to go down that road, arguably every function should check what it's arguments are. I suppose protecting against a float being passed may be worth it since that will silently mess with the results, but you can only hand-hold the user so much.

I'll note though that your manual memoization isn't necessary. functools has a decorator for this:

from functools import lru_cache

@lru_cache(maxsize=int(1e6))  # This could probably be smaller
def _calc3(number: int) -> int:
    if number % 2 == 0:
        next_number = number // 2
    else:
        next_number = number * 3 + 1

    return next_number

Using a dirty timeit timing using seeded random numbers, I found that all three versions perform nearly identically for me:

from timeit import timeit
from random import randint, seed

timeit(lambda: collatz(randint(5, 100)),
       setup=lambda: seed(12345),
       number=int(1e6))

# All take between 7 seconds for me

I used random numbers so the cache is actually getting fully tested instead of just returning the same numbers over and over. The random numbers are seeded, so the results should be reliable.

I'll note, you could also write your own bare-bones memoize decorator as well:

def memoize(f):
    cache = {}

    def wrapper(*args):
        if args in cache:
            return cache[args]

        else:
            result = f(*args)
            cache[args] = result
            return result

    return wrapper

@memoize
def tester(n, m):
    print("Called with", n, m)
    return n + m

>>>> tester(1, 3)
Called with 1 3
4

>>> tester(1, 3)
4

I'll note too though, this could be made into a generator if you wanted to generalize it:

from typing import Generator

def collatz3(number: int) -> Generator[int, None, None]:
    yield number  # To be consistent with the other functions

    new_number = number
    while new_number != 1:
        new_number = _calc3(new_number)
        yield new_number

This may prove to be more memory efficient for longer sequences, depending on how it's used. Now the whole sequence isn't required to be held in memory all at once.


Function help combining multiple vars I am very new to JS and am having a bit of a problem with making this happen.

function updateDisplay23() {

  var statElem = document.getElementById("stat_ht");

  if (statElem) {

    statElem.innerHTML = stats["ht"];

  }

}

I load all the functions from the index at the startup then call the function with:

updateDisplay23()

This works fine and loads the info to the index page as desired. The problem is I have 30 or so functions, and may add many more. This is a lot of calls, I would like to combine them all into one function call.  Someone hinted this may be possible.

Every function needs to be called to run. If you have 30 functions you need to call them all but if you want to call them only once you can do something like this:

            var callThemAll = function() {
                function1();
                function2();
                // call them all like this
            }

But there is also a 'lazy way' if I could call it like that. We create an object and these functions will become it's methods and we can iterate over them:

         var objWithFunctions = {
            myFirstFunction: function() {
                // code here
            }
            // rest of your functions
        }

        for(fn in objWithFunctions) {
            objWithFunctions[fn].call();
        }
        // all methods are being called

I wrote a full example here: http://jsbin.com/gaseti/1/

Edit:
After seeing your code(you posted it somewhere) the difference bettwen your function are just 2 strings.
You can make only one function with 2 parameters:

You can insert this into your code

            function updateDisplay(param1, param2) {

              var statElem = document.getElementById(param1);

              if (statElem) {

                statElem.innerHTML = stats[param2];

              }

            }

Call like this:

            updateDisplay("stat_ht", "ht");

Now, to call them all we could do this. Save all parameters into 2 separated arrays

var param1s = ["stat_ht","stat_ht","stat_ht"], param2s = ["ht","ht","ht"];

Call updateDisplay for each of this

            if(param1s.length == param2s.length) {
                for(var i = 0; i <= params1.length; i++) {
                    updateDisplay(param1s[i], param2s[i]);
                }
            }


Decompress files files in a directory recursively Currently I'm trying to redo this code to avoid the breaking line because of the 80 characters rule:

def decompress_all(directory_path, remove_after):
    """
    """
    try:
        if 0 in [ decompress(file_path, remove_after) \
                  for file_path in files_within(directory_path) ]:
            decompress_all(directory_path, remove_after)
        return 0
    except:
        return 1

Python version 2.6.

The docstring is empty. What is this function supposed to do? What does it return?
A bare except: is a bad idea, because it catches all exceptions, including KeyboardInterrupt and SystemExit. If you have some particular exception that you want to catch, then name it. But do you really need to catch any exceptions here? By catching exceptions you conceal information about what happened — instead of an error message and a traceback, all you get is the number 1, which tells you nothing.
The result of the recursive call to decompress_all is discarded and so is lost. If there were an exception inside the recursive call you'd never find out about it.
In POSIX, it's conventional for functions to return 0 for success and non-zero for failure. But in Python, it's conventional for functions either to return True for success and False for failure, or to return nothing for success, and raise an exception for failure.
The function calls itself with the same arguments. Why does it do this? What prevents this from recursing forever? I guess the idea here is that multiple layers of decompression might need to be undone, for example if one .zip file contains another .zip file. But I think this is not at all obvious and deserves a comment.
Instead of recursing, use a loop.

Revised code:

def decompress_all(directory_path, remove_after):
    """Repeatedly decompress all files under directory_path until no more
    files can be decompressed. The argument remove_after is passed to
    decompress.

    """
    # Decompression may extract more compressed files, so loop
    # until no more files need to be decompressed.
    while sum(decompress(filename, remove_after) == 0
              for filename in files_within(directory_path)):
        pass


Ranking and sorting on Array/List My apology, I am quite new to posting a question in this forum.

I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.

I tried doing that, code is working what it was supposed to do but it seems very ambiguous and tightly coupled, I can't even write a unit test for it.

Could someone have a look and suggest do I need to minimize and simplify this class so that I can write a Unit Test class for this.

  I have pasted main method class, If anyone wants me to paste other
  relevent classes as well so do ask me please.

Any suggestion(s)/workaround(s) would be much appreciated.

Many thanks,

public class JournalAnalyzer {
    final static int LENGTH_OF_JOURNAL = 5; //Length Journal array
    static int count = 0;
    static Integer ranking = 1;
    static Journal[] journals = new Journal[LENGTH_OF_JOURNAL];
    static ArrayList<Journal> list = new ArrayList<Journal>();
    static Object[] scoreList = new Object[LENGTH_OF_JOURNAL];
    static String journalName;
    static Double journalScore;
    static Integer journalRank;
    static Boolean journalReview;

private static void initData(Journal[] journals) {
    journals[0] = new Journal(0, "Journal A", 5.6, false);
    journals[1] = new Journal(0, "Journal B", 2.6, false);
    journals[2] = new Journal(0, "Journal C", 3.2, false);
    journals[3] = new Journal(0, "Journal D", 4.1, false);
    journals[4] = new Journal(0, "Journal E", 1.6, false);
}

private static int fillJournalList(int count, Journal[] journals,
        int LENGTH_OF_JOURNAL, ArrayList<Journal> list) {

    for (int i = 0; i < LENGTH_OF_JOURNAL; i++) {
        journalRank = new Integer(journals[i].getRank());
        journalName = new String(journals[i].getJournal());
        journalScore = new Double(journals[i].getScore());
        journalReview = new Boolean(journals[i].getIsReviewed());

        if (!journalReview) {
            Journal value = new Journal(journalRank, journalName,
                    journalScore, journalReview);
            list.add(value);
            count++;
        } else {
            continue;
        }
    }
    return count;
}

private static void GenerateRanking(Integer ranking, int count,
        ArrayList<Journal> list, Object[] scoreList) {
    Double scoreComparatorOne;
    Double scoreComparatorTwo;

    Comparator<Journal> scores = new SortScore();
    Collections.sort(list, scores);

    for (int i = 0; i < count; i++) {
        scoreComparatorOne = (list.get(i)).getScore();
        if (i == 0) {
            scoreComparatorTwo = (list.get(i)).getScore();
        } else {
            scoreComparatorTwo = (list.get(i - 1)).getScore();
        }
        if (scoreComparatorOne.equals(scoreComparatorTwo)) {
            if (ranking == 0) {
                ranking += 1;
            } else {
                ranking = ranking;
            }
        } else {
            ranking = i + 1;
        }

        (list.get(i)).setRank(ranking);
        scoreList[i] = (list.get(i));

    }
}

private static void displayJournal(int counter, Object[] scoreList) {
    JournalOutput printer = new JournalOutput();
    printer.display(count, scoreList);
    System.exit(0);
}

public static void main(String[] args) throws IOException {
    initData(journals);
    count = fillJournalList(count, journals, LENGTH_OF_JOURNAL, list);
    GenerateRanking(ranking, count, list, scoreList);
    displayJournal(count, scoreList);
}
 }

Your biggest problem is that you are using static for everything.  Change all of the static variables to instance variables, and all of the static methods (apart from main) into instance methods.  Then have your main method create an instance of JournalAnalyzer and call the (now instance) methods on that instance.

That will make the code more testable.  Another thing you need to do to improve testability is to make the methods you want to test public.


Project Euler Problem 2 in Java Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

I wrote a solution to this second problem from Project Euler, and would appreciate a review of it. Here's the code:

package Problems.Level_1;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Manish on 10/14/2015.
 * find sum of even terms of Fibonacci series whose values do not exceed four million
 */
public class Problem_2 {

    private List<Integer> generateFibonacci() {
        List<Integer> numbers = new ArrayList<>();
        int first = 1;
        int last = 2;
        numbers.add(first);
        numbers.add(last);
        int sum = 0;
        //modify for loop to limit value = 4 mil?
        //for(int i = 2; i < limit; i++)
            while(sum <= 4000000){
            sum = first + last;
            numbers.add(sum);
            first = last;
            last = sum;
        }

        return numbers;
    }

    //method to generate int array from a List of integers
    private int[] buildIntArray(List<Integer> integers) {
        int[] ints = new int[integers.size()];
        int i = 0;
        for (Integer n : integers) {
            ints[i++] = n;
        }
        return ints;
    }

    //method to calculate sum of even items in array
    private int calculateEvenSum(int[] numList){
        int result = 0;
        for(int i = 0; i < numList.length; i++) {
            if(numList[i] % 2 == 0) {
                result += numList[i];
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Problem_2 p2 = new Problem_2();

        //System.out.println("The first 10 numbers of the Fibonacci Series are: " + p2.generateFibonacci(10));
        //System.out.println("Enter the limit.");
       // int l = new Scanner(System.in).nextInt();

        List<Integer> list = p2.generateFibonacci();
        int[] numList = p2.buildIntArray(list);
        int answer = p2.calculateEvenSum(numList);

        System.out.println("The sum is: " + answer);
    }
}

Right off the bat, I get that it might not be the best idea to generate an entire Fibnoacci sequence, the sum can probably be determined without that. Then there might be things like creating and storing a List, creating and storing an array from the List, etc.

Does this solution cause too much of an unnecessary overhead?

Yes, it is unnecessary to create a sequence, then add it. Just simply add while counting up. Take a look at my question and this answer; it will simply create the sequence while adding, without even having to store the sequence, just the result and the previous numbers. It takes the advantage of the fact that every three Fibonacci numbers in the sequence is an even number, so inside the while loop, all it needs to do, is add the result, then skip 2 numbers. The code (for convenience) is down below:

public class EvenFibonacciFinder {
    private static final int MAX_NUM = 4_000_000;

    public static void main(String[] args)
    {
        long time = System.nanoTime();
        int fib1 = 1;
        int fib2 = 2;
        long sum = 0;

        while (f2 <= MAX_NUM) {
            int fib3;
            sum += fib2;
            // This skips three ahead in the sequence.
            fib3 = fib1 + fib2;
            fib1 = fib2 + fib3;
            fib2 = fib1 + fib3;
        }
        long end = System.nanoTime();
        System.out.println("Result: " + sum +
                "\nTime used for calculation in nanoseconds: " +
                (end - time));
    }
}


Get Set vs passing class at init? I have the main form with a list inside and i need to open another form and edit the list in the main. Generally i'm doing something like ...

    public class Form1 : Form
            {
                List<objectType> obj = new List<objectType>();
                private void button_EDIT_BUTTONS_Click(object sender, EventArgs e)
                {
                    EDIT_BUTTONS edit_b = new EDIT_BUTTONS(this);
                    edit_b.Show();
                }
            }
      public partial class EDIT_BUTTONS : Form
     {
        Form1 main;
        public EDIT_BUTTONS(Form1 mainP)
        {
            InitializeComponent();
            main = mainP;
        }
        button = main.obj.Find(x => x.ID == object.ID);
............................................................
        //modify button

     }

My question is to pass the main form like this only to expose the list object or i should Create setters and getters in main form ?

You should only pass the list to the second form. If you pass the entire first form you are exposing somethings that wouldn't be best, and coupling the two forms tightly.


Using static management class to control db transactions through an EF6 I have the class below to manage my specific implementation of a membership system using entity framework 6.1

Is the use of static access correct in this case? as far as I understood that EF context is not thread-safe so I'm instantiating one with every call through the using statement. My second question, is the use of Boolean variable okay to signal failure in db transactions? an important point about this class is that it's going to be used quite frequently as the authentication wont rely on any session established with the user, it's also important to note that the users of this system will be quite limited.

Edit: I'm aware I can use the new identity system or any of the membership providers offered by ASP.NET but this custom provider is quite specific to a Windows authentication system and the use of any cookie-based system is not possible.

public static class AccountManager
{
    private enum Role { User, Comment, CommentControl, Sysadmin }

    public static bool IsUserInRole(string username, string role)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var status = false;
            var foundAcc = ctx.Accounts.Where(x => x.Username == username);
            if (foundAcc.Any())
            {
                var s = foundAcc.SingleOrDefault();
                if (s != null)
                {
                    var exitingRole = s.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));
                    if (exitingRole.Any())
                    {
                        status = true;
                    }
                }
            }
            return status;
        }
    }

    public static bool IsUserCached(string username)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var result = true;
            var foundAcc = ctx.Accounts.Where(x => x.Username == username);
            if (!foundAcc.Any())
            {
                result = false;
            }
            return result;
        }
    }

    public static bool CacheUser(string username)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var status = false;

            try
            {
                var newAcc = new Account
                {
                    Active = true,
                    Username = username,
                };
                ctx.Accounts.Add(newAcc);
                ctx.SaveChanges();

                AssignRole(newAcc.Username, Role.User);
                status = true;
            }
            catch
            { }

            return status;
        }
    }

    public static bool AssignRoleComment(string username)
    {
        return AssignRole(username, Role.Comment);
    }

    public static bool AssignRoleCommentControl(string username)
    {
        return AssignRole(username, Role.CommentControl);
    }

    public static bool AssignRoleSysAdmin(string username)
    {
        return AssignRole(username, Role.Sysadmin);
    }

    private static bool AssignRole(string accountName, Role role)
    {
        using (var ctx = new AccountsDbCtx())
        {
            var completed = false;
            var roleToAssign = ctx.Roles.SingleOrDefault(x => x.Role1 == (int)role);

            try
            {
                var currentAccount = ctx.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));

                if (currentAccount != null && roleToAssign != null) currentAccount.Roles.Add(roleToAssign);

                ctx.SaveChanges();

                completed = true;

            }
            catch
            {}

            return completed;
        }
    }
}

umm yes, you could do it that way.

  as far as I understood that EF context is not thread-safe so I'm
  instantiating one with every call through the using statement

Where did you read this?  I'm not denying it it's just that I have not read this before and I haven't experienced too many problems with using EF in the case of one instance per request.

  My second question, is the use of Boolean variable ok to signal
  failure in db transactions

Maybe.  But how are you going to know what actually went wrong?  All that's going to happen is you know something went wrong but when it comes to diagnosing it you will be at a dead end because you have swallowed the exception (so to speak).  Given that your exceptions seeming to be handling cases such as the database offline, or connection issues I think it would be best to bubble those up as that would be a core system fault and you would want to know more info.

Here's an alternative solution using a non-static class and sharing the Database context between methods.

  NOTE:  I would actually consider removing the default empty
  constructor and IDisposable if you were using an IOC framework to
  instantiate the context as that would be responsible for your instance
  lifetime.  However I'm not sure how your Account Manager would be created.

public class AccountManager : IDisposable
{
    private enum Role { User, Comment, CommentControl, Sysadmin }
    private readonly AccountsDbCtx dbContext;

    public AccountManager(AccountsDbCtx dbContext)
    {
        this.dbContext = dbContext;
    }

    public AccountManager() : this(new AccountsDbCtx())
    {
    }

    public void Dispose()
    {
        dbContext.Dispose();
    {

    public bool IsUserInRole(string username, string role)
    {
        var account = dbContext.Accounts.SingleOrDefault(x => x.Username == username);

        if(account == null)
        {
            return false;
        }

        var existingRole = account.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));

        return existingRole.Any();
    }

    public bool IsUserCached(string username)
    {
        return dbContext.Accounts.Any(x => x.Username == username);
    }

    public void CacheUser(string username)
    {
        dbContext.Accounts.Add(new Account
        {
            Active = true,
            Username = username
        });

        dbContext.Accounts.Add(newAcc);
        dbContext.SaveChanges();

        AssignRoleUser(username);
    }

    public bool AssignRoleUser(string username)
    {
        return AssignRole(username, Role.User);
    }

    public bool AssignRoleComment(string username)
    {
        return AssignRole(username, Role.Comment);
    }

    public bool AssignRoleCommentControl(string username)
    {
        return AssignRole(username, Role.CommentControl);
    }

    public bool AssignRoleSysAdmin(string username)
    {
        return AssignRole(username, Role.Sysadmin);
    }

    private bool AssignRole(string accountName, Role role)
    {
        // Why would a role not exist in our database?
        var roleToAssign = dbContext.Roles.Single(x => x.Role1 == (int)role);
        var currentAccount = dbContext.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));

        if (currentAccount == null)
            return false;

        currentAccount.Roles.Add(roleToAssign);
        dbContext.SaveChanges();

        return IsUserInRole(accountName, role);
    }
}


Extract thoughput value from JMeter log file I use JMeter for load testing and want to report error on CI pipeline when application though put is less than 1/sec. JMeter logs summary of results as -

2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary +    103 in 00:00:30 =    3.4/s Avg:  2937 Min:    48 Max:  7962 Err:     0 (0.00%) Active: 2 Started: 10 Finished: 8
2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary =  12218 in 01:00:03 =    3.4/s Avg:  2942 Min:    20 Max: 27317 Err:     1 (0.01%)
2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary +      1 in 00:00:00 =   66.7/s Avg:  3227 Min:  3227 Max:  3227 Err:     0 (0.00%) Active: 0 Started: 10 Finished: 10
2017/01/17 01:57:00 INFO  - jmeter.reporters.Summariser: summary =  12219 in 01:00:03 =    3.4/s Avg:  2942 Min:    20 Max: 27317 Err:     1 (0.01%)

Herein I would capture the last line and if value of throughput is less than 1 (which is 3.4/s in the current example) then it would be reported as error. Here is the script I wrote to capture value of throughput -

grep "meter.reporters.Summariser: summary" test.log | tail -1 | awk '{print $12}' | cut -d "." -f1

and it gets me 3 which is ok. How can I improve this script?

You are using here four different tools: grep, tail, awk and cut to do the following:

select lines
get the last one
print a given field of that one
extract the integer part of that field

This is clear and it works. However, using four processes is a bit of overkill, since all of these can be performed one-handedly via awk:

awk '/meter.reporters.Summariser: summary/ {rec=$12} END{printf "%d\n", rec}' file

/meter.reporters.Summariser: summary/ {rec=$12}
When reading from the file, /pattern/ will match those lines containing the "pattern". If this happens, the action within {} is performed. In this case, it consists in storing the 12th field.
But wait, weren't we looking for the last line in which this occurs? Yes, and this is exactly what we are doing by overwriting rec every time the pattern happens: last time it is written, it will store the definitive result.
END{printf "%d\n", rec}
Once all lines have been processed, red will have the desired value on the form 3.4/s. We just want the 3 to appear, so we could do some string triming similar to the one you did with cut. However, we can also use awk's printf() to use Format-Control Letters to just print the integer part of it. This will also print 0 if rec is empty:

$ awk 'BEGIN {printf "%s\n", "3.4/s"}'
3.4/s
$ awk 'BEGIN {printf "%d\n", "3.4/s"}'
3
$ awk 'BEGIN {printf "%d\n", ""}'
0

Of course, you could also add the threshold logic in the script.


jQuery Plugin Review - wrapper for jQuery UI's tabs This is a jQuery plug-in I've created that relies on jQuery UI's tabs plug-in. It adds some framework specific logic when setting up tabs:

Fixes a bug in jQuery that appears when an id/class contains a "."
Manages the tab state using a framework specific cookie API (does not use the jQuery cookie plugin)
Exposes a couple of options for transition behavior

I'd love to get some suggestions on how to improve this, as it'll be used widely in the framework.

(function ($) {
    $.fn.dnnTabs = function (options) {
        var opts = $.extend({}, $.fn.dnnTabs.defaultOptions, options),
            $wrap = this;

        $(document).ready(function () {
            // Patch for Period in IDs (jQuery bug)
            $.ui.tabs.prototype._sanitizeSelector = function (hash) {
                // we need this because an id may contain a ":" or a '.'
                return hash.replace(/:/g, "\\:").replace(/\./g, "\\\.");
            };

            var id = 'dnnTabs-' + $wrap.selector.replace('#', '').replace('.', '');
            if (opts.selected === -1) {
                var tabCookie = dnn.dom.getCookie(id);
                if (tabCookie) {
                    opts.selected = tabCookie;
                }
                if (opts.selected === -1) {
                    opts.selected = 0;
                }
            }

            $wrap.tabs({
                show: function (event, ui) {
                    dnn.dom.setCookie(id, ui.index, 1, '/', '', false);
                },
                selected: opts.selected,
                fx: {
                    opacity: opts.opacity,
                    duration: opts.duration
                }
            });
        });

        return $wrap;
    };

    $.fn.dnnTabs.defaultOptions = {
        opacity: 'toggle',
        duration: 'fast',
        selected: -1
    };

})(jQuery);

These are probably more comments, but I'll post them as an "answer", because it's easier.

Could you point out a source or an example for the bug with ids/classes containing . and :, because in a quick test they seem to work fine: http://jsfiddle.net/NSXLc/
I don't think you should use the document ready event. It should be the plugins user's choice when he wants to apply the tabs.
The way you are getting the id for the cookie looks dangerously wrong. You assume the selector is always a simple id or class selector and extending on that you assume, that the selector only matches one element and thus only one one set of tabs are initialized at a time.

It's probably better to do something like this:

$wrap.each(function() { // In case the selector matches multiple elements
  var showEvent = null;
  if (this.id) { // only use cookie if ID is set. TODO: use className as alternative
    var id = 'dnnTabs-' + this.id;
    if (opts.selected === -1) {
      // ...
    }

    showEvent = (function(cookieId) { // closure for cookie id
      return function (event, ui) {
        dnn.dom.setCookie(cookieId, ui.index, 1, '/', '', false);
      }
    })(id);
  }
  $(this).tabs({
    show: showEvent,
    // ...
  });
});


Find all words beginning with a given prefix Today I present some code for finding all words that
begin with a given prefix and some simple test cases for review.

from itertools import chain

sentinel = object()

def insert(tree, word):
    for letter in chain(word, [sentinel]):
        tree = tree.setdefault(letter, {})

def words_beginning_with(start, tree):
    for letter in start:
        try:
            tree = tree[letter]
        except KeyError:
            return
    for word in _all_words(tree):
        yield start + word

def _all_words(tree, start=''):
    for letter, tree in tree.items():
        if letter is sentinel:
            yield start
        else:
            for word in _all_words(tree, start+letter):
                yield word

def test_tree():
    # Simple tests
    tree = {}

    assert [] == list(words_beginning_with('foo', tree))

    insert(tree, 'foo')
    assert {'f': {'o': {'o': {sentinel: {}}}}} == tree

    assert ['foo'] == list(words_beginning_with('foo', tree))

    insert(tree, 'food')
    assert {'f': {'o': {'o': {sentinel: {},
                              'd': {sentinel: {}}}}}} == tree

    assert sorted(['foo', 'food']) == sorted(words_beginning_with('fo', tree))

    insert(tree, 'foody')
    assert sorted(['foo', 'food', 'foody']) == sorted(
        words_beginning_with('fo', tree))

    insert(tree, 'fold')
    assert sorted(['foo', 'fold', 'food', 'foody']) == sorted(
        words_beginning_with('fo', tree))

if __name__ == "__main__":
    test_tree()

I appreciate brutal and honest feedback the most, thanks.

Sentinel could simply be None instead of a "custom" object.
You don't need chain either: just set the sentinel manually at the end of the for loop.
If using Python 3, you can use yield from ... instead of from ...: yield.

def insert(tree, word):
    for letter in word:
        tree = tree.setdefault(letter, {})
    tree[None] = {}  # or = None, it doesn't matter

def words_beginning_with(start, tree):
    for letter in start:
        try:
            tree = tree[letter]
        except KeyError:
            return
    for word in _all_words(tree):
        yield start + word

def _all_words(tree, start=''):
    for letter, tree in tree.items():
        if letter is None:
            yield start
        else:
            yield from _all_words(tree, start + letter):


Splitting out joined table data Consider the following segment of code:

# Fetch my orders
orders = repo.get_orders_for(self._customer[0])

if len(orders) > 0:
    current_order_no = -1
    for (order_number, quantity, pid) in orders:

        # Print new heading if needed
        if order_number is not current_order_no:
            print("Order #{}".format(order_number))
            current_order_no = order_number

        print("    Product #{}, ordered x{}".format(pid, quantity))

I feel like there's just a lot going on. I basically do a JOIN on two tables, and return some orders and their order_items. The JOIN obviously duplicates the order_number on several rows, so I need a way of telling them apart. Is there a better way of doing this in Python (actually, I'll accept any language answer for curiosity!) Or is it my way of joining that's evil?

For the curious, the SQL statement is:

SELECT OrderNumber, Quantity, Product_ProductId FROM `order` JOIN `orderitem` ON `order`.OrderNumber = Order_OrderNumber WHERE CustomerAccount_CustomerId=%s ORDER BY OrderNumber

You can use itertools.groupby to group the items by order number.
Don't use is to compare numbers. is checks object identity and the same number can be represented by different objects:

>>> a=1234
>>> b=1234
>>> a is b
False
>>> a=12
>>> b=12
>>> a is b
True

Checking if len(orders) > 0 before the for loop is redundant. If the list is empty the loop won't run even once.

Revised code:

from itertools import groupby
from operator import itemgetter

# Fetch my orders
orders = repo.get_orders_for(self._customer[0])

for order_number, items in groupby(orders, key=itemgetter(0)):
    print("Order #{}".format(order_number))
    for _, quantity, pid in items:
        print("    Product #{}, ordered x{}".format(pid, quantity))


How might we make this Python Merge Sort implementation more Pythonic? I've implemented a (version of) Merge Sort algorithm in Python. My goal here is two-fold:

Improve understanding of Merge Sort and recursion in a language agnostic way.
Improve understanding of Python conventions and idioms.

The implementation recursively splits the given sequence into left and right sequences and then merges the two subsequences back together sorted in ascending order.

All suggestions for improvement are welcome. I'd especially like feedback on the following:

looping through total length of sequence and the unused variable.
use of try-except blocks.
use of indexing and slicing.

class MergeSort(object):

def sort(self, seq):
    '''
    Sorts a sequence of integers.

    @param seq: an unsorted tuple or list.
    @return:    a new tuple with elements in @seq sorted in ascending order.
    '''
    if(len(seq) <= 1):
        return seq
    else:
        return self._merge(leftSortedSeq=self.sort(seq[0:(len(seq) / 2)]),
                           rightSortedSeq=self.sort(seq[(len(seq) / 2):]))

def _merge(self, leftSortedSeq, rightSortedSeq):
    if(len(leftSortedSeq) == 0):
        return rightSortedSeq
    elif(len(rightSortedSeq) == 0):
        return leftSortedSeq

    leftPointer = 0
    rightPointer = 0
    mergedSeq = []
    mergedSeqLength = len(leftSortedSeq) + len(rightSortedSeq)
    for elementNumber in range(mergedSeqLength):

        try:
            smallestInLeft = leftSortedSeq[leftPointer]
        except IndexError:
            mergedSeq += rightSortedSeq[rightPointer:]
            return tuple(mergedSeq)

        try:
            smallestInRight = rightSortedSeq[rightPointer]
        except IndexError:
            mergedSeq += leftSortedSeq[leftPointer:]
            return tuple(mergedSeq)

        if(smallestInLeft < smallestInRight):
            mergedSeq.append(leftSortedSeq[leftPointer])
            leftPointer += 1
        else:
            mergedSeq.append(rightSortedSeq[rightPointer])
            rightPointer += 1

    return tuple(mergedSeq)

If you have any expression like the one below

if(x == 0)

then you can rewrite it as

if not x

You can get rid of parenthesis and can make it more pythonic by writing like this.

Similarly you an rewrite :

if(len(leftSortedSeq) == 0):
    return rightSortedSeq
elif(len(rightSortedSeq) == 0):
    return leftSortedSeq

as

if not len(leftSortedSeq):
    return rightSortedSeq
elif not len(rightSortedSeq):
    return leftSortedSeq

If I were you I would avoid using excetions for the cases which can be avoided using simple if else. This will give the code more clarity.

We can avoid the exception by changing the code a bit.

I have also avoided conversion to tuple. The concatenation of tuple and list may cause problems. So its better to avoid unnecessary conversions.

lenLeftSeq = len(leftSortedSeq)
lenRightSeq = len(rightSortedSeq)

while leftPointer < lenLeftSeq and rightPointer < lenRightSeq:

    smallestInLeft = leftSortedSeq[leftPointer]
    smallestInRight = rightSortedSeq[rightPointer]

    if(smallestInLeft < smallestInRight):
        mergedSeq.append(smallestInLeft)
        leftPointer += 1
    else:
        mergedSeq.append(smallestInRight)
        rightPointer += 1

return mergedSeq +
             leftSortedSeq[leftPointer:] +
             rightSortedSeq[rightPointer:]


Decomposing bitfield with Haskell: is recursion the only way to do this? Here's a program to take a bitfield like 7 and decompose it into the flags [1,2,4].
Ignore that the algorithm for doing this doesn't use bit shifting/is stupid.

Problems: it seems like I have to have the bithelp function for the sole purpose of calling the other ones, since getFlags and findPower both need to be given given a "starter value" as their second argument (since I can't find a good way to make the argument optional on the first try).

Is there any other way to do what they're doing without recursion? Is recursion like this the standard way to "loop" in FP?

I'll be pleased to be shown anything else I'm doing stupidly here:

-- Algorithm:
-- * given any integer:
-- * find largest power of 2 that fits inside the integer
-- * going from largest to smallest powers of 2, progressively substract any power of 2 that can be subtracted until you get to zero
-- * collect these powers and return them as a list
--
-- These represent the bits that are set within the bitfield
-- E.g. bithelp of 51 = [32,16,2,1]

-- process bitfield
bithelp :: Int -> [Int]
bithelp bitfield = getFlags bitfield $ findPower bitfield 0

-- find starting number: largest power of 2 to fit within bits
findPower :: Int -> Int -> Int
findPower bitfield power
    | 2^power > bitfield = 2^last -- when overshoot bitfield, return last power
    | otherwise = findPower bitfield next
    where next = power + 1
          last = power - 1

-- starting with flag, subtracts down the list of flags, returning list of matches
getFlags :: Int -> Int -> [Int]
getFlags currentBits flag
    | currentBits == flag = [flag] -- only one flag left, last item
    | found = [flag] ++ getFlags remainingBits nextFlag
    | not found = getFlags currentBits nextFlag
    where remainingBits = currentBits - flag
          nextFlag = flag `div` 2
          found = currentBits >= flag -- means bits could be substracted

-- get user input and print list of matched bits
main = do
    putStrLn "Bitfield:"
    line <- getLine
    let bitfield = read line :: Int
    let flags = bithelp bitfield
    putStrLn "List of flags:"
    print flags

A more common way of "initializing" values on the first call is to define an inner worker function.

findPower :: Int -> Int
findPower bitfield = go 0
    where go i = ... -- Note that the bitfield argument is still in scope

Recursion is the standard way to loop in Haskell (so much so that in lots of code you will find locally defined recursive functions named loop), but your code might be more terse without explicit recursion.

Here's my first pass at a rewrite of the findPower function using higher order functions.

findPower :: Int -> Int
findPower i = last . takeWhile (<= i) $ map (2^) [0..]

Note that this function still isn't total, i.e. it will fail when passed Ints <= 0. Your version would recurse until 2^power overflows, whereas mine will fail fast with an empty list exception due to the use of last. It's considered good style to make your Haskell functions total, so here's my second pass.

findPower :: Int -> Maybe Int
findPower 0 = Just 0
findPower i | i < 0     = Nothing
            | otherwise = Just . last . takeWhile (<= i) $ map (2^) [0..]

Using Maybe here is probably overkill, and in fact you probably want your program to crash when given bad input! Here's a final version.

findPower :: Int -> Int
findPower i | i < 0     = error "findPower: Can't find power of negative number"
            | i == 0    = 0
            | otherwise = last . takeWhile (<= i) $ map (2^) [0..]

On this line | found = [flag] ++ ..., if you're adding a single element to the front of a list, this is just regular cons! Use | found = flag : ... instead.

You've defined a lot of constants in where clauses for your two functions which only get used once. Sometimes it can be helpful to give a name to something that might be non-obvious, but in this case it makes your code longer and arguably adds a bit of cognitive overhead to what are very simple transformations. For instance, I would consider this more readable.

getFlags currentBits flag | currentBits == flag = [flag]
                          | currentBits > flag  = flag : getFlags (currentBits - flag) (flag `div` 2)
                          | otherwise           = getFlags currentBits (flag `div` 2)

In your definition of main, you can omit the type annotation from read line and the compiler will deduce you want an Int due to the type signature of bithelp. On its own this is a small change, but leveraging the type system in this way is entirely natural and reduces the number of changes you would have to make if, say, you changed your functions to operate on Integers.

See if this isn't more clear.

main = do putStrLn "Enter a positive integer:"
          nstr <- getLine
          putStrLn "List of flags:"
          print $ bithelp (read nstr)

The last thing to do would be to eliminate the bithelp function by rewriting the getFlags function with a call to findPower inside of it, passed to an inner worker function. I'll leave that as an exercise to the reader.


Pandas dataframe custom forward fillna optimisation I have a function that synchronizes according to some specifications columns of a dataframe.
The functions works, nevertheless I was wondering how to:

Improve performances
Make it more pythonic

Please feel free to leave any suggestions.

Function specifications

Inputs:

df : a dataframe with columns:

[a0,...aN] : a0 to aN names can be any valid string and contains numeric values
[agent,date] : are fixed names, agent contains numeric values and date contains datetime.

sync_with : The columns to synchronize with (a string or an listof string contained in [a0,..., aN] or, by default, an empty list to synchronize all the [a0,...,aN].

Synchronization:

Do a forward fillna grouped by agent values.
Drop the rows where all columns to synchronize with values are empty

Returns : the synchronized dataframe

Here is my function:

import pandas as pd
import numpy as np

def synchronize(df,sync_with=[]):
    _df = df.copy()

    if not isinstance(sync_with,list):
        sync_with = [sync_with]

    _fixed_cols = ['date','agent']
    _fixed_cols.extend(sync_with)
    _colset = [c for c in _df.columns if c not in _fixed_cols]

    for ag in _df.agent.unique():
        _df.loc[_df.agent==ag,_colset] = _df.loc[_df.agent==ag,_colset].fillna(method='ffill')
        if _sync_with:
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].dropna(how='all', subset=_sync_with)
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].fillna(method='ffill')

    return _df.dropna(how='all', subset=_sync_with)

Sample

foo = pd.DataFrame(dict(date=pd.to_datetime(['2010', '2011', '2012', '2013', '2010', '2013', '2015', '2016']),
                        agent=[1,1,1,1,2,2,2,2],
                        _a=[1, np.nan, np.nan, 4, 5, np.nan, 7, 8],
                        _b=[11, 22, np.nan, np.nan, 55, np.nan, 77, np.nan],
                        _c=[111, np.nan, 333, np.nan, np.nan, 666, 777, np.nan]))

Results

# 1. default (13 ms per loop)
print(synchronize(foo))
    _a    _b     _c  agent       date
0  1.0  11.0  111.0      1 2010-01-01
1  1.0  22.0  111.0      1 2011-01-01
2  1.0  22.0  333.0      1 2012-01-01
3  4.0  22.0  333.0      1 2013-01-01
4  5.0  55.0    NaN      2 2010-01-01
5  5.0  55.0  666.0      2 2013-01-01
6  7.0  77.0  777.0      2 2015-01-01
7  8.0  77.0  777.0      2 2016-01-01

# 2. sync with one column (35 ms per loop)
print(synchronize(foo,'_c'))
    _a    _b     _c  agent       date
0  1.0  11.0  111.0      1 2010-01-01
2  1.0  22.0  333.0      1 2012-01-01
5  5.0  55.0  666.0      2 2013-01-01
6  7.0  77.0  777.0      2 2015-01-01

# 3. sync with two columns (35 ms per loop)
print(synchronize(foo,['_a','_b']))
    _a    _b     _c  agent       date
0  1.0  11.0  111.0      1 2010-01-01
1  1.0  22.0  111.0      1 2011-01-01
3  4.0  22.0  333.0      1 2013-01-01
4  5.0  55.0    NaN      2 2010-01-01
6  7.0  77.0  777.0      2 2015-01-01
7  8.0  77.0  777.0      2 2016-01-01

a few ways to make it more pythonic

'private' variables

variable within a function are limited to the scope of that function, so prepending them with a _ is unnecessary

lists

sync_with could also be another Container, like a tuple or so. Only when it is a str you need to convert it.

also be aware of what can go wrong with mutable default arguments. They are instantiated at the moment of function definition. In this case they are not appended to in the function or returned, so it should not pose any problems, but I try to avoid them anyway

fixed_cols can then be assembled like this:

fixed_cols = ['agent', 'date'] + list(sync_with)

Then only if sync_with is an generator, something can go wrong, so I would do something like this:

def synchronize(df, sync_with=None):
    if sync_with is None:
        sync_with = []
    elif isinstance(sync_with, str):
        sync_with = [sync_with, ]
    else:
        sync_with = list(sync_with)

performance

Making a copy initially is unnecessary, unless you will perform operations inplace on the df
You can use DataFrame.groupby.transform, and then select the rows which had any non-null value in the original df

You would get something like this:

def synchronize3(df,sync_with=[]):
    if isinstance(sync_with, str):
        sync_with = [sync_with, ]
    else:
        sync_with = list(sync_with)
    result = df.groupby('agent').transform(lambda x: x.fillna(method='ffill'))
    if sync_with:
        result = result.loc[pd.notnull(df[sync_with]).any(axis=1), :]
    result = result.assign(agent=df['agent']).reindex(columns=df.columns)
    return result

Results:

%timeit synchronize(foo)

9.48 ms ± 527 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit synchronize(foo,'_c')

29 ms ± 817 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit synchronize(foo,['_a','_b'])

27.8 ms ± 608 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

assert synchronize(foo).equals(synchronize3(foo))
%timeit synchronize3(foo)

5.71 ms ± 935 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

  _a  _b  _c  agent   date
0 1.0 11.0    111.0   1   2010-01-01
1 1.0 22.0    111.0   1   2011-01-01
2 1.0 22.0    333.0   1   2012-01-01
3 4.0 22.0    333.0   1   2013-01-01
4 5.0 55.0    NaN     2   2010-01-01
5 5.0 55.0    666.0   2   2013-01-01
6 7.0 77.0    777.0   2   2015-01-01
7 8.0 77.0    777.0   2   2016-01-01

assert synchronize(foo,'_c').equals(synchronize3(foo,'_c'))
%timeit synchronize3(foo,'_c')

6.41 ms ± 131 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

  _a  _b  _c  agent   date
0 1.0 11.0    111.0   1   2010-01-01
2 1.0 22.0    333.0   1   2012-01-01
5 5.0 55.0    666.0   2   2013-01-01
6 7.0 77.0    777.0   2   2015-01-01

assert synchronize(foo,['_a','_b']).equals(synchronize3(foo,['_a','_b']))
%timeit synchronize3(foo,['_a','_b'])

7.33 ms ± 1.16 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

_a    _b  _c  agent   date
0 1.0 11.0    111.0   1   2010-01-01
1 1.0 22.0    111.0   1   2011-01-01
3 4.0 22.0    333.0   1   2013-01-01
4 5.0 55.0    NaN     2   2010-01-01
6 7.0 77.0    777.0   2   2015-01-01
7 8.0 77.0    777.0   2   2016-01-01

bugfixes

the version of your algorithm I used was this:

def synchronize(df,sync_with=[]):
    _df = df.copy()

    if not isinstance(sync_with,list):
        sync_with = [sync_with]

    _fixed_cols = ['date','agent']
    _fixed_cols.extend(sync_with)
    _colset = [c for c in _df.columns if c not in _fixed_cols]

    for ag in _df.agent.unique():
        _df.loc[_df.agent==ag,_colset] = _df.loc[_df.agent==ag,_colset].fillna(method='ffill')
        if sync_with:
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].dropna(how='all', subset=sync_with)
            _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].fillna(method='ffill')
    if sync_with:
        _df = _df.dropna(how='all', subset=sync_with)
    return _df.astype({'agent': 'int64'})  # else the `dtype` is different from the one in my method, throwing of the assertions


Photo gallery user control I am trying to create something that is very reusable here so that I can use it in other sites for other pages etc.

This code is for a simple photo gallery,

I took the code from here, but I changed it a bit and would like to add more functionality to it eventually, though.

PhotoGallery.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PhotoGallery.ascx.cs" Inherits="PhotoGallery" %>

Before and After Pictures

                <asp:Repeater ID="Repeater1" runat="server">
                    <ItemTemplate>
                        <img class="thumbnails" src='<%#Eval("ImageUrl") %>' alt='<%#Eval("ImageUrl") %>' />
                    </ItemTemplate>
                </asp:Repeater>

PhotoGallery.ascx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PhotoGallery : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateImages();
        }
    }

    public string FolderPath {get;set;}

    private void PopulateImages()
    {
        List<Image> myImages = new List<Image>();
        DirectoryInfo DI = new DirectoryInfo(Server.MapPath(FolderPath));
        foreach (var file in DI.GetFiles())
        {
            myImages.Add(new Image { ImageUrl = FolderPath + file.Name });
        }
        Repeater1.DataSource = myImages;
        Repeater1.DataBind();
    }
}

the variable holding the DirectoryInfo object should be named using lower case.
you should always use Sytem.IO.Path.Combine() to combine a folder with a filename.
you could use DirectoryInfo.EnumerateFiles combined with the Select() and assign the returned IEnumerable to the DataSource property of the Repeater control.
you should add spacing to the property FolderPath. Instead of

public string FolderPath {get;set;}

you should use

public string FolderPath { get; set; }

Repeater1 is an ugly name which isn't decsriptive either. Change it to something more descriptive.


Delimiter-matching using Stack in Java Is this code okay?

import java.util.Stack;

public class DelimiterMatching {

    public static void main(String[] args) {

        final String input = "[(A+B)]";

        delimiterCheck(input);
    }

    public static void delimiterCheck(String input) {
        if (input.length() == 0) {
            System.out.println("String is empty");
        }
        Stack<Character> theStack = new Stack<>();
        for (int i = 0; i < input.length(); i++) {
            char individualChar = input.charAt(i);
            if (individualChar == '{' || individualChar == '['
                    || individualChar == '(') {
                theStack.push(individualChar);

            } else if (individualChar == '}' || individualChar == ']'
                    || individualChar == ')') {
                if (!theStack.isEmpty()) {
                    char individualCharRight = theStack.pop();
                    if ((individualChar == '}' && individualCharRight != '{')
                            || (individualChar == ')' && individualCharRight != '(')
                            || (individualChar == ']' && individualCharRight != '[')) {
                        System.out.println("Error at index " + i);
                    }
                }
            }
        }
        if (!theStack.isEmpty()) {
            System.out.println("Error in delimiter");
        }
    }
}

Technically the code is broken: it will accept a ")" string as valid (test at line 25 doesn't flag an error if the stack is empty).

Naming

I think you got a bit overboard. Names shall be descriptive, which doesn't imply that they shall be long. individualCharRight is definitely confusing. I'd suggest something like innermost perhaps.

delimiterCheck also doesn't reflect the nature of the function. It is supposed to test a validity of nested brackets; isNested could be more to the point.

Error reporting

For a low level function I'd recommend to avoid printing anything, but return an error code instead. There are 2 clearly defined error conditions (an unbalanced closing bracket and an unclosed opening one); the method should return an error code and a position of an offending bracket. The latter observation means that a bracket position should be recorder at the stack along with the bracket itself.

Interface

As mentioned above, the method should return an error code and an error location.


Calculating infix expression with no parenthesis This is my Java implementation (\$O(n)\$) about how to calculate infix expression with no parenthesis.

For example, when we input "3 + 4 * 4 / 8", we will get a double type answer is 5.0. Here to make the algorithm simple, we don't consider any parenthesis in the expression.

I think my implementation is kind of tedious and long. Can anyone give me some advice on making it cleaner?

public double computeInfixExpr(String input) {
        String[] expr = input.split(" ");
        int i = 0;
        double operLeft = Integer.valueOf(expr[i++]);
        while (i < expr.length) {
            String operator = expr[i++];
            double operRight = Double.valueOf(expr[i++]);
            switch (operator) {
                case "*":
                    operLeft = operLeft * operRight;
                    break;
                case "/":
                    operLeft = operLeft / operRight;
                    break;
                case "+":
                    while (i < expr.length) {
                        String operator2 = expr[i++];
                        if (operator2.equals("+") || operator2.equals("-")) {
                            i--;
                            break;
                        }
                        if (operator2.equals("*")) {
                            operRight = operRight * Double.valueOf(expr[i++]);
                        }
                        if (operator2.equals("/")) {
                            operRight = operRight / Double.valueOf(expr[i++]);
                        }
                    }
                    operLeft = operLeft + operRight;
                    break;
                case "-":
                    while (i < expr.length) {
                        String operator2 = expr[i++];
                        if (operator2.equals("+") || operator2.equals("-")) {
                            i--;
                            break;
                        }
                        if (operator2.equals("*")) {
                            operRight = operRight * Double.valueOf(expr[i++]);
                        }
                        if (operator2.equals("/")) {
                            operRight = operRight / Double.valueOf(expr[i++]);
                        }
                    }
                    operLeft = operLeft - operRight;
                    break;
            }
        }
        return operLeft;
    }

It is common, when processing things like this, to use a chain-of-responsibility pattern.

In this case, you can create an operator interface, or abstract class:

public interface BinaryOperator {
    public boolean isOwner(String operator);
    public double operateOn(double left, double right);
}

Then, you create an instance of that interface for each operator you support like the following for 'add':

public class AddOperator implements BinaryOperator {
   public boolean isOwner(String op) {
       return "+".equals(op);
   }

    public double operateOn(double left, double right) {
       return left + right;
    }
}

Then, you create an instance for all your supported operators, and then put them in to an array, in precedence order (if you support precedence).

It will look like:

private static final BinaryOperator OPERATORS = {
    new MultiplyOperator(),
    ....
    new AddOperator(),
    new SubtractOperator()
}

and, in your parsing/handling code, you do the following:

public double handle(double left, String parsedOp, double right) {
    for (BinaryOperator op : OPERATORS) {
        if (op.isOwner(parsedOp)) {
            return op.operateOn(left, right);
        }
    }
    throw new UnsupportedOperationException("Can't handle " + parsedOp);
}

This will drastically simplify your code, and it will make it much easier to support other operations too.


Is this code protected against SQL injection attacks? I'm just wondering if this code is good against SQL injection attacks. I don't know how to check if is good. Also I would like to know if is good how I'm working or this is just bad practice?

<?php

if (isset($_POST['register'])) {

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$salt = "Not important";
$password_hash = crypt($password, "$2y$". $salt);

if (strlen($username) > 20) {
    echo "Username is too big";
}elseif (strlen($password) > 32) {
    echo "Password is too big";
}elseif (strlen($email) > 100) {
    echo "E-Mail is too big";
}elseif(strlen($username) == 0 || strlen($password) == 0 || strlen($email) == 0){
    echo "Fill every field";
}
else{
    $sth_username = $dbh->prepare("SELECT username FROM user WHERE username = :username");
    $sth_username->bindParam(":username", $username);
    $sth_email = $dbh->prepare("SELECT email FROM user WHERE email = :email");
    $sth_email->bindParam(":email", $email);
    $sth_username->execute();
    $sth_email->execute();
    if ($result = $sth_username->fetch(PDO::FETCH_OBJ)) {
        print $result->username . "The username is already is use";
    }elseif ($result = $sth_email->fetch(PDO::FETCH_OBJ)){
        print $result->email . "That e-mail is already in use";
    }else{
        $sth = $dbh->prepare("INSERT INTO user (username, password, email, salt) VALUES (:username, :password, :email, :salt)");
        $sth->bindParam(":username", $username);
        $sth->bindParam(":password", $password_hash);
        $sth->bindParam(":email", $email);
        $sth->bindParam(":salt", $salt);
        $sth->execute();
        $sth = $dbh->prepare("INSERT INTO stats (strength,agility,intelligence) VALUES (10,10,10)");
        $sth->execute();

        echo "You have been registered";
    }
}
?>

Looks O.K. to me as well, as far as the SQL injection goes.

However, I'd suggest checking the return value of $sth->execute();, so you capture possible errors (i.e., DB being down).

You might also consider doing a case insensitive search for the existing usernames and e-mails, since "person@gmail.com" is the same address as "Person@GMail.com" and users "Person" and "person" are hard to distinguish.

I think empty($string) is more advisable than strlen($string) == 0.

Last, but not least, adding a "retype your password" field would be a good security against user mistyping what he wants for a password and then ending with a useless account (or having to use "I forgot my password" before the very first login).


Custom Contains() function I have the following function and I was wondering if anyone could come up with something more efficient.

It just has to split both the content and the search string and determine how many words are required to be matched before being true.

For example,

"A dog can run.".ContainsV2("Red Dog Run", 4) = false

"A dog can run.".ContainsV2("Red Dog Run", 2) = true

"A dog can run.".ContainsV2("Red Dog Run") = true

"A dog can run.".ContainsV2("Red Dog Run", MatchAllWords: true) = false

/// <summary>
/// Checks to see if any of the words are contained in the string.
/// </summary>
/// <param name="content"></param>
/// <param name="SearchString">Search string</param>
/// <param name="NumberOfMatches">Specify how many words have to match in the search string.
///  This value is automatically dropped when the user searches less words.
/// I.e. NumberOfMatches = 3 and the user searches 'Bob', NumberOfMatches gets set to 1.</param>
/// <param name="MatchAllWords">If set to true, all of the words in the search string must be contained in what's being checked</param>
/// <returns></returns>
public static bool ContainsV2(this string content, string SearchString, int NumberOfMatches = 1, bool MatchAllWords = false)
{
    var matches = 0;
    var numberOfWords = SearchString.Split(' ').Length;
    // Update required number of matches
    NumberOfMatches = NumberOfMatches > numberOfWords ?
                    numberOfWords :
                    NumberOfMatches;

    if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(SearchString))
    {
        SearchString.Split(' ')
            .ToList()
            .ForEach(w => //Gets the index of each word after being split
                matches += content
                    .IndexOf(
                        StripNonAlphaNumeric(w),
                        StringComparison.OrdinalIgnoreCase
                    ) >= 0 ? 1 : 0
            );
    }
    if (MatchAllWords)
    {
        return matches == numberOfWords;
    }
    return matches >= NumberOfMatches;
}

Here is my first review. See what you can make of it! I left comments for you. They always discuss the code right below.

It is bad style to leave documentation tags empty. Either have no param tag or fill all with appropriate descriptions:

/// <param name="content"></param>
/// <param name="SearchString">Search string</param>
/// <param name="NumberOfMatches">Specify how many words have to match in the search string.

Too much implementation detail in my opinion:

/// This value is automatically dropped when the user searches less words.
/// I.e. NumberOfMatches = 3 and the user searches 'Bob', NumberOfMatches gets set to 1.</param>

Self explanatory name:

/// <param name="MatchAllWords">If set to true, all of the words in the search string must be contained in what's being checked</param>

This is self explanatory, remove the line:

/// <returns></returns>

Use a more telling name like ContainsWords:

public static bool ContainsV2(this string content, string SearchString, int NumberOfMatches = 1, bool MatchAllWords = false)
{
    var matches = 0;
    var numberOfWords = SearchString.Split(' ').Length;

Don't use empty comments like "Sets a variable" or "Updates value". Explain it better or leave out the comment:

    // Update required number of matches

The ?: operator is hard to understand and not necessary here. Rather, use something like in my comment:

    // if (NumberOfMatches > numberOfWords)
    // {
    //    NumberOfMatches = numberOfWords;
    // }
    NumberOfMatches = NumberOfMatches > numberOfWords ?
                    numberOfWords :
                    NumberOfMatches;

You already split the search string above. Either don't check for null or do it in the beginning:

    if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(SearchString))
    {

This is confusing. Reduce the complexity and nesting depth:

        SearchString.Split(' ')
            .ToList()
            .ForEach(w => //Gets the index of each word after being split
                matches += content
                    .IndexOf(
                        StripNonAlphaNumeric(w),
                        StringComparison.OrdinalIgnoreCase
                    ) >= 0 ? 1 : 0
            );
    }

Rather set this at the start of the function. It is confusing here:

    if (MatchAllWords)
    {
        return matches == numberOfWords;
    }
    return matches >= NumberOfMatches;
}


Writing a program to read a maximum of 99 elements in an iteration from a list I want to read a list of elements and pass a maximum of 99 elements to a function for some logical operations.

I have tried this with an array as an example and this code was successful in achieving my purpose.

I just want someone to review it and help optimize it.

/**
 */
package com.review.code.java;

/**
 * i>   Read a List Input,
 * ii>  Call a Function with maximum of 99 elements in one iteration Eg:(0..98; 99..198; 199..297; .....)
 *
 *
 */
public class OptimizeReadingList {

    public static int list_size=107;//252,543,... etc. - Input List Size

    public static int a[] = new int[list_size];

    public static void main(String[] args) {

        int read_max_size = 99;
        int input_list_size = list_size;

        // Add Elements to the Array
        for(int j =0;j<input_list_size;j++){
            a[j]=j+1;
        }

        // Print all the Elements in the List
        for(int j =0;j<input_list_size;j++){
            System.out.print(a[j]+",");
        }

        System.out.println("\n Print only a max of 99 elements in one iteration using the printElements method");

        // Should Call a function printElements with start_index and end_index
        for(int i = 0,ele = (read_max_size-1); i<input_list_size ; ){

            printElements(i,ele);

            // Increment Operations for the next elements(maybe another 99 or less than 99)
            i=(ele+1);
            if((ele+read_max_size > input_list_size)){
                ele=input_list_size;
            }else{
                ele=ele+ele;
            }
        }

    }

    // Consider that this method can read only a maximum of 99 elements in range.
    private static void printElements(int i, int ele) {
        for(int j = i;j<ele;j++){
            System.out.print(a[j]+",");
        }
        System.out.println("\n");
    }

}

First things first, I feel the biggest problem about your code is that your comments lie.

/**
 * i>   Read a List Input,
 * ii>  Call a Function with maximum of 99 elements in one iteration Eg:(0..98; 99..198; 199..297; .....)
 *
 *
 */
public class OptimizeReadingList

There is no List to be seen, and I am not sure what is meant by 'call a function'. Javadocs generally explain what the class/method is supposed to be used for, and they hardly talk about their underlying/reliant methods (except when the @see literal is used). At the very most, sometimes Javadocs cover "implementation notes" or "API notes" highlighting the caveats of such an implementation, but that's all to it.

// Should Call a function printElements with start_index and end_index
for(int i = 0,ele = (read_max_size-1); i<input_list_size ; ){

Should it, should it not? Why so? Even for general Javadoc comments, it sounds weird to be suggesting something so specific... if you decide to rename your method down the road, you'll have to update this comment, which becomes cumbersome in the long run.

// Increment Operations for the next elements(maybe another 99 or less than 99)
i=(ele+1);

Let's start printing batches of 98 instead. You'll have to manually update refrences to 99 throughout your code. Comments should document the 'why' and not the 'how', hence your comments describing how you are selecting maybe the next 99, or less than 99, is usually not recommended.

// Consider that this method can read only a maximum of 99 elements in range.
private static void printElements(int i, int ele) {

I'm only highlighting the method declaration, but nowhere in the method says that a maximum of 99 elements will be read. If I call this as printElements(0, 0);, I will only get a newline output. If I call this as printElements(9000, 10000);, I will probably get an ArrayIndexOutOfBoundsException exception (since you have hard-coded your test array as 107 elements).

So how can I actually achieve what I need?

You say you need a List, so let's see if there are any methods that can help you out with...

  List<E> subList(int fromIndex, int toIndex)

  Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

private static final int BATCH_SIZE = 99;

private static <T> void splitProcess(List<T> list) {
    splitProcess(list, BATCH_SIZE);
}

private static <T> void splitProcess(List<T> list, int batchSize) {
    if (batchSize < 1) {
        throw new IllegalArgumentException("Batch size must not be less than 1.");
    }
    for (int start = 0, end; start < (end = Math.min(list.size(), start + batchSize));
            start = end) {
        System.out.println(list.subList(start, end));
    }
}

Define your desired batch size as BATCH_SIZE = 99.
Have a 1-argument splitProcess(List) method that calls the 'fuller' splitProcess(List, int) method with BATCH_SIZE as the default second argument.
Do some validation for batchSize.
Construct a for-loop with:

two variables representing the start (inclusive) and end (exclusive) points
looping while start < list.size(), and
increment them accordingly.

Then you can call list.subList(start, end), and use it in the way you require.

Javadocs shall be left as an exercise for the reader...


Do HTML tags make a difference? I made a fairly simple template engine (if I could call it that). Basically my server returns something like

string "This text should be [color:red;font-weight:bold; red and bold]"

Then on the client side I have my parser, for HTML in this case

function parse(str){
    return str.replace(/\[(.+?) (.+?)\]/g,'$2');
}

I was wondering, however, do HTML tags make a difference? If I were to use font instead of span, would I win/lose anything?

P.S.: I am aware that this regex may pick up something that wasn't meant to be parsed, but my application doesn't use these braces in texts it returns, so it is alright.

There are several advantages to writing proper HTML and using semantic tags. Instead of asking yourself "How should this look?" Ask yourself "What does this mean?".

What does it mean for a text to be red? Does it mean <em>phasized text? Maybe <strong> text? You can always apply the style="color: red;" on top of that (or even better, with a classname).

What are the advantages?

<font> is deprecated. Today it's still supported, mainly due to idiots who want their sites to run with IE5.5, but that may not be the case in the future. One day, <font> might just stop working altogether. Its behavior is currently undefined in latest versions of HTML, and will lead to unpredictable variations between browser implementations, and between browser versions.
Using proper elements (<em>, <strong> as opposed to <span> or <font>) makes machines understand your text better. That's good for accessibility, SEO, and a bunch of other things that entities which are not actual human readers do.
Using proper elements makes your site look better by default. Say a client does not use CSS, he's on a very old phone, or just uses some obscure browser. <em> shows up as italicized, <strong> shows up as bold. <span> shows up completely normally.

Other than that, if you're already defining all of the CSS rules in your template engine, why not use HTML to begin with? There's no point in complicating things with yet another syntax. Write valid, proper HTML from start to end, and be done with it.


Javascript: timer function This is a function I made for a timer that counts down and performs a callback at the end. It seems to work fine, but I think the code is not very clean and has some unnecessary bits; also I would like some notes on readability. The code:

//timer object function
function Timer (element, callback) {

 var ac, minutes, seconds, finalTimeInSeconds, displayMinutes, displaySeconds, interval = 1000, self = this, timeLeftToNextSecond = 1000, running = false;

 this.set = function(inputMinutes, inputSeconds) {

  finalTimeInSeconds = inputMinutes * 60 + inputSeconds;
  minutes = (Math.floor(finalTimeInSeconds / 60));
  seconds = finalTimeInSeconds % 60;

  this.print();
 }

 this.add = function(inputMinutes, inputSeconds) {

  finalTimeInSeconds += inputMinutes * 60 + inputSeconds;
  finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
  minutes = (Math.floor(finalTimeInSeconds / 60));
  seconds = finalTimeInSeconds % 60;

  this.print();
 }

 this.subtract = function(inputMinutes, inputSeconds) {

  finalTimeInSeconds -= inputMinutes * 60 + inputSeconds;
  if(finalTimeInSeconds < 0) {callback()}
  finalTimeInSeconds = (finalTimeInSeconds < 0) ? 0 : finalTimeInSeconds;
  minutes = (Math.floor(finalTimeInSeconds / 60));
  seconds = finalTimeInSeconds % 60;
  this.print();
 }

 this.reset = function() {

  this.set(0,0);
 }

 this.print = function() {

  displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes; //ternary operator: adds a zero to the beggining
  displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds; //of the number if it has only one caracter.

  $(element).text(displayMinutes + ":" + displaySeconds);
 }

 this.run = function() {

  if (running == false) {
   running = true;

   var _f = function() {
    secondStarted = new Date;
    self.subtract(0, 1);
    interval = 1000;

    var theColorIs = $(element).css("color");
    ac = setTimeout(_f,interval);

   }
   ac = setTimeout(_f, interval);

  }
 }

 this.stop = function() {

  if (running == true) {
   running = false;
   console.log(this + "(" + element + ") was stopped");
   stopped = new Date;
   interval = 1000 - (stopped - secondStarted);
   clearTimeout(ac);
  }
 }

 this.getTotalTimeInSeconds = function() {

  return finalTimeInSeconds;
 }

 this.reset();

}

First is variable names. Most of them make sense... except ac. Everything is so verbose, but ac doesn't really make sense at first glance. One needs to read the code to find out ac is actually a timer ac = setTimeout(_f,interval);.

Next thing I notice is that all your actions seem to do print. The problem here is that the functions are implicitly changing state by calling print. That is, calling out any of the functions implicitly changes the value of displayMinutes, displaySeconds as well as some element's text. Best if add, subtract and the others actually just add and subtract. Leave the printing out of them, and do it separately.

displayMinutes = (minutes.toString().length == 1) ? "0" + minutes : minutes;  //ternary operator: adds a zero to the beggining
displaySeconds = (seconds.toString().length == 1) ? "0" + seconds : seconds;  //of the number if it has only one caracter.

Looks like you're trying to convert numbers into strings padded by zeroes, if needed be. A neat trick to convert numbers into strings is to just add a string before it. Type coercion does the rest for you. Then you can use slice with a negative index to slice starting from the end of the string.

// We assume all numbers are at least 1 digit. Thus we need one zero and 2
// digits to slice off from the right. If it were 3 digit padded numbers,
// we'd need two zeroes and 3 digits to slice off from the right.
var paddedTwoDigitNumber = ('0' + number).slice(-2);

Now I notice your timer relies on setTimeout to count. There are 2 problems here. First, native JS timers aren't precise. That means putting 1000ms delay guarantees that it executes at least 1000ms, but not exactly at 1000. This means, every "tick" may drift off a few ms. The next problem is that you're using setTimeout for each tick. The problem is that internally, it keeps queueing a function as a callback, and every execution, it gets popped off.

A better approach would be to use setInterval, so that you only queue your tick once and you don't have to rely on some recursion call. Next is instead of relying on the timer ticks, you should get the real time using Date.now(). Every timer tick, you store the time andyou check the real time, if a full second has elapsed since last timer tick. Only then do you update your timer. There will always be "drift" on each interval, so you should take that into account as well.

Not sure if you should pepper your variables in "InSeconds" and that's because I suggest you should work with milliseconds in JS. Most Date functions return millisecond time. Also, it's easier to convert milliseconds to seconds (a matter of division) rather than convert seconds to milliseconds (a code overhaul).

I notice that your code relies on jQuery (I see $(element).text()). I think it's best that either jQuery stays out of it (your timer is merely a timer library) or you make it a jQuery plugin. Either way is fine.

If you go with the pure timer route, I suggest you let Timer be an instance of an event emitter class (There's tons of them online. I even created one in 21 lines.) That way, your timer can just emit events when interesting things happen (on start, on stop etc.) and the DOM manipulation code is outside the Timer. You could just have something like timerInstance.on('complete', fnToExecuteOnComplete). jQuery is no longer a concern for the Timer code. It's external.

If you make it a jQuery plugin, it's a matter of doing the following to your code. There are a lot of approaches in building jQuery plugins online. Find one that suits your taste.

$.fn.timer = function(){
  // "this" here is a reference to the element, not wrapped in jQuery.
  // Then put your operations here.
}

// To use, it would be something like
$(element).timer({ mins: 60, seconds: 00 });

// To operate
$(element).timer('add', 1, 2);


Get icon from website, show and update icon I was thinking the other day how could I get the icon from a website and make it show and update when it is updated on the site so I made this code:

URL url2 = null;
boolean updateIcon = true;
try {
    url2 = new URL("https://dl.dropboxusercontent.com/s/70rhm66myw8ay2v/Perception%20Logo.png");
} catch (MalformedURLException ex) {
    updateIcon = false;
    ex.printStackTrace();
}
if (updateIcon) {
    System.out.println("[Perception] Icon updated.");
    if (ComputerCheck.isWindows()) {
        Image bimg = Toolkit.getDefaultToolkit().getImage(url2);
        this.setIconImage(bimg);
    } else if (ComputerCheck.isMac()) {
        Application application = Application.getApplication();
        Image image = Toolkit.getDefaultToolkit().getImage(url2);
        application.setDockIconImage(image);
    }
}

And it works 100% fine but it makes the startup time a lot slower. I was wondering how could I optimize this.

I'd restructure this code significantly. The first thing I'd do is move the image-retrieval into a separate method and the image placing would then be "simpler"..

Compare your code against:

Image image = getRemoteLogo();
if (image != null) {
    // Logo updated
    updateLogo(image);
}

This is largely reimagining what you're doing, and depending on how you prefer it, you might move the nullcheck into updateLogo.

This allows you to hide the image and get rid of the IMO .. clunky null-initialization before the try-block:

private Image getRemoteLogo() {
    try {
       URL remoteUrl = new URL(Config.getRemoteLogoUrl());
       return Toolkit.getDefaultToolkit().getImage(remoteUrl);
    } catch (MalformedURLException ex) {
       // this is the point where you can slap the programmer :D
       ex.printStackTrace();
       return null;
    }
}

This neatly hides the hardcoded dropbox URL in a (not further specified) Configuration, which allows changing the logo location without having to replace classes.

Also it cleanly abstracts away the Image-loading and has clear behavior in error cases. It also gets rid of the superfluous boolean flag you have.

The updateLogo(Image) is history then, you do your ComputerCheck and set the image accordingly.

The startup slowdown is something you'll have to live with.

Oh and I changed the variable names slightly. Use speaking names wherever possible, future maintainers (including yourself) may not be able to map out which number corresponds to which URL :)


Generating a day event calendar based on an array of objects I wanted to get some eyes on some code that I wrote, and see if anyone can help improve what I did. Just looking for some constructive feedback to help make my code more performant, and more elegant.

From a high level my code needs to accomplish the following:

  Create a function that takes an array of objects that each represent an event. Each object in the array has a start and end time represented in minutes. The start and end times are represented as minutes after 9am. For example {start:30, end: 60} represents an event that starts at 9:30am and ends at 10am. The function takes the objects, and plots them as events on a vertical timeline. Events that have crossover will split the container in half, while events that don’t crossover will take the whole container width.

Here is the JS that I wrote to accomplish the above task:

//sample data - array of objects that represent events
var myArray = [
{start: 30, end: 130},
{start: 140, end: 147},
{start: 145, end: 155},
{start: 150, end: 175},
{start: 200, end: 250},
];

var myFunc = function(a) {
  //sort the input array from earliest start time to latest. Items with identical start times will compare end times - the longer duration item resolves with lower index. Assumes no exact duplicate items.
  var sortedDates = a.sort(function(a,b) {
    var caseOne= (a.end>b.end) ? -1 : 1,
        caseTwo= a.start - b.start;

    return (a.start===b.start) ? caseOne : caseTwo;
  });

  for(var i=0; i<sortedDates.length; i++) {
    var currentItem = sortedDates[i],
        itemDuration = currentItem.end-currentItem.start,
        itemTop = currentItem.start,
        prevItem = sortedDates[i-1],
        nextItem = sortedDates[i+1],
        newDiv = document.createElement('div');

    //set a default direction to each item
    currentItem.direction = 'left';

    //determine which items overlap and set a property to indicate
    if(nextItem !== undefined && (currentItem.end - nextItem.start > 0)) {
      currentItem.overlap = true;
      nextItem.overlap = true;
    }

    //ensure items flow in UI by staggering overlapping items
    if(prevItem !== undefined && (prevItem.direction === 'left')) {
      currentItem.direction = 'right';
    }

    //set class names on new DOM element based on overlap
    if(currentItem.overlap === true) {
      if(currentItem.hasOwnProperty('direction')) {
        newDiv.setAttribute('class', 'split '+currentItem.direction);
      }
      else {
        newDiv.setAttribute('class', 'split');
      }
    }

    //set the size and position based on computed duration and start time
    newDiv.setAttribute('style', 'height:'+itemDuration+'px; top:'+itemTop+'px');

    //insert new element into DOM
    document.getElementById('stuff').appendChild(newDiv);
  }
};

Here is a rough working example.

Comments are in the code:

var myArray = [
    { start: 30, end: 130 },
    { start: 140, end: 147 },
    { start: 145, end: 155 },
    { start: 150, end: 175 },
    { start: 200, end: 250 }
];

var myFunc = function (dates) {

    // sort the input array from earliest start time to latest. Items with
    // identical start times will compare end times - the longer duration
    // item resolves with lower index. Assumes no exact duplicate items.
    var sortedDates = dates.sort(function (a, b) {
            // replaced the
            // var caseOne = (a.end > b.end) ? -1 : 1,
            //     caseTwo = a.start - b.start;
            // return (a.start===b.start) ? caseOne : caseTwo
            // with a shorter short cut, considering the start value are the same,
            // it evaluates to falsy (0) and the other part is taken, if evaluated
            // to truthy, the value of the first difference is taken.
            return a.start - b.start || b.end - a.end;
        }),
        factor = 2; // for some more space

    // i change the for (...) loop to the more handy Array.forEach loop
    sortedDates.forEach(function (item, i, o) {

        var itemDuration = factor * (item.end - item.start), // applied factor
            itemTop = factor * item.start,                   // applied factor
            prevItem = o[i - 1],
            nextItem = o[i + 1],
            newDiv = document.createElement('div');

        // set a default direction to each item
        item.direction = 'left';

        // determine which items overlap and set a property to indicate
        // changed the comparison nextItem !== undefined to simply nextItem
        // and the subtraction to a direct comparison
        if (nextItem && item.end > nextItem.start) {
            item.overlap = true;
            nextItem.overlap = true;
        }

        // ensure items flow in UI by staggering overlapping items
        // changed the comparison prevItem !== undefined to simply prevItem
        if (prevItem && prevItem.direction === 'left') {
            item.direction = 'right';
        }

        // set class names on new DOM element based on overlap
        // replaced item.overlap === true with item.overlap because if not set
        // then it evaluates to false and if set, but false the it stays false,
        // otherwise if set and set to true, it evaluates true, then no furter
        // comparison is needed

        // the other change is the comparison of item.hasOwnProperty('direction')
        // here logical or is applied, because item.direction evaluates to false
        // if not set, with the || '' we get an empty string, but if set, then
        // only this result becomes the value
        item.overlap && newDiv.setAttribute('class', 'split ' + item.direction || '');

        //set the size and position based on computed duration and start time
        newDiv.setAttribute('style', 'height:' + itemDuration + 'px; top:' + itemTop + 'px');
        // to see some information
        newDiv.innerText = i + ': ' + item.start + ' - ' + item.end;

        //insert new element into DOM
        console.log(newDiv);
        document.getElementById('calendar').appendChild(newDiv);
    });

};

myFunc(myArray);
#calendar {
    height: 720px;
    width: 100%;
    position: relative;
}
#calendar div {
    position: absolute;
    width: 100%;
    min-height: 5px;
    background: brown;
}
#calendar .split {
    width: 50%;
    background: pink;
}
.right {
    right: 0;
}
.left {
    left: 0;
}


Determine if 1 Queen can take King This challenge was pretty simple - be given the coordinates of a king and a queen on a chess board and determine if the king is in check.

Input is the number of test cases with each test case on a new line, king coordinates first. I read in via text file.

Output "Y" or "N" as the result for each test case.

e.g.

input data:
8
b4 b8
b4 e7
b4 d2
b4 g4
f2 b1
f2 c4
f2 d5
f2 g7

answer:
Y Y Y Y N N N N

I tried a bunch of stuff using System.Text.Encoding to try to figure out how to get the ascii char code from my letters, but ended up falling back on to what I know (Microsoft.VisualBasic).

Option Explicit On
Option Strict On
Option Infer On
Option Compare Text

Imports System.IO
Module Module1

    <STAThread>
    Sub Main()
        Const PATH = "C:\Temp\kingqueen.txt"
        Dim fileContents As String() = System.IO.File.ReadAllLines(PATH)
        Dim numberOfScenarios As Integer = Convert.ToInt32(fileContents(0))
        Dim result As String
        Dim king As String
        Dim queen As String
        For game As Integer = 1 To numberOfScenarios
            king = fileContents(game).Substring(0, 2)
            queen = fileContents(game).Substring(fileContents(game).Length - 2, 2)
            result = result & TestLines(king, queen) & " "
        Next
        result.Trim()
        Console.WriteLine(result)
    End Sub

    Private Function TestLines(ByVal king As String, ByVal queen As String) As String
        Dim kingsub As String = king.Substring(0, 1)
        If king.Substring(0, 1) = queen.Substring(0, 1) Or king.Substring(king.Length - 1, 1) = queen.Substring(queen.Length - 1, 1) Then
            Return "Y"
        Else
            Return TestDiagonals(king, queen)
        End If
    End Function

    Private Function TestDiagonals(ByVal king As String, ByVal queen As String) As String
        Dim kingRank As Integer = Microsoft.VisualBasic.Strings.AscW(king.Substring(0, 1))
        Dim kingFile As Integer = Convert.ToInt32(king.Substring(1, 1))
        Dim queenRank As Integer = Microsoft.VisualBasic.Strings.AscW(queen.Substring(0, 1))
        Dim queenFile As Integer = Convert.ToInt32(queen.Substring(1, 1))

        If (kingRank + kingFile = queenRank + queenFile) Or (kingRank - kingFile = queenRank - queenFile) Then
            Return "Y"
        Else
            Return "N"
        End If
    End Function
End Module

I would suggest that rather than try parsing strings all through your code, try this.

The code below creates a couple of new things. a numeric coordinate structure, a scenario, which is a pair of coordinates, and a list of scenarios.

There are also a couple of functions to parse the text file and each chess location into coordinates. Further down the line, it makes thing easier when you come to checking the queen and king locations.

Module Module1
    Structure Coord
        Dim Rank As Integer
        Dim File As Integer
    End Structure

    Structure Scenario
        Dim King As Coord
        Dim Queen As Coord
    End Structure

    Dim Scenarios As New List(Of Scenario)
    Dim fileContents() As String
    <STAThread>
    Sub Main()
        Const PATH = "C:\Temp\kingqueen.txt"
        fileContents = System.IO.File.ReadAllLines(PATH)
        ParseTextFile()
        Dim result As String = ""
        For Each testScenario As Scenario In Scenarios
            result = result & TestLines(testScenario) & " "
        Next
        result.Trim()
        Console.WriteLine(result)
        Console.ReadLine()
    End Sub

    Private Function ParsePieceLocationAsCoord(chessCoord As String) As Coord
        Dim tempPoint As New Coord
        tempPoint.File = Asc(chessCoord(0)) - 96
        tempPoint.Rank = Val(chessCoord(1))
        Return tempPoint
    End Function

    Private Sub ParseTextFile()
        Scenarios.Clear()
        For Each line As String In fileContents
            Dim newScenario As Scenario
            newScenario.King = ParsePieceLocationAsCoord(line.Substring(0, 2))
            newScenario.Queen = ParsePieceLocationAsCoord(line.Substring(3, 2))
            Scenarios.Add(newScenario)
        Next
    End Sub

    Private Function TestLines(testScenario As Scenario) As String
        With testScenario
            If .King.Rank = .Queen.Rank Or .King.File = .Queen.File Then
                Return "Y"
            Else
                Return TestDiagonals(testScenario)
            End If
        End With
    End Function

    Private Function TestDiagonals(testScenario As Scenario) As String
        With testScenario
            If (.King.Rank + .King.File = .Queen.Rank + .Queen.File) Or (.King.Rank - .King.File = .Queen.Rank - .Queen.File) Then
                Return "Y"
            Else
                Return "N"
            End If
        End With
    End Function


Am I using async C# correctly? I have the following bit of code the calls out to two different command line components (each wrapped in their own Task)

public async Task<FileInfo> RasterizeAllPdfs(IEnumerable<Uri> targetUris, FileInfo destination = null)
{
    // rasterize uris to files in the rasterizedOutput directory
    await rasterize(rasterizedOutput.Value, targetUris);
    // concatenate all pdfs in this directory
    return await concatenatePdfs(rasterizedOutput.Value.EnumerateFiles("*.pdf"), destination);
}

What I would like is for the method to return a task immediately and for the returned task to become resolved once the task returned by concatentatePdfs finishes running.

It seems to work correctly (as in it's returning correct output) but I'm not 100% sure that I'm using the async and await keywords properly

You are using async/await absolutely correctly, that's how they were supposed to be used.

Please note that from this code it's hard to tell whether the method will return the Task immediately, since it will be waiting synchronously for rasterize method to return the Task, and thus the answer depends on the implementation of rasterize.

As a side note - you are using implicit dependency here (first method prepares files in folder, and second method enumerates all pdf files there). I would prefer explicit dependency: rasterize to return a collection of FileInfo objects consumed by the concatenatePdfs method.