Quantcast
Channel: 未分类 –懒得折腾
Viewing all 759 articles
Browse latest View live

Algorithms II: 3-way radix quicksort

$
0
0
Suppose that you run 3-way radix quicksort (do not shuffle) on the following
array of 12 strings:

    7637 8658 3548 2618 4264 8833 6517 4646 8688 7571 7116 3617 

What is the array immediately after the first partitioning step?
Here is the contents of the array after each step:

     lt   i  gt     0    1    2    3    4    5    6    7    8    9   10   11 
    ------------------------------------------------------------------------
      0   1  11  7637 8658 3548 2618 4264 8833 6517 4646 8688 7571 7116 3617 
      0   1  10  7637 3617 3548 2618 4264 8833 6517 4646 8688 7571 7116 8658 
      1   2  10  3617 7637 3548 2618 4264 8833 6517 4646 8688 7571 7116 8658 
      2   3  10  3617 3548 7637 2618 4264 8833 6517 4646 8688 7571 7116 8658 
      3   4  10  3617 3548 2618 7637 4264 8833 6517 4646 8688 7571 7116 8658 
      4   5  10  3617 3548 2618 4264 7637 8833 6517 4646 8688 7571 7116 8658 
      4   5   9  3617 3548 2618 4264 7637 7116 6517 4646 8688 7571 8833 8658 
      4   6   9  3617 3548 2618 4264 7637 7116 6517 4646 8688 7571 8833 8658 
      5   7   9  3617 3548 2618 4264 6517 7116 7637 4646 8688 7571 8833 8658 
      6   8   9  3617 3548 2618 4264 6517 4646 7637 7116 8688 7571 8833 8658 
      6   8   8  3617 3548 2618 4264 6517 4646 7637 7116 7571 8688 8833 8658 
      6   9   8  3617 3548 2618 4264 6517 4646 7637 7116 7571 8688 8833 8658


Algorithms, Part II Assignment 3

$
0
0

Programming Assignment 3: Baseball Elimination

Given the standings in a sports division at some point during the season, determine which teams have been mathematically eliminated from winning their division.

The baseball elimination problem.   In the baseball elimination problem, there is a division consisting of N teams. At some point during the season, team i has w[i] wins, l[i] losses, r[i] remaining games, and g[i][j] games left to play against team j. A team is mathematically eliminated if it cannot possibly finish the season in (or tied for) first place. The goal is to determine exactly which teams are mathematically eliminated. For simplicity, we assume that no games end in a tie (as is the case in Major League Baseball) and that there are no rainouts (i.e., every scheduled game is played).

The problem is not as easy as many sports writers would have you believe, in part because the answer depends not only on the number of games won and left to play, but also on the schedule of remaining games. To see the complication, consider the following scenario:

 
                w[i] l[i] r[i]        g[i][j]
i  team         wins loss left   Atl Phi NY  Mon
------------------------------------------------
0  Atlanta       83   71    8     -   1   6   1
1  Philadelphia  80   79    3     1   -   0   2
2  New York      78   78    6     6   0   -   0
3  Montreal      77   82    3     1   2   0   -

Montreal is mathematically eliminated since it can finish with at most 80 wins and Atlanta already has 83 wins. This is the simplest reason for elimination. However, there can be more complicated reasons. For example, Philadelphia is also mathematically eliminated. It can finish the season with as many as 83 wins, which appears to be enough to tie Atlanta. But this would require Atlanta to lose all of its remaining games, including the 6 against New York, in which case New York would finish with 84 wins. We note that New York is not yet mathematically eliminated despite the fact that it has fewer wins than Philadelphia.

It is sometimes not so easy for a sports writer to explain why a particular team is mathematically eliminated. Consider the following scenario from the American League East on August 30, 1996:

                w[i] l[i] r[i]          g[i][j]
i  team         wins loss left   NY Bal Bos Tor Det
---------------------------------------------------
0  New York      75   59   28     -   3   8   7   3
1  Baltimore     71   63   28     3   -   2   7   4
2  Boston        69   66   27     8   2   -   0   0
3  Toronto       63   72   27     7   7   0   -   0
4  Detroit       49   86   27     3   4   0   0   -

It might appear that Detroit has a remote chance of catching New York and winning the division because Detroit can finish with as many as 76 wins if they go on a 27-game winning steak, which is one more than New York would have if they go on a 28-game losing streak. Try to convince yourself that Detroit is already mathematically eliminated. Here’s one ad hoc explanation; we will present a simpler explanation below.

A maxflow formulation.   We now solve the baseball elimination problem by reducing it to the maxflow problem. To check whether team x is eliminated, we consider two cases.

  • Trivial elimination. If the maximum number of games team x can win is less than the number of wins of some other team i, then team x is trivially eliminated (as is Montreal in the example above). That is, if w[x] +r[x] < w[i], then team x is mathematically eliminated.
  • Nontrivial elimination. Otherwise, we create a flow network and solve a maxflow problem in it. In the network, feasible integral flows correspond to outcomes of the remaining schedule. There are vertices corresponding to teams (other than team x) and to remaining divisional games (not involving team x). Intuitively, each unit of flow in the network corresponds to a remaining game. As it flows through the network froms to t, it passes from a game vertex, say between teams i and j, then through one of the team vertices i or j, classifying this game as being won by that team.More precisely, the flow network includes the following edges and capacities.
    • We connect an artificial source vertex s to each game vertex i-j and set its capacity to g[i][j]. If a flow uses all g[i][j] units of capacity on this edge, then we interpret this as playing all of these games, with the wins distributed between the team vertices i and j.
    • We connect each game vertex i-j with the two opposing team vertices to ensure that one of the two teams earns a win. We do not need to restrict the amount of flow on such edges.
    • Finally, we connect each team vertex to an artificial sink vertex t. We want to know if there is some way of completing all the games so that team x ends up winning at least as many games as team i. Since teamx can win as many as w[x] + r[x] games, we prevent team i from winning more than that many games in total, by including an edge from team vertex i to the sink vertex with capacity w[x] + r[x] - w[i].

    If all edges in the maxflow that are pointing from s are full, then this corresponds to assigning winners to all of the remaining games in such a way that no team wins more games than x. If some edges pointing from sare not full, then there is no scenario in which team x can win the division. In the flow network below Detroit is team x = 4.

    What the min cut tells us.   By solving a maxflow problem, we can determine whether a given team is mathematically eliminated. We would also like to explain the reason for the team’s elimination to a friend in nontechnical terms (using only grade-school arithmetic). Here’s such an explanation for Detroit’s elimination in the American League East example above. With the best possible luck, Detroit finishes the season with 49 + 27 = 76 wins. Consider the subset of teams R = { New York, Baltimore, Boston, Toronto }. Collectively, they already have 75 + 71 + 69 + 63 = 278 wins; there are also 3 + 8 + 7 + 2 + 7 = 27 remaining games among them, so these four teams must win at least an additional 27 games. Thus, on average, the teams in R win at least 305 / 4 = 76.25 games. Regardless of the outcome, one team in R will win at least 77 games, thereby eliminating Detroit.

In fact, when a team is mathematically eliminated there always exists such a convincing certificate of elimination, where R is some subset of the other teams in the division. Moreover, you can always find such a subset Rby choosing the team vertices on the source side of a min s-t cut in the baseball elimination network. Note that although we solved a maxflow/mincut problem to find the subset R, once we have it, the argument for a team’s elimination involves only grade-school algebra.

Your assignment.   Write an immutable data type BaseballElimination that represents a sports division and determines which teams are mathematically eliminated by implementing the following API:

public BaseballElimination(String filename)                    // create a baseball division from given filename in format specified below
public              int numberOfTeams()                        // number of teams
public Iterable<String> teams()                                // all teams
public              int wins(String team)                      // number of wins for given team
public              int losses(String team)                    // number of losses for given team
public              int remaining(String team)                 // number of remaining games for given team
public              int against(String team1, String team2)    // number of remaining games between team1 and team2
public          boolean isEliminated(String team)              // is given team eliminated?
public Iterable<String> certificateOfElimination(String team)  // subset R of teams that eliminates given team; null if not eliminated

The last six methods should throw a java.lang.IllegalArgumentException if one (or both) of the input arguments are invalid teams.

Input format.   The input format is the number of teams in the division N followed by one line for each team. Each line contains the team name (with no internal whitespace characters), the number of wins, the number of losses, the number of remaining games, and the number of remaining games against each team in the divsion. For example, the input files teams4.txt and teams5.txt correspond to the two examples discussed above.

% more teams4.txt
4
Atlanta       83 71  8  0 1 6 1
Philadelphia  80 79  3  1 0 0 2
New_York      78 78  6  6 0 0 0
Montreal      77 82  3  1 2 0 0

% more teams5.txt
5
New_York    75 59 28   0 3 8 7 3
Baltimore   71 63 28   3 0 2 7 4
Boston      69 66 27   8 2 0 0 0
Toronto     63 72 27   7 7 0 0 0
Detroit     49 86 27   3 4 0 0 0

You may assume that N ≥ 1 and that the input files are in the specified format and internally consistent. Note that a team’s total number of remaining games does not necessarily equal the number of remaining games against divisional rivals since teams may play opponents outside of their own division.

Output format.   Use the following main() function, which reads in a sports division from an input file and prints out whether each team is mathematically eliminated and a certificate of elimination for each team that is eliminated:

public static void main(String[] args) {
    BaseballElimination division = new BaseballElimination(args[0]);
    for (String team : division.teams()) {
        if (division.isEliminated(team)) {
            StdOut.print(team + " is eliminated by the subset R = { ");
            for (String t : division.certificateOfElimination(team))
                StdOut.print(t + " ");
            StdOut.println("}");
        }
        else {
            StdOut.println(team + " is not eliminated");
        }
    }
}

Below is the desired output:

% java BaseballElimination teams4.txt
Atlanta is not eliminated
Philadelphia is eliminated by the subset R = { Atlanta New_York }
New_York is not eliminated
Montreal is eliminated by the subset R = { Atlanta }

% java BaseballElimination teams5.txt
New_York is not eliminated
Baltimore is not eliminated
Boston is not eliminated
Toronto is not eliminated
Detroit is eliminated by the subset R = { New_York Baltimore Boston Toronto }

Analysis.   Analyze the worst-case memory usage and running time of your algorithm.

  • What is the order of growth of the amount of memory (in the worst case) that your program uses to determine whether one team is eliminated? In particular, how many vertices and edges are in the flow network as a function of the number of teams N?
  • What is the order of growth of the running time (in the worst case) of your program to determine whether one team is eliminated as a function of the number of teams N? In your calculation, assume that the order of growth of the running time (in the worst case) to compute a maxflow in a network with V vertices and E edges is V E2.

Also, use the output of your program to answer the following question:

  • Consider the sports division defined in teams12.txt. Explain in nontechnical terms (using the results of certificate of elimination and grade-school arithmetic) why Japan is mathematically eliminated.

Extra credit.   Create and submit an interesting test input file (in the specified format) and name it teams.txt. Your input file should contain one or more teams whose elimination would not be obvious to a sports writer. Ideally, your input file should be based on real-world data.

Submission.   Submit BaseballElimination.java and any other files needed to compile your program (excluding those in stdlib.jar and algs4.jar).

This assignment was developed by Kevin Wayne.
Copyright © 2003.


public class BaseballElimination {
    private int numberOfTeams;
    private LinearProbingHashST<String, Integer> teams;
    private int [] w;
    private int [] l;
    private int [] r;
    private int [][] g;
    private LinearProbingHashST<String, SET<String>> certificateOfElimination;
    private LinearProbingHashST<String, Boolean> isEliminated;
    
    // create a baseball division from given filename in format specified below
    public BaseballElimination(String filename) {
        In baseballEliminationIn = new In(new java.io.File(filename));
        numberOfTeams = baseballEliminationIn.readInt();
        teams = new LinearProbingHashST<String, Integer>();
        certificateOfElimination = new LinearProbingHashST<String, SET<String>>();
        isEliminated = new LinearProbingHashST<String, Boolean>();
        w = new int[numberOfTeams];
        l = new int[numberOfTeams];
        r = new int[numberOfTeams];
        g = new int[numberOfTeams][numberOfTeams];
        
        for (int i = 0; i < numberOfTeams; i++) {
            String team = baseballEliminationIn.readString();
            teams.put(team, i);
            w[i] = baseballEliminationIn.readInt();
            l[i] = baseballEliminationIn.readInt();
            r[i] = baseballEliminationIn.readInt();
            for (int j = 0; j < numberOfTeams; j++) {
                g[i][j] = baseballEliminationIn.readInt();
            }
        }
    }
    
    // number of teams
    public int numberOfTeams() {
        return numberOfTeams;
    }
    
    // all teams
    public Iterable<String> teams() {
        return teams.keys();
    }
    
    // number of wins for given team
    public int wins(String team) {
        if (!teams.contains(team)) {
            throw new IllegalArgumentException();
        }
        return w[teams.get(team)];
    }
    
    // number of losses for given team
    public int losses(String team) {
        if (!teams.contains(team)) {
            throw new IllegalArgumentException();
        }
        return l[teams.get(team)];
    }
    
    // number of remaining games for given team
    public int remaining(String team) {
        if (!teams.contains(team)) {
            throw new IllegalArgumentException();
        }
        return r[teams.get(team)];
    }
    
    // number of remaining games between team1 and team2
    public int against(String team1, String team2) {
        if (!teams.contains(team1) || !teams.contains(team2)) {
            throw new IllegalArgumentException();
        }
        return g[teams.get(team1)][teams.get(team2)];
    }
    
    private void eliminateAnalysis(String team) {
        int index = teams.get(team);
        int wx = w[index];
        int rx = r[index];
        SET<String> set = new SET<String>();
        for (String key: teams.keys()) {
            int i = teams.get(key);
            if (i == index) continue;
            if (w[i] > wx + rx) {
                set.add(key);
            }
        }
        if (set.size() > 0) {
            certificateOfElimination.put(team, set);
            isEliminated.put(team, true);
            return;
        }

        
        int gamesNode = (numberOfTeams - 1) * (numberOfTeams - 2)/2 + 1;
        int V = 1 + gamesNode + (numberOfTeams - 1) + 1;
        FlowNetwork flowNetwork = new FlowNetwork(V - 1);
        int incr = 1;
        for (int i = 0; i < numberOfTeams; i++) {
            for (int j = i + 1; j < numberOfTeams; j++) {
                if ((i != index) && (j != index)) {
                    FlowEdge flowEdge1 = new FlowEdge(0, incr, g[i][j]);
                    flowNetwork.addEdge(flowEdge1);
                    int teamNodeIndex = i;
                    if (teamNodeIndex > index) {
                        teamNodeIndex = teamNodeIndex - 1;
                    }
                    int endIndex = gamesNode + teamNodeIndex;
                    FlowEdge f2 = new FlowEdge(incr, endIndex, Integer.MAX_VALUE);
                    flowNetwork.addEdge(f2);
                    teamNodeIndex = j;
                    if (teamNodeIndex > index) {
                        teamNodeIndex = teamNodeIndex - 1;
                    }
                    endIndex = gamesNode + teamNodeIndex;
                    FlowEdge f3 = new FlowEdge(incr, endIndex, Integer.MAX_VALUE);
                    flowNetwork.addEdge(f3);                    
                    incr++;
                }
            }
        }
        
        for (int i = 0; i < numberOfTeams; i++) {
            if (i == index) continue;
            int teamNodeIndex = i;
            if (teamNodeIndex > index) {
                teamNodeIndex = teamNodeIndex - 1;
            }
            int startIndex = gamesNode + teamNodeIndex;
            int endIndex = flowNetwork.V() - 1;
            FlowEdge flowEdge = new FlowEdge(startIndex, endIndex, wx + rx - w[i]);
            flowNetwork.addEdge(flowEdge);
        }
        int endIndex = flowNetwork.V() - 1;
        FordFulkerson maxflow = new FordFulkerson(flowNetwork, 0, endIndex);
        //StdOut.println(flowNetwork);
        boolean result = false;
        for (FlowEdge e : flowNetwork.adj(0))
            if ((e.flow() != e.capacity()) && e.flow() >= 0) {
                result = true;
                break;
            }
        if (result) {
            set = new SET<String>();
            for (String key: teams.keys()) {
                int i = teams.get(key);
                if (i == index) continue;
                int teamNodeIndex = i;
                if (teamNodeIndex > index) {
                    teamNodeIndex = teamNodeIndex - 1;
                }
                if (maxflow.inCut(gamesNode + teamNodeIndex)) {
                    set.add(key);
                }
            }            
            certificateOfElimination.put(team, set);
            isEliminated.put(team, true);
        } else {
            certificateOfElimination.put(team, null);
            isEliminated.put(team, false);
        }
    }
    // is given team eliminated?
    public boolean isEliminated(String team) {
        if (!teams.contains(team)) {
            throw new IllegalArgumentException();
        }
        if (!isEliminated.contains(team)) {
            eliminateAnalysis(team);
        }
        return isEliminated.get(team);
    }
    
    // subset R of teams that eliminates given team; null if not eliminated
    public Iterable<String> certificateOfElimination(String team) {
        if (!teams.contains(team)) {
            throw new IllegalArgumentException();
        }
        if (!certificateOfElimination.contains(team)) {
            eliminateAnalysis(team);
        }
        return certificateOfElimination.get(team);
    } 
    
    public static void main(String[] args) {
        BaseballElimination division = new BaseballElimination(args[0]);
        
        //StdOut.println(division.isEliminated("Japan"));
        for (String team : division.teams()) {
            if (division.isEliminated(team)) {
                StdOut.print(team + " is eliminated by the subset R = { ");
                for (String t : division.certificateOfElimination(team))
                    StdOut.print(t + " ");
                StdOut.println("}");
            }
            else {
                StdOut.println(team + " is not eliminated");
            }
        }
    }
}


Computational Photography Programming Assignment 3 – Image

$
0
0
import numpy as np
import scipy.signal
import cv2

def generating_kernel(a):
  '''Return a 5x5 generating kernel with parameter a.
  '''
  w_1d = np.array([0.25 - a/2.0, 0.25, a, 0.25, 0.25 - a/2.0])
  return np.outer(w_1d, w_1d)

def reduce(image):
  '''Reduce the image to half the size.

  image - a float image of shape (r, c)
  output - a float image of shape (ceil(r/2), ceil(c/2))
  
  For instance, if the input is 5x7, the output will be 3x4.

  You should filter the image with a generating kernel of a = 0.4, and then
  sample every other point.

  Please consult the lectures and tutorial videos for a more in-depth discussion
  of the reduce function.
  '''
  out = None
  # Insert your code here ------------------------------------------------------
  kernel = generating_kernel(0.4)
  import scipy.signal
  smooth = scipy.signal.convolve(image, kernel, 'same')
  size = image.shape
  import math
  width = int(math.ceil(size[0]/2.0))
  height = int(math.ceil(size[1]/2.0))
  out = np.zeros((width, height), dtype = np.float)
  for i in range(width):
    for j in range(height):
      out[i, j] = smooth[2*i, 2*j]

  # ----------------------------------------------------------------------------
  return out
  
def expand(image):
  '''Expand the image to double the size.

  image - a float image of shape (r, c)
  output - a float image of shape (2*r, 2*c)

  You should upsample the image, and then filter it with a generating kernel of
  a = 0.4. Finally, scale the output by the appropraite amount to make sure that
  the net weight contributing to each output pixel is 1.

  Please consult the lectures and tutorial videos for a more in-depth discussion
  of the expand function.
  '''
  out = None
  # Insert your code here ------------------------------------------------------
  (width, height) = image.shape
  out = np.zeros((2*width, 2*height), dtype = np.float)
  for i in range(width):
    for j in range(height):
      out[2*i, 2*j] = image[i, j]
  kernel = generating_kernel(0.4)

  # ----------------------------------------------------------------------------
  return out

def test():
  '''This script will perform a unit test on your function, and provide useful
  output.
  '''
  # Each subsequent layer is a reduction of the previous one
  reduce1 =[np.array([[   0.,    0.,    0.,    0.,    0.,    0.,    0.,    0.],
                      [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    0.],
                      [   0.,    0.,  255.,  255.,  255.,  255.,    0.,    0.],
                      [   0.,    0.,  255.,  255.,  255.,  255.,    0.,    0.],
                      [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    0.],
                      [   0.,    0.,    0.,    0.,    0.,    0.,    0.,    0.]]),
            np.array([[   0.64,    8.92,   12.11,    3.82],
                      [   8.29,  116.03,  157.46,   49.73],
                      [   3.82,   53.55,   72.67,   22.95]]),
            np.array([[ 12.21,  31.85],
                      [ 17.62,  45.97]]),
            np.array([[ 9.77]])] 

  reduce2 = [np.array([[ 255.,  255.,  255.,  255.,  255.,  255.,  255.],
                       [ 255.,  255.,  255.,  255.,  255.,  255.,  255.],
                       [ 255.,  255.,  125.,  125.,  125.,  255.,  255.],
                       [ 255.,  255.,  125.,  125.,  125.,  255.,  255.],
                       [   0.,    0.,    0.,    0.,    0.,    0.,    0.]]),
             np.array([[ 124.62,  173.95,  173.95,  124.62],
                       [ 165.35,  183.1 ,  183.1 ,  165.35],
                       [  51.6 ,   49.2 ,   49.2 ,   51.6 ]]),
             np.array([[  72.85,  104.71],
                       [  49.53,   68.66]]),
             np.array([[ 31.37]])] 

  if __name__ == "__main__":
    print 'Evaluating reduce.'
  for red_pyr in reduce1, reduce2:
    for imgin, true_out in zip(red_pyr[0:-1], red_pyr[1:]):
      if __name__ == "__main__":
        print "input:\n{}\n".format(imgin)

      usr_out = reduce(imgin)

      if not type(usr_out) == type(true_out):
        if __name__ == "__main__":
          print "Error- reduce out has type {}. Expected type is {}.".format(
              type(usr_out), type(true_out))
        return False

      if not usr_out.shape == true_out.shape:
        if __name__ == "__main__":
          print "Error- reduce out has shape {}. Expected shape is {}.".format(
              usr_out.shape, true_out.shape)
        return False

      if not usr_out.dtype == true_out.dtype:
        if __name__ == "__main__":
          print "Error- reduce out has dtype {}. Expected dtype is {}.".format(
              usr_out.dtype, true_out.dtype)
        return False

      if not np.all(np.abs(usr_out - true_out) < 1):
        if __name__ == "__main__":
          print "Error- reduce out has value:\n{}\nExpected value:\n{}".format(
              usr_out, true_out)
        return False

  if __name__ == "__main__":
    print "reduce passed.\n"
    print "Evaluating expand."

  expandin = [np.array([[255]]),
              np.array([[125, 255],
                        [255,   0]]),
              np.array([[ 255.,    0.,  125.,  125.,  125.],
                        [ 255.,    0.,  125.,  125.,  125.],
                        [  50.,   50.,   50.,   50.,   50.]])] 

  expandout =[np.array([[ 163.2 ,  102.  ],
                        [ 102.  ,   63.75]]),
              np.array([[ 120.8 ,  164.75,  175.75,  102.  ],
                        [ 164.75,  158.75,  121.  ,   63.75],
                        [ 175.75,  121.  ,   42.05,   12.75],
                        [ 102.  ,   63.75,   12.75,    0.  ]]),
              np.array([[ 183.6, 114.75, 34.2, 56.25, 101.25, 112.5, 112.5,112.5, 101.25,  56.25],
                        [ 204. ,  127.5,  38.,  62.5,  112.5,  125.,  125., 125.,  112.5,  62.5 ],
                        [ 188.1, 119.75, 39.2, 61.25, 106.25, 117.5, 117.5,117.5, 105.75,  58.75],
                        [ 124.5,  88.75, 44. , 56.25,  81.25,  87.5,  87.5, 87.5,  78.75,  43.75],
                        [  56.4,  52.75, 43.8, 46.25,  51.25,  52.5,  52.5, 52.5,  47.25,  26.25],
                        [  22.5,    25.,  25.,   25.,    25.,   25.,   25.,  25.,   22.5,  12.5 ]])]

  for imgin, true_out in zip(expandin, expandout):
    if __name__ == "__main__":
      print "input:\n{}\n".format(imgin)

    usr_out = expand(imgin)

    if not type(usr_out) == type(true_out):
      if __name__ == "__main__":
        print "Error- expand out has type {}. Expected type is {}.".format(
            type(usr_out), type(true_out))
      return False

    if not usr_out.shape == true_out.shape:
      if __name__ == "__main__":
        print "Error- expand out has shape {}. Expected shape is {}.".format(
            usr_out.shape, true_out.shape)
      return False

    if not usr_out.dtype == true_out.dtype:
      if __name__ == "__main__":
        print "Error- expand out has dtype {}. Expected dtype is {}.".format(
            usr_out.dtype, true_out.dtype)
      return False

    if not np.all(np.abs(usr_out - true_out) < 1):
      if __name__ == "__main__":
        print "Error- expand out has value:\n{}\nExpected value:\n{}".format(
            usr_out, true_out)
      return False

  if __name__ == "__main__":
    print "expand passed."

  if __name__ == "__main__":
    print "All unit tests successful."
  return True

if __name__ == "__main__":
  print "Performing unit tests. Your functions will be accepted if your result is\
    within 1 of the correct output."
  np.set_printoptions(precision=1)

  test()


Dining philosophers problem

$
0
0
package posa

import scala.actors.Actor

/**
 * Actor representing a philosopher.
 * When receives message n, will eat n times and terminate. Eat sequence:
 * 1. picks up left chopstick (may block until available)
 * 2. picks up right chopstick (may block until available)
 * 3. eats
 * 4. puts down right chopstick
 * 5. puts down left chopstick
 */
class Philosopher(id: Int, leftChopstick: Int, rightChopstick: Int) extends Actor {
  def act() {
    receive {
      case n: Int =>
        // Repeat the eat sequence n times
        for (i <- 1 to n) {
          while (!Dinner.pickUpChopstick(id, leftChopstick, true)) {}
          while (!Dinner.pickUpChopstick(id, rightChopstick, false)) {}
          Console.printf("Philosopher %s eats.%n", id.toString)
          Dinner.putDownChopstick(id, rightChopstick, false)
          Dinner.putDownChopstick(id, leftChopstick, true)
        }
        exit()
    }
  }
}

/**
 * Dinner of 5 philosophers, each eating 5 times.
 */
object Dinner extends App {
  // Map to print out side
  val side: Map[Boolean, String] = Map(true -> "Left", false -> "Right")
  
  // Array of Booleans representing chopsticks, true means they are on the table
  val chopsticks: Array[Boolean] = Array.fill(5)(true)
  
  // List of Philosopher actors, and their respective chopsticks
  val philosophers: List[Philosopher] = List(
    new Philosopher(1, 0, 1),
    new Philosopher(2, 1, 2),
    new Philosopher(3, 2, 3),
    new Philosopher(4, 3, 4),
    new Philosopher(5, 4, 0)
  )
  
  // Let the feast begin
  philosophers.foreach(_.start)
  Console.println("Dinner is starting!")
  philosophers.foreach(_ ! 5)
  while (philosophers.exists(_.getState != Actor.State.Terminated)) {}
  Console.println("Dinner is over!")
  
  /**
   * Synchronized method, attempting to pick up a given chopstick by a philosopher.
   * Returns true if the chopstick was available and picked up successfully.
   * In order to prevent deadlocks, left hand side chopsticks can only be picked up if there are at least 2 chopsticks on the table.
   * Right hand side chopsticks can be picked up as long as they are on the table (philosophers always pick up left chopstick first).
   * The synchronization is the JVM native implementation of the Monitor Object pattern. 
   * In this case the monitor of the Dinner object is used, ensuring that only one chopstick can be picked up at a time. 
   */
  def pickUpChopstick(philosopher: Int, chopstick: Int, isLeft: Boolean): Boolean = synchronized {
    val result = chopsticks(chopstick) && (!isLeft || chopsticks.count(c => c) > 1)
    if (result) {
      Console.printf("Philosopher %s picks up %s chopstick.%n", philosopher.toString, side(isLeft))
      chopsticks(chopstick) = false;
    }
    result
  }
  
  /**
   * Puts down the given chopstick by a philosopher.
   * No synchronization is needed.
   */
  def putDownChopstick(philosopher: Int, chopstick: Int, isLeft: Boolean) = {
    Console.printf("Philosopher %s puts down %s chopstick.%n", philosopher.toString, side(isLeft))
    chopsticks(chopstick) = true
  }
  
}


Learn to Program: Crafting Quality Code

$
0
0
# Do not import any modules. If you do, the tester may reject your submission.

# Constants for the contents of the maze.

# The visual representation of a wall.
WALL = '#'

# The visual representation of a hallway.
HALL = '.'

# The visual representation of a brussels sprout.
SPROUT = '@'

# Constants for the directions. Use these to make Rats move.

# The left direction.
LEFT = -1

# The right direction.
RIGHT = 1

# No change in direction.
NO_CHANGE = 0

# The up direction.
UP = -1

# The down direction.
DOWN = 1

# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'


class Rat:
    """ A rat caught in a maze. """

    # Write your Rat methods here.
    def __init__(self, symbol, row, col):
    """(Rat, str, int, int) -> NoneType"""
        self.symbol = symbol
        self.row = row
        self.col = col
        self.num_sprouts_eaten = 0
    def set_location(self, row, col):
    """(Rat, int, int) -> NoneType"""
        self.row = row
        self.col = col
    def eat_sprout(self):
    """(Rat) -> NoneType"""
        self.num_sprouts_eaten = self.num_sprouts_eaten + 1
    def __str__(self):
    """(Rat) -> str"""
         return self.symbol + ' at ('+ self.row +', '+ self.col +') ate ' + self.num_sprouts_eaten + ' sprouts.'
class Maze:
    """ A 2D maze. """
    def __init__(self, maze, rat_1, rat_2):
    """(Maze, list of list of str, Rat, Rat) -> NoneType"""
        self.maze = maze
        self.rat_1 = rat_1
        self.rat_2 = rat_2
        self.num_sprouts_left = 0
        for i in range(maze):
             for j in range(len(maze[i])):
                 if (maze[i][j] == SPROUT):
                     self.num_sprouts_left = self.num_sprouts_left + 1

    def is_wall(self, row, col):
    """(Maze, int, int) -> bool"""
        return maze[row][col] == WALL
    def get_character(self, row, col):
    """(Maze, int, int) -> str"""
        return maze[row][col]
    def move(self, rat, vDir, hDir):
    """(Maze, Rat, int, int) -> bool"""
        row = rat.row + vDir
        col = rat.col + hDir
        if (maze[row][col] == WALL):
            return False
        else:
            if (maze[row][col] == SPROUT):
                rat.eat_sprout()
                maze[row][col] = HALL
                self.num_sprouts_left = self.num_sprouts_left - 1
            rat.set_location(row, col)
            return True
    def __str__(self):
    """(Maze) -> str"""          
         maze[rat_1.row][rat_1.col] == rat_1.symbol
         maze[rat_2.row][rat_2.col] == rat_2.symbol
         result = str(maze) + str(rat_1) + str(rat_2)
         maze[rat_1.row][rat_1.col] == HALL
         maze[rat_2.row][rat_2.col] == HALL
         return result
    # Write your Maze methods here.

The Hardware/Software Interface Lab 1

$
0
0

Lab 1: Instructions


When you’re ready to submit your solution, go to the assignments list.


Lab 1: Manipulating Bits Using C

Overview

The purpose of this assignment is to become more familiar with data at the bit-level representation. You’ll do this by solving a series of programming “puzzles”. Many of these puzzles may seem artificial, but in fact bit manipulations are very useful in cryptography, data encoding, implementing file formats (e.g., MP3), etc. By working your way through these problems, you will get very familiar with bit representations and hopefully will have some fun. You will also be doing some very basic pointer manipulations and arithmetic. Again, the purpose is to get you familiar with data representations and pointers.

Instructions

Perform an update to your course-materials directory on the by running the update-course command from a terminal window. On the script’s success, you should find the provided code for lab1 in your course-materials directory. As a convenience, here is an archive of the course-materials directory as of this lab assignment: lab1.tar.gz.

The lab1 folder contains a number of tools, described later, a bits.c file, and a pointer.c file. Both files contain skeletons for the programming puzzles, along with a comment block that describes exactly what the function must do and what restrictions there are on its implementation. Your assignment is to complete each function skeleton using:

  • only straightline code (i.e., no loops or conditionals);
  • a limited number of C arithmetic and logical operators; and
  • no constants larger than 8 bits (i.e., 0 – 255 inclusive).

The intent of the restrictions is to require you to think about the data as bits – because of the restrictions, your solutions won’t be the most efficient way to accomplish the function’s goal, but the process of working out the solution should make the notion of data as bits completely clear.

Similarly, you will start working with basic pointers and use them to compute the size of different data items in memory and to modify the contents of an array

The Bit Puzzles

This section describes the puzzles that you will be solving in bits.c. More complete (and definitive, should there be any inconsistencies) documentation is found in the bits.c file itself.

Bit Manipulations

The table below describes a set of functions that manipulate and test sets of bits. The Rating column gives the difficulty rating (the number of points) for each puzzle and the Description column states the desired output for each puzzle along with the constraints. See the comments in bits.c for more details on the desired behavior of the functions. You may also refer to the test functions in tests.c. These are used as reference functions to express the correct behavior of your functions, although they don’t satisfy the coding rules for your functions.

Rating Function Name Description
1 bitAnd x & y using only ~ and |
1 bitXor x ^ y using only ~ and &
1 thirdBits return word with every third bit (starting from the least significant bit) set to 1
2 getByte Extract byte n from word x
3 logicalShift shift x to the right by n, using a logical shift
4 bang Compute !x without using !
Extra Credit:
3 conditional x ? y : z

Two’s Complement Arithmetic

The following table describes a set of functions that make use of the two’s complement representation of integers. Again, refer to the comments in bits.c and the reference versions in tests.c for more information.

Rating Function Name Description
2 fitsBits returns 1 if x can be represented as an n-bit, two’s complement integer
2 sign return 1 if positive, 0 if zero, and -1 if negative
3 addOK Determine if x+y can be computed without overflow
Extra Credit:
4 isPower2 returns 1 if x is a power of 2, and 0 otherwise

Checking Your Work

We have included two tools to help you check the correctness of your work.

dlc is a modified version of an ANSI C compiler from the MIT CILK group that you can use to check for compliance with the coding rules for each puzzle. The typical usage is:

$ ./dlc bits.c

The program runs silently unless it detects a problem, such as an illegal operator, too many operators, or non-straightline code in the integer puzzles. Running with the -e switch:

$ ./dlc -e bits.c

causes dlc to print counts of the number of operators used by each function. Type ./dlc -help for a list of command line options.

btest is a program that checks the functional correctness of the code in bits.c. To build and use it, type the following two commands:

$ make
$ ./btest

Notice that you must rebuild btest each time you modify your bits.c file. (You rebuild it by typing make.) You’ll find it helpful to work through the functions one at a time, testing each one as you go. You can use the -f flag to instruct btest to test only a single function:

$ ./btest -f bitXor

You can feed it specific function arguments using the option flags -1-2, and -3:

$ ./btest -f bitXor -1 7 -2 0xf

Check the file README for documentation on running the btest program.

Advice

Start early on bits.c, if you get stuck on one problem move on. You may find you suddenly realize the solution the next day. Puzzle over the problems yourself, it is much more rewarding to find the solution yourself than stumble upon someone else’s solution. If you do not quite meet the operator limit don’t worry there will be partial credit, but often times working with a suboptimal solution will allow you to see how to improve it.

Do not include the <stdio.h> header file in your bits.c file, as it confuses dlc and results in some non-intuitive error messages. You will still be able to use printf in your bits.c file for debugging without including the <stdio.h> header, although gcc will print a warning that you can ignore.

You should be able to use the debugger on your code. For example:

$ make
gcc -O -Wall -m32 -g -lm -o btest bits.c btest.c decl.c tests.c
gcc -O -Wall -m32 -g -o fshow fshow.c
gcc -O -Wall -m32 -g -o ishow ishow.c
$ gdb ./btest
GNU gdb (GDB) Fedora (7.1-34.fc13)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Reading symbols from /homes/iws/dvhc/cse351/lab1/src/btest...done.
(gdb) b bitXor
Breakpoint 1 at 0x8048717: file bits.c, line 144.
(gdb) r
Starting program: /homes/iws/dvhc/cse351/lab1/src/btest
ScoreRatingErrorsFunction

Breakpoint 1, bitXor (x=-2147483648, y=-2147483648) at bits.c:144
144}
(gdb) p x
$1 = -2147483648
(gdb) p/x x
$2 = 0x80000000
(gdb) q
A debugging session is active.

Inferior 1 [process 12728] will be killed.

Quit anyway? (y or n) y

The dlc program enforces a stricter form of C declarations than is the case for C++ or that is enforced by gcc. In particular, in a block (what you enclose in curly braces) all your variable declarations must appear before any statement that is not a declaration. For example, dlc will complain about the following code:

int foo(int x)
{
    int a = x;
    a *= 3;     /* Statement that is not a declaration */
    int b = a;  /* ERROR: Declaration not allowed here */
}

Instead, you must declare all your variables first, like this:

int foo(int x)
{
    int a = x;
    int b;
    a *= 3;
    b = a;
}

Using Pointers

This section describes the four functions you will be completing in pointer.c that is also in the lab1 folder you downloaded. Refer to the file pointer.c itself for more complete details.

Pointer Arithmetic

The first three functions in pointer.c ask you to compute the size (in bytes) of various data elements (ints, doubles, and pointers). You will accomplish this by noting that arrays of these data elements allocate contiguous space in memory so that one element follows the next. You are permitted to use casts for these functions.

Manipulating Data Using Pointers

The fourth function in pointer.c asks you to change the value of an element of an array using only the starting address of the array. You will add the appropriate value to the pointer to create a new pointer to the data element to be modified.

The next two functions deal with boundings checking of pointers and the final function deals with more bit manipulation. You

Checking your work

For pointer.c, we have included a simple test harness: ptest.c. You can test your solutions like this:

$ make ptest
$ ./ptest

This test harness only checks if your solutions return the expected result, not if they meet the specific criteria of each problem. We will review your solutions to ensure they meet the restrictions of the assignment.

Submitting Your Work

You will be able to submit your assignment with the submit-hw script that is bundled with the lab1 course-materials update. Using the script should be straight-forward, but it does expect you to not move/rename any files from the ”course-materials” directory. Open a terminal and type the following commands:

  submit-hw lab1.bits
  submit-hw lab1.pointer

This will submit both bits.c and pointer.c (one file per command). However, you may just want to submit all parts for Lab1 together. You may use the following command to do so. It will save you the trouble of calling both commands, but it will still count as a submission for each part.

  submit-hw lab1

After calling the submit-hw script, you will be prompted for your Coursera username and then your submission password. Your submission password is NOT the same as your regular Coursera account password!!!! You may locate your submission password at the top of the assignments list page.

After providing your credentials, the submit-hw script will run some basic checks on your code. For bits.c, it will run the driver.pl script and warn you if you get below a score of 41 (full-credit without the extra-credit). For pointer.c, it will simply check to see if ptest reports any failures to the tests.

Once confirming that you wish to submit, with a working Internet connection, the script should submit your code properly. You can go to the assignments list page to double-check that it has been submitted and check your score as well as any feedback the auto-grader gives you. You may also download your submission code from this page, if you wish.

// Rating: 1
int bitAnd(int, int);
int test_bitAnd(int, int);
int bitXor(int, int);
int test_bitXor(int, int);
int thirdBits();
int test_thirdBits();
// Rating: 2
int fitsBits(int, int);
int test_fitsBits(int, int);
int sign(int);
int test_sign(int);
int getByte(int, int);
int test_getByte(int, int);
// Rating: 3
int logicalShift(int, int);
int test_logicalShift(int, int);
int addOK(int, int);
int test_addOK(int, int);
// Rating: 4
int bang(int);
int test_bang(int);
// Extra Credit: Rating: 3
int conditional(int, int, int);
int test_conditional(int, int, int);
// Extra Credit: Rating: 4
int isPower2(int);
int test_isPower2(int);

/*
 * CSE 351 HW1 (Data Lab )
 *
 * *
 * bits.c - Source file with your solutions to the Lab.
 * This is the file you will hand in to your instructor.
 *
 * WARNING: Do not include the header; it confuses the dlc
 * compiler. You can still use printf for debugging without including
 * , although you might get a compiler warning. In general,
 * it's not good practice to ignore compiler warnings, but in this
 * case it's OK.
 */

#if 0
/*
 * Instructions to Students:
 *
 * STEP 1: Read the following instructions carefully.
 */

You will provide your solution to this homework by
editing the collection of functions in this source file.

INTEGER CODING RULES:

 Replace the "return" statement in each function with one
 or more lines of C code that implements the function. Your code
 must conform to the following style:

 int Funct(arg1, arg2, ...) {
 /* brief description of how your implementation works */
 int var1 = Expr1;
 ...
 int varM = ExprM;

 varJ = ExprJ;
 ...
 varN = ExprN;
 return ExprR;
 }

 Each "Expr" is an expression using ONLY the following:
 1. Integer constants 0 through 255 (0xFF), inclusive. You are
 not allowed to use big constants such as 0xffffffff.
 2. Function arguments and local variables (no global variables).
 3. Unary integer operations ! ~
 4. Binary integer operations & ^ | + << >>

 Some of the problems restrict the set of allowed operators even further.
 Each "Expr" may consist of multiple operators. You are not restricted to
 one operator per line.

 You are expressly forbidden to:
 1. Use any control constructs such as if, do, while, for, switch, etc.
 2. Define or use any macros.
 3. Define any additional functions in this file.
 4. Call any functions.
 5. Use any other operations, such as &&, ||, -, or ?:
 6. Use any form of casting.
 7. Use any data type other than int. This implies that you
 cannot use arrays, structs, or unions.

 You may assume that your machine:
 1. Uses 2s complement, 32-bit representations of integers.
 2. Performs right shifts arithmetically.
 3. Has unpredictable behavior when shifting an integer by more
 than the word size.

EXAMPLES OF ACCEPTABLE CODING STYLE:
 /*
 * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
 */
 int pow2plus1(int x) {
 /* exploit ability of shifts to compute powers of 2 */
 return (1 << x) + 1;
 }

 /*
 * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
 */
 int pow2plus4(int x) {
 /* exploit ability of shifts to compute powers of 2 */
 int result = (1 << x);
 result += 4;
 return result;
 }

NOTES:
 1. Use the dlc (data lab checker) compiler (described in the handout) to
 check the legality of your solutions.
 2. Each function has a maximum number of operators (! ~ & ^ | + << >>)
 that you are allowed to use for your implementation of the function.
 The max operator count is checked by dlc. Note that '=' is not
 counted; you may use as many of these as you want without penalty.
 3. Use the btest test harness to check your functions for correctness.
 4. The maximum number of ops for each function is given in the
 header comment for each function. If there are any inconsistencies
 between the maximum ops in the writeup and in this file, consider
 this file the authoritative source.

/*
 * STEP 2: Modify the following functions according the coding rules.
 *
 * IMPORTANT. TO AVOID GRADING SURPRISES:
 * Use the dlc compiler to check that your solutions conform
 * to the coding rules.
 */

#endif
// Rating: 1
/*
 * bitAnd - x&y using only ~ and |
 * Example: bitAnd(6, 5) = 4
 * Legal ops: ~ |
 * Max ops: 8
 * Rating: 1
 */
int bitAnd(int x, int y) {
 return ~(~x | ~y);
}
/*
 * bitXor - x^y using only ~ and &
 * Example: bitXor(4, 5) = 1
 * Legal ops: ~ &
 * Max ops: 14
 * Rating: 1
 */
int bitXor(int x, int y) {
 return ~(~x & ~y);
}
/*
 * thirdBits - return word with every third bit (starting from the LSB) set to 1
 * and the rest set to 0
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 8
 * Rating: 1
 */
int thirdBits(void) {
 return 2;
}
// Rating: 2
/*
 * fitsBits - return 1 if x can be represented as an
 * n-bit, two's complement integer.
 * 1 <= n <= 32
 * Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 15
 * Rating: 2
 */
int fitsBits(int x, int n) {
 return 2;
}
/*
 * sign - return 1 if positive, 0 if zero, and -1 if negative
 * Examples: sign(130) = 1
 * sign(-23) = -1
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 10
 * Rating: 2
 */
int sign(int x) {
 return 2;
}
/*
 * getByte - Extract byte n from word x
 * Bytes numbered from 0 (LSB) to 3 (MSB)
 * Examples: getByte(0x12345678,1) = 0x56
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 6
 * Rating: 2
 */
int getByte(int x, int n) {
 return 2;
}
// Rating: 3
/*
 * logicalShift - shift x to the right by n, using a logical shift
 * Can assume that 0 <= n <= 31
 * Examples: logicalShift(0x87654321,4) = 0x08765432
 * Legal ops: ~ & ^ | + << >>
 * Max ops: 20
 * Rating: 3
 */
int logicalShift(int x, int n) {
 return 2;
}
/*
 * addOK - Determine if can compute x+y without overflow
 * Example: addOK(0x80000000,0x80000000) = 0,
 * addOK(0x80000000,0x70000000) = 1,
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 20
 * Rating: 3
 */
int addOK(int x, int y) {
 return 2;
}
// Rating: 4
/*
 * bang - Compute !x without using !
 * Examples: bang(3) = 0, bang(0) = 1
 * Legal ops: ~ & ^ | + << >>
 * Max ops: 12
 * Rating: 4
 */
int bang(int x) {
 return 2;
}
// Extra Credit: Rating: 3
/*
 * conditional - same as x ? y : z
 * Example: conditional(2,4,5) = 4
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 16
 * Rating: 3
 */
int conditional(int x, int y, int z) {
 return 2;
}
// Extra Credit: Rating: 4
/*
 * isPower2 - returns 1 if x is a power of 2, and 0 otherwise
 * Examples: isPower2(5) = 0, isPower2(8) = 1, isPower2(0) = 0
 * Note that no negative number is a power of 2.
 * Legal ops: ! ~ & ^ | + << >>
 * Max ops: 20
 * Rating: 4
 */
int isPower2(int x) {
 return 2;
}
/*
 * CSE 351 HW1 (Data Lab - Pointers)
 *
 * <Please put your name and userid here>
 *
 * pointer.c - Source file with your solutions to the Lab.
 *          This is the file you will hand in to your instructor.
 *
 * WARNING: Do not include the <stdio.h> header; it confuses the dlc
 * compiler. You can still use printf for debugging without including
 * <stdio.h>, the following function declaration should prevent a
 * compiler warning. In general, it's not good practice to ignore
 * compiler warnings, but in this case it's OK.
 */
int printf(const char *, ...);

#if 0
/*
 * Instructions to Students:
 *
 * STEP 1: Read the following instructions carefully.
 */

You will provide your solution to this homework by
editing the collection of functions in this source file.

INTEGER CODING RULES:

  Replace the "return" statement in each function with one
  or more lines of C code that implements the function. Your code
  must conform to the following style:

  int Funct(arg1, arg2, ...) {
      /* brief description of how your implementation works */
      int var1 = Expr1;
      ...
      int varM = ExprM;

      varJ = ExprJ;
      ...
      varN = ExprN;
      return ExprR;
  }

  Each "Expr" is an expression using ONLY the following:
  1. Integer constants 0 through 255 (0xFF), inclusive. You are
      not allowed to use big constants such as 0xffffffff.
  2. Function arguments and local variables (no global variables).
  3. For 1-4, only Unary integer operations *, & and Binary integer
      operations - + * are allowed. For the last three, you may also
      use shifts (<<, >>), ~, ==, and ^.

  Some of the problems restrict the set of allowed operators even further.
  Each "Expr" may consist of multiple operators. You are not restricted to
  one operator per line.

  You are expressly forbidden to:
  1. Use any control constructs such as if, do, while, for, switch, etc.
  2. Define or use any macros.
  3. Define any additional functions in this file.
  4. Call any functions.
  5. Use any other operations, such as &&, ||, ?: or sizeof.
  6. Use any data type other than those already in the declarations provided.

  You may assume that your machine:
  1. Uses 2s complement, 32-bit representations of integers.
  2. Performs right shifts arithmetically.
  3. Has unpredictable behavior when shifting an integer by more
     than the word size.

/*
 * STEP 2: Modify the following functions according the coding rules.
 *
 * Test the code below in your own 'main' program.
 *
 */

#endif

/*
 * Return the size of an integer in bytes.
 */
int intSize() {
  int intArray[10];
  int * intPtr1;
  int * intPtr2;
  // TODO: Write code to compute size of an integer.

  return 2;
}

/*
 * Return the size of a double in bytes.
 */
int doubleSize() {
  double doubArray[10];
  double * doubPtr1;
  double * doubPtr2;
  // TODO: Write code to compute size of a double.

  return 2;
}

/*
 * Return the size of a pointer in bytes.
 */
int pointerSize() {
  double * ptrArray[10];
  double ** ptrPtr1;
  double ** ptrPtr2;
  // TODO: Write code to compute size of a pointer.

  return 2;
}

/*
 * Modify intArray[5] to be the value 351 using only &intArray and
 * pointer arithmetic.
 */
int changeValue() {
  int intArray[10];
  int * intPtr1 = intArray;
  int * intPtr2;
  // TODO: Write code to change value of intArray[5] to 351 using only
  //       intPtr1 and the + operator.

  return intArray[5];
}


/*
 * Return 1 if ptr1 and ptr2 are within the *same* 64-byte aligned
 * block (or word) of memory. Return zero otherwise.
 *
 * Operators / and % and loops are NOT allowed.
 */
int withinSameBlock(int * ptr1, int * ptr2) {
  // TODO
  return 2;
}

/*
 * Return 1 if ptr points to an element within the specified intArray,
 * 0 otherwise.
 */
int withinArray(int * intArray, int size, int * ptr) {
  // TODO
  return 2;
}
/*
 * Return x with the n bits that begin at position p inverted (i.e.,
 * turn 0 into 1 and vice versa) and the rest left unchanged. Consider
 * the indices of x to begin with the low-order bit numbered as 0.
 */
int invert(int x, int p, int n) {
  // TODO
  return 2;
}

Algorithms, Part II Assignment 4

$
0
0

COS 226 Programming Assignment

Burrows-Wheeler Data Compression Algorithm

Implement the Burrows-Wheeler data compression algorithm. This revolutionary algorithm outcompresses gzip and PKZIP, is relatively easy to implement, and is not protected by any patents. It forms the basis of the Unix compression utililty bzip2.

The Burrows-Wheeler compression algorithm consists of three algorithmic components, which are applied in succession:

 

  1. Burrows-Wheeler transform. Given a typical English text file, transform it into a text file in which sequences of the same character occur near each other many times. 
  2. Move-to-front encoding. Given a text file in which sequences of the same character occur near each other many times, convert it into a text file in which certain characters appear more frequently than others. 
  3. Huffman compression. Given a text file in which certain characters appear more frequently than others, compress it by encoding freqently occuring characters with short codewords and rare ones with long codewords.

The final step is the one that compresses the message: it is particularly effective because the first two steps result in a text file in which certain characters appear much more frequently than others. To expand a message, apply the inverse operations in reverse order: first apply the Huffman expansion, then the move-to-front decoding, and finally the inverse Burrows-Wheeler transform. Your task is to implement Burrows-Wheeler and move-to-front components efficiently.

Binary input and binary output. To enable that your programs work with binary data, you will use the libraries BinaryStdIn.java and BinaryStdOut.java described in Algorithms, 4th edition. To display the binary output when debugging, you can useHexDump.java, which takes a command-line argument N, reads bytes from standard input and writes them to standard output in hexadecimal, N per line.

% more abra.txt
ABRACADABRA!

% java HexDump 16 < abra.txt
41 42 52 41 43 41 44 41 42 52 41 21
96 bits

Note that 'A' is 41 (hex) in ASCII.

Huffman encoding and decoding. Huffman.java (Program 5.10 in Algorithms, 4th edition) implements the classic Huffman compression and expansion algorithms.

% java Huffman - < abra.txt | java HexDump 16
50 4a 22 43 43 54 a8 40 00 00 01 8f 96 8f 94
120 bits
% java Huffman - < abra.txt | java Huffman +
ABRACADABRA!

You will not write any code for this step.

Move-to-front encoding and decoding. The main idea of move-to-front encoding is to maintain an ordered sequence of all of the characters in the alphabet, and repeatedly read in a character from the input message, print out the position in which that character appears, and move that character to the front of the sequence. As a simple example, if the initial ordering over a 6-character alphabet is A B C D E F, and we want to encode the input CAAABCCCACCF, then we would update the move-to-front sequences as follows:

move-to-front    in   out
-------------    ---  ---
 A B C D E F      C    2 
 C A B D E F      A    1
 A C B D E F      A    0
 A C B D E F      A    0
 A C B D E F      B    2
 B A C D E F      C    2
 C B A D E F      C    0
 C B A D E F      C    0
 C B A D E F      A    2
 A C B D E F      C    1
 C A B D E F      C    0
 C A B D E F      F    5
 F C A B D E

If the same character occurs next to each other many times in the input, then many of the output values will be small integers, such as 0, 1, and 2. The extremely high frequency of certain characters makes an ideal scenario for Huffman coding.

 

  • Move-to-front encoding. Your task is to maintain an ordered sequence of the 256 extended ASCII characters. Initialize the sequence by making the ith character in the sequence equal to the ith extended ASCII character. Now, read in each 8-bit character c from standard input one at a time, output the 8-bit index in the sequence where c appears, and move c to the front.
    % java MoveToFront - < abra.txt | java HexDump 16
    41 42 52 02 44 01 45 01 04 04 02 26
    96 bits

     

  • Move-to-front decoding. Initialize an ordered sequence of 256 characters, where extended ASCII character i appears ith in the sequence. Now, read in each 8-bit character i (but treat it as an integer between 0 and 255) from standard input one at a time, write the ith character in the sequence, and move that character to the front. Check that the decoder recovers any encoded message.
    % java MoveToFront - < abra.txt | java MoveToFront +
    ABRACADABRA!

Name your program MoveToFront.java and organize it using the following API:

public class MoveToFront {
    // apply move-to-front encoding, reading from standard input and writing to standard output
    public static void encode()

    // apply move-to-front decoding, reading from standard input and writing to standard output
    public static void decode()

    // if args[0] is '-', apply move-to-front encoding
    // if args[0] is '+', apply move-to-front decoding
    public static void main(String[] args)
}

The running time of move-to-front encoding and decoding should be proportional to R N in the worst case and proportional to N in practice on inputs that arise when compressing typical English text, where N is the number of characters in the input and R is the alphabet size.

Circular suffix array. To efficiently implement the key component in the Burrows-Wheeler transform, you will use a fundamental data structure known as the circular suffix array, which describes the abstraction of a sorted array of the N circular suffixes of a string of length N. As an example, consider the string “ABRACADABRA!” of length 12. The table below shows its 12 circular suffixes and the result of sorting them.

 i       Original Suffixes           Sorted Suffixes         index[i]
--    -----------------------     -----------------------    --------
 0    A B R A C A D A B R A !     ! A B R A C A D A B R A    11
 1    B R A C A D A B R A ! A     A ! A B R A C A D A B R    10
 2    R A C A D A B R A ! A B     A B R A ! A B R A C A D    7
 3    A C A D A B R A ! A B R     A B R A C A D A B R A !    0
 4    C A D A B R A ! A B R A     A C A D A B R A ! A B R    3
 5    A D A B R A ! A B R A C     A D A B R A ! A B R A C    5
 6    D A B R A ! A B R A C A     B R A ! A B R A C A D A    8
 7    A B R A ! A B R A C A D     B R A C A D A B R A ! A    1
 8    B R A ! A B R A C A D A     C A D A B R A ! A B R A    4
 9    R A ! A B R A C A D A B     D A B R A ! A B R A C A    6
10    A ! A B R A C A D A B R     R A ! A B R A C A D A B    9
11    ! A B R A C A D A B R A     R A C A D A B R A ! A B    2

We define index[i] to be the index of the original suffix that appears ith in the sorted array. For example, index[11] = 2 means that the 2nd original suffix appears 11th in the sorted order (i.e., last alphabetically).

Your job is to implement the following circular suffix array API, which provides the client access to the index[] values:

public class CircularSuffixArray {
    public CircularSuffixArray(String s)  // circular suffix array of s
    public int length()                   // length of s
    public int index(int i)               // returns index of ith sorted suffix
}

Your data type must use linear space; the methods length() and index() must take constant time. Prior to Java 7, Update 6, the array of circular suffixes could be constructed in linear space using the substring() method. It now takes quadratic space—do not explicitly generate the N suffixes. Instead, precompute and store the index[] array, which requires only linear space.

Burrows-Wheeler transform. The goal of the Burrows-Wheeler transform is not to compress a message, but rather to transform it into a form that is more amenable to compression. The transform rearranges the characters in the input so that there are lots of clusters with repeated characters, but in such a way that it is still possible to recover the original input. It relies on the following intuition: if you see the letters hen in English text, then most of the time the letter preceding it is t or w. If you could somehow group all such preceding letters together (mostly t‘s and some w‘s), then you would have an easy opportunity for data compression.

 

  • Burrows-Wheeler encoding. The Burrows-Wheeler transform of a string s of length N is defined as follows: Consider the result of sorting the N circular suffixes of s. The Burrows-Wheeler transform is the last column in the sorted suffixes array t[], preceded by the row number first in which the original string ends up. Continuing with the “ABRACADABRA!” example above, we highlight the two components of the Burrows-Wheeler transform in the table below.
     i     Original Suffixes          Sorted Suffixes       t    index[i]
    --    -----------------------     -----------------------    --------
     0    A B R A C A D A B R A !     ! A B R A C A D A B R A    11
     1    B R A C A D A B R A ! A     A ! A B R A C A D A B R    10
     2    R A C A D A B R A ! A B     A B R A ! A B R A C A D    7
    *3    A C A D A B R A ! A B R     A B R A C A D A B R A !   *0
     4    C A D A B R A ! A B R A     A C A D A B R A ! A B R    3
     5    A D A B R A ! A B R A C     A D A B R A ! A B R A C    5
     6    D A B R A ! A B R A C A     B R A ! A B R A C A D A    8
     7    A B R A ! A B R A C A D     B R A C A D A B R A ! A    1
     8    B R A ! A B R A C A D A     C A D A B R A ! A B R A    4
     9    R A ! A B R A C A D A B     D A B R A ! A B R A C A    6
    10    A ! A B R A C A D A B R     R A ! A B R A C A D A B    9
    11    ! A B R A C A D A B R A     R A C A D A B R A ! A B    2

    Since the original string ABRACADABRA! ends up in row 3, we have first = 3. Thus, the Burrows-Wheeler transform is

    3
    ARD!RCAAAABB

    Notice how there are 4 consecutive As and 2 consecutive Bs—these clusters make the message easier to compress.

    % java BurrowsWheeler - < abra.txt | java HexDump 16
    00 00 00 03 41 52 44 21 52 43 41 41 41 41 42 42
    128 bits

    Also, note that the integer 3 is represented using 4 bytes (00 00 00 03). The character 'A' is represented by hex 41, the character 'R' by 52, and so forth. 

  • Burrows-Wheeler decoder. Now, we describe how to invert the Burrows-Wheeler transform and recover the original input string. If the jth original suffix (original string, shifted j characters to the left) is the ith row in the sorted order, we define next[i]to be the row in the sorted order where the (j + 1)st original suffix appears. For example, if first is the row in which the original input string appears, then next[first] is the row in the sorted order where the 1st original suffix (the original string left-shifted by 1) appears; next[next[first]] is the row in the sorted order where the 2nd original suffix appears; next[next[next[first]]] is the row where the 3rd original suffix appears; and so forth. 
    • Decoding the message given t[], first, and the next[] array. The input to the Burrows-Wheeler decoder is the last column t[] of the sorted suffixes along with first. From t[], we can deduce the first column of the sorted suffixes because it consists of precisely the same characters, but in sorted order.
       i      Sorted Suffixes     t      next
      --    -----------------------      ----
       0    ! ? ? ? ? ? ? ? ? ? ? A        3
       1    A ? ? ? ? ? ? ? ? ? ? R        0
       2    A ? ? ? ? ? ? ? ? ? ? D        6
      *3    A ? ? ? ? ? ? ? ? ? ? !        7
       4    A ? ? ? ? ? ? ? ? ? ? R        8
       5    A ? ? ? ? ? ? ? ? ? ? C        9
       6    B ? ? ? ? ? ? ? ? ? ? A       10
       7    B ? ? ? ? ? ? ? ? ? ? A       11
       8    C ? ? ? ? ? ? ? ? ? ? A        5
       9    D ? ? ? ? ? ? ? ? ? ? A        2
      10    R ? ? ? ? ? ? ? ? ? ? B        1
      11    R ? ? ? ? ? ? ? ? ? ? B        4

      Now, given the next[] array and first, we can reconstruct the original input string because the first character of the ith original suffix is the ith character in the input string. In the example above, since first = 3, we know that the original input string appears in row 3; thus, the original input string starts with 'A' (and ends with '!'). Since next[first] = 7, the next original suffix appears in row 7; thus, the next character in the original input string is 'B'. Since next[next[first]] =11, the next original suffix appears in row 11; thus, the next character in the original input string is 'R'

    • Construction the next[] array from t[] and first. Amazingly, the information contained in the Burrows-Wheeler transform suffices to reconstruct the next[] array, and, hence, the original message! Here’s how. It is easy to deduce a next[]value for a character that appears exactly once in the input string. For example, consider the suffix that starts with 'C'. By inspecting the first column, it appears 8th in the sorted order. The next original suffix after this one will have the character 'C'as its last character. By inspecting the last column, the next original appears 5th in the sorted order. Thus, next[8] = 5. Similarly, 'D' and '!' each occur only once, so we can deduce that next[9] = 2 and next[0] = 3.
       i      Sorted Suffixes     t      next
      --    -----------------------      ----
       0    ! ? ? ? ? ? ? ? ? ? ? A        3
       1    A ? ? ? ? ? ? ? ? ? ? R
       2    A ? ? ? ? ? ? ? ? ? ? D
      *3    A ? ? ? ? ? ? ? ? ? ? !
       4    A ? ? ? ? ? ? ? ? ? ? R 
       5    A ? ? ? ? ? ? ? ? ? ? C
       6    B ? ? ? ? ? ? ? ? ? ? A
       7    B ? ? ? ? ? ? ? ? ? ? A
       8    C ? ? ? ? ? ? ? ? ? ? A        5
       9    D ? ? ? ? ? ? ? ? ? ? A        2
      10    R ? ? ? ? ? ? ? ? ? ? B
      11    R ? ? ? ? ? ? ? ? ? ? B

      However, since 'R' appears twice, it may seem ambiguous whether next[10] = 1 and next[11] = 4, or whether next[10] = 4 and next[11] = 1. Here’s the key rule that resolves the apparent ambiguity:

      If sorted row i and j both start with the same character and i < j, then next[i] < next[j].

      This rule implies next[10] = 1 and next[11] = 4. Why is this rule valid? The rows are sorted so row 10 is lexicographically less than row 11. Thus the ten unknown characters in row 10 must be less than the ten unknown characters in row 11 (since both start with 'R'). We also know that between the two rows that end with 'R', row 1 is less than row 4. But, the ten unknown characters in row 10 and 11 are precisely the first ten characters in rows 1 and 4. Thus, next[10] = 1 andnext[11] = 4 or this would contradict the fact that the suffixes are sorted.

    Check that the decoder recovers any encoded message.

    % java BurrowsWheeler - < abra.txt | java BurrowsWheeler +
    ABRACADABRA!

Name your program BurrowsWheeler.java and organize it using the following API:

public class BurrowsWheeler {
    // apply Burrows-Wheeler encoding, reading from standard input and writing to standard output
    public static void encode()

    // apply Burrows-Wheeler decoding, reading from standard input and writing to standard output
    public static void decode()

    // if args[0] is '-', apply Burrows-Wheeler encoding
    // if args[0] is '+', apply Burrows-Wheeler decoding
    public static void main(String[] args)
}

The running time of your Burrows-Wheeler encoder should be proportional to N + R in the worst case, excluding the time to construct the circular suffix array. The running time of your Burrows-Wheeler decoder should be proportional to N + R in the worst case.

Analysis (optional). Once you have MoveToFront.java and BurrowsWheeler.java working, compress some of these text files; then, test it on some binary files. Calculate the compression ratio achieved for each file and report the time to compress and expand each file. (Here, compression and expansion consists of applying BurrowsWheelerMoveToFront, and Huffman in succession.) Finally, determine the order of growth of the running time of each of your encoders and decoders, both in the worst case and on typical Englist text inputs.

Deliverables. Submit MoveToFront.javaBurrowsWheeler.java, and CircularSuffixArray.java along with any other helper files needed to run your program (excluding those in stdlib.jar and algs4.jar).

This assignment was developed by Kevin Wayne.
Copyright © 2004.
 
 

public class MoveToFront {    
    public static void encode() {
        byte[] mtf = new byte[256];
        for (int i = 0; i < mtf.length; i++) {
            mtf[i] = (byte) i;
        }        
        while (!BinaryStdIn.isEmpty()) {
            byte value = BinaryStdIn.readByte();
            int index = 0;
            byte temp = mtf[0];
            if (value != temp) {
                mtf[0] = value;
                while (value != temp) {
                    index++;
                    index = index % 256;
                    final byte temp2 = temp;
                    temp = mtf[index];
                    mtf[index] = temp2;
                }
            }
            BinaryStdOut.write((byte) index);
        }
        BinaryStdIn.close();
        BinaryStdOut.close();
    }
    
    public static void decode() {
        byte[] mtf = new byte[256];
        for (int i = 0; i < mtf.length; i++) {
            mtf[i] = (byte) i;
        }
        while (!BinaryStdIn.isEmpty()) {
            int index = BinaryStdIn.readByte();
            if (index < 0) {
                index = index + 256;
            }
            byte value = mtf[index];
            System.arraycopy(mtf, 0, mtf, 1, index);
            mtf[0] = value;
            BinaryStdOut.write(value);
        }
        BinaryStdOut.close();
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        if      (args[0].equals("-")) encode();
        else if (args[0].equals("+")) decode();
        else throw new IllegalArgumentException("Illegal command line argument");        
    }
}

public class CircularSuffixArray {
    private int [] index;
    
    public CircularSuffixArray(String s) {
        char[] input = s.toCharArray();
        int size = input.length;
        index = new int[size];
        for (int i = 0; i < size; i++) {
            index[i] = i;
        }
        sort(0, size, input, 0);
    }
    
    private void sort(int lo, int hi, char [] input, int shift) {
        int size = input.length;
        if (hi == lo + 1) return;
        if (hi == lo + 2) {
            int start1 = (index[lo] + shift) % size;
            int start2 = (index[lo + 1] + shift) % size;
            while (input[start1] == input[start2]) {
                start1 = (start1 + 1) % size;
                start2 = (start2 + 1) % size;
            }
            if (input[start1] > input[start2]) {
                int temp = index[lo];
                index[lo] = index[lo + 1];
                index[lo + 1] = temp;                
            }
            return;
        }
        int [] counter = new int[256];

        for (int i = lo; i < hi; i++) {
            counter[input[(index[i] + shift) % size]]++;
        }
        int [] offsetTable = new int[256];
        offsetTable[0] = 0;
        for (int i = 1; i < 256; i++) {
            offsetTable[i] = offsetTable[i - 1] + counter[i - 1];
        }
        
        int [] index1 = new int[hi - lo];
        for (int i = lo; i < hi; i++) {
            char c = input[(index[i] + shift) % size];
            index1[offsetTable[c]] = index[i]; 
            offsetTable[c]++;
        }
        for (int i = lo; i < hi; i++) {
            index[i] = index1[i - lo];
        }
        for (char r = 0; r < 255; r++) {
            if (counter[r] > 1) {
                sort(offsetTable[r] - counter[r] + lo, offsetTable[r + 1] - counter[r + 1] + lo, input, shift + 1);
            }
        }
    }
        
    public int length() {
        return index.length;
    }
    
    public int index(int i) {
        if (i >= index.length) {
            throw new IllegalArgumentException("Illegal command line argument");
        }
        return index[i];
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        String s = BinaryStdIn.readString();
        CircularSuffixArray c = new CircularSuffixArray(s);
        for (int i = 0; i < c.length(); i++) {
            System.out.println(c.index(i));
        }
    }

}

import java.util.Arrays;

public class BurrowsWheeler {
    public static void encode() {
        String s = BinaryStdIn.readString();
        CircularSuffixArray c = new CircularSuffixArray(s);
        int size = c.length();
        int first = -1;
        char[] lastCol = new char[size];        
        for (int i = 0; i < size; i++) {
            if (c.index(i) == 0) {
                first = i;
                lastCol[i] = s.charAt(size - 1);
            } else {            
                lastCol[i] = s.charAt(c.index(i) - 1);
            }
        }
        BinaryStdOut.write(first);        
        for (int i = 0; i < size; i++) {
            BinaryStdOut.write(lastCol[i]); 
        }                
        BinaryStdOut.close();
    }
    
    public static void decode() {
        int first = BinaryStdIn.readInt();
        String s = BinaryStdIn.readString();
        char[] lastColumn = s.toCharArray();
        int size = lastColumn.length;
        int[] next = new int[size];
        char [] firstColumn = new char[size];        
        for (int i = 0; i < size; i++) {
            firstColumn[i] = lastColumn[i];
        }        
        Arrays.sort(firstColumn);
        int index = 0;
        for (int i = 0; i < size; i++) {
            char c = firstColumn[i];
            while (lastColumn[index] != c) {
                index = (index + 1) % size;                
            }
            next[i] = index;
            if (i == size - 1) 
                break;
            if (firstColumn[i + 1] == c) {
                index = (index + 1) % size;
            } else {
                index = 0;
            }
        }
        for (int i = 0; i < size; i++) {
            BinaryStdOut.write(firstColumn[first]);
            first = next[first];
        }
        BinaryStdOut.close();
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        if      (args[0].equals("-")) encode();
        else if (args[0].equals("+")) decode();
        else throw new IllegalArgumentException("Illegal command line argument");        
    }
}


Computational Photography Programming Assignment 4 – Video Textures

$
0
0

part0

import numpy as np
import cv2

def video_volume(image_list):
  '''Create a video volume from the image list.

  Input:
    image_list - a list of frames. Each element of the list contains a numpy
    array of a colored image. You may assume that each frame has the same shape,
    (rows, cols, 3).

  Output:
    output - a single 4d numpy array. This array should have dimensions
    (time, rows, cols, 3) and dtype np.uint8.
  '''
  output = None
  # Insert your code here ------------------------------------------------------
  (rows, cols, color) = image_list[0].shape
  output = np.zeros((len(image_list), rows, cols, color), dtype = np.uint8)
  for i in range(len(image_list)):
    output[i,:,:,:] = image_list[i]
  # ----------------------------------------------------------------------------
  return output

def ssd(video_volume):
  '''Compute the sum of squared distances for each pair of frames in video volume.
  Input:
    video_volume - as returned by your video_volume function.

  Output:
    output - a square 2d numpy array of dtype float. output[i,j] should contain 
    the dsum of square differences between frames i and j.
  '''
  output = None
  # Insert your code here ------------------------------------------------------
  (frames, rows, cols, color) = video_volume.shape
  output = np.zeros((frames, frames), dtype = np.float)
  for i in range(frames):
    image_i = video_volume[i,:,:,:]
    for j in range(frames):
      image_j = video_volume[j,:,:,:]
      total = 0.0
      diff_image = image_i - image_j
      for k1 in range(rows):
        for k2 in range(cols):
          for k3 in range(3):
            total = total + diff_image[k1,k2,k3] * diff_image[k1,k2,k3]
      output[i, j] = total
  # ----------------------------------------------------------------------------
  return output

def test():
  '''This script will perform a unit test on your function, and provide useful
  output.
  '''
  image_list1 = [np.array([[[ 0,  0,  0],
                            [ 0,  0,  0]]], dtype = np.uint8),
                 np.array([[[ 1,  1,  1],
                            [ 1,  1,  1]]], dtype = np.uint8),
                 np.array([[[ 2,  2,  2],
                            [ 2,  2,  2]]], dtype = np.uint8),
                 np.array([[[ 3,  3,  3],
                            [ 3,  3,  3]]], dtype = np.uint8)] 

  video_volume1 = np.array([[[[ 0,  0,  0],
                              [ 0,  0,  0]]],
                            [[[ 1,  1,  1],
                              [ 1,  1,  1]]],
                            [[[ 2,  2,  2],
                              [ 2,  2,  2]]],
                            [[[ 3,  3,  3],
                              [ 3,  3,  3]]]], dtype = np.uint8) 

  image_list2 =[np.array([[[2, 2, 2],
                           [2, 2, 2],
                           [2, 2, 2],
                           [2, 2, 2]],
                          [[2, 2, 2],
                           [2, 2, 2],
                           [2, 2, 2],
                           [2, 2, 2]]], dtype = np.uint8),
                np.array([[[1, 1, 1],
                           [1, 1, 1],
                           [1, 1, 1],
                           [1, 1, 1]],
                          [[1, 1, 1],
                           [1, 1, 1],
                           [1, 1, 1],
                           [1, 1, 1]]], dtype = np.uint8),
                np.array([[[0, 0, 0],
                           [0, 0, 0],
                           [0, 0, 0],
                           [0, 0, 0]],
                          [[0, 0, 0],
                           [0, 0, 0],
                           [0, 0, 0],
                           [0, 0, 0]]], dtype = np.uint8)] 

  video_volume2 = np.array([[[[2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2]],
                             [[2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2]]],
                            [[[1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1]],
                             [[1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1]]],
                            [[[0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0]],
                             [[0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0]]]], dtype = np.uint8)

  diff1 = np.array([[  0.,   6.,  24.,  54.],
                    [  6.,   0.,   6.,  24.],
                    [ 24.,   6.,   0.,   6.],
                    [ 54.,  24.,   6.,   0.]], dtype = np.float) 

  diff2 = np.array([[  0.,  24.,  96.],
                    [ 24.,   0.,  24.],
                    [ 96.,  24.,   0.]], dtype = np.float) 

  if __name__ == "__main__":
    print 'Evaluating video_volume.'
  for img_list, true_out in zip((image_list1, image_list2), (video_volume1, video_volume2)):
    if __name__ == "__main__":
      print "input:\n{}\n".format(img_list)

    usr_out = video_volume(img_list)

    if not type(usr_out) == type(true_out):
      if __name__ == "__main__":
        print "Error- video_volume has type {}. Expected type is {}.".format(
            type(usr_out), type(true_out))
      return False

    if not usr_out.shape == true_out.shape:
      if __name__ == "__main__":
        print "Error- video_volume has shape {}. Expected shape is {}.".format(
            usr_out.shape, true_out.shape)
      return False

    if not usr_out.dtype == true_out.dtype:
      if __name__ == "__main__":
        print "Error- video_volume has dtype {}. Expected dtype is {}.".format(
            usr_out.dtype, true_out.dtype)
      return False

    if not np.all(usr_out == true_out):
      if __name__ == "__main__":
        print "Error- video_volume has value:\n{}\nExpected value:\n{}".format(
            usr_out, true_out)
      return False

  if __name__ == "__main__":
    print "video_volume passed."
    print "evaluating ssd"

  for vid_volume, true_out in zip((video_volume1, video_volume2), (diff1, diff2)):
    if __name__ == "__main__":
      print "input:\n{}\n".format(vid_volume)

    usr_out = ssd(vid_volume)

    if not type(usr_out) == type(true_out):
      if __name__ == "__main__":
        print "Error- ssd has type {}. Expected type is {}.".format(
            type(usr_out), type(true_out))
      return False

    if not usr_out.shape == true_out.shape:
      if __name__ == "__main__":
        print "Error- ssd has shape {}. Expected shape is {}.".format(
            usr_out.shape, true_out.shape)
      return False

    if not usr_out.dtype == true_out.dtype:
      if __name__ == "__main__":
        print "Error- ssd has dtype {}. Expected dtype is {}.".format(
            usr_out.dtype, true_out.dtype)
      return False

    if not np.all(np.abs(usr_out - true_out) < 1.):
      if __name__ == "__main__":
        print "Error- ssd has value:\n{}\nExpected value:\n{}".format(
            usr_out, true_out)
      return False

  if __name__ == "__main__":
    print "All unit tests successful."
  return True

if __name__ == "__main__":
  print "Performing unit tests.(ssd will be accepted if the output is within 1 of the expected output.)"
  np.set_printoptions(precision=1)

  test()

part1

import numpy as np
import cv2
import scipy.signal

def binomial_filter_5():
  ''' Create a binomial filter of length 4.
  '''
  return np.array([ 0.0625,  0.25  ,  0.375 ,  0.25  ,  0.0625], dtype=float)

def diff2(diff1):
  '''Compute the transition costs between frames, taking dynamics into account.
  
  Input:
  diff1 - a difference matrix as produced by your ssd function.

  Output:
  output - a new difference matrix that takes preceding and following frames into 
           account. The cost of transitioning from i to j should weight the 
           surrounding frames according to the binomial filter provided to you 
           above. So, the difference between i and j has weight 0.375, the frames
           immediately following weight 0.25, etc...

           The output difference matrix should have the same dtype as the input,
           but be 4 rows and columns smaller, corresponding to only the frames
           that have valid dynamics.

  Hint: there is a very efficient way to do this with 2d convolution. Think about
        the coordinates you are using as you consider the preceding and following
        frame pairings.
  '''
  output = None
  # Insert your code here ------------------------------------------------------
  w_1d = binomial_filter_5()
  (w_size) = w_1d.shape
  (rows, cols) = diff1.shape
  output = np.zeros((rows - 4, cols - 4), dtype = np.float)
  for i in range(2, rows - 2, 1):
    for j in range(2, cols - 2, 1):
      total = 0.0;
      for k in range(-2, 3, 1):
          total = total + diff1[i + k, j + k]*w_1d[k + 2]
      output[i - 2, j - 2] = total
  #kernel = np.outer(w_1d, w_1d)
  #output = scipy.signal.convolve2d(diff1, kernel, 'valid')
  # ----------------------------------------------------------------------------
  return output

def test():
  '''This script will perform a unit test on your function, and provide useful
  output.
  '''
  d1 = np.zeros((9,9), dtype = float) 
  d1[4,4] = 1

  d2 = np.eye(5, dtype = float)

  out1 = np.array([[ 0.0625,  0.    ,  0.    ,  0.    ,  0.    ],
                   [ 0.    ,  0.25  ,  0.    ,  0.    ,  0.    ],
                   [ 0.    ,  0.    ,  0.375 ,  0.    ,  0.    ],
                   [ 0.    ,  0.    ,  0.    ,  0.25  ,  0.    ],
                   [ 0.    ,  0.    ,  0.    ,  0.    ,  0.0625]], dtype = float)

  out2 = np.array([[1.]], dtype = float)

  if __name__ == "__main__":
    print 'Evaluating diff2.'
  for d, true_out in zip((d1, d2), (out1, out2)):
    if __name__ == "__main__":
      print "input:\n{}\n".format(d)

    usr_out = diff2(d) 

    if not type(usr_out) == type(true_out):
      if __name__ == "__main__":
        print "Error- diff2 output has type {}. Expected type is {}.".format(
            type(usr_out), type(true_out))
      return False

    if not usr_out.shape == true_out.shape:
      if __name__ == "__main__":
        print "Error- diff2 output has shape {}. Expected shape is {}.".format(
            usr_out.shape, true_out.shape)
      return False

    if not usr_out.dtype == true_out.dtype:
      if __name__ == "__main__":
        print "Error- diff2 output has dtype {}. Expected dtype is {}.".format(
            usr_out.dtype, true_out.dtype)
      return False

    if not np.all(np.abs(usr_out - true_out) < 0.05):
      if __name__ == "__main__":
        print "Error- diff2 output has value:\n{}\nExpected value:\n{}".format(
            usr_out, true_out)
      return False

  if __name__ == "__main__":
    print "diff2 passed."

  if __name__ == "__main__":
    print "All unit tests successful."
  return True

if __name__ == "__main__":
  print "Performing unit tests. (Your output will be accepted if it is within .05 of the true output)"
  np.set_printoptions(precision=1)

  test()

part2

import numpy as np
import cv2
import sys
import scipy.signal

def find_biggest_loop(diff2, alpha):
  '''Given the difference matrix, find the longest and smoothest loop that we can.
  
  Inputs:
  diff2 - a square 2d numpy array of dtype float. Each cell contains the cost
          of transitioning from frame i to frame j in the input video.

  alpha - a parameter for how heavily you should weigh the size of the loop
          relative to the transition cost of the loop. Larger alphas favor
          longer loops.

  Outputs:
  s - the beginning frame of the longest loop.
  f - the final frame of the longest loop.

  s, f will the indices in the diff2 matrix that give the maximum score
  according to the following metric:

  alpha*(f-s) - diff2[f,s]
  '''
  s = None
  f = None
  # Insert your code here ------------------------------------------------------
  (rows, cols) = diff2.shape
  maxValue = -10000
  for ss in range(rows):
    for ff in range(cols):
      val = alpha*(ff-ss) - diff2[ff,ss]
      if val > maxValue:
        maxValue = val
        s = ss
        f = ff
  # ----------------------------------------------------------------------------
  return s, f

def synthesize_loop(video_volume, s, f):
  '''Pull out the given loop from video.
  
  Input:
  video_volume - a (t, row, col, 3) array, as created by your video_volume function.
  i - the index of the starting frame.
  j - the index of the ending frame.

  Output:
  output - a list of arrays of size (row, col, 3) and dtype np.uint8, similar to
  the original input the video_volume function in part0.
  '''
  output = [] 
  # Insert your code here ------------------------------------------------------
  for i in range(s, f + 1, 1):
    output.append(video_volume[i, :, :, :])
  # ----------------------------------------------------------------------------
  return output

def test():
  '''This script will perform a unit test on your function, and provide useful
  output.
  '''
  d1 = np.ones((5,5), dtype = float)
  a1 = 1
  out1 = (0,4)

  d2 = np.array([[ 0.,  1.,  1.,  5.],
                 [ 1.,  0.,  3.,  4.],
                 [ 1.,  3.,  0.,  5.],
                 [ 5.,  4.,  5.,  0.]])
  a2 = 1 
  out2 = (0,2)

  d3 = np.array([[ 0.,  1.,  4.],
                 [ 1.,  0.,  1.],
                 [ 4.,  1.,  0.]])   
  a3 = 2
  out3 = (0,1)

  if __name__ == "__main__":
    print 'Evaluating find_biggest_loop'
  for d, a, true_out in zip((d1, d2, d3), (a1, a2, a3), (out1, out2, out3)):
    if __name__ == "__main__":
      print "input:\n{}\n".format(d)
      print "alpha = {}".format(a)

    usr_out = find_biggest_loop(d, a)

    if not usr_out == true_out:
      if __name__ == "__main__":
        print "Error- find_biggest_loop is {}. Expected output is {}.".format(
            usr_out, true_out)
      return False

  if __name__ == "__main__":
    print "find_biggest_loop passed."
    print "testing synthesize_loop."

  video_volume1 = np.array([[[[ 0,  0,  0],
                              [ 0,  0,  0]]],
                            [[[ 1,  1,  1],
                              [ 1,  1,  1]]],
                            [[[ 2,  2,  2],
                              [ 2,  2,  2]]],
                            [[[ 3,  3,  3],
                              [ 3,  3,  3]]]], dtype = np.uint8) 

  video_volume2 = np.array([[[[2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2]],
                             [[2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2],
                              [2, 2, 2]]],
                            [[[1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1]],
                             [[1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1]]],
                            [[[0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0]],
                             [[0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0],
                              [0, 0, 0]]]], dtype = np.uint8)

  frames1 = (2,3)
  frames2 = (1,1)


  out1 = [np.array([[[ 2,  2,  2],
                     [ 2,  2,  2]]], dtype = np.uint8),
          np.array([[[ 3,  3,  3],
                     [ 3,  3,  3]]], dtype = np.uint8)]

  out2 = [np.array([[[1, 1, 1],
                     [1, 1, 1],
                     [1, 1, 1],
                     [1, 1, 1]],
                    [[1, 1, 1],
                     [1, 1, 1],
                     [1, 1, 1],
                     [1, 1, 1]]], dtype = np.uint8)]

  for video_volume, frames, true_out in zip((video_volume1, video_volume2), 
      (frames1, frames2), (out1, out2)):
    if __name__ == "__main__":
      print "input:\n{}\n".format(video_volume)
      print "input frames:\n{}\n".format(frames)

    usr_out = synthesize_loop(video_volume, frames[0], frames[1])

    if not type(usr_out) == type(true_out):
      if __name__ == "__main__":
        print "Error- synthesize_loop has type {}. Expected type is {}.".format(
            type(usr_out), type(true_out))
      return False

    if not len(usr_out) == len(true_out):
      if __name__ == "__main__":
        print "Error - synthesize_loop has len {}. Expected len is {}.".format(
            len(usr_out), len(true_out))
        return False

    for usr_img, true_img in zip(usr_out, true_out):
      if not type(usr_img) == type(true_img):
        if __name__ == "__main__":
          print "Error- synthesize_loop has type {}. Expected type is {}.".format(
              type(usr_img), type(true_img))
        return False

      if not usr_img.shape == true_img.shape:
        if __name__ == "__main__":
          print "Error- synthesize_loop has shape {}. Expected shape is {}.".format(
              usr_img.shape, true_img.shape)
        return False

      if not usr_img.dtype == true_img.dtype:
        if __name__ == "__main__":
          print "Error- synthesize_loop has dtype {}. Expected dtype is {}.".format(
              usr_img.dtype, true_img.dtype)
        return False

      if not np.all(usr_img == true_img):
        if __name__ == "__main__":
          print "Error- synthesize_loop has value:\n{}\nExpected value:\n{}".format(
              usr_img, true_img)
        return False

  if __name__ == "__main__":
    print "synthesize_loop passed."

  if __name__ == "__main__":
    print "All unit tests successful."
  return True

if __name__ == "__main__":
  print "Performing unit tests."

  test()


MOE Interactive Maps Unsolved issues

$
0
0

1. Wells Record Data’s French translation “Puit enregistrer des données” is not correct.

2. m.a.s.l in PGMN water level is English. French translation is required.

3. PGMN Chemistry data has a long text.


OPS Dental and Medical insurance

$
0
0

http://www.opseu.org/ops/benefits/

Plan Name:
Dental OPSEU – ER
Plan Provider:
Great West Life Assurance Co.
Coverage:
Employee Only
Group Number:
330021
Customer Service: Ext:

Plan Name:
Vision/Hearing OPSEU – ER
Plan Provider:
Manulife Financial
Coverage:
Employee Only
Group Number:
15900


Algorithms, Part II Interview Questions

$
0
0

Interview Questions: Undirected Graphs

Question 1

Nonrecursive depth-first search. Implement depth-first search in an undirected graph without using recursion.
Your Answer Score Explanation
Total 0.00 / 0.00
Question ExplanationHint: use an explicit stack.

Question 2

Diameter and center of a tree. Given a connected graph with no cycles
  • Diameter: design a linear-time algorithm to find the longest simple path in the graph.
  • Center: design a linear-time algorithm to find a vertex such that its maximum distance from any other vertex is minimized.
Your Answer Score Explanation
Total 0.00 / 0.00
Question ExplanationHint (diameter): to compute the diameter, pick a vertex s; run BFS from s; then run BFS again from the vertex that is furthest from s.
Hint (center): consider vertices on the longest path.

Question 3

Eulierian cycle. An Eulierian cycle in a graph is a cycle (not necessarily simple) that uses every edge in the graph exactly one.
  • Show that a graph has an Eulerian cycle if and only if it is both connected and every vertex has even degree.
  • Design a linear-time algorithm to determine whether a graph has an Eulerian cycle, and if so, find one.
Your Answer Score Explanation
Total 0.00 / 0.00
Question ExplanationHint: use depth-first search and piece together the cycles you discover.

 Interview Questions: Directed Graphs

Question 1

Shortest directed cycle. Given a digraph G, design an efficient algorithm to find a directed cycle with the minimum number of edges (or report that the graph is acyclic). The running time of your algorithm should be at most proportional to V(E+V) and use space proportional to E+V, where V is the number of vertices and E is the number of edges.
Your Answer Score Explanation
Total 0.00 / 0.00
Question Explanation

Hint: run BFS from each vertex.

Question 2

Hamiltonian path in a DAG. Given a directed acyclic graph, design a linear-time algorithm to determine whether it has a Hamiltonian path (a simple path that visits every vertex), and if so, find one.
Your Answer Score Explanation
Total 0.00 / 0.00
Question Explanation

Hint: topological sort.

Question 3

Reachable vertex. 
  • DAG: Design a linear-time algorithm to determine whether a DAG has a vertex that is reachable from every other vertex, and if so, find one. 
  • Digraph: Design a linear-time algorithm to determine whether a digraph has a vertex that is reachable from every other vertex, and if so, find one.
Your Answer Score Explanation
Total 0.00 / 0.00
Question Explanation

Hint (DAG): compute the outdegree of each vertex.
Hint (digraph): compute the strong components and look at the kernel DAG (the digraph that results when you contract each strong component to a single vertex).

Interview Questions: Minimum Spanning Trees

Question 1

Bottleneck minimum spanning tree. Given a connected edge-weighted graph, design an efficient algorithm to find a minimum bottleneck spanning tree. The bottleneck capacity of a spanning tree is the weights of its largest edge. A minimum bottleneck spanning tree is a spanning tree of minimum bottleneck capacity.
Your Answer Score Explanation
Total 0.00 / 0.00
Question Explanation

Hint: prove that an MST is a minimum bottleneck spanning tree.
Extra challenge: Compute a minimum bottleneck spanning tree in linear time in the worst case. Assume that you can compute the median of n keys in linear time in the worst case.

Question 2

Is an edge in a MST. Given an edge-weighted graph G and an edge e, design a linear-time algorithm to determine whether e appears in some MST of G.
Note: Since your algorithm must take linear time in the worst case, you cannot afford to compute the MST itself.
Your Answer Score Explanation
Total 0.00 / 0.00
Question Explanation

Hint: consider the subgraph G′ of G containing only those edges whose weight is strictly less than that of e.

Question 3

Minimum-weight feedback edge set. A feedback edge set of a graph is a subset of edges that contains at least one edge from every cycle in the graph. If the edges of a feedback edge set are removed, the resulting graph is acyclic. Given an edge-weighted graph, design an efficient algorithm to find a feedback edge set of minimum weight. Assume the edge weights are positive.
Your Answer Score Explanation
Total 0.00 / 0.00
Question Explanation

Hint: complement of an MST.


Algorithms, Part II Linear Programming Exercise

$
0
0

Feedback — Linear Programming

You submitted this quiz on Wed 1 May 2013 1:51 PM PDT -0700. You got a score of 2.80 out of 3.00. You can attempt again, if you’d like.

To specify an array or sequence of values in an answer, you must separate the values by a single space character (with no punctuation and with no leading or trailing whitespace). For example, if the question asks for the first ten powers of two (starting at 1), the only accepted answer is:

1 2 4 8 16 32 64 128 256 512

If you wish to discuss a particular question and answer in the forums, please post the entire question and answer, including the seed (which is used by the course staff to uniquely identify the question) and the explanation (which contains the correct answer).

Question 1

(seed = 735654)
Which of the following constraints can be modeled using linear programming?
Your Answer Score Explanation
x1 - 2x2 - 3x3 - 4x4 <= 10.
0.20
x1 - 2x2 - 3x3 - 4x4 <= -10.
0.20
x1, x2, x3, x4 are either 0 or 1
0.20
x1, x2, x3, x4 are unconstrained
0.00
x1 + 1/2 x2 + 1/3 x3 + 1/4 x4 <= 10.
0.20
Total 0.80 / 1.00
Question Explanation

Question 2

(seed = 42623)
Consider the following linear programming simplex tableaux with 3 equations and 8 variables:

    maximize Z
     - 10/3 x0  +    2 x1  +    1 x2                                   +  1/4 x6  -  3/5 x7    -  Z    = -210
    ---------------------------------------------------------------------------------------------------------
     -    1 x0  -  5/2 x1  - 10/3 x2             +    1 x4             +  7/5 x6  +  9/5 x7            =    6
     +  9/2 x0  -   10 x1  -  4/3 x2                        +    1 x5  +    8 x6  +    4 x7            =   54
     -    1 x0  +    1 x1  -    1 x2  +    1 x3                        -   10 x6  +    3 x7            =   54
            x0  ,      x1  ,      x2  ,      x3  ,      x4  ,      x5  ,      x6  ,      x7           >=    0


Which variable could be the next to *enter* the basis? Check all that apply.
Your Answer Score Explanation
x0
0.12
x1
0.12
x2
0.12
x3
0.12
x4
0.12
x5
0.12
x6
0.12
x7
0.12
Total 1.00 / 1.00
Question Explanation

The basis is { x4, x5, x3 }.
The nonbasic variables are { x0, x1, x2, x6, x7 }.
The entering variables are those nonbasic variables with a positive objective function coefficient.

Question 3

(seed = 522611)
Consider the following linear programming simplex tableaux with 5 equations and 9 variables:

    maximize Z
                           -  3/4 x2  +  9/5 x3             -  9/5 x5             -  3/2 x7               -  Z    = -246
    --------------------------------------------------------------------------------------------------------------------
                           -  7/5 x2  -  1/4 x3             -    3 x5             +    2 x7  +    1 x8            =   42
                           +  1/5 x2  +    2 x3  +    1 x4  -  9/5 x5             -  2/5 x7                       =   18
     +    1 x0             -  1/3 x2  +  9/4 x3             +  2/5 x5             +   10 x7                       =    6
                +    1 x1  -    1 x2  -  4/5 x3             -  7/3 x5             +    6 x7                       =   30
                           +    5 x2  +    4 x3             +  7/2 x5  +    1 x6  -  5/2 x7                       =   30
            x0  ,      x1  ,      x2  ,      x3  ,      x4  ,      x5  ,      x6  ,      x7  ,      x8           >=    0


Suppose that variable x3 is the variable chosen to enter the basis.
Which variable could be the next to *leave* the basis? Check all that apply.
Your Answer Score Explanation
x0
0.11
x1
0.11
x2
0.11
x3
0.11
x4
0.11
x5
0.11
x6
0.11
x7
0.11
x8
0.11
Total 1.00 / 1.00
Question Explanation

The basis is { x8, x4, x0, x1, x6 }.
The nonbasic variables are { x2, x3, x5, x7 }.
The entering variable is x3.
The min ratio test determines the leaving variable: min ratio = { *, 9, 8/3, *, 15/2 } = 8/3.
The minimum occurs in row 2, which corresponds to basic variable x0.
The leaving variables is x0.

Pattern-Oriented Software Architectures for Concurrent and Networked Software Echo Server

$
0
0

ATTN: As with all peer-assessments, you will receive the average of your 4 scores.  For the programming assignments, you will receive the maximum score out of the ones you submit (so if you get 30/30 for Java and 20/30 for C++, you will get 30/30 for Programming Assignment 2).

The purpose of this assignment is to deepen your understanding of the Wrapper Facade pattern, the Reactor pattern and the (Acceptor role of the) Acceptor-Connector pattern in the context of Java Netty. In particular, you will write a platform-independent reactive server program that accepts a connection from a client and echos back what the client sent. In brackets below are some hints about what kinds of Netty classes you might want to look up to do these (see the Netty Javadocs and examples for more background).

In addition to the Netty NIO Socket wrappers, the component that you should use for this assignment are the ServerBootstrap and ServerSocketChannelFactory. The other hints are simply for your convenience.

The reactive server program should do the following activities:
  • Create an EchoServerHandler that inherits from SimpleChannelUpstreamHandler and implement its messageReceived() hook method so that it echos back back the client’s input either (a) a “chunk” at a time or (b) a “line” at a time (i.e., until the symbols “\n”, “\r”, or “\r\n” are read), rather than a character at a time.   You can additionally override methods such as channelOpen for example to show logging information.
  • Create a ChannelPipelineFactory which sets up a pipeline for processing the inbound messages.
  • Configure the ServerSocketChannelFactory that inherits from ServerChannelFactory, and binds the ServerBootstrap class to an appropriate InetSocketAddress.
  • Configure the ServerBootstrap class with appropriate thread pools to run the events. Configure the bootstrap object with a PipelineFactory.
  • When a client connection request arrives, the ServerChannelFactory and ChannelPipeline work together to pass events to the EchoServerHandler.
  • Note that implementing SimpleChannelUpstreamHandler takes care of the connection acceptance.
  • For this assignment, you can simply exit the server process (using Ctrl+C) when you’re done, which will close down all the open sockets.

Make sure your solution clearly indicates which classes play which roles in the Wrapper Facade, Reactor, and/or Acceptor-Connector patterns.

Please implement this server program in Java using the the Netty library–which you can download from http://netty.io/ (we recommend you use Netty 3.6.x) along with  documentation at http://docs.jboss.org/netty/3.2/guide/–and put the server code in a single file.  A second file may optionally be included for a simple console client (clearly named) if you write one during your solution development as a test program and wish to include it for the convenience of evaluators, but it is not required and will not be assessed as part of this exercise, just used as a test driver for your server.  You can also use a telnet client (such as putty) as a test driver for your server.

An evaluator should be able to compile it with a command such as “javac -cp netty.jar Program.java”  and execute it with ‘java -cp .:netty.jar Program port_number’ (and ’java -cp .;netty.jar Program port_number’ for Windows) and your program should successfully run! Note that the netty’s distribution jar (which can be downloaded here http://netty.io/downloads.html ) is provided by the evaluator.Rubric30 possible points
  •  5 points – code is well-structured and design makes sense
  • 15 points – Wrapper Facade, Reactor, and Acceptor-Connector patterns are used correctly (and the classes in the solution are clearly mapped to the appropriate roles in the patterns)
  • 5 points – code demonstrates the appropriate level of readability for others to understand the intent and execution of the program
  • 5 points – code compiles and runs smoothly

NOTE: Name your file something like “Program.txt” instead of “Program.java” so that the uploader will accept your code!

javac -cp netty-3.6.5.Final.jar;junit-4.8.2.jar *.java
java -cp .;netty-3.6.5.Final.jar EchoServer

java -cp .;netty-3.6.5.Final.jar EchoClient

java -cp .;netty-3.6.5.Final.jar;junit-4.8.2.jar EchoServiceTester localhost 8080

 

//package posacns;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import junit.framework.JUnit4TestAdapter;
import junit.textui.TestRunner;

import org.junit.Test;

public class EchoServiceTester {

    public static final String ERROR_BYTES = "Server sent wrong bytes after service reaction time. Try to increase the service reaction time if the response came truncated.";

    private static int portNumber = 2048;
    private static String hostName = "127.0.0.1";
    private static int serverReactionTime = 100;
    private static String EOL = System.getProperty("line.separator");

    public static void main(String[] args) {

        System.out.println("Stand alone textui JUnit test.");
        System.out.println();
        System.out.println("-------------------------------------------------------------------------------");
        System.out.println();
        System.out.println("Usage: [portNumber [hostName [serverReactionTime]]]");
        System.out.println();
        System.out.println("Arguments:");
        System.out.println();
        System.out.println("    portNumber           The server port.");
        System.out.println("    hostName             Server host name.");
        System.out.println("    serverReactionTime   The time in milliseconds that this test will wait");
        System.out.println("                         for the server to reply.");
        System.out.println();
        System.out.println("Default values are:");
        System.out.println();
        System.out.println("    portNumber           = " + portNumber);
        System.out.println("    hostName             = " + hostName);
        System.out.println("    serverReactionTime   = " + serverReactionTime);
        System.out.println();
        System.out.println("-------------------------------------------------------------------------------");
        System.out.println();

        if (args.length >= 1) {
            try {
                portNumber = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                System.err.println(String.format("Invalid argument: %s. Should be integer.", args[0]));
                System.exit(1);
            }
        }

        if (args.length >= 2) {
            hostName = args[1];
        }

        if (args.length == 3) {
            try {
                serverReactionTime = Integer.parseInt(args[2]);
            } catch (NumberFormatException e) {
                System.err.println(String.format("Invalid argument: %s. Should be integer.", args[2]));
                System.exit(2);
            }
        }

        System.out.println("Using these parameters:");
        System.out.println();
        System.out.println("    portNumber           = " + portNumber);
        System.out.println("    hostName             = " + hostName);
        System.out.println("    serverReactionTime   = " + serverReactionTime);
        System.out.println();
        System.out.println("-------------------------------------------------------------------------------");
        System.out.println();

        TestRunner.run(new JUnit4TestAdapter(EchoServiceTester.class));

    }

    @Test
    public void connectionToServer() throws UnknownHostException, IOException {

        /*
         * Description
         */

        System.out.println("Checking if it is possible to connect to the server...");

        /*
         * Test
         */

        Socket socket = new Socket(hostName, portNumber);
        assertTrue("Could not create a socket to the server.", socket.isConnected());
        socket.close();
        assertTrue("Successfully created a socket to the server, but failed to close this socket.", socket.isClosed());

    }

    @Test
    public void echoFromServer() throws UnknownHostException, IOException, InterruptedException {

        /*
         * Description
         */

        System.out.println("Checking if the server echoes a short message...");

        /*
         * Test
         */

        Socket socket = new Socket(hostName, portNumber);
        byte[] bytes = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + EOL).getBytes();
        socket.getOutputStream().write(bytes);
        // Waits for the server to respond
        Thread.sleep(serverReactionTime);
        int available = socket.getInputStream().available();
        byte[] actual = new byte[available];
        socket.getInputStream().read(actual);
        socket.close();

        assertArrayEquals(ERROR_BYTES, bytes, actual);

    }

    @Test
    public void randomLongEchoFromServer() throws UnknownHostException, IOException, InterruptedException {

        /*
         * Test parameter
         */
        int messageSize = 1024;

        /*
         * Description
         */

        System.out.println("Checking if the server echoes a long random message...");

        /*
         * Test
         */

        byte[] bytes0 = new byte[messageSize];
        for (int i = 0; i < messageSize; i++) {
            bytes0[i] = (byte)(32 + Math.random() * (126 - 32));
        }

        byte[] bytes = (new String(bytes0) + EOL).getBytes();

        Socket socket = new Socket(hostName, portNumber);
        socket.getOutputStream().write(bytes);
        // Waits for the server to respond
        Thread.sleep(serverReactionTime);
        int available = socket.getInputStream().available();
        byte[] actual = new byte[available];
        socket.getInputStream().read(actual);
        socket.close();

        assertArrayEquals(ERROR_BYTES, bytes, actual);

    }

    @Test
    public void multipleEchoesFromServer() throws UnknownHostException, IOException, InterruptedException {

        /*
         * Test parameter
         */

        int messages = 300;

        /*
         * Description
         */

        System.out.println("Checking if the server echoes several messages from the same client...");

        /*
         * Test
         */

        Socket socket = new Socket(hostName, portNumber);

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

            byte[] bytes = ("Message" + i + EOL).getBytes();
            socket.getOutputStream().write(bytes);
            // Waits for the server to respond
            Thread.sleep(serverReactionTime);
            int available = socket.getInputStream().available();
            byte[] actual = new byte[available];
            socket.getInputStream().read(actual);
            assertArrayEquals(ERROR_BYTES, bytes, actual);

            System.out.print(".");

        }

        System.out.println();

        socket.close();

    }

    @Test
    public void concurrentClients() throws UnknownHostException, IOException, InterruptedException {

        /*
         * Test parameter
         */

        int numConcurrentClients = 40;

        /*
         * Description
         */

        System.out.println("Checking if the server echoes several messages from several clients simultaneously connected (although the server is NOT required to pass this test)...");

        /*
         * Test
         */

        ArrayList sockets = new ArrayList(numConcurrentClients);

        for (int i = 0; i < numConcurrentClients; i++) {
            sockets.add(new Socket(hostName, portNumber));
        }

        // Random strings
        ArrayList testData = new ArrayList();
        testData.add("Rio");
        testData.add("Tokyo");
        testData.add("NYC");
        testData.add("Madrid");
        testData.add("Cairo");

        for (String testDatum : testData) {
            for (Socket socket : sockets) {
                byte[] bytes = (testDatum + EOL).getBytes();
                socket.getOutputStream().write(bytes);
                // Waits for the server to respond
                Thread.sleep(serverReactionTime);
                int available = socket.getInputStream().available();
                byte[] actual = new byte[available];
                socket.getInputStream().read(actual);

                assertArrayEquals(ERROR_BYTES, bytes, actual);

                System.out.print(".");
            }
        }

        System.out.println();

       for (Socket socket : sockets) {
            socket.close();
        }
    }

}

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
//package org.jboss.netty.example.echo;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

/**
 * Echoes back any received data from a client.
 */
public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void run() {
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new EchoServerHandler());
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new EchoServer(port).run();
    }
}

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
//package org.jboss.netty.example.echo;

import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 * Handler implementation for the echo server.
 */
public class EchoServerHandler extends SimpleChannelUpstreamHandler {

    private static final Logger logger = Logger.getLogger(
            EchoServerHandler.class.getName());
	private static final int CHUNK_SIZE = 50;
    private final AtomicLong transferredBytes = new AtomicLong();

	private byte[] state = new byte[CHUNK_SIZE];
	private int stateSize = 0;

    public long getTransferredBytes() {
        return transferredBytes.get();
    }

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        // Send back the received message to the remote peer.
		ChannelBuffer cb = (ChannelBuffer) e.getMessage();
		byte[] input = cb.array();
        //transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
		for (int i = 0; i < input.length; i++)
			System.out.println(input[i]);
		System.out.println("");
		for (int i = 0; i < input.length; i++) {
			if (stateSize == CHUNK_SIZE - 1) { //It is full.
				e.getChannel().write(ChannelBuffers.wrappedBuffer(state));
				stateSize = 0;
			} else if (input[i] == 10 || input[i] == 13) {
				byte[] output = new byte[stateSize + 1];
				for (int j = 0; j < stateSize; j++) {
					output[j] = state[j];
				}
				output[stateSize] = input[i];
				e.getChannel().write(ChannelBuffers.wrappedBuffer(output));
				stateSize = 0;
			} else {
				state[stateSize] = input[i];
				stateSize++;
			}
		}
        //e.getChannel().write(e.getMessage());
		//e.getChannel().write(ChannelBuffers.wrappedBuffer(input));
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        // Close the connection when an exception is raised.
        logger.log(
                Level.WARNING,
                "Unexpected exception from downstream.",
                e.getCause());
        e.getChannel().close();
    }
}

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
//p/ackage org.jboss.netty.example.echo;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

/**
 * Sends one message when a connection is open and echoes back any received
 * data to the server.  Simply put, the echo client initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClient {

    private final String host;
    private final int port;
    private final int firstMessageSize;

    public EchoClient(String host, int port, int firstMessageSize) {
        this.host = host;
        this.port = port;
        this.firstMessageSize = firstMessageSize;
    }

    public void run() {
        // Configure the client.
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        new EchoClientHandler(firstMessageSize));
            }
        });

        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

        // Wait until the connection is closed or the connection attempt fails.
        future.getChannel().getCloseFuture().awaitUninterruptibly();

        // Shut down thread pools to exit.
        bootstrap.releaseExternalResources();
    }

    public static void main(String[] args) throws Exception {
        // Print usage if no argument is specified.
        if (args.length < 2 || args.length > 3) {
            System.err.println(
                    "Usage: " + EchoClient.class.getSimpleName() +
                    "   []");
            return;
        }

        // Parse options.
        final String host = args[0];
        final int port = Integer.parseInt(args[1]);
        final int firstMessageSize;
        if (args.length == 3) {
            firstMessageSize = Integer.parseInt(args[2]);
        } else {
            firstMessageSize = 256;
        }

        new EchoClient(host, port, firstMessageSize).run();
    }
}

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
//package org.jboss.netty.example.echo;

import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 * Handler implementation for the echo client.  It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends SimpleChannelUpstreamHandler {

    private static final Logger logger = Logger.getLogger(
            EchoClientHandler.class.getName());

    private final ChannelBuffer firstMessage;
    private final AtomicLong transferredBytes = new AtomicLong();

    /**
     * Creates a client-side handler.
     */
    public EchoClientHandler(int firstMessageSize) {
        if (firstMessageSize <= 0) {
            throw new IllegalArgumentException(
                    "firstMessageSize: " + firstMessageSize);
        }
        firstMessage = ChannelBuffers.buffer(firstMessageSize);
        for (int i = 0; i < firstMessage.capacity(); i ++) {
            firstMessage.writeByte((byte) i);
        }
		//firstMessage.writeByte('\n');
		//System.out.println(firstMessage);
    }

    public long getTransferredBytes() {
        return transferredBytes.get();
    }

    @Override
    public void channelConnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) {
        // Send the first message.  Server will not send anything here
        // because the firstMessage's capacity is 0.
        e.getChannel().write(firstMessage);
    }

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        // Send back the received message to the remote peer.
        //transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
       // e.getChannel().write(e.getMessage());
		ChannelBuffer cb = (ChannelBuffer) e.getMessage();
		byte[] input = cb.array();
        //transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes());
		for (int i = 0; i < input.length; i++)
			System.out.println(input[i]);
		System.out.println("");
        //e.getChannel().write(e.getMessage());
		e.getChannel().write(ChannelBuffers.wrappedBuffer(input));
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        // Close the connection when an exception is raised.
        logger.log(
                Level.WARNING,
                "Unexpected exception from downstream.",
                e.getCause());
        e.getChannel().close();
    }
}



The Hardware/Software Interface Lab 2

$
0
0

Lab 2: Instructions

 

When you’re ready to submit your solution, go to the assignments list.

 

 

Lab 2: Disassembling and Defusing a Binary Bomb

Overview

The nefarious Dr. Evil has planted a slew of “binary bombs” on our machines. A binary bomb is a program that consists of a sequence of phases. Each phase expects you to type a particular string on stdin. If you type the correct string, then the phase is defused and the bomb proceeds to the next phase. Otherwise, the bomb explodes by printing “BOOM!!!” and then terminating. The bomb is defused when every phase has been defused.

There are too many bombs for us to deal with, so we are giving everyone a bomb to defuse. Your mission, which you have no choice but to accept, is to defuse your bomb before the due date. Good luck, and welcome to the bomb squad!

Instructions

The bombs were constructed specifically for 64-bit machines. You should do this assignment on the 64-bit Linux VM and be sure it works there (or at least test your solution there before submitting it!) so that you can be sure it works when we grade it. In fact, there is a rumor that Dr. Evil has ensured the bomb will always blow up if run elsewhere. There are several other tamper-proofing devices built into the bomb as well, or so they say.

Perform an update to your course-materials directory on the VM by running the update-course command from a terminal window. On the script’s success, you should find the provided code for lab2 in your course-materials directory. As a convenience, here is an archive of the course-materials directory as of this lab assignment: lab2.tar.gz. The lab2 directory should then contain the following files:

  • bomb: The executable binary bomb
  • bomb.c: Source file with the bomb’s main routine
  • defuser.txt: File in which you write your defusing solution

Your job is to defuse the bomb. You can use many tools to help you with this; please look at the tools section for some tips and ideas. The best way is to use a debugger to step through the disassembled binary.

The bomb has 5 regular phases. The 6th phase is extra credit (worth half as much as a regular phase), and rumor has it that a secret 7th phase exists. If it does and you can find and defuse it, you will receive additional extra credit points. The phases get progressively harder to defuse, but the expertise you gain as you move from phase to phase should offset this difficulty. Nonetheless, the latter phases are not easy, so please don’t wait until the last minute to start. (If you’re stumped, check the hints section at the end of this document.)

The bomb ignores blank input lines. If you run your bomb with a command line argument, for example,

 ./bomb defuser.txt

then it will read the input lines from defuser.txt until it reaches EOF (end of file), and then switch over to stdin (standard input from the terminal). In a moment of weakness, Dr. Evil added this feature so you don’t have to keep retyping the solutions to phases you have already defused.

To avoid accidentally detonating the bomb, you will need to learn how to single-step through the assembly code and how to set breakpoints. You will also need to learn how to inspect both the registers and the memory states. One of the nice side-effects of doing the lab is that you will get very good at using a debugger. This is a crucial skill that will pay big dividends the rest of your career.

Resources

There are a number of online resources that will help you understand any assembly instructions you may encounter while examining the bomb. In particular, the programming manuals for x86-64 processors distributed by Intel and AMD are exceptionally valuable. They both describe the same ISA, but sometimes one may be easier to understand than the other.

Useful for this Lab

Not Directly Useful, but Good Brainfood Nonetheless

x86-64 Calling Conventions

As a reminder, the x86-64 ISA passes the first six arguments to a function in registers. Registers are used in the following order: rdirsirdxrcxr8r9. The return value for functions is passed in rax.

Tools (Read This!!)

There are many ways of defusing your bomb. You can examine it in great detail without ever running the program, and figure out exactly what it does. This is a useful technique, but it not always easy to do. You can also run it under a debugger, watch what it does step by step, and use this information to defuse it. This is probably the fastest way of defusing it.

We do make one request, please do not use brute force! You could write a program that will try every possible key to find the right one, but the number of possibilities is so large that you won’t be able to try them all in time.

There are many tools which are designed to help you figure out both how programs work, and what is wrong when they don’t work. Here is a list of some of the tools you may find useful in analyzing your bomb, and hints on how to use them.

  • gdb: The GNU debugger is a command line debugger tool available on virtually every platform. You can trace through a program line by line, examine memory and registers, look at both the source code and assembly code (we are not giving you the source code for most of your bomb), set breakpoints, set memory watch points, and write scripts. Here are some tips for using gdb.
    • To keep the bomb from blowing up every time you type in a wrong input, you’ll want to learn how to set breakpoints.
    • The CS:APP Student Site has a very handy gdb summary (there is also a more extensive tutorial).
    • For other documentation, type help at the gdb command prompt, or type “man gdb”, or “info gdb” at a Unix prompt. Some people also like to run gdb under gdb-mode in emacs
  • objdump -t bomb: This will print out the bomb’s symbol table. The symbol table includes the names of all functions and global variables in the bomb, the names of all the functions the bomb calls, and their addresses. You may learn something by looking at the function names!
  • objdump -d bomb: Use this to disassemble all of the code in the bomb. You can also just look at individual functions. Reading the assembler code can tell you how the bomb works. Although objdump -d gives you a lot of information, it doesn’t tell you the whole story. Calls to system-level functions may look cryptic. For example, a call to sscanf might appear as: 8048c36: e8 99 fc ff ff call 80488d4 <_init+0x1a0> To determine that the call was to sscanf, you would need to disassemble within gdb.
  • strings -t x bomb: This utility will display the printable strings in your bomb and their offset within the bomb.

Looking for a particular tool? How about documentation? Don’t forget, the commands apropos and man are your friends. In particular, man ascii is more useful than you’d think. If you get stumped, use the course’s discussion board.

Hints

If you’re still having trouble figuring out what your bomb is doing, here are some hints for what to think about at each stage: (1) comparison, (2) loops, (3) switch statements, (4) recursion, (5) pointers and arrays, (6) sorting linked lists.

Submitting Your Work

You will be able to submit your assignment with the submit-hw script that is bundled with the course-materials. Using the script should be straight-forward, but it does expect you to not move/rename any files from the ”course-materials” directory. Open a terminal and type the following command:

  submit-hw lab2

After calling the submit-hw script, you will be prompted for your Coursera username and then your submission password. Your submission password is NOT the same as your regular Coursera account password!!!! You may locate your submission password at the top of the assignments list page.

After providing your credentials, the submit-hw script will run some basic checks on your code. For lab 2, this means that it checks that you have passed the first 5 phases correctly.

Once confirming that you wish to submit, with a working Internet connection, the script should submit your code properly. You can go to the assignments list page to double-check that it has been submitted and check your score as well as any feedback the auto-grader gives you. You may also download your submission code from this page, if you wish.


Algorithms, Part II Final Exam Part II

$
0
0

Final Exam Part II

The due date for this quiz is Mon 20 May 2013 8:59 AM PDT -0700.

To specify an array or sequence of values in an answer, you must separate the values by a single space character (with no punctuation and with no leading or trailing whitespace). For example, if the question asks for the first ten powers of two (starting at 1), the only accepted answer is:

1 2 4 8 16 32 64 128 256 512

If you wish to discuss a particular question and answer in the forums, please post the entire question and answer, including the seed (which is used by the course staff to uniquely identify the question) and the explanation (which contains the correct answer).
In accordance with the Coursera Honor Code, I (Yinhuan Yuan) certify that the answers here are my own work.

Question 1

(seed = 388464)
Which of the following statements about connectivity in an undirected graph are true? Check all that apply.
If there are two edge-disjoint paths connecting vertices u and v, then there is a simple cycle containing both u and v.
If you delete two edges from a graph G, its number of strong components can increase by at most 2.
A graph G that has a unique simple path between every pair of vertices has exactly V-1 edges.
Given a graph G and a vertex s, G is connected if and only if every vertex is connected to s.
Removing any edge from a connected graph G breaks the graph into two connected components.

Question 2

(seed = 599575)
Which of the following statements about depth-first search are guaranteed to be true? Check all that apply.
If a vertex has no edges pointing from it, it will be first in any postorder
The postorder of a digraph G is the reverse of its preorder.
If there is a unique vertex reachable from every other vertex in a digraph, it will be first in some postorder.
The reverse postorder of a digraph's reverse is the same as the postorder of the digraph.
If a digraph has a vertex with no edges pointing from it, then some vertex with no edges pointing from it will be first in any postorder.

Question 3

(seed = 694838)
Which of the following statements about minimum spanning trees (MSTs) are guaranteed to be true? Check all that apply.
Let G be a connected edge-weighted graph and let T be a MST of G. Then, the cheapest spanning tree of G besides T can be obtained by deleting the most expensive edge in T and computing the MST of the resulting graph.
Let G be a connected edge-weighted graph and let T be an MST of G. If you decrease the weight of some edge in T, then T will still be a MST.
Let G be a connected edge-weighted graph with distinct edge weights and no parallel edges. Then, the MST must contain the third cheapest edge.
Let T and T' be two MSTs of some edge-weighted graph and let a[] and b[] be the sorted array of edge weights. Then a[i] = b[i] for each i.
Let G be a connected edge-weighted graph with distinct edge weights and let (A, B) be a cut with at least 3 crossing edges. Then, the MST can contain the smallest and third smallest crossing edges without containing the second smallest crossing edge.

Question 4

(seed = 959653)
Which of the following statements about shortest paths are true? Check all that apply.
If you run the Bellman-Ford algorithm on an edge-weighted digraph with positive edge weights and the shortest path from s to t has k edges, then Bellman-Ford will require at least k passes.
Bellman-Ford finds the shortest simple path from s to every other vertex, even if the edge weights are arbritary positive or negative integers.
Bellman-Ford finds the shortest simple path from s to every other vertex, even if the edge weights are positive or negative integers, provided there are no negative cycles.
Let G be a digraph with positive edge weights. During Bellman-Ford, if you trace back the edgeTo[] entries starting from v back to s, the path has distance equal to distTo[v].
Let G be a digraph with positive edge weights. Suppose that you increase the length of an edge by x. Then, the length of the shortest path from s to t can increase by more than x.

Question 5

(seed = 392474)
Which of the following statements about maxflow and mincut are guaranteeed to be true? Check all that apply.
If all edge capacities are increased by an additive constant, then any mincut in the original network is a mincut in the modified network.
There exists a maxflow for which there is no directed cycle on which every edge carries positive flow.
Given a mincut (S, T) if the capacity of one edge is decreased by x, the value of the maxflow will decrease by exactly x.
If all edge capacities are integral, then any maxflow has integer flow on each edge.
If the capacity of some cut (S, T) equals the value of some flow f, then f is a maxflow.

Question 6

(seed = 725630)
The column on the left contains the original input of 24 strings to be sorted;
the column on the right contains the strings in sorted order; the other 7 columns contain the
contents at some intermediate step during one of the 3 radix sorting algorithms listed below.

    moth   lamb   boar   puma   ibex   toad   bass   boar   bass   
    puma   hare   bass   tuna   boar   clam   boar   dove   boar   
    ibex   carp   carp   lamb   dove   boar   carp   bass   carp   
    boar   bass   clam   toad   kiwi   gnat   clam   carp   clam   
    dove   ibex   dove   dove   carp   wren   dove   erne   dove   
    kiwi   mink   erne   sole   erne   ibex   erne   clam   erne   
    carp   lion   gnat   hare   lion   sole   gnat   hare   gnat   
    tuna   kiwi   hare   mole   lamb   mole   hare   gnat   hare   
    sole   clam   ibex   erne   gnat   mule   ibex   ibex   ibex   
    lion   slug   kiwi   mule   loon   puma   kiwi   loon   kiwi   
    lamb   gnat   lion   slug   hare   lamb   lion   lamb   lamb   
    wren   toad   lamb   moth   clam   tuna   lamb   lion   lion   
    gnat   boar   loon   kiwi   bass   erne   loon   kiwi   loon   
    loon   sole   moth   mink   moth   mink   moth   moth   mink   
    hare   mole   mole   clam   mink   lion   mole   mink   mole   
    clam   loon   mink   lion   mole   loon   mink   mole   moth   
    bass   moth   mule   wren   mule   hare   mule   mule   mule   
    oryx   dove   oryx   loon   slug   carp   oryx   slug   oryx   
    slug   wren   puma   carp   oryx   bass   puma   oryx   puma   
    mole   erne   sole   boar   toad   moth   sole   toad   slug   
    toad   oryx   slug   bass   wren   slug   slug   wren   sole   
    erne   mule   tuna   gnat   sole   dove   tuna   sole   toad   
    mink   puma   toad   ibex   tuna   kiwi   toad   tuna   tuna   
    mule   tuna   wren   oryx   puma   oryx   wren   puma   wren   
    ----   ----   ----   ----   ----   ----   ----   ----   ----   
     0      ?      ?      ?      ?      ?      ?      ?      4     

Match up each column with the corresponding sorting algorithm from the given list:

    0. Original input
    1. LSD radix sort
    2. MSD radix sort
    3. 3-way radix quicksort (no shuffle)
    4. Sorted

You may use an algorithm more than once. Your answer should be a sequence of 9 integers between
0 and 4 (starting with 0 and ending with 4) and with each integer separated by a single space.

Hint: think about algorithm invariants. Do not trace code.

Answer for Question 6

Question 7

(seed = 727971)
What is the Burrows-Wheeler inverse transform of the following?

    5  B D A C D D A A 

Your answer should be a sequence of 8 characters, with a single space
separating each character.

Answer for Question 7

Question 8

(seed = 955798)
Which problems are known to have the same asymptotic complexity as multiplying two N-bit integers? Check all that apply.
Computing the remainder when dividing one N-bit integer into an N-bit integer.
Adding two N-bit integers.
Computing the remainder when dividing an N-bit integer by 17.
Squaring an N-bit integer.
Factoring an N-bit integer.

Question 9

(seed = 908805)
Consider the following linear programming simplex tableaux with 6 equations and 8 variables:

    maximize Z
                -    3 x1                                                         +  3/4 x7    -  Z    = -156
    ---------------------------------------------------------------------------------------------------------
                +    4 x1                                   +    1 x5             +    1 x7            =   18
     +    1 x0  -    1 x1                                                         -  6/5 x7            =   24
                +  3/2 x1                        +    1 x4                        +  3/5 x7            =   42
                +  5/4 x1  +    1 x2                                              +  1/2 x7            =   48
                +    2 x1                                              +    1 x6  -  5/2 x7            =   30
                +  5/2 x1             +    1 x3                                                        =   48
            x0  ,      x1  ,      x2  ,      x3  ,      x4  ,      x5  ,      x6  ,      x7           >=    0

What is the value of variable x5 in the current basic feasible solution?
Specify your answer with two digits after the decimal place.

Answer for Question 9

Question 10

(seed = 940895)
A problem is intractable if and only if it cannot be solved in
linear time
constant time
exponential space
exponential time
polynomial time

Question 11

(seed = 899132)
You are applying for a job at a new software technology company. Your interviewer asks you
to identify which of the following tasks are known to be possible. Check all that apply.
Given an undirected graph and two vertices s and t, find a path from s to t in E + V time.
Given an undirected graph, design an E + V algorithm to find a spanning tree.
Given an undirected graph, find an edge whose removal increases the number of connected components in (E+V) E time.
Given an digraph, design an E V algorithm to find the shortest directed cycle.
Given a digraph with positive edge weights and two vertices s and t, design an E + V algorithm to find a max st-flow.

Question 12

(seed = 121999)
You are applying for a job at a new software technology company. Your interviewer asks you
to identify which of the following tasks are known to be possible. Check all that apply.
Given an array of N strings, sort them in time linear in N in the worst case.
Determine whether a pattern string of length M is a substring of a text string of length N using a constant amount of extra memory.
Compute the suffix array of a string of length N in time proportional to N log N in the worst case.
Determine whether an M-character regular expression matches an N-character text in time polynomial in M and N.
Construct a DFA corresponding to an M-character regular expression.

Question 1

(seed = 388464)
Which of the following statements about connectivity in an undirected graph are true? Check all that apply.
Your Answer Score Explanation
If there are two edge-disjoint paths connecting vertices u and v, then there is a simple cycle containing both u and v.
0.00
If you delete two edges from a graph, its number of connected components can increase by at most 2.
0.20
A graph that has a unique simple path between every pair of vertices has exactly V-1 edges.
0.20
Given a graph and a vertex s, the graph has one connected component if and only if every vertex is connected to s.
0.20
Removing any edge from a connected graph breaks the graph into two connected components.
0.20
Total 0.80 / 1.00
Question Explanation

Question 2

(seed = 599575)
Which of the following statements about depth-first search in a digraph are guaranteed to be true? Check all that apply.
Your Answer Score Explanation
If a vertex has outdegree 0, then it will be first in any postorder.
0.00
The postorder of a digraph is the reverse of its preorder.
0.20
If there is a vertex reachable from every other vertex, it will be first in some postorder.
0.00
The reverse postorder of G^R is equal to the postorder of G.
0.20
If there is a vertex with outdegree 0, then some vertex with outdegree 0 will be first in any postorder.
0.00
Total 0.40 / 1.00
Question Explanation

Question 3

(seed = 694838)
Which of the following statements about minimum spanning trees (MSTs) are guaranteed to be true? Check all that apply.
Your Answer Score Explanation
Let G be a connected edge-weighted graph and let T be a MST of G. Then, the cheapest spanning tree of G besides T can be obtained by deleting the most expensive edge in T and computing the MST of the resulting graph.
0.20
Let G be a connected edge-weighted graph and let T be an MST of G. If you decrease the weight of some edge in T, then T will still be a MST.
0.20
Let G be a connected edge-weighted graph with distinct edge weights and no parallel edges. Then, the MST must contain the third cheapest edge.
0.20
Let T and T' be two MSTs of some edge-weighted graph and let a[] and b[] be the sorted array of edge weights for T and T', respectively. Then a[i] = b[i] for each i.
0.20
Let G be a connected edge-weighted graph with distinct edge weights and let (A, B) be a cut with at least 3 crossing edges. Then, the MST can contain the smallest and third smallest crossing edges without containing the second smallest crossing edge.
0.20
Total 1.00 / 1.00
Question Explanation

Question 4

(seed = 959653)
Which of the following statements about shortest paths are true? Check all that apply.
Your Answer Score Explanation
If you run the Bellman-Ford algorithm on an edge-weighted digraph with positive edge weights and the shortest path from s to t has k edges, then Bellman-Ford will require at least k passes.
0.00
Bellman-Ford finds the shortest simple path from s to every other vertex, even if the edge weights are arbritary positive or negative integers.
0.20
Bellman-Ford finds the shortest simple path from s to every other vertex, even if the edge weights are positive or negative integers, provided there are no negative cycles.
0.20
Let G be a digraph with positive edge weights. During Bellman-Ford, if you trace back the edgeTo[] entries starting from v back to s, the path has distance equal to distTo[v].
0.00
Let G be a digraph with positive edge weights. Suppose that you increase the length of an edge by x. Then, the length of the shortest path from s to t can increase by more than x.
0.20
Total 0.60 / 1.00
Question Explanation

Question 5

(seed = 392474)
Which of the following statements about maxflow and mincut are guaranteeed to be true? Check all that apply.
Your Answer Score Explanation
If all edge capacities are increased by an additive constant, then any mincut in the original network is a mincut in the modified network.
0.00
There exists a maxflow for which there is no directed cycle on which every edge carries positive flow.
0.00
Given a mincut (A, B), if the capacity of one edge from A to B is decreased by x, then the value of the maxflow will decrease by exactly x.
0.00
If all edge capacities are integral, then any maxflow has integer flow on each edge.
0.00
If the capacity of some cut (A, B) equals the value of some flow f, then f is a maxflow.
0.00
Total 0.00 / 1.00
Question Explanation

Question 6

(seed = 725630)
The column on the left contains the original input of 24 strings to be sorted;
the column on the right contains the strings in sorted order; the other 7 columns contain the
contents at some intermediate step during one of the 3 radix sorting algorithms listed below.

    moth   lamb   boar   puma   ibex   toad   bass   boar   bass   
    puma   hare   bass   tuna   boar   clam   boar   dove   boar   
    ibex   carp   carp   lamb   dove   boar   carp   bass   carp   
    boar   bass   clam   toad   kiwi   gnat   clam   carp   clam   
    dove   ibex   dove   dove   carp   wren   dove   erne   dove   
    kiwi   mink   erne   sole   erne   ibex   erne   clam   erne   
    carp   lion   gnat   hare   lion   sole   gnat   hare   gnat   
    tuna   kiwi   hare   mole   lamb   mole   hare   gnat   hare   
    sole   clam   ibex   erne   gnat   mule   ibex   ibex   ibex   
    lion   slug   kiwi   mule   loon   puma   kiwi   loon   kiwi   
    lamb   gnat   lion   slug   hare   lamb   lion   lamb   lamb   
    wren   toad   lamb   moth   clam   tuna   lamb   lion   lion   
    gnat   boar   loon   kiwi   bass   erne   loon   kiwi   loon   
    loon   sole   moth   mink   moth   mink   moth   moth   mink   
    hare   mole   mole   clam   mink   lion   mole   mink   mole   
    clam   loon   mink   lion   mole   loon   mink   mole   moth   
    bass   moth   mule   wren   mule   hare   mule   mule   mule   
    oryx   dove   oryx   loon   slug   carp   oryx   slug   oryx   
    slug   wren   puma   carp   oryx   bass   puma   oryx   puma   
    mole   erne   sole   boar   toad   moth   sole   toad   slug   
    toad   oryx   slug   bass   wren   slug   slug   wren   sole   
    erne   mule   tuna   gnat   sole   dove   tuna   sole   toad   
    mink   puma   toad   ibex   tuna   kiwi   toad   tuna   tuna   
    mule   tuna   wren   oryx   puma   oryx   wren   puma   wren   
    ----   ----   ----   ----   ----   ----   ----   ----   ----   
     0      ?      ?      ?      ?      ?      ?      ?      4     


Match up each column with the corresponding sorting algorithm from the given list:

    0. Original input
    1. LSD radix sort
    2. MSD radix sort
    3. 3-way radix quicksort (no shuffle)
    4. Sorted

You may use an algorithm more than once. Your answer should be a sequence of 9 integers between
0 and 4 (starting with 0 and ending with 4) and with each integer separated by a single space.

Hint: think about algorithm invariants. Do not trace code.

Answer for Question 6

You entered:
Your Answer Score Explanation
0 3 2 1 3 3 2 3 4 0.00
Total 0.00 / 1.00
Question Explanation

The correct answer is:0 1 2 1 3 1 2 3 4

 0: Original input
 1: LSD radix sort after 3 passes
 2: MSD radix sort after the first call to key-indexed counting
 1: LSD radix sort after 1 pass
 3: 3-way radix quicksort after the first partitioning step
 1: LSD radix sort after 2 passes
 2: MSD radix sort after the second call to key-indexed counting
 3: 3-way radix quicksort after the second partitioning step
 4: Sorted

Question 7

(seed = 727971)
What is the Burrows-Wheeler inverse transform of the following?

    5  B D A C D D A A 

Your answer should be a sequence of 8 characters, with a single space
separating each character.

Answer for Question 7

You entered:
Your Answer Score Explanation
0.00
Total 0.00 / 1.00
Question Explanation

The correct answer is:D A D C B A A D


Below are the sorted cyclic suffixes and the next[] array:

  i  suffixes[i]   t   next[i]
 -----------------------------
  0  A ? ? ? ? ? ? B     2
  1  A ? ? ? ? ? ? D     6
  2  A ? ? ? ? ? ? A     7
  3  B ? ? ? ? ? ? C     0
  4  C ? ? ? ? ? ? D     3
* 5  D ? ? ? ? ? ? D     1
  6  D ? ? ? ? ? ? A     4
  7  D ? ? ? ? ? ? A     5

Since first = 5, the first character is D (the first character in row 5).

Since next[5] = 1, the second character is A (the first character in row 1).

Since next[next[5]] = 6, the third character is D (the first character in row 6).

Since next[next[next[5]]] = 4, the fourth character is C (the first character in row 4).

Question 8

(seed = 955798)
Which problems are known to have the same asymptotic complexity as multiplying two N-bit integers? Check all that apply.
Your Answer Score Explanation
Computing the remainder when dividing one N-bit integer into an N-bit integer.
0.20
Adding two N-bit integers.
0.20
Computing the remainder when dividing an N-bit integer by 17.
0.20
Squaring an N-bit integer.
0.20
Factoring an N-bit integer.
0.20
Total 1.00 / 1.00
Question Explanation

Question 9

(seed = 908805)
Consider the following linear programming simplex tableaux with 6 equations and 8 variables:

    maximize Z
                -    3 x1                                                         +  3/4 x7    -  Z    = -156
    ---------------------------------------------------------------------------------------------------------
                +    4 x1                                   +    1 x5             +    1 x7            =   18
     +    1 x0  -    1 x1                                                         -  6/5 x7            =   24
                +  3/2 x1                        +    1 x4                        +  3/5 x7            =   42
                +  5/4 x1  +    1 x2                                              +  1/2 x7            =   48
                +    2 x1                                              +    1 x6  -  5/2 x7            =   30
                +  5/2 x1             +    1 x3                                                        =   48
            x0  ,      x1  ,      x2  ,      x3  ,      x4  ,      x5  ,      x6  ,      x7           >=    0


What is the value of variable x5 in the current basic feasible solution?
Specify your answer with two digits after the decimal place.

Answer for Question 9

You entered:
Your Answer Score Explanation
0.00
Total 0.00 / 1.00
Question Explanation

The basis is { x5, x0, x4, x2, x6, x3 }.
The nonbasic variables are { x1, x7 }.
The basic variable x5 appears in row 0.
Its current value equals the value of the RHS entry in that row, which is 18.

Question 10

(seed = 940895)
A problem is intractable if and only if it cannot be solved in
Your Answer Score Explanation
linear time
0.20
constant time
0.20
exponential space
0.20
exponential time
0.20
polynomial time
0.20
Total 1.00 / 1.00
Question Explanation

Question 11

(seed = 899132)
You are applying for a job at a new software technology company. Your interviewer asks you
to identify which of the following tasks are known to be possible. Check all that apply.
Your Answer Score Explanation
Given an undirected graph and two vertices s and t, find a path from s to t in E + V time.
0.00 BFS or DFS
Given an undirected graph, design an E + V algorithm to find a spanning tree.
0.00 BFS or DFS.
Given an undirected graph, find an edge whose removal increases the number of connected components in (E+V) E time.
0.00 Remove each each and count number of components. Finding such a bridge edge can also be solved in E+V time using DFS.
Given an digraph, design an E V algorithm to find the shortest directed cycle.
0.20 Run BFS from each vertex s. The shortest directed cycle through s is an edge v->s, plus a shortest path from s to v.
Given a digraph with positive edge weights and two vertices s and t, design an E + V algorithm to find a max st-flow.
0.20 Best known algorithm is approximately E V.
Total 0.40 / 1.00
Question Explanation

Question 12

(seed = 121999)
You are applying for a job at a new software technology company. Your interviewer asks you
to identify which of the following tasks are known to be possible. Check all that apply.
Your Answer Score Explanation
Given an array of N strings, sort them in time linear in N in the worst case.
0.00 The strings might be long.
Determine whether a pattern string of length M is a substring of a text string of length N using a constant amount of extra memory.
0.20 Brute-force substring search.
Compute the suffix array of a string of length N in time proportional to N log N in the worst case.
0.20 Use Manber-Myers algorithm.
Determine whether an M-character regular expression matches an N-character text in time polynomial in M and N.
0.20 Our RE-to-NFA construction algorithm + NFA simulation algorithm.
Construct a DFA corresponding to an M-character regular expression.
0.00 Kleene’s theorem implies this.
Total 0.60 / 1.00
Question Explanation



PGMN and PWQMN test cases

$
0
0

PGMN test case: search W0000036-1 and make sure the Chemistry tab contain the sample date of 31/10/2011.
search W0000001-1 and make sure the water level chart has the data between 2011 and 2012.
search 39 and make sure the precipitation chart has the data between 2011 and 2012.

Modify the maxYearCoordinate to 2012.


why parseInt(’08′) is giving 0, whereas parseInt(’07′) is giving 7

$
0
0

I am working on javascript, and I seem to find this strange, that the javascript function parseInt(’08′) is returning 0 and parseInt(’07′) is returning 7.

this behavior seems to be there in Firefox.

parseInt(’08′) is returning 8 in IE, but 0 in Firefox..

Why? I want parseInt(’08′) to return 8, as expected and getting in IE.

 

Yeah, I came across this one before. It is really odd because some browsers interpret this as you wanting to parse it in base 8. Consider the following article:

http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C85006A6604

basically, you have to tell the parser to use base 10 numbers:

parseInt('08', '10');

 


QT + OpenCV

$
0
0

QT Console

 

#include <opencv2/opencv.hpp>
//#include <opencv2/highgui/highgui.hpp>

int main(int argc, char *argv[])
{
    cv::Mat image = cv::imread("img.jpg");
            cv::namedWindow("My Image");
    cv::imshow("My Image", image);
    cv::waitKey(5000);
    return 1;
}

pro file

#-------------------------------------------------
#
# Project created by QtCreator 2013-06-17T14:15:10
#
#-------------------------------------------------

QT       += core

QT       -= gui

TARGET = myQTConsoleProject
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp

INCLUDEPATH += ~/opencv/opencv-2.4.5/include/
LIBS += -L/usr/local/lib \
-lopencv_core \
-lopencv_highgui \
-lopencv_imgproc \
-lopencv_features2d \
-lopencv_calib3d

 

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Open Image"), ".",
        tr("Image Files (*.png *.jpg *.jpeg *.bmp)"));
    image= cv::imread(fileName.toLatin1().data());
    cv::namedWindow("Original Image");
    cv::imshow("Original Image", image);
}

void MainWindow::on_pushButton_2_clicked()
{
    cv::flip(image,image,1);
    cv::namedWindow("Output Image");
    cv::imshow("Output Image", image);
}

Calculate Primes

$
0
0
// Fibonacci
// http://en.wikipedia.org/wiki/Fibonacci_number
var isPrime = function(n, arr) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] > Math.sqrt(n)) {
			break;
		}
		if ((n % arr[i]) == 0) {
			return false;
		}
	}
	return true;
};

 // Fibonacci: closed form expression
 // http://en.wikipedia.org/wiki/Golden_ratio#Relationship_to_Fibonacci_sequence
var calculatePrime = function(arr) {
	if(arr.length == 0) {
		return [2];
	}
	var i = arr[arr.length - 1] + 1;
	while (!isPrime(i, arr)) {
		i = i + 1;
	}
	arr.push(i)
	return arr;
};

// Find first K Fibonacci numbers via basic for loop
var firstPrimeNumber = function(k) {
	var i = 1;
	var arr = [];
	while (arr.length < k) {
		arr = calculatePrime(arr);
	}
	return arr;
};

 // Print to console
 var fmt = function(arr) {
	return arr.join(",");
	//return arr;
 };

 var k = 100;
 //console.log("firstkfib(" + k + ")");
 //console.log(fmt(firstPrimeNumber(k)));
 var fs = require('fs');
 var outfile = "prime.txt";
 var out = fmt(firstPrimeNumber(k));
 fs.writeFileSync(outfile, out);  
 //console.log("Script: " + __filename + "\nWrote: " + out + "To: " + outfile);


The Battle of Modern Javascript Frameworks

$
0
0

The Battle of Modern Javascript Frameworks – Part I

Posted April 10, 2013 by Bradley Trager and Roman Kagan & filed under Javascript Libraries.

Welcome to the Javascript Framework revolution.  Since the release of JQuery in 2006, client-side javascript has entered a renaissance, and many developers have decided to shift much of the functionality of there applications to the client side, while using the server primarily to send and recieve data.  Shifting functionality to the client side enables the potential for a much more powerful and responsive UI, which has always been an advantage of native apps. But with JQuery alone it still takes a great deal of effort to create a web app with the unparalled feel of a native app. Now everyone is wondering what will be the next paradigm in client-side development, and more importantly which framework they should choose for their next application. There are over 20 mainstream frameworks that operate on top (or next to) JQuery for developers to choose from (seeTodo MVC Project). No to mention several smaller more focused libraries.

This article will be the first in a series of posts that will hopefully shed light one several major frameworks in order to give you a picture of the advantages and disadvantages of each one, and help you to choose which one is right for your next project.  But before we talk about any specific frameworks, we will first outline some of the major features that these types of frameworks offer, and then we will outline our requirements in evaluating different frameworks.

Overview

In the words of Knockout.js creator Steve Sanderson “All the technologies follow from the view that serious JavaScript applications require proper data models and ability to do client-side rendering, not just server rendering plus some Ajax and jQuery code.” All the frameworks that we will discuss implement their data model as part of an MVC type architecture or some variation of MVC, and most have some sort of built in templating. A data model enables features like dependency tracking, and data-binding as well as the idea of “state” within a web app. Data models also make it much easier to sync data with the server. Templating enables applications to programmatically render views that are modular and reusable. As we evaluate each framework, we will look at how it implements these features and what additional features it offers that come as a result of the data model and templating.

Requirements

1.                Features

What are the main features the framework offers? And how do they meet the needs of the project?

2.                Strength of the Project and Community

Who are the core developers? How many people are active in the community? How well documented is the framework?

3.                Ease of Learning

How easy is the framework for developers to learn and use?

4.                Compatibility and Extensibility

Is the framework compatible with 3rd party libraries? Is it easily extensible?

5.                Testing and Debugging?

Are there any tools for testing and debugging? What are common debuging methods?

6.                Pros and Cons

Part II – Knockout.js

Knockout is the simplest of all the frameworks as well as one of the smallest. It does not claim to be able to solve all your problems, but it does claim to do a few useful things (see “features” below) and do it better than the alternatives. In the words of Knockout creator Steve Sanderson, it is “low risk” because its uses are focused and it is compatible with any other technologies you are using and you can use it in a very small part of your application or your entire application. For someone who wants to take their project to the next level without too much risk, knockout is a great choice.

Features

-Model-View-ViewModel architecture
-Tracks changes in your data by wrapping all your variables in an “observable function” creating a dependency graph which automatically controls the flow of events when something changes in your application.
-DOM or String-Based Templating for modularizing view and rendering them programmatically

Strength of the Project and Community

The Knockout project was released by Steve Sanderson (who is now on the Microsoft ASP.NET team) back in 2010 before he came to Microsoft. Since then a second version has been released, there have been a number of plugins written for it, Microsoft has incorporated intellisense support for it into Visual Studio 2012, and developers Michael Best and Ryan Niemeyer have joined the core Knockout.js development team. As a rough estimate of the size of the community, there are currently 3,533 people who have starred the KO GitHub repository, and 5,055 stack-overflow questions with knockout tags.

Ease of Learning

The documentation for knockout is probably the best we have ever seen. It has an amazing interactive tutorial system, live examples, and the documentation is extremely comprehensive and easy to understand. For most developers already familiar with javascript it should not take more than a few days to get up and running.

Compatibility and Extensibility

Knockout is compatible with any back-end technology and on the front-end it does as much or as little as you decide. Knockout purposely leaves many decisions to the developer to decide letting developers pick the best tool to meet their specific needs. Knockout has no opinion about how you communicate with the server or how you choose to do routing, but there are several third party libraries that do a fine job of these things (like sammy.js for routing and upshot.js for data-access). Knockout is one of the only frameworks that actually offers support for IE 6 if that is something you are interested in. It goes without mentioning that it works fine next to JQuery. Knockout is easily extensible. To modify or extend the default functionality, Knockout offers a features like custom bindings, and custom functions. As mentioned above, there are also several plugins already written for knockout.

Testing and Debugging

As of now, we have not seen any specific debugging tools for knockout, but it works fine with Javascript testing tools such as jasmine. Since knockout uses dependency injection, it is well suited for unit testing. Console.log() is handy, and knockout also offers a function ko.toJSON() which converts a KO view model to JSON and can be bound to a text area somewhere on the page so that developers can see in real time how their data is changing. For testing and prototyping, we find that it is easy to use implement knockout applications in jsfiddle.

Pros

-Highly compatible with other 3rd party js libraries
-Easy to learn and use
-Dependencies are handled through a dependency graph which targets specific data as opposed to updating entire models when data changes like in Angular.js. This may increase performance in data-heavy applications compared to “dirt checking” which Angular uses (but see this post on Stack Overflow which defends Angular’s approach).

Cons

-All javascript variables and arrays are functions (aka KO observables) as opposed to angular which can be a little confusing at first for some people. But it should be noted that all native javascript array functions like splice(), indexOf(), push() etc. are implemented by Knockout and may be used on KO observables.
-HTML views can get messy as declarative bindings increase. This can be mitigated to some extent through the use of custom bindings, computed observables and by attaching events to the DOM using JQuery (see Unobtrusive Event Handling) instead of using the data-bind attribute.
-Additional functionality like data-access and url-routing are not included. If you are looking for an end to end solution that offers a complete toolbox of common web-app functionality, you should probably check out frameworks like Angular or Ember.

Part III: Backbone.js

Right now Backbone.js is probably the most popular as well as simplest of the modern javascript frameworks. As its name describes, it main goal is to give a nice MVC structure to your javascript code. Backbones goal is to clean up your code by organizing all your data and event handlers into javascript objects. This way, events can be triggered whenever your data model changes thereby avoiding a lot of messy JQuery selectors and event bindings. It also has nice features for accessing data through RESTful APIs and URL routing. Other than that, Backbone tries to leave as much as possible up to the developer.

Features

-MVC style architecture for organizing your code
-Models and collections which can be persisted through a RESTful API
-Views which can automatically update by listening for changes in your model
-An optional routing system to define states of your app for single page applications

Strength of the Project and Community

Backbone.js has been in development since 2010 and in March 2013 just released version 1.0. It has one of the largest community of all the Javascript frameworks with rough indicators of 13,623 stars on GitHub, and 8,209 questions on stack-overflow. Many well known projects are using Backbone in their apps like DocumentCloud, LinkedIn Mobile, Walmart Mobile, Groupon, and CodeSchool just to name a few.

Ease of Learning

On one hand, backbone is a relatively simple library. If you go to their website, you will find a link to the annotated source code, which shouldn’t be hard for the average developer to read and understand. On the other hand, backbone has several concepts (e.i. model, collection, view and router), and the documentation is not as extensive as knockout or angular for example. Also, inexperienced programmers could quickly get into trouble if they are not aware of proper conventions when using backbone.js. Backbone also relies heavily on underscore.js, so it is necessary to learn underscore first or pick it up along the way. From our own experience and hearing other stories, it takes longer to get up and running with backbone in comparison to knockout. On the other hand, even though the concepts in backbone may be difficult to grasp at first, once you get it you will not need so much time to discover the rest of its functionality.

Compatibility and Extensibility

Backbone like knockout does not force you to do anything in a particular way. It is great for those who prefer to make their own decisions on the lower level. It basically just gives you a nice MVC type structure for your javascript. Yes, it offers solutions for routing and data-access, but if you prefer to do those things differently, it is up to you. It can work in a small part of your application as well as the entire application.

Testing and Debugging

There seem to be some plugins written to help debugging, but we have not used them so we cannot comment on how useful they are. We have seen that people using Jasmine to run unit tests in backbone. In general, we find that backbone can be relatively difficult at times to debug.

Pros

-Relatively mature, proven framework with a strong community behind it
-Many extensions and scaffolding tools available
-Flexible, works fine for a new project or improving an existing one

Cons

-Lacks data-binding
-Requires a large amount of boiler-plate code
-Could be dangerous if programmers do not follow proper conventions

Part IV: Angular.js

Angular.js is the first framework that officially calls itslef a framework as opposed to knockout and backbone which actually refer to themselves as libraries. Angular claims to be great even for small local applications, but it is probably better suited as a foundation to base a whole new project on. Angular seeks to combine a complete toolbox for building dynamic single page web apps. It is relatively fast to produce applications, and requires less boilerplate code in comparison to backbone.js. As co-creator, Brad Green claims that at google, angular was used to write an application in three weeks that previously took 6 months, and since then many have had similar experiences.

Features

-Data binding (Uses “Dirty Checking” instead of Change Listeners. See this post on Stack Overflow.)
-Dependency injection
-DOM-based templating
-Routing and Deep-Linking
-Model-View-”Whatever” architecture
-Built it form validation
-Data persistence methods that work with RESTful APIs
-Web Components or “Directives” (Define your own HTML syntax)

Testing and Debugging

This is one area where Angular is outstanding. Angular comes packaged with built in testing tools, and there is a list of other tools available. Batarang is an extension for chrome that monitors your app’s model and measures your app’s performance. As we find by the rest of the frameworks, jasmine works, but there is also a plugin testacular (spectacular test runner) which allows you to run jasmine test on multiple browsers. Yet another extension available is Angular Scenario Runner which automates testing by simulating user interactions. Finally, since Angular uses dependency injection, it makes it ideal for unit testing.

Strength of the Project and Community

Angular was initially developed internally by Google, and now that it has been open sourced, Google continues to support its development. Angular has 8,523 Stars on GitHub, and 4,239 questions on stack overflow.

Ease of Learning

Angular is certainly more complex than knockout and backbone. It surely requires a bigger time investment. With that said, we feel that getting started with Angular is rather easy especially if you are familiar with knockout since the data-binding features are used in a very similar way. Angular also has comprehensive and well organized tutorials with plenty of examples on there website.

Compatibility and Extensibility

As far as compatibility goes, Angular can function in a particular part of your application so it does not get in the way of other frameworks you may be using. Angular is more abstract than knockout and backbone, it makes more decisions for you behind the scenes so that you can write less code, but this inevitably makes it harder to customize on a lower level. On a higher level, Angular gives the developer an API with extensive options.

Pros

-Uses primitive javascript types instead of function wrappers (“dirty checking”)
-Loaded with functionality
-Easy to get started
-Fast development and smaller amounts of boiler-plate code compared to backbone
-Makes testing easy and offers many testing tools
-Working with standards bodies to make browsers operate in the same way as angular

Cons

-Takes longer to learn than knockout and backbone
-Has not been proven in as many mainstream projects compared to backbone.js

Part V – Ember.js

Ember as it is described by its creators is ambitious and opinionated. The goal of developing ember is simple; create a web framework that will enable web apps to rival native apps. To accomplish this, ember offers an end to end solution with all the features you need to create a single page web app functioning in unison. Ember also seeks to abstract as much as possible from the programmer in order to take care of all the small decisions that programmers would otherwise have to make. Therefore, it is also opinionated about how certain things should be done including how you name your objects, and how you organize your files. Ember is also ambitious in the sense that one should ideally use ember for “ambitious” projects where the goal is to produce an outstanding web app that will have the feel of a native app.

Features

-Sophisticated handlebars templates
-Views that respond to events
-Routing for representing the state of the model and view in your application and enabling deep linking to return to a particular state
-Models that are persistable with a REST api
-Controllers which produce computed properties from the model and pass it to a view
-API for performing operations on Enumerable objects

Strength of the Project and Community

Ember’s development is lead by Yehuda Katz and Tom Dale. Yehuda Katz is also on the JQuery and Ruby on Rails core teams. As a rough indicator of community size, there are currently 351 questions on stack overflow. 6,676 stars on GitHub. Ember just recently released its version 1.0, and before that was undergoing a good deal of changes. But despite the turbulent state of ember, several companies decided to take the plunge into using ember as their client-side framework. Ember data is still not in its version 1.0 state, and it does not yet ship together with ember.

Ease of Learning

The documentation for Ember, though not as impressive as that of Knockout or Angular, is quite comprehensive and easy to go through. There is a 30 minute video demonstration to get started, and then a complete development guide full of examples. Ember certainly has more concepts to understand than knockout and backbone, but getting started is relatively easy.

Compatibility and Extensibility

Since Ember uses handlebars for templating, it should be possible to plug-in any 3rd party plugin for extending templates. Out of the package, ember offers custom helpers for use in templates and the REST adapter for controlling how your application handles requests to the server. If you need to integrate ember with 3rd party libraries, you may need to set embers “EXTEND_PROTOTYPES” option to false. In this case you will have to manually tell ember to extend your objects by wrapping them in what ember calls convenience methods.

Testing and Debugging

Like the other javascript frameworks, developer tools like chrome web inspector work great for debugging ember (see this great debugging demonstration by Tom Dale). Ember also works with jasmine for unit testing. One useful tip for testing the routing in an app is to specify the “LOG_TRANSITIONS” option when you instantiate your app as follows.

 

App = Ember.Application.create({

  LOG_TRANSITIONS: true

});
Unlike Angular, Ember does not currently come with any built in testing tools.

Pros

-Sophisticated templating for managing more complex views
-Can quickly and easily convert a multi-page site into single page app using the routing feature
-Fast development, easy to read markup, smaller maintainable of code
-Full-featured
-Easy to get started

Cons

-Relatively new framework (v1.0 just released)
-Ember Data is not yet at v1.0 so it is separate
-Lacks custom HTML tags like directives in Angular
-Lacks extensive testing tools like Angular
-Doesn’t integrate easily with 3rd party libraries

Conclusion – Which One to Choose

On one hand, each javascript framework has its unique advantages and it is reasonable to say that each one has its place in web development. On the other hand, these frameworks have a similar goal. They are all excellent frameworks and there will certainly be a place for each one as web apps continue to become more and more sophisticated. The factors that determine which one you choose will be based on a combination of your projects needs and your personal preference of how you as a developer like to accomplish things.

Knockout

For a small project or improving an existing project knockout is a great choice. It is simple to get started with and integrates nicely with other 3rd party libraries. And if you decide at some point that you need a more powerful framework like Angular or Ember, you will already be ahead of the learning curve since they all use data-binding in a similar way. If you want to keep knockout you can easily add things like routing and data-access features through a number of third party libraries.

For larger projects knockouts view model could start to get a bit complicated because computed data is not separated nicely from persistable data, and increasing numbers event handlers may become hard to keep track of.

Backbone

If you are an experienced javascript programmer looking for a mature, proven framework that provides MVC architecture to your code while maintaining as much low-level control as possible and offering easy REST api data access plus routing, backbone would be a good choice. For larger scale projects, or if you don’t like writing so much boiler-plate code, the plugin marionette.js could be helpful.

Angular

If you need a fully loaded framework that seeks to rival native apps, reduce the amount of time and code it takes to write a web app, and you can handle a somewhat steep learning curve Angular or Ember would be a good choice. It is very hard to choose between Angular and Ember as the both seek to do similar things.

Angular has appeal in the fact that it is backed by Google, it is somewhat more mature, and it offers some interesting features like custom HTML directives and integrated testing tools. It is also easier to localize it to run in specific areas of your app to avoid conflicting with other javascript libraries you are using elsewhere.

Ember

Ember like Angular is a fully loaded framework that seeks to rival native apps and reduce the amount of time and code it takes to write a web app with an even steeper learning curve than Angular. Some developers may prefer Embers style since it is modeled after the Cocoa framework in iOS development making it similar to programming native apps.


Viewing all 759 articles
Browse latest View live