id
stringlengths
36
36
text
stringlengths
1
1.25M
782e0be8-80de-4ae6-b902-60d20e05a6cb
public void setStart(int start) { this.start = start; }
00e01105-328b-47d8-a5c6-82feea6db977
public int getEnd() { return end; }
27a080f3-26a5-4b24-82fb-f23ce15880d6
public void setEnd(int end) { this.end = end; }
83814093-7e13-4f33-b5fc-e0e3e54e4c16
@Override public boolean equals(Object o) { if(!(o instanceof Swap)) return false; Swap other = (Swap) o; if(other.start == start || other.start == end) { if(other.end == end || other.end == start) { return true; } } return false; }
41591ff0-6e46-4304-bec5-562a727c13e6
public String toString(){ return "Swap(" + start + ", "+ end+ ")"; }
3ebced6a-bbe2-455c-8bd9-13f87f6c0c41
public String getName() { return "Bubble Sort"; }
a68e5bf0-6a30-4ed6-8f58-56d686490d8b
public BubbleSort(double ... data){ super(data); }
e46fdf76-6930-4e5a-8384-ff6d078b3ba6
public BubbleSort(ArrayList<Double> data){ super(data); }
1409ad13-59dc-4e8d-87ce-b5dc9d57f3f2
public LinkedList<Swap> sort(){ for (int len = data.size(); len >= 0; len--) { for (int i = 1; i < len; i++) { if (data.get(i) < data.get(i - 1)) { doSwap(i - 1, i); } } } return swapList; }
43358f5f-2df4-4863-bb04-2b34015107b6
@Override public Object clone() { Sorter out = new BubbleSort((ArrayList<Double>)getData().clone()); out.swapList = (LinkedList<Swap>) swapList.clone(); out.scrambledData = (ArrayList<Double>) scrambledData.clone(); return out; }
221af21e-fda0-4cec-b67c-5baec6b3e51c
public HeapSort(double ... data) { super(data); }
a5c50337-88f4-4605-b3e4-a76d733eea40
public HeapSort(ArrayList<Double> data) { super(data); }
d926073d-55f3-4299-b771-adc7e74ac598
@Override public LinkedList<Swap> sort() { pileUp(); for(int i = data.size()-1; i > 0; i--) { doSwap(0, i); heapify(0, i-1); } return swapList; }
a6ea1e06-abde-47cf-bd8b-8e5a177eaf1f
private void pileUp() { for(int i = data.size()/2 - 1; i >= 0; i--) { heapify(i, data.size()-1); } }
8688e949-4b85-4751-ac1d-4689ede6f168
private void heapify(int start, int end) { double here = data.get(start); int leftIndex = start*2 + 1; int rightIndex = start*2 + 2; int largestIndex = start; if(leftIndex <= end && data.get(leftIndex) > here) { largestIndex = leftIndex; } if(rightIndex <= end && data.get(rightIndex) > data.get(largestIndex)) { largestIndex = rightIndex; } if(largestIndex != start) { doSwap(start, largestIndex); heapify(largestIndex, end); } }
53c9517c-ce0b-4309-baa7-6bad4db5b886
@Override public String getName() { return "Heap Sort"; }
f927d5e8-f5b1-4955-9b0e-5239c69802a2
@Override public Object clone() { Sorter out = new HeapSort((ArrayList<Double>)getData().clone()); out.swapList = (LinkedList<Swap>) swapList.clone(); out.scrambledData = (ArrayList<Double>) scrambledData.clone(); return out; }
f92b6f25-ebe1-41d1-8158-a32ba3287d80
public SortSlowDisplay(int numRect, Sorter[] sorter) { super(numRect, sorter); // TODO Auto-generated constructor stub }
8481fd8a-88bc-4b30-8fab-8a4893788e31
@Override public void run(){ for(Sorter s : allTheSorters){ s.nextStep(); } repaint(); }
a4894d1a-dc9d-4dab-af96-ed3dc9987d8a
public abstract void run();
ebeaa306-4fd5-440d-9de3-30c28177dd67
public SortDisplay( int numRect, Sorter ... sorter) { this.numRect = numRect; allTheSorters = new ArrayList<Sorter>(); for( Sorter s : sorter){ allTheSorters.add((Sorter)s.clone()); } clearThenAddData(allTheSorters); setup(); }
9088b835-59c5-4dd2-b744-a4f0ad5640b9
private void clearThenAddData(ArrayList<Sorter> sorter) { ArrayList<Double> data = new ArrayList<Double>(); for(double i = 0; i < 360; i += ((double)360)/numRect ){//add the integer values to the array, they must be evenly spaces and cover the range from 0 to 360 for a full rainbow data.add(i); } Collections.shuffle(data); //randomize the integer values in the array for( Sorter s : sorter){ s.setData((ArrayList<Double>)data.clone());//for all the sorters set the data to the scrambled array s.sort(); } }
fb17877b-6ea9-4f5d-99e9-ca45b16fa72e
private void setup() { JButton step = new JButton("Go"); setLayout(new BorderLayout()); setSize(900, 300); setToMiddle(); setResizable(true); add(new Display(), BorderLayout.CENTER); add(new sideNameBar(), BorderLayout.WEST); step.addActionListener(new Runner(this)); add(step, BorderLayout.EAST); }
a22aee84-0dc7-4e47-bed3-0b522c81da21
Runner(Runnable r){ thingToMake = r; }
dbd63af0-9bde-49ff-9655-3f0b29bde069
public void actionPerformed(ActionEvent e) { Thread runner = new Thread(thingToMake, "runner"); runner.start(); }
4c6cf556-2dc9-49bc-9a84-cacd9f528e79
private void setToMiddle() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); Point mid = new Point( (int)((dim.getWidth() - getWidth()) / 2), (int)((dim.getHeight() - getHeight()) / 2) ); setLocation(mid); }
09256a05-14d7-46ad-9eeb-318ff70cfc83
public sideNameBar () { setup(); }
d59d47e0-6d1e-4c0f-b304-8b16b7762760
private void setup() { JLabel addingSorter; setLayout(new GridLayout(allTheSorters.size(),1)); for(Sorter thisSorter: allTheSorters ) { addingSorter = new JLabel(thisSorter.getName()); add(addingSorter); } }
b9e8f514-3b87-4314-82ee-1453f3d45467
public Display (){ setBorder(new TitledBorder (new EtchedBorder(), "Sorting Algorithm")); }
8b55b776-10da-41c8-b72b-f37cf00d3174
@Override public void paintComponent(Graphics g) { super.paintComponent(g); //int widthRect = (int) ((getWidth()*.93)/numRect); int heightRect = (int) ((getHeight()*.85)/allTheSorters.size()); int numPrinted = 0; for(Sorter curSorter : allTheSorters){ curSorter.draw(20,(numPrinted)* (heightRect+5)+20 , heightRect, getWidth(), g); numPrinted++; } }
a628f418-33d4-4b81-986e-b31ad7d972f8
public MainFrame() { JButton fastButton = new JButton("Compare Algorithms"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Sort Shower"); setSize(750, 200); setResizable(false); numRects = new JTextField("A Number goes in here"); setLayout(new BorderLayout()); add(new SortChoicePanel(), BorderLayout.NORTH); fastButton.addActionListener(new Guo(numRects)); add(numRects, BorderLayout.EAST); add(fastButton, BorderLayout.CENTER); }
8d324096-693c-499c-8eae-2d246880f90c
private void setSorter(Sorter newSorter) { sorter = newSorter; }
32a723b1-136b-4253-a014-d1b5b244d632
public SortChoicePanel() { setLayout(new BorderLayout()); JPanel sortersPanel = new JPanel(); for (Sorter s: sorters) { JButton button = new SorterButton(s,numRects); sortersPanel.add(button); } add(sortersPanel, BorderLayout.WEST); JPanel displaysPanel = new JPanel(); add(displaysPanel, BorderLayout.EAST); }
b2390d74-ca65-487d-b0ba-08416835f13c
public SorterButton(Sorter s,JTextField numRects) { super("Step-by-step " + s.getName()); sorter = s; addActionListener(new Gho(numRects)); }
5e2faf4e-194f-40a1-a9ee-1bed7f0a12cb
public Gho (JTextField numRects){ this.numRects = numRects; }
85fd5d11-7e58-43df-a523-e3e37e0e7e0e
public void actionPerformed(ActionEvent e) { int parsedInt = 10; try{ parsedInt = Integer.parseInt(numRects.getText()); } catch(NumberFormatException n) { } SortDisplay popUp = new SortSlowDisplay(parsedInt,new Sorter[] {sorter}); popUp.setVisible(true); }
a4151fb4-8adb-4727-953f-9fb7f60d2c08
public Guo (JTextField numRects){ this.numRects = numRects; }
633fec92-a5f9-4251-b21b-b8d27472c5de
public void actionPerformed(ActionEvent e) { int fromTextField = 10; try{ fromTextField = Integer.parseInt(numRects.getText()); } catch(NumberFormatException n) { } SortDisplay popUp = new SortFastDisplay(fromTextField,sorters); popUp.setVisible(true); }
e04a6c8f-21e3-4b73-8945-f643ab6a1f1f
public static void main(String args[]) { MainFrame mf = new MainFrame(); mf.setVisible(true); }
04869c43-e884-40fa-841c-6bf864371d61
public SortFastDisplay(int numRect, Sorter[] sorter) { super(numRect, sorter); speed = new JTextField("Delay"); add(speed,BorderLayout.SOUTH); }
25d7567f-89c2-4267-b7b9-22bb500b5df0
@Override public void run() { allTheSorters = (ArrayList<Sorter>)allTheSorters.clone(); int numDone = 0; while(numDone < allTheSorters.size()){ numDone=0; for(Sorter s : allTheSorters){ if(!s.nextStep()){ numDone++; } } int speedNum; try { speedNum = Integer.parseInt(speed.getText()); } catch (NumberFormatException e) { speedNum = 50; } try { repaint(); Thread.sleep(speedNum); } catch (InterruptedException e) { } } }
26d1dba8-c378-42d4-923a-ddc661e95500
@Test public void testEmptyString(){ assertEquals(0, stringCalculator.add("")); }
a3de64fd-940a-4c5f-98d1-403502ce308c
@Test public void testSingleNumber(){ assertEquals(17, stringCalculator.add("17")); }
81b4f595-e7e6-4038-a861-002fad46a06a
@Test public void testCommaSeparateNumber(){ assertEquals(2356, stringCalculator.add("2341,15")); }
1f4633a4-547f-4f46-9963-b6330e4d52cc
@Test public void testNewlineSeparateNumber(){ assertEquals(35, stringCalculator.add("34\n1")); }
b94b0e64-b768-414c-bf45-b71830678ca0
@Test public void testCustomSeparator(){ assertEquals(7, stringCalculator.add("//;\n5;2")); }
5e67cfe9-dd98-4e9d-9697-99443ce66622
public int add(String inputString) { if (inputString.isEmpty()) { return 0; } if (hasCustomSeparator(inputString)) { char customSeparator = inputString.charAt(2); String stringToCalculate = inputString.substring(4); return add(stringToCalculate, customSeparator); } else { return add(inputString, STANDARD_SEPARATOR); } }
c9a98386-690c-4456-ad51-1d6c784f5192
private boolean hasCustomSeparator(String inputString) { return inputString.startsWith(DEFINE_CUSTOM_SEPARATOR); }
324361f8-679b-40a8-acd3-b542c5a61268
private int add(String s, char customSeparator) { int result = 0; for (String n : s.split("[\n" + customSeparator + "]")) { result += Integer.parseInt(n); } return result; }
ad1a2b9b-f95e-48eb-b2a3-a9a329743f10
public TennisGame(String player1Name, String player2Name) { this.player1Name = player1Name; this.player2Name = player2Name; }
1f18426f-01ca-47c2-894a-d79c9474f570
public void wonPoint(String playerName) { if (playerName == "player1") m_score1 += 1; else m_score2 += 1; }
c3b9050e-9a89-48bf-9256-715c8d48b734
public String getScore() { String score = ""; int tempScore=0; if (m_score1==m_score2) { switch (m_score1) { case 0: score = "Love-All"; break; case 1: score = "Fifteen-All"; break; case 2: score = "Thirty-All"; break; case 3: score = "Forty-All"; break; default: score = "Deuce"; break; } } else if (m_score1>=4 || m_score2>=4) { int minusResult = m_score1-m_score2; if (minusResult==1) score ="Advantage player1"; else if (minusResult ==-1) score ="Advantage player2"; else if (minusResult>=2) score = "Win for player1"; else score ="Win for player2"; } else { for (int i=1; i<3; i++) { if (i==1) tempScore = m_score1; else { score+="-"; tempScore = m_score2;} switch(tempScore) { case 0: score+="Love"; break; case 1: score+="Fifteen"; break; case 2: score+="Thirty"; break; case 3: score+="Forty"; break; } } } return score; }
80d4fa8f-9e74-472e-93a2-53be9c92300c
public TennisGameTest(int player1Score, int player2Score, String expectedScore) { this.player1Score = player1Score; this.player2Score = player2Score; this.expectedScore = expectedScore; }
f120a960-45b2-465c-a229-0438fa0de1a4
@Parameters public static Collection<Object[]> getAllScores() { return Arrays.asList(new Object[][] { { 0, 0, "Love-All" }, { 1, 1, "Fifteen-All" }, { 2, 2, "Thirty-All"}, { 3, 3, "Forty-All"}, { 4, 4, "Deuce"}, { 1, 0, "Fifteen-Love"}, { 0, 1, "Love-Fifteen"}, { 2, 0, "Thirty-Love"}, { 0, 2, "Love-Thirty"}, { 3, 0, "Forty-Love"}, { 0, 3, "Love-Forty"}, { 4, 0, "Win for player1"}, { 0, 4, "Win for player2"}, { 2, 1, "Thirty-Fifteen"}, { 1, 2, "Fifteen-Thirty"}, { 3, 1, "Forty-Fifteen"}, { 1, 3, "Fifteen-Forty"}, { 4, 1, "Win for player1"}, { 1, 4, "Win for player2"}, { 3, 2, "Forty-Thirty"}, { 2, 3, "Thirty-Forty"}, { 4, 2, "Win for player1"}, { 2, 4, "Win for player2"}, { 4, 3, "Advantage player1"}, { 3, 4, "Advantage player2"}, { 5, 4, "Advantage player1"}, { 4, 5, "Advantage player2"}, { 15, 14, "Advantage player1"}, { 14, 15, "Advantage player2"}, { 6, 4, "Win for player1"}, { 4, 6, "Win for player2"}, { 16, 14, "Win for player1"}, { 14, 16, "Win for player2"}, }); }
20167232-c5f5-46af-973a-03ee1635b3d9
@Test public void checkAllScores() { TennisGame game = new TennisGame("player1", "player2"); int highestScore = Math.max(this.player1Score, this.player2Score); for (int i = 0; i < highestScore; i++) { if (i < this.player1Score) game.wonPoint("player1"); if (i < this.player2Score) game.wonPoint("player2"); } assertEquals(this.expectedScore, game.getScore()); }
f8884a54-5d9b-443f-a0d2-0ce3e6832e4d
@Test public void realisticGame() { TennisGame game = new TennisGame("player1", "player2"); String[] points = {"player1", "player1", "player2", "player2", "player1", "player1"}; String[] expected_scores = {"Fifteen-Love", "Thirty-Love", "Thirty-Fifteen", "Thirty-All", "Forty-Thirty", "Win for player1"}; for (int i = 0; i < 6; i++) { game.wonPoint(points[i]); assertEquals(expected_scores[i], game.getScore()); } }
c9646c02-0650-486d-94c4-632db9e0dccd
public Background(int width, int height, int lineDistance) { super(); setPreferredSize(new Dimension(width, height)); this.lineDistance = lineDistance; setOpaque(true); setBackground(Color.yellow); setForeground(Color.orange); }
52a47481-dbfd-4d5a-95bf-dfa463bfa2b4
public void paintComponent(Graphics g) { super.paintComponent(g); int height = getHeight(); for (int i = 0; i < this.getWidth(); i+= lineDistance) g.drawLine(i, 0, i, height); }
dc66854d-c383-443c-907f-afe0909364ad
public static void main(String[] args) { new Table(); }
8f0fb978-3b2a-4786-b353-1b7560a88839
public Table() { super("Planning Game Simulation"); JComponent buttons = makeButtons(); this.getContentPane().add(buttons, "West"); body = new Background(1000, 1000, 190); body.addContainerListener(new ContainerListener() { // Listen for container changes so we know when // to update selection highlight public void componentAdded(ContainerEvent e) { resetSelection(); } public void componentRemoved(ContainerEvent e) { resetSelection(); } private void resetSelection() { if (selection != null) selection.setBorder(BorderFactory.createLineBorder(Color.blue, 6)); if (body.getComponentCount() == 0) { selection = null; } else { selection = (Card) body.getComponent(0); selection.setBorder(BorderFactory.createLineBorder(Color.red, 6)); } } }); JScrollPane scroll = new JScrollPane(body); scroll.setPreferredSize(new Dimension(100, 100)); this.getContentPane().add(scroll, "Center"); summary = new JLabel("", SwingConstants.CENTER); summary.setText(summary()); this.getContentPane().add(summary, "South"); this.pack(); this.setSize(800, 600); }
e5a5f99e-d7e8-403e-ae9e-e06ca56d9bd6
public void componentAdded(ContainerEvent e) { resetSelection(); }
b1b1f1c5-0561-4334-a493-58a492a1e2df
public void componentRemoved(ContainerEvent e) { resetSelection(); }
590c48f5-9f9b-4d92-8695-0e581705e648
private void resetSelection() { if (selection != null) selection.setBorder(BorderFactory.createLineBorder(Color.blue, 6)); if (body.getComponentCount() == 0) { selection = null; } else { selection = (Card) body.getComponent(0); selection.setBorder(BorderFactory.createLineBorder(Color.red, 6)); } }
992f42c3-2827-4198-a0b0-510bfc1836d5
private JComponent makeButtons() { JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(new JLabel("Customer")); makeCustomerButtons(panel); panel.add(new JLabel(" ")); panel.add(new JLabel("Programmer")); makeProgrammerButtons(panel); JPanel outer = new JPanel(new BorderLayout()); outer.add(panel, "North"); outer.add(new JLabel(""), "Center"); return outer; }
f1f89e7a-e3d9-4596-9ecf-5d23a07fa610
private void makeCustomerButtons(JPanel panel) { JButton button; button = new JButton("New"); panel.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Card card = new Card(); body.add(card, 0); selection = card; updateCost(); repaint(); } }); button = new JButton("Split"); panel.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (selection == null) return; Card card = new Card(selection); body.add(card, 0); selection = card; updateCost(); body.repaint(); } }); button = new JButton("Delete"); panel.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (body.getComponentCount() == 0) return; body.remove(0); selection = null; if (body.getComponentCount() != 0) selection = (Card) body.getComponent(0); updateCost(); body.repaint(); } }); button = new JButton("Plan"); panel.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringBuffer report = new StringBuffer(); // Check for cards that need est. or splitting for (int i = 0; i < body.getComponentCount(); i++) { Card card = (Card) body.getComponent(i); if (card.needsEstimate()) report.append( "Needs estimate: " + card.title() + "\n"); else if (card.needsSplit()) report.append( "Needs to be split: " + card.title() + "\n"); } if (report.length() == 0) JOptionPane.showMessageDialog( body, "Plan OK; no cards need estimates or splitting", "Issues in plan", JOptionPane.OK_OPTION); else JOptionPane.showMessageDialog( body, report.toString(), "Issues in plan", JOptionPane.OK_OPTION); } }); }
353cb365-1c72-4eec-9bb0-e3dc394687d5
public void actionPerformed(ActionEvent e) { Card card = new Card(); body.add(card, 0); selection = card; updateCost(); repaint(); }
9c0b6042-d02d-4664-a002-c1258d996919
public void actionPerformed(ActionEvent e) { if (selection == null) return; Card card = new Card(selection); body.add(card, 0); selection = card; updateCost(); body.repaint(); }
2353f298-e963-4ac4-ac92-6db3a7d83e7f
public void actionPerformed(ActionEvent e) { if (body.getComponentCount() == 0) return; body.remove(0); selection = null; if (body.getComponentCount() != 0) selection = (Card) body.getComponent(0); updateCost(); body.repaint(); }
5a73a98e-b475-4adb-ad86-e377356e0719
public void actionPerformed(ActionEvent e) { StringBuffer report = new StringBuffer(); // Check for cards that need est. or splitting for (int i = 0; i < body.getComponentCount(); i++) { Card card = (Card) body.getComponent(i); if (card.needsEstimate()) report.append( "Needs estimate: " + card.title() + "\n"); else if (card.needsSplit()) report.append( "Needs to be split: " + card.title() + "\n"); } if (report.length() == 0) JOptionPane.showMessageDialog( body, "Plan OK; no cards need estimates or splitting", "Issues in plan", JOptionPane.OK_OPTION); else JOptionPane.showMessageDialog( body, report.toString(), "Issues in plan", JOptionPane.OK_OPTION); }
341ba728-ff7a-43f8-b641-15f2be6e9be0
private void makeProgrammerButtons(JPanel panel) { JButton button; button = new JButton("Cost"); panel.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (selection == null) return; selection.rotateCost(); updateCost(); } }); button = new JButton("Velocity"); panel.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { velocity++; if (velocity >= 10) velocity = 1; updateCost(); } }); }
fe44aee8-5245-4ed2-b3a4-b492bda4f425
public void actionPerformed(ActionEvent e) { if (selection == null) return; selection.rotateCost(); updateCost(); }
edf8f927-ffee-461c-9d16-0136be29fa85
public void actionPerformed(ActionEvent e) { velocity++; if (velocity >= 10) velocity = 1; updateCost(); }
81d005a2-8aa0-4da1-a1ba-f74569b48ddb
private void updateCost() { summary.setText(summary()); }
26b0f970-bba3-4e02-8b57-953aca46ebf5
private String summary() { StringBuffer result = new StringBuffer(); result.append( "Est. Velocity (points/iteration): " + velocity + ". "); result.append("Total cost (points): " + cost() + ". "); result.append("#Cards: " + body.getComponentCount() + ". "); result.append( "Est. #iterations: " + (cost() + velocity - 1)/ velocity + ". "); return result.toString(); }
d31c6623-495a-4b06-b7f1-7f8ee2048e39
private int cost() { int total = 0; for (int i = 0; i < body.getComponentCount(); i++) { Card card = (Card) body.getComponent(i); total += card.cost(); } return total; }
e4797544-cbbe-438f-8ff9-971bffb27c3e
EthernetPort(String host, int port) { System.out.printf("EthernetPort to host %s, port %d\n", host, port); try { this.socket = new java.net.Socket(host, port); this.inputStream = socket.getInputStream(); this.outputStream = socket.getOutputStream(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
e2d6921f-9ce3-48fe-909c-9b530e038064
@Override public InputStream getInputStream() { return inputStream; }
a97a5e7f-2f19-4ad2-9880-d3bd018e83a0
@Override public OutputStream getOutputStream() { return outputStream; }
9dd173c4-47eb-44b9-a3cf-47a1f8496533
@Override public void close() throws IOException { socket.close(); }
05ae1276-31b7-427c-b4f9-36c137ad01bd
public static void main(String[] args) { try { System.out.println("Start"); System.out.println("sun.arch.data.model: " + System.getProperty("sun.arch.data.model")); Configurator configurator = new Configurator(args); Port p = configurator.getPort(); UserInputLoop inputLoop = configurator.getUserInputLoop(); if (p instanceof SerialPort) { Enumeration e = CommPortIdentifier.getPortIdentifiers(); while (e.hasMoreElements()) { CommPortIdentifier id = (CommPortIdentifier) e.nextElement(); System.out.println("Available: " + id.getName()); } } PortFeedbackLoop feedbackLoop = new DefaultPortFeedbackLoop(); feedbackLoop.start(p.getInputStream()); inputLoop.start(p.getOutputStream()); // blocks forever p.close(); } catch (Exception e) { System.out.println(e); } System.out.println("Goodbye!"); }
9d62ebfa-1888-4f1c-a8bf-142f17a3612c
void start(OutputStream os) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.print("> "); String input = br.readLine(); sendBytes(getBytesFromInputLine(input), os); System.out.println(); } }
cf07529b-043b-4389-a2e8-71bf9a9b184a
private void sendBytes(byte[] bytes, OutputStream os) throws IOException { os.write(bytes); os.flush(); }
e5302539-18ff-4cf8-959e-43552af156f7
abstract byte[] getBytesFromInputLine(String inputLine);
f408bb1a-52fd-40d2-ab9b-51c9dce1c844
byte[] getBytesFromInputLine(String inputLine) { try { return inputLine.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException(e); } }
c876a6ca-bf98-46c5-887b-ef4c7b167dbf
byte[] getBytesFromInputLine(String inputLine) { return hexStringToByteArray(inputLine); }
07da2230-9268-490f-900d-5b797ed5352a
public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; }
6368c6a0-8daa-4dcd-9742-c7a2fbb82f54
public void start(final InputStream is) { Thread t = new Thread(new Runnable() { @Override public void run() { try { while (true) { char[] bytes = readBytesWithTO(is, 5000); if (bytes.length > 0) { System.out.println(interpretFeedbackBytes(bytes)); } } } catch (IOException e) { e.printStackTrace(); } } }); t.start(); }
172348ee-8828-47dd-8b4e-c6eb6ef69569
@Override public void run() { try { while (true) { char[] bytes = readBytesWithTO(is, 5000); if (bytes.length > 0) { System.out.println(interpretFeedbackBytes(bytes)); } } } catch (IOException e) { e.printStackTrace(); } }
60247834-76d5-49c1-91c9-2f85e24e5c7e
private static char[] readBytesWithTO(InputStream is, long toMillis) throws IOException { long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start <= toMillis) { int available = is.available(); if (available > 0) { char[] bytes = new char[available]; for (int i = 0; i < available; i++) { bytes[i] = (char) is.read(); } return bytes; } else { try { Thread.sleep(30); } catch(InterruptedException e) { Thread.currentThread().interrupt(); // restoring the interrupt, someone may be interested in it, we just ignore. } } } return new char[0]; // timeout }
2b9fed52-9660-4d20-a909-0f210c3a62a6
abstract String interpretFeedbackBytes(char[] bytes);
2a528592-7412-4265-9a24-2a862ab78f19
@Override String interpretFeedbackBytes(char[] bytes) { return "reading: (length = " + bytes.length + ")" + "\n as HEX: " + charArrayAsHex(bytes) + "\n as text: " + new String(bytes); }
595be1fa-b120-455e-bc19-2d22f43bb1a9
private static String charArrayAsHex(char[] bytes) { StringBuilder bld = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { char current = bytes[i]; char lsp = hexArray[current & 0x0F]; // lowest 4 bits char msp = hexArray[current >>> 4]; // greatest 4 bits bld.append(msp).append(lsp); } return bld.toString(); }
52048479-b866-44f2-877e-2e8406e1577f
Configurator(String[] args) throws Exception { try { if ("HEX".equalsIgnoreCase(args[0])) { userInputLoop = new Main.HEXUserInputLoop(); } else if ("ASCII".equalsIgnoreCase(args[0])) { userInputLoop = new Main.ASCIIUserInputLoop(); } if ("SERIAL".equalsIgnoreCase(args[1])) { String portName = args[2]; port = new SerialPort(portName); } else if ("TCP".equalsIgnoreCase(args[1])) { String host = args[2]; int portNum = Integer.parseInt(args[3]); port = new EthernetPort(host, portNum); } else if ("TCPSERVER".equalsIgnoreCase(args[1])) { int portNum = Integer.parseInt(args[2]); port = new EthernetServerPort(portNum); } else { throw new Exception("wrong configuration parameters"); } } catch (ArrayIndexOutOfBoundsException e) { throw new Exception("wrong configuration parameters"); } }
6b43bf13-03c4-4374-b054-c8f1827e0ee9
Port getPort() { return port; }
d6d32943-123f-47c4-bf3b-d3f5bbedc66a
Main.UserInputLoop getUserInputLoop() { return userInputLoop; }
0b8505e2-8bbb-4a58-a2b7-517b84e3a51b
EthernetServerPort(int port) throws IOException { System.out.printf("EthernetServerPort on port %d\n", port); ServerSocket serverSocket = new ServerSocket(port); System.out.println("Waiting for client connection..."); Socket clientSocket = serverSocket.accept(); System.out.println("Client accepted!"); this.inputStream = clientSocket.getInputStream(); this.outputStream = clientSocket.getOutputStream(); }
2ba07314-65b6-44df-bc69-c0c96e5787bf
@Override public InputStream getInputStream() { return inputStream; }
cd4eb636-f1f9-4c4e-8a7e-9913864e79a6
@Override public OutputStream getOutputStream() { return outputStream; }
3b31efd1-f066-4802-9872-c718e82e0e19
@Override public void close() throws IOException { socket.close(); }
ecdddf3c-a928-4d47-82fb-ad965d3a4d5a
public SerialPort(final String name) throws IOException, PortInUseException, NoSuchPortException { System.out.printf("SerialPort %s\n", name); CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(name); port = portId.open(this.toString(), 3000); outputStream = port.getOutputStream(); inputStream = port.getInputStream(); System.out.println("Port is opened:" + name); }